title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
InfyTQ Interview Experience Upgradation Test 2020 - GeeksforGeeks
18 Jan, 2021 Hello Everyone, I am here to share my experience with my InfyTQ journey. InfyTQ is a certification exam which also offers placement opportunity. I was a zero to programming, and I was wondering how I am going to clear this round. I have only practiced 15 days on hackerearth algorithm section especially string manipulation. Then I got to know I have to clear the screening test before the actual round because in 2019 there was no screening test but there were taking it in 2020. So I have learned MCQs through many MCQ sites. Round 1: My 1st Round was Conducted in the last week of Feb 2020. I was very excited about this round. And This exam is divided into 2 sections and each section having 20 questions. Section 1 had an Aptitude Question which is of the Basic level. Section 2 had an Objective type Question which is of Medium and this question is from Programming Language (we have a choice between Python & Java, Which we have to choose during slot Booking), Data Structure, DBMS [MySQL and 1 question is from MongoDB]. I chose python. I Got my result after 4-6 days and I Qualified for Round 2 Successfully Round 2: My round 2 Exams were scheduled for the last week of March. But, Due to COVID-19, it is scheduled a few more times. And finally, it is conducted on the 3rd week of June. This exam also had 2 sections. Section1 had 2 Coding Questions, 1 question was easy and another was medium. Section 2 is the same as round 1. And to clear this round one has to score more than 65%. Note: If you are zero to programming/python/database 15 days of hard work is enough to crack all the rounds. We are the four friends who were preparing for it from the beginning, and we all are clearing these rounds easily. Interview: My Interview was scheduled for 24th Nov. And I got the mail just 1 day before the interview. My Interview was 35-40 min. long. I don’t know why my interview goes that long because my friends were having only a 15-25 minute long interview The question that the interviewer asked: Tell me something about yourself.Tell me something about your projects/certifications.He asked me to share my screen to make a prime number program and simple file handling program in python.I have mentioned the latest tech like ReactJS, MongoDB so he asked questions from these techs (Basic).Technology awareness questions. (if I am aware of cloud, machine learning, etc.).Some data structure questions (array, linked list, and their difference, etc.) Tell me something about yourself. Tell me something about your projects/certifications. He asked me to share my screen to make a prime number program and simple file handling program in python. I have mentioned the latest tech like ReactJS, MongoDB so he asked questions from these techs (Basic). Technology awareness questions. (if I am aware of cloud, machine learning, etc.). Some data structure questions (array, linked list, and their difference, etc.) Note: Keep a smile on your face during the Interview it gave u confidence and positivity. I got my interview result after exactly two weeks. I was selected and happy (Role: system engineer) just after 2 days, there is mine up-gradation test #no-preparation Upgradation Test: There was 3 question contain 50 marks (easy), 75 marks (med), and 100 marks (hard). Question 1: Write a program to add all the natural numbers till N but in binary.Python3Python3#input: 2(value of N)#output: 11#Explanation: binary of 1= 01#binary of 2= 10#01+10=11 result=0for i in range(1,N+1): result+=int(bin(i)[2:])return result Question 1: Write a program to add all the natural numbers till N but in binary. Python3 #input: 2(value of N)#output: 11#Explanation: binary of 1= 01#binary of 2= 10#01+10=11 result=0for i in range(1,N+1): result+=int(bin(i)[2:])return result Question 2: Longest Common Subsequence in two given strings. I have used python as it was my favorite till this test. I don’t know why it is getting the time limit to exceed and only one test case gets passed. After discussing it with my seniors. They advised me not to use python in CP. Question 2: Longest Common Subsequence in two given strings. I have used python as it was my favorite till this test. I don’t know why it is getting the time limit to exceed and only one test case gets passed. After discussing it with my seniors. They advised me not to use python in CP. I was disappointed with the result but guess what they are taking this round again due to technical issues. I got a second chance Tomorrow is my re-test. I don’t want to disappoint myself this time as I was learning Dynamic Programming since last week and I have also switched to C++ as one can give this round in any language. Let’s see what happens. Dynamic Programming learning: Initially I have watched a youtube, he is best at teaching dynamic programming. And I was reading articles and practicing on the Geekforgeeks platform. Geekforgeeks has all standard as well as ques variations on its platform. Learn the DP section from Youtube and Geekforgeeks DP section. Thank You Infosys Infosys-InfyTQ Infosys-interview-experience Marketing Interview Experiences Infosys 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 Amazon Interview Experience for SDE-1 (Off-Campus) 2022 Amazon Interview Experience Amazon Interview Experience for SDE-1 EPAM Interview Experience (Off-Campus) Amazon Interview Experience (Off-Campus) 2022 JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021 Amazon Interview Experience for SDE-1 (On-Campus) Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus)
[ { "code": null, "e": 26261, "s": 26233, "text": "\n18 Jan, 2021" }, { "code": null, "e": 26406, "s": 26261, "text": "Hello Everyone, I am here to share my experience with my InfyTQ journey. InfyTQ is a certification exam which also offers placement opportunity." }, { "code": null, "e": 26789, "s": 26406, "text": "I was a zero to programming, and I was wondering how I am going to clear this round. I have only practiced 15 days on hackerearth algorithm section especially string manipulation. Then I got to know I have to clear the screening test before the actual round because in 2019 there was no screening test but there were taking it in 2020. So I have learned MCQs through many MCQ sites." }, { "code": null, "e": 27306, "s": 26789, "text": "Round 1: My 1st Round was Conducted in the last week of Feb 2020. I was very excited about this round. And This exam is divided into 2 sections and each section having 20 questions. Section 1 had an Aptitude Question which is of the Basic level. Section 2 had an Objective type Question which is of Medium and this question is from Programming Language (we have a choice between Python & Java, Which we have to choose during slot Booking), Data Structure, DBMS [MySQL and 1 question is from MongoDB]. I chose python." }, { "code": null, "e": 27378, "s": 27306, "text": "I Got my result after 4-6 days and I Qualified for Round 2 Successfully" }, { "code": null, "e": 27755, "s": 27378, "text": "Round 2: My round 2 Exams were scheduled for the last week of March. But, Due to COVID-19, it is scheduled a few more times. And finally, it is conducted on the 3rd week of June. This exam also had 2 sections. Section1 had 2 Coding Questions, 1 question was easy and another was medium. Section 2 is the same as round 1. And to clear this round one has to score more than 65%." }, { "code": null, "e": 27864, "s": 27755, "text": "Note: If you are zero to programming/python/database 15 days of hard work is enough to crack all the rounds." }, { "code": null, "e": 27979, "s": 27864, "text": "We are the four friends who were preparing for it from the beginning, and we all are clearing these rounds easily." }, { "code": null, "e": 28118, "s": 27979, "text": "Interview: My Interview was scheduled for 24th Nov. And I got the mail just 1 day before the interview. My Interview was 35-40 min. long. " }, { "code": null, "e": 28230, "s": 28118, "text": "I don’t know why my interview goes that long because my friends were having only a 15-25 minute long interview " }, { "code": null, "e": 28271, "s": 28230, "text": "The question that the interviewer asked:" }, { "code": null, "e": 28724, "s": 28271, "text": "Tell me something about yourself.Tell me something about your projects/certifications.He asked me to share my screen to make a prime number program and simple file handling program in python.I have mentioned the latest tech like ReactJS, MongoDB so he asked questions from these techs (Basic).Technology awareness questions. (if I am aware of cloud, machine learning, etc.).Some data structure questions (array, linked list, and their difference, etc.)" }, { "code": null, "e": 28758, "s": 28724, "text": "Tell me something about yourself." }, { "code": null, "e": 28812, "s": 28758, "text": "Tell me something about your projects/certifications." }, { "code": null, "e": 28918, "s": 28812, "text": "He asked me to share my screen to make a prime number program and simple file handling program in python." }, { "code": null, "e": 29021, "s": 28918, "text": "I have mentioned the latest tech like ReactJS, MongoDB so he asked questions from these techs (Basic)." }, { "code": null, "e": 29103, "s": 29021, "text": "Technology awareness questions. (if I am aware of cloud, machine learning, etc.)." }, { "code": null, "e": 29182, "s": 29103, "text": "Some data structure questions (array, linked list, and their difference, etc.)" }, { "code": null, "e": 29272, "s": 29182, "text": "Note: Keep a smile on your face during the Interview it gave u confidence and positivity." }, { "code": null, "e": 29439, "s": 29272, "text": "I got my interview result after exactly two weeks. I was selected and happy (Role: system engineer) just after 2 days, there is mine up-gradation test #no-preparation" }, { "code": null, "e": 29542, "s": 29439, "text": "Upgradation Test: There was 3 question contain 50 marks (easy), 75 marks (med), and 100 marks (hard). " }, { "code": null, "e": 29800, "s": 29542, "text": " Question 1: Write a program to add all the natural numbers till N but in binary.Python3Python3#input: 2(value of N)#output: 11#Explanation: binary of 1= 01#binary of 2= 10#01+10=11 result=0for i in range(1,N+1): result+=int(bin(i)[2:])return result" }, { "code": null, "e": 29882, "s": 29800, "text": " Question 1: Write a program to add all the natural numbers till N but in binary." }, { "code": null, "e": 29890, "s": 29882, "text": "Python3" }, { "code": "#input: 2(value of N)#output: 11#Explanation: binary of 1= 01#binary of 2= 10#01+10=11 result=0for i in range(1,N+1): result+=int(bin(i)[2:])return result", "e": 30053, "s": 29890, "text": null }, { "code": null, "e": 30341, "s": 30053, "text": "Question 2: Longest Common Subsequence in two given strings. I have used python as it was my favorite till this test. I don’t know why it is getting the time limit to exceed and only one test case gets passed. After discussing it with my seniors. They advised me not to use python in CP." }, { "code": null, "e": 30629, "s": 30341, "text": "Question 2: Longest Common Subsequence in two given strings. I have used python as it was my favorite till this test. I don’t know why it is getting the time limit to exceed and only one test case gets passed. After discussing it with my seniors. They advised me not to use python in CP." }, { "code": null, "e": 30982, "s": 30629, "text": "I was disappointed with the result but guess what they are taking this round again due to technical issues. I got a second chance Tomorrow is my re-test. I don’t want to disappoint myself this time as I was learning Dynamic Programming since last week and I have also switched to C++ as one can give this round in any language. Let’s see what happens. " }, { "code": null, "e": 31301, "s": 30982, "text": "Dynamic Programming learning: Initially I have watched a youtube, he is best at teaching dynamic programming. And I was reading articles and practicing on the Geekforgeeks platform. Geekforgeeks has all standard as well as ques variations on its platform. Learn the DP section from Youtube and Geekforgeeks DP section." }, { "code": null, "e": 31311, "s": 31301, "text": "Thank You" }, { "code": null, "e": 31319, "s": 31311, "text": "Infosys" }, { "code": null, "e": 31334, "s": 31319, "text": "Infosys-InfyTQ" }, { "code": null, "e": 31363, "s": 31334, "text": "Infosys-interview-experience" }, { "code": null, "e": 31373, "s": 31363, "text": "Marketing" }, { "code": null, "e": 31395, "s": 31373, "text": "Interview Experiences" }, { "code": null, "e": 31403, "s": 31395, "text": "Infosys" }, { "code": null, "e": 31501, "s": 31403, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31552, "s": 31501, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 31594, "s": 31552, "text": "Amazon AWS Interview Experience for SDE-1" }, { "code": null, "e": 31650, "s": 31594, "text": "Amazon Interview Experience for SDE-1 (Off-Campus) 2022" }, { "code": null, "e": 31678, "s": 31650, "text": "Amazon Interview Experience" }, { "code": null, "e": 31716, "s": 31678, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 31755, "s": 31716, "text": "EPAM Interview Experience (Off-Campus)" }, { "code": null, "e": 31801, "s": 31755, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 31873, "s": 31801, "text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021" }, { "code": null, "e": 31923, "s": 31873, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" } ]
GATE | GATE-CS-2015 (Set 1) | Question 47 - GeeksforGeeks
29 Sep, 2021 A positive edge-triggered D flip-flop is connected to a positive edge-triggered JK flipflop as follows. The Q output of the D flip-flop is connected to both the J and K inputs of the JK flip-flop, while the Q output of the JK flip-flop is connected to the input of the D flip-flop. Initially, the output of the D flip-flop is set to logic one and the output of the JK flip-flop is cleared. Which one of the following is the bit sequence (including the initial state) generated at the Q output of the JK flip-flop when the flip-flops are connected to a free-running common clock? Assume that J = K = 1 is the toggle mode and J = K = 0 is the state-holding mode of the JK flip-flop. Both the flip-flops have non-zero propagation delays.(A) 0110110...(B) 0100100...(C) 011101110...(D) 011001100...Answer: (A)Explanation: Initially Q output of D – FF = 1 Initially Q output of JK – FF = 0 Now with the help of present state and next state table we can see what is happening in circuit. Toggle: J = K = 1 Hold : J = K = 0 We see from table Q output of D-FF is going to next state input of JK-FF and the bits sequence produced is like 110110..... Including initial condition (0) we get output as 0110110110.... Hence answer is (A) part. Another Explanation: Here, it is given that JK flip flop will toggle when J = K = 1 and it will retain the output if J = K = 0.Also, the output of the D flip flop would remain the same as the input. So, we have Initial output : D = 1 JK = 0 After clock 1 : D = 0 (D gets 0 as input from initial output of JK, so output = 0) JK = 1 (J = K = 1 from initial output of D, so output would be toggled from 0 to 1) After clock 2 : D = 1 (D gets 1 as input from previous output of JK, so output = 1) JK = 1 (J = K = 0 from previous output of D, so output would be retained to 1) After clock 3 : D = 1 (D gets 1 as input from previous output of JK, so output = 1) JK = 0 (J = K = 1 from previous output of D, so output would be toggled from 1 to 0) After clock 4 : D = 0 (D gets 0 as input from previous output of JK, so output = 0) JK = 1 (J = K = 1 from previous output of D, so output would be toggled from 0 to 1) After clock 5 : D = 1 (D gets 1 as input from previous output of JK, so output = 1) JK = 1 (J = K = 0 from previous output of D, so output would be retained to 1) Thus, the bit sequence generated at the Q output of the JK flip flop will be 0110110... YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersSequential Circuits : Latches and Flip Flops : GATE PYQs with Rishabh SetiyaWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:008:00 / 30:16•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=ngYeqE_gFV0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question GATE-CS-2015 (Set 1) GATE-GATE-CS-2015 (Set 1) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE MOCK 2017 | Question 24 GATE | GATE-CS-2006 | Question 47 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25869, "s": 25841, "text": "\n29 Sep, 2021" }, { "code": null, "e": 26688, "s": 25869, "text": "A positive edge-triggered D flip-flop is connected to a positive edge-triggered JK flipflop as follows. The Q output of the D flip-flop is connected to both the J and K inputs of the JK flip-flop, while the Q output of the JK flip-flop is connected to the input of the D flip-flop. Initially, the output of the D flip-flop is set to logic one and the output of the JK flip-flop is cleared. Which one of the following is the bit sequence (including the initial state) generated at the Q output of the JK flip-flop when the flip-flops are connected to a free-running common clock? Assume that J = K = 1 is the toggle mode and J = K = 0 is the state-holding mode of the JK flip-flop. Both the flip-flops have non-zero propagation delays.(A) 0110110...(B) 0100100...(C) 011101110...(D) 011001100...Answer: (A)Explanation: " }, { "code": null, "e": 26722, "s": 26688, "text": "Initially Q output of D – FF = 1" }, { "code": null, "e": 26757, "s": 26722, "text": "Initially Q output of JK – FF = 0" }, { "code": null, "e": 26854, "s": 26757, "text": "Now with the help of present state and next state table we can see what is happening in circuit." }, { "code": null, "e": 26872, "s": 26854, "text": "Toggle: J = K = 1" }, { "code": null, "e": 26889, "s": 26872, "text": "Hold : J = K = 0" }, { "code": null, "e": 27013, "s": 26889, "text": "We see from table Q output of D-FF is going to next state input of JK-FF and the bits sequence produced is like 110110....." }, { "code": null, "e": 27077, "s": 27013, "text": "Including initial condition (0) we get output as 0110110110...." }, { "code": null, "e": 27103, "s": 27077, "text": "Hence answer is (A) part." }, { "code": null, "e": 27124, "s": 27103, "text": "Another Explanation:" }, { "code": null, "e": 27302, "s": 27124, "text": "Here, it is given that JK flip flop will toggle when J = K = 1 and it will retain the output if J = K = 0.Also, the output of the D flip flop would remain the same as the input." }, { "code": null, "e": 27314, "s": 27302, "text": "So, we have" }, { "code": null, "e": 27337, "s": 27314, "text": "Initial output : D = 1" }, { "code": null, "e": 27344, "s": 27337, "text": "JK = 0" }, { "code": null, "e": 27428, "s": 27344, "text": "After clock 1 : D = 0 (D gets 0 as input \nfrom initial output of JK, so output = 0)" }, { "code": null, "e": 27512, "s": 27428, "text": "JK = 1 (J = K = 1 from initial output of D, so output would be toggled from 0 to 1)" }, { "code": null, "e": 27597, "s": 27512, "text": "After clock 2 : D = 1 (D gets 1 as input \nfrom previous output of JK, so output = 1)" }, { "code": null, "e": 27676, "s": 27597, "text": "JK = 1 (J = K = 0 from previous output of D, so output would be retained to 1)" }, { "code": null, "e": 27760, "s": 27676, "text": "After clock 3 : D = 1 (D gets 1 as input\nfrom previous output of JK, so output = 1)" }, { "code": null, "e": 27845, "s": 27760, "text": "JK = 0 (J = K = 1 from previous output of D, so output would be toggled from 1 to 0)" }, { "code": null, "e": 27929, "s": 27845, "text": "After clock 4 : D = 0 (D gets 0 as input\nfrom previous output of JK, so output = 0)" }, { "code": null, "e": 28014, "s": 27929, "text": "JK = 1 (J = K = 1 from previous output of D, so output would be toggled from 0 to 1)" }, { "code": null, "e": 28098, "s": 28014, "text": "After clock 5 : D = 1 (D gets 1 as input\nfrom previous output of JK, so output = 1)" }, { "code": null, "e": 28177, "s": 28098, "text": "JK = 1 (J = K = 0 from previous output of D, so output would be retained to 1)" }, { "code": null, "e": 28265, "s": 28177, "text": "Thus, the bit sequence generated at the Q output of the JK flip flop will be 0110110..." }, { "code": null, "e": 29170, "s": 28265, "text": " YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersSequential Circuits : Latches and Flip Flops : GATE PYQs with Rishabh SetiyaWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:008:00 / 30:16•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=ngYeqE_gFV0\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 29191, "s": 29170, "text": "GATE-CS-2015 (Set 1)" }, { "code": null, "e": 29217, "s": 29191, "text": "GATE-GATE-CS-2015 (Set 1)" }, { "code": null, "e": 29222, "s": 29217, "text": "GATE" }, { "code": null, "e": 29320, "s": 29222, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29354, "s": 29320, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 29388, "s": 29354, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 29422, "s": 29388, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 29455, "s": 29422, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 29491, "s": 29455, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 29527, "s": 29491, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 29561, "s": 29527, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 29595, "s": 29561, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 29629, "s": 29595, "text": "GATE | GATE-CS-2009 | Question 38" } ]
Inverting the Burrows - Wheeler Transform - GeeksforGeeks
26 Oct, 2017 Prerequisite: Burrows – Wheeler Data Transform Algorithm Why inverse of BWT? The main idea behind it: 1. The remarkable thing about BWT algorithm is that this particular transform is invertible with minimal data overhead. 2. To compute inverse of BWT is to undo the BWT and recover the original string. The naive method of implementing this algorithm can be studied from here. The naive approach is speed and memory intensive and requires us to store |text| cyclic rotations of the string |text|. 3. Let’s discuss a faster algorithm where we have with us only two things:i. bwt_arr[] which is the last column of sorted rotations list given as “annb$aa”.ii. ‘x’ which is the row index at which our original string “banana$” appears in the sorted rotations list. We can see that ‘x’ is 4 in the example below. Row Index Original Rotations Sorted Rotations ~~~~~~~~~ ~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~ 0 banana$ $banana 1 anana$b a$banan 2 nana$ba ana$ban 3 ana$ban anana$b *4 na$bana banana$ 5 a$banan na$bana 6 $banana nana$ba 4. An important observation: If the jth original rotation (which is original rotation shifted j characters to the left) is the ith row in the sorted order, then l_shift[i] records in the sorted order where (j+1)st original rotation appears. For example, the 0th original rotation “banana$” is row 4 of sorted order, and since l_shift[4] is 3, the next original rotation “anana$b” is row 3 of the sorted order. Row Index Original Rotations Sorted Rotations l_shift ~~~~~~~~~ ~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~ ~~~~~~~ 0 banana$ $banana 4 1 anana$b a$banan 0 2 nana$ba ana$ban 5 3 ana$ban anana$b 6 *4 na$bana banana$ 3 5 a$banan na$bana 1 6 $banana nana$ba 2 5. Our job is to deduce l_shift[] from the information available to us which is bwt_arr[] and ‘x’ and with its help compute the inverse of BWT. How to compute l_shift[] ?1. We know BWT which is “annb$aa”. This implies that we know all the characters of our original string, even though they’re permuted in wrong order. 2. By sorting bwt_arr[], we can reconstruct first column of sorted rotations list and we call it sorted_bwt[]. Row Index Sorted Rotations bwt_arr l_shift ~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~ 0 $ ? ? ? ? ? a 4 1 a ? ? ? ? ? n 2 a ? ? ? ? ? n 3 a ? ? ? ? ? b *4 b ? ? ? ? ? $ 3 5 n ? ? ? ? ? a 6 n ? ? ? ? ? a 3. Since ‘$’ occurs only once in the string ‘sorted_bwt[]’ and rotations are formed using cyclic wrap around, we can deduce that l_shift[0] = 4. Similarly, ‘b’ occurs once, so we can deduce that l_shift[4] = 3. 4. But, because ‘n’ appears twice, it seems ambiguous whether l_shift[5] = 1 and l_shift[6] = 2 or whether l_shift[5] = 2 and l_shift[6] = 1. 5. Rule to solve this ambiguity is that if rows i and j both start with the same letter and i<j, then l_shift[i] < l_shift[j]. This implies l_shift[5] = 1 and l_shift[6] =2. Continuing in a similar fashion, l_shift[] gets computed to the following. Row Index Sorted Rotations bwt_arr l_shift ~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~ 0 $ ? ? ? ? ? a 4 1 a ? ? ? ? ? n 0 2 a ? ? ? ? ? n 5 3 a ? ? ? ? ? b 6 *4 b ? ? ? ? ? $ 3 5 n ? ? ? ? ? a 1 6 n ? ? ? ? ? a 2 Why is the ambiguity resolving rule valid? 1. The rotations are sorted in such a way that row 5 is lexicographically less than row 6. 2. Thus, the five unknown characters in row 5 must be less than the five unknown characters in row 6 (as both start with ‘n’). 3. We also know that between the two rows than end with ‘n’, row 1 is lower than row 2. 4. But, the five unknown characters in rows 5 and 6 are precisely the first five characters in rows 1 and 2 or this would contradict the fact that rotations were sorted. 5. Thus, l_shift[5] = 1 and l_shift[6] = 2. Way of implementation: 1. Sort BWT: Using qsort(), we arrange characters of bwt_arr[] in sorted order and store it in sorted_arr[]. 2. Compute l_shift[]:i. We take an array of pointers struct node *arr[], each of which points to a linked list. ii. Making each distinct character of bwt_arr[] a head node of a linked list, we append nodes to the linked list whose data part contains index at which that character occurs in bwt_arr[]. i *arr[128] Linked Lists ~~~~~~~~~ ~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~ 37 $ -----> 4 -> NULL 97 a -----> 0 -> 5 -> 6 -> NULL 110 n -----> 1 -> 2 -> NULL 98 b -----> 3 -> NULL iii. Making distinct characters of sorted_bwt[] heads of linked lists, we traverse linked lists and get corresponding l_shift[] values. int[] l_shift = { 4, 0, 5, 6, 3, 1, 2 }; 3. Iterating string length times, we decode BWT with x = l_shift[x] and output bwt_arr[x]. x = l_shift[4] x = 3 bwt_arr[3] = 'b' x = l_shift[3] x = 6 bwt_arr[6] = 'a' Examples: Input : annb$aa // Burrows - Wheeler Transform 4 // Row index at which original message // appears in sorted rotations list Output : banana$ Input : ard$rcaaaabb 3 Output : abracadabra$ Following is the C code for way of implementation explained above: // C program to find inverse of Burrows// Wheeler transform#include <stdio.h>#include <stdlib.h>#include <string.h> // Structure to store info of a node of// linked liststruct node { int data; struct node* next;}; // Compares the characters of bwt_arr[]// and sorts them alphabeticallyint cmpfunc(const void* a, const void* b){ const char* ia = (const char*)a; const char* ib = (const char*)b; return strcmp(ia, ib);} // Creates the new nodestruct node* getNode(int i){ struct node* nn = (struct node*)malloc(sizeof(struct node)); nn->data = i; nn->next = NULL; return nn;} // Does insertion at end in the linked listvoid addAtLast(struct node** head, struct node* nn){ if (*head == NULL) { *head = nn; return; } struct node* temp = *head; while (temp->next != NULL) temp = temp->next; temp->next = nn;} // Computes l_shift[]void* computeLShift(struct node** head, int index, int* l_shift){ l_shift[index] = (*head)->data; (*head) = (*head)->next;} void invert(char bwt_arr[]){ int i,len_bwt = strlen(bwt_arr); char* sorted_bwt = (char*)malloc(len_bwt * sizeof(char)); strcpy(sorted_bwt, bwt_arr); int* l_shift = (int*)malloc(len_bwt * sizeof(int)); // Index at which original string appears // in the sorted rotations list int x = 4; // Sorts the characters of bwt_arr[] alphabetically qsort(sorted_bwt, len_bwt, sizeof(char), cmpfunc); // Array of pointers that act as head nodes // to linked lists created to compute l_shift[] struct node* arr[128] = { NULL }; // Takes each distinct character of bwt_arr[] as head // of a linked list and appends to it the new node // whose data part contains index at which // character occurs in bwt_arr[] for (i = 0; i < len_bwt; i++) { struct node* nn = getNode(i); addAtLast(&arr[bwt_arr[i]], nn); } // Takes each distinct character of sorted_arr[] as head // of a linked list and finds l_shift[] for (i = 0; i < len_bwt; i++) computeLShift(&arr[sorted_bwt[i]], i, l_shift); printf("Burrows - Wheeler Transform: %s\n", bwt_arr); printf("Inverse of Burrows - Wheeler Transform: "); // Decodes the bwt for (i = 0; i < len_bwt; i++) { x = l_shift[x]; printf("%c", bwt_arr[x]); }} // Driver program to test functions aboveint main(){ char bwt_arr[] = "annb$aa"; invert(bwt_arr); return 0;} Output: Burrows - Wheeler Transform: annb$aa Inverse of Burrows - Wheeler Transform: banana$ Time Complexity: O(nLogn) as qsort() takes O(nLogn) time. Exercise: Implement inverse of Inverse of Burrows – Wheeler Transform in O(n) time. Source:http://www.cs.princeton.edu/courses/archive/fall07/cos226/assignments/burrows.html This article is contributed by Anureet Kaur. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++ Check whether two strings are anagram of each other Longest Palindromic Substring | Set 1 Caesar Cipher in Cryptography Top 50 String Coding Problems for Interviews Length of the longest substring without repeating characters Reverse words in a given string
[ { "code": null, "e": 26215, "s": 26187, "text": "\n26 Oct, 2017" }, { "code": null, "e": 26272, "s": 26215, "text": "Prerequisite: Burrows – Wheeler Data Transform Algorithm" }, { "code": null, "e": 26317, "s": 26272, "text": "Why inverse of BWT? The main idea behind it:" }, { "code": null, "e": 26437, "s": 26317, "text": "1. The remarkable thing about BWT algorithm is that this particular transform is invertible with minimal data overhead." }, { "code": null, "e": 26712, "s": 26437, "text": "2. To compute inverse of BWT is to undo the BWT and recover the original string. The naive method of implementing this algorithm can be studied from here. The naive approach is speed and memory intensive and requires us to store |text| cyclic rotations of the string |text|." }, { "code": null, "e": 27023, "s": 26712, "text": "3. Let’s discuss a faster algorithm where we have with us only two things:i. bwt_arr[] which is the last column of sorted rotations list given as “annb$aa”.ii. ‘x’ which is the row index at which our original string “banana$” appears in the sorted rotations list. We can see that ‘x’ is 4 in the example below." }, { "code": null, "e": 27466, "s": 27023, "text": " Row Index Original Rotations Sorted Rotations\n ~~~~~~~~~ ~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~\n 0 banana$ $banana\n 1 anana$b a$banan\n 2 nana$ba ana$ban\n 3 ana$ban anana$b\n *4 na$bana banana$\n 5 a$banan na$bana\n 6 $banana nana$ba\n" }, { "code": null, "e": 27876, "s": 27466, "text": "4. An important observation: If the jth original rotation (which is original rotation shifted j characters to the left) is the ith row in the sorted order, then l_shift[i] records in the sorted order where (j+1)st original rotation appears. For example, the 0th original rotation “banana$” is row 4 of sorted order, and since l_shift[4] is 3, the next original rotation “anana$b” is row 3 of the sorted order." }, { "code": null, "e": 28347, "s": 27876, "text": "Row Index Original Rotations Sorted Rotations l_shift \n~~~~~~~~~ ~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~ ~~~~~~~\n 0 banana$ $banana 4\n 1 anana$b a$banan 0\n 2 nana$ba ana$ban 5\n 3 ana$ban anana$b 6\n *4 na$bana banana$ 3\n 5 a$banan na$bana 1\n 6 $banana nana$ba 2\n" }, { "code": null, "e": 28491, "s": 28347, "text": "5. Our job is to deduce l_shift[] from the information available to us which is bwt_arr[] and ‘x’ and with its help compute the inverse of BWT." }, { "code": null, "e": 28666, "s": 28491, "text": "How to compute l_shift[] ?1. We know BWT which is “annb$aa”. This implies that we know all the characters of our original string, even though they’re permuted in wrong order." }, { "code": null, "e": 28777, "s": 28666, "text": "2. By sorting bwt_arr[], we can reconstruct first column of sorted rotations list and we call it sorted_bwt[]." }, { "code": null, "e": 29160, "s": 28777, "text": " Row Index Sorted Rotations bwt_arr l_shift \n ~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~ \n 0 $ ? ? ? ? ? a 4\n 1 a ? ? ? ? ? n\n 2 a ? ? ? ? ? n\n 3 a ? ? ? ? ? b\n *4 b ? ? ? ? ? $ 3\n 5 n ? ? ? ? ? a\n 6 n ? ? ? ? ? a\n" }, { "code": null, "e": 29371, "s": 29160, "text": "3. Since ‘$’ occurs only once in the string ‘sorted_bwt[]’ and rotations are formed using cyclic wrap around, we can deduce that l_shift[0] = 4. Similarly, ‘b’ occurs once, so we can deduce that l_shift[4] = 3." }, { "code": null, "e": 29513, "s": 29371, "text": "4. But, because ‘n’ appears twice, it seems ambiguous whether l_shift[5] = 1 and l_shift[6] = 2 or whether l_shift[5] = 2 and l_shift[6] = 1." }, { "code": null, "e": 29762, "s": 29513, "text": "5. Rule to solve this ambiguity is that if rows i and j both start with the same letter and i<j, then l_shift[i] < l_shift[j]. This implies l_shift[5] = 1 and l_shift[6] =2. Continuing in a similar fashion, l_shift[] gets computed to the following." }, { "code": null, "e": 30215, "s": 29762, "text": " Row Index Sorted Rotations bwt_arr l_shift \n ~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~ \n 0 $ ? ? ? ? ? a 4\n 1 a ? ? ? ? ? n 0\n 2 a ? ? ? ? ? n 5\n 3 a ? ? ? ? ? b 6\n *4 b ? ? ? ? ? $ 3\n 5 n ? ? ? ? ? a 1\n 6 n ? ? ? ? ? a 2\n" }, { "code": null, "e": 30258, "s": 30215, "text": "Why is the ambiguity resolving rule valid?" }, { "code": null, "e": 30349, "s": 30258, "text": "1. The rotations are sorted in such a way that row 5 is lexicographically less than row 6." }, { "code": null, "e": 30476, "s": 30349, "text": "2. Thus, the five unknown characters in row 5 must be less than the five unknown characters in row 6 (as both start with ‘n’)." }, { "code": null, "e": 30564, "s": 30476, "text": "3. We also know that between the two rows than end with ‘n’, row 1 is lower than row 2." }, { "code": null, "e": 30734, "s": 30564, "text": "4. But, the five unknown characters in rows 5 and 6 are precisely the first five characters in rows 1 and 2 or this would contradict the fact that rotations were sorted." }, { "code": null, "e": 30778, "s": 30734, "text": "5. Thus, l_shift[5] = 1 and l_shift[6] = 2." }, { "code": null, "e": 30801, "s": 30778, "text": "Way of implementation:" }, { "code": null, "e": 30910, "s": 30801, "text": "1. Sort BWT: Using qsort(), we arrange characters of bwt_arr[] in sorted order and store it in sorted_arr[]." }, { "code": null, "e": 31022, "s": 30910, "text": "2. Compute l_shift[]:i. We take an array of pointers struct node *arr[], each of which points to a linked list." }, { "code": null, "e": 31211, "s": 31022, "text": "ii. Making each distinct character of bwt_arr[] a head node of a linked list, we append nodes to the linked list whose data part contains index at which that character occurs in bwt_arr[]." }, { "code": null, "e": 31490, "s": 31211, "text": " i *arr[128] Linked Lists\n~~~~~~~~~ ~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~ \n 37 $ -----> 4 -> NULL\n 97 a -----> 0 -> 5 -> 6 -> NULL\n 110 n -----> 1 -> 2 -> NULL\n 98 b -----> 3 -> NULL\n" }, { "code": null, "e": 31626, "s": 31490, "text": "iii. Making distinct characters of sorted_bwt[] heads of linked lists, we traverse linked lists and get corresponding l_shift[] values." }, { "code": null, "e": 31673, "s": 31626, "text": " int[] l_shift = { 4, 0, 5, 6, 3, 1, 2 };\n" }, { "code": null, "e": 31764, "s": 31673, "text": "3. Iterating string length times, we decode BWT with x = l_shift[x] and output bwt_arr[x]." }, { "code": null, "e": 31874, "s": 31764, "text": " x = l_shift[4] \n x = 3\n bwt_arr[3] = 'b'\n\n x = l_shift[3] \n x = 6\n bwt_arr[6] = 'a'\n" }, { "code": null, "e": 31884, "s": 31874, "text": "Examples:" }, { "code": null, "e": 32100, "s": 31884, "text": "Input : annb$aa // Burrows - Wheeler Transform\n 4 // Row index at which original message \n // appears in sorted rotations list \nOutput : banana$\n\nInput : ard$rcaaaabb\n 3\nOutput : abracadabra$\n" }, { "code": null, "e": 32167, "s": 32100, "text": "Following is the C code for way of implementation explained above:" }, { "code": "// C program to find inverse of Burrows// Wheeler transform#include <stdio.h>#include <stdlib.h>#include <string.h> // Structure to store info of a node of// linked liststruct node { int data; struct node* next;}; // Compares the characters of bwt_arr[]// and sorts them alphabeticallyint cmpfunc(const void* a, const void* b){ const char* ia = (const char*)a; const char* ib = (const char*)b; return strcmp(ia, ib);} // Creates the new nodestruct node* getNode(int i){ struct node* nn = (struct node*)malloc(sizeof(struct node)); nn->data = i; nn->next = NULL; return nn;} // Does insertion at end in the linked listvoid addAtLast(struct node** head, struct node* nn){ if (*head == NULL) { *head = nn; return; } struct node* temp = *head; while (temp->next != NULL) temp = temp->next; temp->next = nn;} // Computes l_shift[]void* computeLShift(struct node** head, int index, int* l_shift){ l_shift[index] = (*head)->data; (*head) = (*head)->next;} void invert(char bwt_arr[]){ int i,len_bwt = strlen(bwt_arr); char* sorted_bwt = (char*)malloc(len_bwt * sizeof(char)); strcpy(sorted_bwt, bwt_arr); int* l_shift = (int*)malloc(len_bwt * sizeof(int)); // Index at which original string appears // in the sorted rotations list int x = 4; // Sorts the characters of bwt_arr[] alphabetically qsort(sorted_bwt, len_bwt, sizeof(char), cmpfunc); // Array of pointers that act as head nodes // to linked lists created to compute l_shift[] struct node* arr[128] = { NULL }; // Takes each distinct character of bwt_arr[] as head // of a linked list and appends to it the new node // whose data part contains index at which // character occurs in bwt_arr[] for (i = 0; i < len_bwt; i++) { struct node* nn = getNode(i); addAtLast(&arr[bwt_arr[i]], nn); } // Takes each distinct character of sorted_arr[] as head // of a linked list and finds l_shift[] for (i = 0; i < len_bwt; i++) computeLShift(&arr[sorted_bwt[i]], i, l_shift); printf(\"Burrows - Wheeler Transform: %s\\n\", bwt_arr); printf(\"Inverse of Burrows - Wheeler Transform: \"); // Decodes the bwt for (i = 0; i < len_bwt; i++) { x = l_shift[x]; printf(\"%c\", bwt_arr[x]); }} // Driver program to test functions aboveint main(){ char bwt_arr[] = \"annb$aa\"; invert(bwt_arr); return 0;}", "e": 34633, "s": 32167, "text": null }, { "code": null, "e": 34641, "s": 34633, "text": "Output:" }, { "code": null, "e": 34728, "s": 34641, "text": "\nBurrows - Wheeler Transform: annb$aa\nInverse of Burrows - Wheeler Transform: banana$\n" }, { "code": null, "e": 34786, "s": 34728, "text": "Time Complexity: O(nLogn) as qsort() takes O(nLogn) time." }, { "code": null, "e": 34870, "s": 34786, "text": "Exercise: Implement inverse of Inverse of Burrows – Wheeler Transform in O(n) time." }, { "code": null, "e": 34960, "s": 34870, "text": "Source:http://www.cs.princeton.edu/courses/archive/fall07/cos226/assignments/burrows.html" }, { "code": null, "e": 35260, "s": 34960, "text": "This article is contributed by Anureet Kaur. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 35385, "s": 35260, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 35393, "s": 35385, "text": "Strings" }, { "code": null, "e": 35401, "s": 35393, "text": "Strings" }, { "code": null, "e": 35499, "s": 35401, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35556, "s": 35499, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 35592, "s": 35556, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 35645, "s": 35592, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 35681, "s": 35645, "text": "Convert string to char array in C++" }, { "code": null, "e": 35733, "s": 35681, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 35771, "s": 35733, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 35801, "s": 35771, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 35846, "s": 35801, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 35907, "s": 35846, "text": "Length of the longest substring without repeating characters" } ]
Find Unique Combinations of All Elements from Two Vectors in R - GeeksforGeeks
18 Apr, 2022 The number of possible combinations of two vectors can be computed by multiplying all the successive elements of the first vector with the corresponding elements of the second vector. In case, the two vectors have unique elements, the resultant table or data frame formed has m * n elements, where m is the length of the first vector and n is the length of the second vector, respectively. R programming language provides us in-built method as well as external packages to find out the possible pairs easily. expand.grid() in R can be used to generate a data frame where the rows are all possible unique combinations formed on taking elements from the argument vectors. More than 2 argument vectors can also be specified. The columns can be assigned customized names, otherwise, the row names are automatic. The number of rows in the data frame is equivalent to the total plausible combinations. Syntax: expand.grid(vec1...n) Example: R # declaring first integer vectorvec1 <- c(1:3) # declaring second string vectorvec2 <- c("GeeksForGeeks","CSE") # creating a data frame of vector1 and vector2 combinationsexpand.grid("col1"= vec1,"col2" = vec2) Output col1 col2 1 1 GeeksForGeeks 2 2 GeeksForGeeks 3 3 GeeksForGeeks 4 1 CSE 5 2 CSE 6 3 CSE The “tidyr” package in the R language can be installed and loaded into the working directory. The crossing() method of this package is used to create a cross joining of the input vectors to generate all the plausible combinations. The names can also be supplied by using named argument listing during function call. The order of appearance of elements in the vector is retained. Syntax: crossing(vec1...n) Example: R library("tidyr") # declaring first integer vectorvec1 <- letters[1:4] # declaring second string vectorvec2 <- c(8:10) # creating a data frame of vector1# and vector2 combinationscrossing(vec1,vec2) Output # A tibble: 12 x 2 vec1 vec2 <chr> <int> 1 a 8 2 a 9 3 a 10 4 b 8 5 b 9 6 b 10 7 c 8 8 c 9 9 c 10 10 d 8 11 d 9 12 d 10 The data.table library can be installed and loaded into the working space. CJ method which refers to (C)ross (J)oin of this package can be used to create a data.table formed from the cross product of the vectors. Multiple argument vectors can be supplied to this method. The output is returned to the form of a data.table using this approach. Syntax: CJ(vec1..n, sorted = TRUE, unique = FALSE) Parameter : vec1.. n : input argument vectors sorted : indicator of whether the order of input vectors is to be retained or not. unique : indicator of whether only the unique values of the result should be displayed Example: R library("data.table") # declaring first character vectorvec1 <- letters[1:4] # declaring second integer vectorvec2 <- c(8:10) # declaring third integer vectorvec3 <- c(1:2) # creating a data frame of vector1# and vector2 combinationsCJ(vec1, vec2, vec3, unique = TRUE) Output: vec1 vec2 vec3 1: a 8 1 2: a 8 2 3: a 9 1 4: a 9 2 5: a 10 1 6: a 10 2 7: b 8 1 8: b 8 2 9: b 9 1 10: b 9 2 11: b 10 1 12: b 10 2 13: c 8 1 14: c 8 2 15: c 9 1 16: c 9 2 17: c 10 1 18: c 10 2 19: d 8 1 20: d 8 2 21: d 9 1 22: d 9 2 23: d 10 1 24: d 10 2 varshagumber28 Picked R Vector-Programs R-Vectors 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 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 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": 26487, "s": 26459, "text": "\n18 Apr, 2022" }, { "code": null, "e": 26997, "s": 26487, "text": "The number of possible combinations of two vectors can be computed by multiplying all the successive elements of the first vector with the corresponding elements of the second vector. In case, the two vectors have unique elements, the resultant table or data frame formed has m * n elements, where m is the length of the first vector and n is the length of the second vector, respectively. R programming language provides us in-built method as well as external packages to find out the possible pairs easily. " }, { "code": null, "e": 27385, "s": 26997, "text": "expand.grid() in R can be used to generate a data frame where the rows are all possible unique combinations formed on taking elements from the argument vectors. More than 2 argument vectors can also be specified. The columns can be assigned customized names, otherwise, the row names are automatic. The number of rows in the data frame is equivalent to the total plausible combinations. " }, { "code": null, "e": 27393, "s": 27385, "text": "Syntax:" }, { "code": null, "e": 27415, "s": 27393, "text": "expand.grid(vec1...n)" }, { "code": null, "e": 27424, "s": 27415, "text": "Example:" }, { "code": null, "e": 27426, "s": 27424, "text": "R" }, { "code": "# declaring first integer vectorvec1 <- c(1:3) # declaring second string vectorvec2 <- c(\"GeeksForGeeks\",\"CSE\") # creating a data frame of vector1 and vector2 combinationsexpand.grid(\"col1\"= vec1,\"col2\" = vec2)", "e": 27637, "s": 27426, "text": null }, { "code": null, "e": 27644, "s": 27637, "text": "Output" }, { "code": null, "e": 27791, "s": 27644, "text": " col1 col2\n1 1 GeeksForGeeks\n2 2 GeeksForGeeks\n3 3 GeeksForGeeks\n4 1 CSE\n5 2 CSE\n6 3 CSE" }, { "code": null, "e": 28171, "s": 27791, "text": "The “tidyr” package in the R language can be installed and loaded into the working directory. The crossing() method of this package is used to create a cross joining of the input vectors to generate all the plausible combinations. The names can also be supplied by using named argument listing during function call. The order of appearance of elements in the vector is retained. " }, { "code": null, "e": 28179, "s": 28171, "text": "Syntax:" }, { "code": null, "e": 28198, "s": 28179, "text": "crossing(vec1...n)" }, { "code": null, "e": 28207, "s": 28198, "text": "Example:" }, { "code": null, "e": 28209, "s": 28207, "text": "R" }, { "code": "library(\"tidyr\") # declaring first integer vectorvec1 <- letters[1:4] # declaring second string vectorvec2 <- c(8:10) # creating a data frame of vector1# and vector2 combinationscrossing(vec1,vec2)", "e": 28407, "s": 28209, "text": null }, { "code": null, "e": 28414, "s": 28407, "text": "Output" }, { "code": null, "e": 28657, "s": 28414, "text": "# A tibble: \n12 x 2 \nvec1 vec2 \n<chr> <int> \n1 a 8 \n2 a 9 \n3 a 10 \n4 b 8 \n5 b 9 \n6 b 10 \n7 c 8 \n8 c 9 \n9 c 10\n10 d 8 \n11 d 9 \n12 d 10" }, { "code": null, "e": 29001, "s": 28657, "text": "The data.table library can be installed and loaded into the working space. CJ method which refers to (C)ross (J)oin of this package can be used to create a data.table formed from the cross product of the vectors. Multiple argument vectors can be supplied to this method. The output is returned to the form of a data.table using this approach. " }, { "code": null, "e": 29054, "s": 29001, "text": "Syntax: CJ(vec1..n, sorted = TRUE, unique = FALSE) " }, { "code": null, "e": 29067, "s": 29054, "text": "Parameter : " }, { "code": null, "e": 29102, "s": 29067, "text": "vec1.. n : input argument vectors " }, { "code": null, "e": 29186, "s": 29102, "text": "sorted : indicator of whether the order of input vectors is to be retained or not. " }, { "code": null, "e": 29273, "s": 29186, "text": "unique : indicator of whether only the unique values of the result should be displayed" }, { "code": null, "e": 29282, "s": 29273, "text": "Example:" }, { "code": null, "e": 29284, "s": 29282, "text": "R" }, { "code": "library(\"data.table\") # declaring first character vectorvec1 <- letters[1:4] # declaring second integer vectorvec2 <- c(8:10) # declaring third integer vectorvec3 <- c(1:2) # creating a data frame of vector1# and vector2 combinationsCJ(vec1, vec2, vec3, unique = TRUE)", "e": 29553, "s": 29284, "text": null }, { "code": null, "e": 29561, "s": 29553, "text": "Output:" }, { "code": null, "e": 30027, "s": 29561, "text": " vec1 vec2 vec3\n1: a 8 1\n2: a 8 2\n3: a 9 1\n4: a 9 2\n5: a 10 1\n6: a 10 2\n7: b 8 1\n8: b 8 2\n9: b 9 1\n10: b 9 2\n11: b 10 1\n12: b 10 2\n13: c 8 1\n14: c 8 2\n15: c 9 1\n16: c 9 2\n17: c 10 1\n18: c 10 2\n19: d 8 1\n20: d 8 2\n21: d 9 1\n22: d 9 2\n23: d 10 1\n24: d 10 2" }, { "code": null, "e": 30042, "s": 30027, "text": "varshagumber28" }, { "code": null, "e": 30049, "s": 30042, "text": "Picked" }, { "code": null, "e": 30067, "s": 30049, "text": "R Vector-Programs" }, { "code": null, "e": 30077, "s": 30067, "text": "R-Vectors" }, { "code": null, "e": 30088, "s": 30077, "text": "R Language" }, { "code": null, "e": 30099, "s": 30088, "text": "R Programs" }, { "code": null, "e": 30197, "s": 30099, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30249, "s": 30197, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 30284, "s": 30249, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 30322, "s": 30284, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 30380, "s": 30322, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30423, "s": 30380, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 30481, "s": 30423, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30524, "s": 30481, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 30573, "s": 30524, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30623, "s": 30573, "text": "How to filter R dataframe by multiple conditions?" } ]
Find N Arithmetic Means between A and B - GeeksforGeeks
04 May, 2022 Given three integers A, B and N the task is to find N Arithmetic means between A and B. We basically need to insert N terms in an Arithmetic progression. where A and B are first and last terms. Examples: Input : A = 20 B = 32 N = 5 Output : 22 24 26 28 30 The Arithmetic progression series as 20 22 24 26 28 30 32 Input : A = 5 B = 35 N = 5 Output : 10 15 20 25 30 Approach : Let A1, A2, A3, A4......An be N Arithmetic Means between two given numbers A and B . Then A, A1, A2 ..... An, B will be in Arithmetic Progression . Now B = (N+2)th term of the Arithmetic progression . So : Finding the (N+2)th term of the Arithmetic progression Series where d is the Common Difference B = A + (N + 2 – 1)d B – A = (N + 1)d So the Common Difference d is given by. d = (B – A) / (N + 1) So now we have the value of A and the value of the common difference(d), now we can find all the N Arithmetic Means between A and B. C++ Java Python3 C# PHP Javascript // C++ program to find n arithmetic// means between A and B#include <bits/stdc++.h>using namespace std; // Prints N arithmetic means between// A and B.void printAMeans(int A, int B, int N){ // calculate common difference(d) float d = (float)(B - A) / (N + 1); // for finding N the arithmetic // mean between A and B for (int i = 1; i <= N; i++) cout << (A + i * d) <<" "; } // Driver code to test aboveint main(){ int A = 20, B = 32, N = 5; printAMeans(A, B, N); return 0;} // java program to illustrate// n arithmetic mean between// A and Bimport java.io.*;import java.lang.*;import java.util.*; public class GFG { // insert function for calculating the means static void printAMeans(int A, int B, int N) { // Finding the value of d Common difference float d = (float)(B - A) / (N + 1); // for finding N the Arithmetic // mean between A and B for (int i = 1; i <= N; i++) System.out.print((A + i * d) + " "); } // Driver code public static void main(String args[]) { int A = 20, B = 32, N = 5; printAMeans(A, B, N); }} # Python3 program to find n arithmetic# means between A and B # Prints N arithmetic means# between A and B.def printAMeans(A, B, N): # Calculate common difference(d) d = (B - A) / (N + 1) # For finding N the arithmetic # mean between A and B for i in range(1, N + 1): print(int(A + i * d), end = " ") # Driver codeA = 20; B = 32; N = 5printAMeans(A, B, N) # This code is contributed by Smitha Dinesh Semwal // C# program to illustrate// n arithmetic mean between // A and Busing System; public class GFG { // insert function for calculating the means static void printAMeans(int A, int B, int N) { // Finding the value of d Common difference float d = (float)(B - A) / (N + 1); // for finding N the Arithmetic // mean between A and B for (int i = 1; i <= N; i++) Console.Write((A + i * d) + " "); } // Driver code public static void Main() { int A = 20, B = 32, N = 5; printAMeans(A, B, N); }}// Contributed by vt_m <?php// PHP program to find n arithmetic// means between A and B // Prints N arithmetic means// between A and B.function printAMeans($A, $B, $N){ // calculate common // difference(d) $d = ($B - $A) / ($N + 1); // for finding N the arithmetic // mean between A and B for ($i = 1; $i <= $N; $i++) echo ($A + $i * $d) ," ";} // Driver Code $A = 20; $B = 32; $N = 5; printAMeans($A, $B, $N); // This code is Contributed by vt_m.?> <script> // JavaScript program to find n arithmetic// means between A and B // Prints N arithmetic means// between A and B.function printAMeans(A, B, N){ // Calculate common difference(d) let d = (B - A) / (N + 1) // For finding N the arithmetic // mean between A and B for(let i = 1; i < N + 1; i++) document.write(Math.floor(A + i * d)," ")} // Driver codelet A = 20, B = 32, N = 5;printAMeans(A, B, N) // This code is contributed by Shinjanpatra </script> 22 24 26 28 30 vt_m ManasChhabra2 shinjanpatra arithmetic progression series statistical-algorithms Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Modulo Operator (%) in C/C++ with Examples Print all possible combinations of r elements in a given array of size n Segment Tree | Set 1 (Sum of given range) Prime Numbers Merge two sorted arrays The Knight's tour problem | Backtracking-1 Program to find GCD or HCF of two numbers Product of Array except itself Write a program to reverse digits of a number Find minimum number of coins that make a given value
[ { "code": null, "e": 26337, "s": 26309, "text": "\n04 May, 2022" }, { "code": null, "e": 26541, "s": 26337, "text": "Given three integers A, B and N the task is to find N Arithmetic means between A and B. We basically need to insert N terms in an Arithmetic progression. where A and B are first and last terms. Examples:" }, { "code": null, "e": 26707, "s": 26541, "text": "Input : A = 20 B = 32 N = 5\nOutput : 22 24 26 28 30\nThe Arithmetic progression series as \n20 22 24 26 28 30 32 \n\nInput : A = 5 B = 35 N = 5\nOutput : 10 15 20 25 30" }, { "code": null, "e": 27253, "s": 26707, "text": "Approach : Let A1, A2, A3, A4......An be N Arithmetic Means between two given numbers A and B . Then A, A1, A2 ..... An, B will be in Arithmetic Progression . Now B = (N+2)th term of the Arithmetic progression . So : Finding the (N+2)th term of the Arithmetic progression Series where d is the Common Difference B = A + (N + 2 – 1)d B – A = (N + 1)d So the Common Difference d is given by. d = (B – A) / (N + 1) So now we have the value of A and the value of the common difference(d), now we can find all the N Arithmetic Means between A and B. " }, { "code": null, "e": 27257, "s": 27253, "text": "C++" }, { "code": null, "e": 27262, "s": 27257, "text": "Java" }, { "code": null, "e": 27270, "s": 27262, "text": "Python3" }, { "code": null, "e": 27273, "s": 27270, "text": "C#" }, { "code": null, "e": 27277, "s": 27273, "text": "PHP" }, { "code": null, "e": 27288, "s": 27277, "text": "Javascript" }, { "code": "// C++ program to find n arithmetic// means between A and B#include <bits/stdc++.h>using namespace std; // Prints N arithmetic means between// A and B.void printAMeans(int A, int B, int N){ // calculate common difference(d) float d = (float)(B - A) / (N + 1); // for finding N the arithmetic // mean between A and B for (int i = 1; i <= N; i++) cout << (A + i * d) <<\" \"; } // Driver code to test aboveint main(){ int A = 20, B = 32, N = 5; printAMeans(A, B, N); return 0;}", "e": 27806, "s": 27288, "text": null }, { "code": "// java program to illustrate// n arithmetic mean between// A and Bimport java.io.*;import java.lang.*;import java.util.*; public class GFG { // insert function for calculating the means static void printAMeans(int A, int B, int N) { // Finding the value of d Common difference float d = (float)(B - A) / (N + 1); // for finding N the Arithmetic // mean between A and B for (int i = 1; i <= N; i++) System.out.print((A + i * d) + \" \"); } // Driver code public static void main(String args[]) { int A = 20, B = 32, N = 5; printAMeans(A, B, N); }}", "e": 28484, "s": 27806, "text": null }, { "code": "# Python3 program to find n arithmetic# means between A and B # Prints N arithmetic means# between A and B.def printAMeans(A, B, N): # Calculate common difference(d) d = (B - A) / (N + 1) # For finding N the arithmetic # mean between A and B for i in range(1, N + 1): print(int(A + i * d), end = \" \") # Driver codeA = 20; B = 32; N = 5printAMeans(A, B, N) # This code is contributed by Smitha Dinesh Semwal", "e": 28919, "s": 28484, "text": null }, { "code": "// C# program to illustrate// n arithmetic mean between // A and Busing System; public class GFG { // insert function for calculating the means static void printAMeans(int A, int B, int N) { // Finding the value of d Common difference float d = (float)(B - A) / (N + 1); // for finding N the Arithmetic // mean between A and B for (int i = 1; i <= N; i++) Console.Write((A + i * d) + \" \"); } // Driver code public static void Main() { int A = 20, B = 32, N = 5; printAMeans(A, B, N); }}// Contributed by vt_m", "e": 29565, "s": 28919, "text": null }, { "code": "<?php// PHP program to find n arithmetic// means between A and B // Prints N arithmetic means// between A and B.function printAMeans($A, $B, $N){ // calculate common // difference(d) $d = ($B - $A) / ($N + 1); // for finding N the arithmetic // mean between A and B for ($i = 1; $i <= $N; $i++) echo ($A + $i * $d) ,\" \";} // Driver Code $A = 20; $B = 32; $N = 5; printAMeans($A, $B, $N); // This code is Contributed by vt_m.?>", "e": 30044, "s": 29565, "text": null }, { "code": "<script> // JavaScript program to find n arithmetic// means between A and B // Prints N arithmetic means// between A and B.function printAMeans(A, B, N){ // Calculate common difference(d) let d = (B - A) / (N + 1) // For finding N the arithmetic // mean between A and B for(let i = 1; i < N + 1; i++) document.write(Math.floor(A + i * d),\" \")} // Driver codelet A = 20, B = 32, N = 5;printAMeans(A, B, N) // This code is contributed by Shinjanpatra </script>", "e": 30531, "s": 30044, "text": null }, { "code": null, "e": 30546, "s": 30531, "text": "22 24 26 28 30" }, { "code": null, "e": 30551, "s": 30546, "text": "vt_m" }, { "code": null, "e": 30565, "s": 30551, "text": "ManasChhabra2" }, { "code": null, "e": 30578, "s": 30565, "text": "shinjanpatra" }, { "code": null, "e": 30601, "s": 30578, "text": "arithmetic progression" }, { "code": null, "e": 30608, "s": 30601, "text": "series" }, { "code": null, "e": 30631, "s": 30608, "text": "statistical-algorithms" }, { "code": null, "e": 30644, "s": 30631, "text": "Mathematical" }, { "code": null, "e": 30657, "s": 30644, "text": "Mathematical" }, { "code": null, "e": 30664, "s": 30657, "text": "series" }, { "code": null, "e": 30762, "s": 30664, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30805, "s": 30762, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 30878, "s": 30805, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 30920, "s": 30878, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 30934, "s": 30920, "text": "Prime Numbers" }, { "code": null, "e": 30958, "s": 30934, "text": "Merge two sorted arrays" }, { "code": null, "e": 31001, "s": 30958, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 31043, "s": 31001, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 31074, "s": 31043, "text": "Product of Array except itself" }, { "code": null, "e": 31120, "s": 31074, "text": "Write a program to reverse digits of a number" } ]
Facebook Transcoder - GeeksforGeeks
02 Dec, 2020 Transcoder was proposed by researchers at Facebook in September 2020 in the paper titled “Unsupervised Translation of Programming Languages”. The goal of the project was to train AI to understand the code in a different language and able to convert the code from one language to another. Many of the companies have code base in old programming languages like COBOL, and if they want to shift their codebase to newer programming languages like Java, C++, or Python, they required a lot of money and effort to do that. In that case, Transcoder can save a lot of resources. Model : For TransCoder, the authors use a sequence-to-sequence (seq2seq) model with attention. The seq2seq architecture is consists of an encoder and a decoder with a transformer architecture. The authors use a single shared model for all programming languages. For training the model they proposed three principles: Cross Programming language model (XLM) Pre-training: Pre-training is an important part as it ensures that if a different piece of code expressing the same instruction should be mapped to the same representation regardless of programming language. The author observed that pre-training with masked language modeling objective leads to significant improvements in pre-training on monolingual source code De-noising Auto Encoding: Since the XLM pre-training generates high-quality embedding for the encoder architecture but still, the decoder lacks the training to translate the code. Therefore, the model trained with Demising -Encoding objective where the model is trained to predict a sequence of tokens given a corrupted version of that sequence. Back Translation: In practice, XLM pre-training and denoising auto-encoding alone is enough to generate translations. However, the quality of these translations tends to low, as the model is never trained to translate functions from one language to another. To address this issue, the authors use the back-translation method. This back-translation method is commonly used where we have a large monolingual (of one language) dataset. In this method, the model is trained to translate source to target and vice- versa parallelly. Datasets and Training details: Training Architecture: The authors use transformer architecture with 6 layers, 8 attention heads, and set the dimensionality of the model to 1024. They use a single encoder and a single decoder for all programming languages. After pre-training, the authors trained the model with Denoising Auto Encoding and Back translation objective alternatively. For optimizing the model, the authors use Adam Optimizer. Preprocessing: The authors use javalang tokenizer for Java, tokenizer of the standard library for Python, and the clang tokenizer for C++. These tokenizers ensure that meaningless modifications in the code do not have any impact on the tokenized sequence. t-SNE visualization of cross-lingual token embedding. Embedding of Similar token in a different language are closer to each other Datasets Used: For training, the authors use the Github public dataset available on Google BigQuery and filter the repositories which permit redistribution of parts of projects and select java, python, and C++ codes. The authors use function level code for training evaluation because they are short enough to fit in a single batch and allows easy evaluation by using the output generated from that function. For validation and testing, the authors used multiple language solutions for problems on the GeeksforGeeks platform. Implementation: Python3 # First clone the git repository for transcoder# in local environment! git clone https: // github.com/facebookresearch/TransCoder transcoder/ # Download the model files (link given in official# git repository)! wget https: // dl.fbaipublicfiles.com/transcoder/model_1.pth / # Since transcoder is implemeneted in pytorch, # we need to install pytorch first! pip install torch torchvision # Now install other required documentations! pip install numpy fastBPE Moses Apex libclang submitit six sacrebleu == 1.2.11 # Now we run the translate.py file with following arguments:# src_lang = source language file# tgt_lang = target language file# model_path = path of the model which we downloaded above# > file.java/cpp/py = file which we want to convert# the command below may take some time to run! sudo python transcoder/translate.py - -src_lang java - -tgt_lang python - -model_path model_1.pth > code2.java C++ void worstFit(int blockSize[], int m, int processSize[], int n) { int allocation[n]; memset(allocation, -1, sizeof(allocation)); for(int i = 0; i < n; i ++){ int wstIdx = – 1; for(int j = 0; j < m; j++){ if(blockSize[j] >= processSize[i]){ if(wstIdx == – 1) wstIdx = j; else if(blockSize[wstIdx] < blockSize[j]) wstIdx = j; } } if(wstIdx != -1){ allocation[i] = wstIdx; blockSize[wstIdx] -= processSize[i]; } } cout << “\nProcess No.\tProcess Size\tBlock no.\n”; for(int i = 0; i < n; i++){ cout << ” ” << i+1 << “\t\t” << processSize[i] << “\t\t”; if(allocation[i] != -1) cout << allocation[i] + 1; else cout << “Not Allocated”; cout << endl; } } Python def worstFit(blockSize, m, processSize, n): allocation = [-1] * n for i in range(n): wstIdx = -1 for j in range(m): if blockSize[j] >= processSize[i]: if wstIdx == -1: wstIdx = j elif blockSize[wstIdx] < blockSize[j]: wstIdx = j if wstIdx != -1: allocation[i] = wstIdx blockSize[wstIdx] -= processSize[i] print(“\nProcess No.\tProcess Size\tBlock no.\n”) for i in range(n): print(” ” + str(i+1) + “\t\t” + str(processSize[i]) + “\t\t”) if allocation[i] != -1: print(allocation[i] + 1) else: print(“Not Allocated”) print() Java public static int max(int a, int b){ return a > b ? a : b; } public static void createDirectory(Path path) throws IOException { if(!Files.exists(path)) { Files.createDirectories(path); } } Python def max(a, b): return a if a > b else b def create_directory(path): if not os.path.exists(path): os.makedirs(path) Results and Evaluation methods: Evaluation Metric: For the most part of studies, the authors used the BLEU score, another metric used by authors called Reference match which simply means the percentage of translations that perfectly match the ground truth reference. However, these metrics do not ensure the syntactic correctness of the program. The author used another metric called Computational Accuracy, which compares the output of source function and hypothesis function. Beam Search: The authors experimented with two evaluation metrics, either by taking the model only returns the hypothesis with the highest log-probability (Greedy search) or by taking top-N log probabilities. The authors found significant improvement in accuracy when they used beam search, up to 33.7% in Java → Python with Beam of N=25. Below are the results when they used Greedy Search. Below are the evaluation results based on BEAM search of N=25: The authors compared Transcoder with two existing frameworks j2py (java-to-python) with 38.3 computational accuracy and Tangible software’s C++-to-Java converter with 61% computational accuracy. Transcoder clearly outperforms both of these. References: Transcoder Paper Transcoder GitHub official Repository Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm Intuition of Adam Optimizer CNN | Introduction to Pooling Layer Convolutional Neural Network (CNN) in Machine Learning Markov Decision Process Singular Value Decomposition (SVD) k-nearest neighbor algorithm in Python SARSA Reinforcement Learning Q-Learning in Python
[ { "code": null, "e": 25589, "s": 25561, "text": "\n02 Dec, 2020" }, { "code": null, "e": 26160, "s": 25589, "text": "Transcoder was proposed by researchers at Facebook in September 2020 in the paper titled “Unsupervised Translation of Programming Languages”. The goal of the project was to train AI to understand the code in a different language and able to convert the code from one language to another. Many of the companies have code base in old programming languages like COBOL, and if they want to shift their codebase to newer programming languages like Java, C++, or Python, they required a lot of money and effort to do that. In that case, Transcoder can save a lot of resources." }, { "code": null, "e": 26168, "s": 26160, "text": "Model :" }, { "code": null, "e": 26477, "s": 26168, "text": "For TransCoder, the authors use a sequence-to-sequence (seq2seq) model with attention. The seq2seq architecture is consists of an encoder and a decoder with a transformer architecture. The authors use a single shared model for all programming languages. For training the model they proposed three principles:" }, { "code": null, "e": 26879, "s": 26477, "text": "Cross Programming language model (XLM) Pre-training: Pre-training is an important part as it ensures that if a different piece of code expressing the same instruction should be mapped to the same representation regardless of programming language. The author observed that pre-training with masked language modeling objective leads to significant improvements in pre-training on monolingual source code" }, { "code": null, "e": 27225, "s": 26879, "text": "De-noising Auto Encoding: Since the XLM pre-training generates high-quality embedding for the encoder architecture but still, the decoder lacks the training to translate the code. Therefore, the model trained with Demising -Encoding objective where the model is trained to predict a sequence of tokens given a corrupted version of that sequence." }, { "code": null, "e": 27753, "s": 27225, "text": "Back Translation: In practice, XLM pre-training and denoising auto-encoding alone is enough to generate translations. However, the quality of these translations tends to low, as the model is never trained to translate functions from one language to another. To address this issue, the authors use the back-translation method. This back-translation method is commonly used where we have a large monolingual (of one language) dataset. In this method, the model is trained to translate source to target and vice- versa parallelly." }, { "code": null, "e": 27784, "s": 27753, "text": "Datasets and Training details:" }, { "code": null, "e": 28192, "s": 27784, "text": "Training Architecture: The authors use transformer architecture with 6 layers, 8 attention heads, and set the dimensionality of the model to 1024. They use a single encoder and a single decoder for all programming languages. After pre-training, the authors trained the model with Denoising Auto Encoding and Back translation objective alternatively. For optimizing the model, the authors use Adam Optimizer." }, { "code": null, "e": 28448, "s": 28192, "text": "Preprocessing: The authors use javalang tokenizer for Java, tokenizer of the standard library for Python, and the clang tokenizer for C++. These tokenizers ensure that meaningless modifications in the code do not have any impact on the tokenized sequence." }, { "code": null, "e": 28578, "s": 28448, "text": "t-SNE visualization of cross-lingual token embedding. Embedding of Similar token in a different language are closer to each other" }, { "code": null, "e": 29104, "s": 28578, "text": "Datasets Used: For training, the authors use the Github public dataset available on Google BigQuery and filter the repositories which permit redistribution of parts of projects and select java, python, and C++ codes. The authors use function level code for training evaluation because they are short enough to fit in a single batch and allows easy evaluation by using the output generated from that function. For validation and testing, the authors used multiple language solutions for problems on the GeeksforGeeks platform." }, { "code": null, "e": 29120, "s": 29104, "text": "Implementation:" }, { "code": null, "e": 29128, "s": 29120, "text": "Python3" }, { "code": "# First clone the git repository for transcoder# in local environment! git clone https: // github.com/facebookresearch/TransCoder transcoder/ # Download the model files (link given in official# git repository)! wget https: // dl.fbaipublicfiles.com/transcoder/model_1.pth / # Since transcoder is implemeneted in pytorch, # we need to install pytorch first! pip install torch torchvision # Now install other required documentations! pip install numpy fastBPE Moses Apex libclang submitit six sacrebleu == 1.2.11 # Now we run the translate.py file with following arguments:# src_lang = source language file# tgt_lang = target language file# model_path = path of the model which we downloaded above# > file.java/cpp/py = file which we want to convert# the command below may take some time to run! sudo python transcoder/translate.py - -src_lang java - -tgt_lang python - -model_path model_1.pth > code2.java", "e": 30042, "s": 29128, "text": null }, { "code": null, "e": 30046, "s": 30042, "text": "C++" }, { "code": null, "e": 30110, "s": 30046, "text": "void worstFit(int blockSize[], int m, int processSize[], int n)" }, { "code": null, "e": 30112, "s": 30110, "text": "{" }, { "code": null, "e": 30131, "s": 30112, "text": "int allocation[n];" }, { "code": null, "e": 30175, "s": 30131, "text": "memset(allocation, -1, sizeof(allocation));" }, { "code": null, "e": 30204, "s": 30175, "text": "for(int i = 0; i < n; i ++){" }, { "code": null, "e": 30223, "s": 30204, "text": " int wstIdx = – 1;" }, { "code": null, "e": 30252, "s": 30223, "text": " for(int j = 0; j < m; j++){" }, { "code": null, "e": 30290, "s": 30252, "text": " if(blockSize[j] >= processSize[i]){" }, { "code": null, "e": 30311, "s": 30290, "text": " if(wstIdx == – 1)" }, { "code": null, "e": 30327, "s": 30311, "text": " wstIdx = j;" }, { "code": null, "e": 30372, "s": 30327, "text": " else if(blockSize[wstIdx] < blockSize[j])" }, { "code": null, "e": 30388, "s": 30372, "text": " wstIdx = j;" }, { "code": null, "e": 30392, "s": 30388, "text": " }" }, { "code": null, "e": 30395, "s": 30392, "text": " }" }, { "code": null, "e": 30414, "s": 30395, "text": " if(wstIdx != -1){" }, { "code": null, "e": 30440, "s": 30414, "text": " allocation[i] = wstIdx;" }, { "code": null, "e": 30479, "s": 30440, "text": " blockSize[wstIdx] -= processSize[i];" }, { "code": null, "e": 30482, "s": 30479, "text": " }" }, { "code": null, "e": 30484, "s": 30482, "text": "}" }, { "code": null, "e": 30536, "s": 30484, "text": "cout << “\\nProcess No.\\tProcess Size\\tBlock no.\\n”;" }, { "code": null, "e": 30564, "s": 30536, "text": "for(int i = 0; i < n; i++){" }, { "code": null, "e": 30623, "s": 30564, "text": " cout << ” ” << i+1 << “\\t\\t” << processSize[i] << “\\t\\t”;" }, { "code": null, "e": 30675, "s": 30623, "text": " if(allocation[i] != -1) cout << allocation[i] + 1;" }, { "code": null, "e": 30681, "s": 30675, "text": " else" }, { "code": null, "e": 30708, "s": 30681, "text": " cout << “Not Allocated”;" }, { "code": null, "e": 30722, "s": 30708, "text": "cout << endl;" }, { "code": null, "e": 30724, "s": 30722, "text": "}" }, { "code": null, "e": 30726, "s": 30724, "text": "}" }, { "code": null, "e": 30733, "s": 30726, "text": "Python" }, { "code": null, "e": 30777, "s": 30733, "text": "def worstFit(blockSize, m, processSize, n):" }, { "code": null, "e": 30799, "s": 30777, "text": "allocation = [-1] * n" }, { "code": null, "e": 30818, "s": 30799, "text": "for i in range(n):" }, { "code": null, "e": 30831, "s": 30818, "text": " wstIdx = -1" }, { "code": null, "e": 30851, "s": 30831, "text": " for j in range(m):" }, { "code": null, "e": 30888, "s": 30851, "text": " if blockSize[j] >= processSize[i]:" }, { "code": null, "e": 30908, "s": 30888, "text": " if wstIdx == -1:" }, { "code": null, "e": 30923, "s": 30908, "text": " wstIdx = j" }, { "code": null, "e": 30965, "s": 30923, "text": " elif blockSize[wstIdx] < blockSize[j]:" }, { "code": null, "e": 30980, "s": 30965, "text": " wstIdx = j" }, { "code": null, "e": 30998, "s": 30980, "text": " if wstIdx != -1:" }, { "code": null, "e": 31023, "s": 30998, "text": " allocation[i] = wstIdx" }, { "code": null, "e": 31061, "s": 31023, "text": " blockSize[wstIdx] -= processSize[i]" }, { "code": null, "e": 31112, "s": 31061, "text": " print(“\\nProcess No.\\tProcess Size\\tBlock no.\\n”)" }, { "code": null, "e": 31132, "s": 31112, "text": " for i in range(n):" }, { "code": null, "e": 31166, "s": 31132, "text": " print(” ” + str(i+1) + “\\t\\t” +" }, { "code": null, "e": 31199, "s": 31166, "text": " str(processSize[i]) + “\\t\\t”)" }, { "code": null, "e": 31225, "s": 31199, "text": " if allocation[i] != -1:" }, { "code": null, "e": 31253, "s": 31225, "text": " print(allocation[i] + 1)" }, { "code": null, "e": 31261, "s": 31253, "text": " else:" }, { "code": null, "e": 31287, "s": 31261, "text": " print(“Not Allocated”)" }, { "code": null, "e": 31297, "s": 31287, "text": " print()" }, { "code": null, "e": 31302, "s": 31297, "text": "Java" }, { "code": null, "e": 31339, "s": 31302, "text": "public static int max(int a, int b){" }, { "code": null, "e": 31361, "s": 31339, "text": "return a > b ? a : b;" }, { "code": null, "e": 31363, "s": 31361, "text": "}" }, { "code": null, "e": 31428, "s": 31363, "text": "public static void createDirectory(Path path) throws IOException" }, { "code": null, "e": 31430, "s": 31428, "text": "{" }, { "code": null, "e": 31454, "s": 31430, "text": "if(!Files.exists(path))" }, { "code": null, "e": 31456, "s": 31454, "text": "{" }, { "code": null, "e": 31488, "s": 31456, "text": " Files.createDirectories(path);" }, { "code": null, "e": 31490, "s": 31488, "text": "}" }, { "code": null, "e": 31492, "s": 31490, "text": "}" }, { "code": null, "e": 31499, "s": 31492, "text": "Python" }, { "code": null, "e": 31514, "s": 31499, "text": "def max(a, b):" }, { "code": null, "e": 31545, "s": 31514, "text": " return a if a > b else b" }, { "code": null, "e": 31573, "s": 31545, "text": "def create_directory(path):" }, { "code": null, "e": 31608, "s": 31573, "text": " if not os.path.exists(path):" }, { "code": null, "e": 31642, "s": 31608, "text": " os.makedirs(path)" }, { "code": null, "e": 31674, "s": 31642, "text": "Results and Evaluation methods:" }, { "code": null, "e": 32120, "s": 31674, "text": "Evaluation Metric: For the most part of studies, the authors used the BLEU score, another metric used by authors called Reference match which simply means the percentage of translations that perfectly match the ground truth reference. However, these metrics do not ensure the syntactic correctness of the program. The author used another metric called Computational Accuracy, which compares the output of source function and hypothesis function." }, { "code": null, "e": 32459, "s": 32120, "text": "Beam Search: The authors experimented with two evaluation metrics, either by taking the model only returns the hypothesis with the highest log-probability (Greedy search) or by taking top-N log probabilities. The authors found significant improvement in accuracy when they used beam search, up to 33.7% in Java → Python with Beam of N=25." }, { "code": null, "e": 32511, "s": 32459, "text": "Below are the results when they used Greedy Search." }, { "code": null, "e": 32574, "s": 32511, "text": "Below are the evaluation results based on BEAM search of N=25:" }, { "code": null, "e": 32815, "s": 32574, "text": "The authors compared Transcoder with two existing frameworks j2py (java-to-python) with 38.3 computational accuracy and Tangible software’s C++-to-Java converter with 61% computational accuracy. Transcoder clearly outperforms both of these." }, { "code": null, "e": 32827, "s": 32815, "text": "References:" }, { "code": null, "e": 32844, "s": 32827, "text": "Transcoder Paper" }, { "code": null, "e": 32882, "s": 32844, "text": "Transcoder GitHub official Repository" }, { "code": null, "e": 32899, "s": 32882, "text": "Machine Learning" }, { "code": null, "e": 32916, "s": 32899, "text": "Machine Learning" }, { "code": null, "e": 33014, "s": 32916, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33055, "s": 33014, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 33088, "s": 33055, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 33116, "s": 33088, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 33152, "s": 33116, "text": "CNN | Introduction to Pooling Layer" }, { "code": null, "e": 33207, "s": 33152, "text": "Convolutional Neural Network (CNN) in Machine Learning" }, { "code": null, "e": 33231, "s": 33207, "text": "Markov Decision Process" }, { "code": null, "e": 33266, "s": 33231, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 33305, "s": 33266, "text": "k-nearest neighbor algorithm in Python" }, { "code": null, "e": 33334, "s": 33305, "text": "SARSA Reinforcement Learning" } ]
Program to check congruency of two triangles - GeeksforGeeks
18 Jul, 2018 Given four arrays of 3 numbers each which represents sides and angles of two triangles. The task is to check if the two triangles are Congruent or not. Also print the theorem by which they are congruent. Note: All sides and angles given as input are for valid triangles. Examples: Input : side1 = [3, 4, 5] angle1 = [90, 60, 30] side2 = [4, 3, 5] angle2 = [60, 30, 90] Output: Triangles are congruent by SSS SAS ASA AAS HL. Input : side1 = [3, 5, 6] angle1 = [80, 50, 50] side2 = [1, 1, 1] angle2 = [60, 60, 60] Output: Triangles are not congruent Congruent triangles are two or more triangles that have all corresponding sides that are equal or a pair of sides and between angle are equal or a pair of angle and side between are equal or a pair of angle and other side are equal or hypotenuse and one side are equal. The congruency of triangles can be proved by the following theorems: Side-Side-Side (SSS) Congruency criteria: If all the sides of a triangle are equal to the sides of another triangle then the triangles are said to be congruent by the property of Side-Side-Side (SSS).In above triangle ABC and A’B’C’ if, AB=A’B’ and BC=B’C’ and CA=C’A’ then, triangles are congruent.Side-Angle-Side (SAS) Congruent criteria: If two sides of the two triangles are equal and the angle between them is same in both triangle then the triangles are said to be congruent by the property of Side-Angle-Side (SAS). In above triangle ABC and A’B’C’ if, AB=A’B’ and BC=B’C’ and = triangles are congruent.Angle-Side-Angle (ASA) Congruent criteria :If two angles of the two triangles are equal and the length of side between them is same in both triangle then the triangles are said to be congruent by the property of Angle-Side-Angle (ASA).In above triangle ABC and A’B’C’ if, = and = and BC=B’C’ then, triangles are congruent.Angle-Angle-Side (AAS) Congruent criteria :If two angles of the two triangles are equal and the length of other side is same in both triangle then the triangles are said to be congruent by the property of Angle-Angle-Side (AAS). In above triangle ABC and A’B’C’ if, = and = and CA=C’A’ then, triangles are congruent.Hypotenuse-Leg (HL) Congruent criteria :If the hypotenuse of the two triangles are equal and the length of any other one side is same in both triangle then the triangles are said to be congruent by the property of Hypotenuse-Leg (HL). Side-Side-Side (SSS) Congruency criteria: If all the sides of a triangle are equal to the sides of another triangle then the triangles are said to be congruent by the property of Side-Side-Side (SSS).In above triangle ABC and A’B’C’ if, AB=A’B’ and BC=B’C’ and CA=C’A’ then, triangles are congruent. Side-Angle-Side (SAS) Congruent criteria: If two sides of the two triangles are equal and the angle between them is same in both triangle then the triangles are said to be congruent by the property of Side-Angle-Side (SAS). In above triangle ABC and A’B’C’ if, AB=A’B’ and BC=B’C’ and = triangles are congruent. Angle-Side-Angle (ASA) Congruent criteria :If two angles of the two triangles are equal and the length of side between them is same in both triangle then the triangles are said to be congruent by the property of Angle-Side-Angle (ASA).In above triangle ABC and A’B’C’ if, = and = and BC=B’C’ then, triangles are congruent. Angle-Angle-Side (AAS) Congruent criteria :If two angles of the two triangles are equal and the length of other side is same in both triangle then the triangles are said to be congruent by the property of Angle-Angle-Side (AAS). In above triangle ABC and A’B’C’ if, = and = and CA=C’A’ then, triangles are congruent. Hypotenuse-Leg (HL) Congruent criteria :If the hypotenuse of the two triangles are equal and the length of any other one side is same in both triangle then the triangles are said to be congruent by the property of Hypotenuse-Leg (HL). Below is the implementation of the above theorems. # Python program to check # similarity between two triangles. # Function for SAS congruencydef cong_sas(s1, s2, a1, a2): s1 = [float(i) for i in s1] s2 = [float(i) for i in s2] a1 = [float(i) for i in a1] a2 = [float(i) for i in a2] s1.sort() s2.sort() a1.sort() a2.sort() # Check for SAS # angle b / w two smallest sides is largest. if s1[0] == s2[0] and s1[1] == s2[1]: # since we take angle b / w the sides. if a1[2] == a2[2]: return 1 if s1[1] == s2[1] and s1[2] == s2[2]: if a1[0] == a2[0]: return 1 if s1[2] == s2[2] and s1[0] == s2[0]: if a1[1] == a2[1]: return 1 return 0 # Function for ASA congruencydef cong_asa(s1, s2, a1, a2): s1 = [float(i) for i in s1] s2 = [float(i) for i in s2] a1 = [float(i) for i in a1] a2 = [float(i) for i in a2] s1.sort() s2.sort() a1.sort() a2.sort() # Check for ASA # side b / w two smallest angle is largest. if a1[0] == a2[0] and a1[1] == a2[1]: # since we take side b / w the angle. if s1[2] == s2[2]: return 1 if a1[1] == a2[1] and a1[2] == a2[2]: if s1[0] == s2[0]: return 1 if a1[2] == a2[2] and a1[0] == a2[0]: if s1[1] == s2[1]: return 1 return 0 # Function for AAS congruencydef cong_aas(s1, s2, a1, a2): s1 = [float(i) for i in s1] s2 = [float(i) for i in s2] a1 = [float(i) for i in a1] a2 = [float(i) for i in a2] s1.sort() s2.sort() a1.sort() a2.sort() # Check for AAS # side other two smallest angle is smallest or 2nd smallest. if a1[0] == a2[0] and a1[1] == a2[1]: # since we take side other than angles. if s1[0] == s2[0] or s1[1] == s2[1]: return 1 if a1[1] == a2[1] and a1[2] == a2[2]: if s1[1] == s2[1] or s1[2] == s2[2]: return 1 if a1[2] == a2[2] and a1[0] == a2[0]: if s1[0] == s2[0] or s1[2] == s2[2]: return 1 return 0 # Function for HL congruencydef cong_hl(s1, s2): s1 = [float(i) for i in s1] s2 = [float(i) for i in s2] s1.sort() s2.sort() # Check for HL if s1[2] == s2[2]: if s1[1] == s2[1] or s1[0] == s2[0]: return 1 return 0 # Function for SSS congruencydef cong_sss(s1, s2): s1 = [float(i) for i in s1] s2 = [float(i) for i in s2] s1.sort() s2.sort() # Check for SSS if(s1[0] == s2[0] and s1[1] == s2[1] and s1[2] == s2[2]): return 1 return 0 # Driver Code s1 = [3, 4, 5]s2 = [4, 3, 5] a1 = [90, 60, 30]a2 = [60, 30, 90] # function call for SSS congruencysss = cong_sss(s1, s2) # function call for SAS congruency sas = cong_sas(s1, s2, a1, a2) # function call for ASA congruency asa = cong_asa(s1, s2, a1, a2) # function call for AAS congruencyaas = cong_aas(s1, s2, a1, a2) # function call for HL congruencyhl = cong_hl(s1, s2, ) # Check if triangles are congruent or not if sss or sas or asa or aas or hl : print "Triangles are congruent by", if sss: print "SSS", if sas: print "SAS", if asa: print "ASA", if aas: print "AAS", if hl: print "HL",else: print "Triangles are not congruent" Triangles are congruent by SSS SAS ASA AAS HL math school-programming triangle Geometric School Programming Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for distance between two points on earth Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Optimum location of point to minimize total distance Check whether a given point lies inside a triangle or not Closest Pair of Points | O(nlogn) Implementation Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26141, "s": 26113, "text": "\n18 Jul, 2018" }, { "code": null, "e": 26345, "s": 26141, "text": "Given four arrays of 3 numbers each which represents sides and angles of two triangles. The task is to check if the two triangles are Congruent or not. Also print the theorem by which they are congruent." }, { "code": null, "e": 26412, "s": 26345, "text": "Note: All sides and angles given as input are for valid triangles." }, { "code": null, "e": 26422, "s": 26412, "text": "Examples:" }, { "code": null, "e": 26713, "s": 26422, "text": "Input : side1 = [3, 4, 5] angle1 = [90, 60, 30]\n side2 = [4, 3, 5] angle2 = [60, 30, 90]\nOutput: Triangles are congruent by SSS SAS ASA AAS HL. \n\nInput : side1 = [3, 5, 6] angle1 = [80, 50, 50]\n side2 = [1, 1, 1] angle2 = [60, 60, 60]\nOutput: Triangles are not congruent\n" }, { "code": null, "e": 26983, "s": 26713, "text": "Congruent triangles are two or more triangles that have all corresponding sides that are equal or a pair of sides and between angle are equal or a pair of angle and side between are equal or a pair of angle and other side are equal or hypotenuse and one side are equal." }, { "code": null, "e": 27052, "s": 26983, "text": "The congruency of triangles can be proved by the following theorems:" }, { "code": null, "e": 28544, "s": 27052, "text": "Side-Side-Side (SSS) Congruency criteria: If all the sides of a triangle are equal to the sides of another triangle then the triangles are said to be congruent by the property of Side-Side-Side (SSS).In above triangle ABC and A’B’C’ if, AB=A’B’ and BC=B’C’ and CA=C’A’ then, triangles are congruent.Side-Angle-Side (SAS) Congruent criteria: If two sides of the two triangles are equal and the angle between them is same in both triangle then the triangles are said to be congruent by the property of Side-Angle-Side (SAS). In above triangle ABC and A’B’C’ if, AB=A’B’ and BC=B’C’ and = triangles are congruent.Angle-Side-Angle (ASA) Congruent criteria :If two angles of the two triangles are equal and the length of side between them is same in both triangle then the triangles are said to be congruent by the property of Angle-Side-Angle (ASA).In above triangle ABC and A’B’C’ if, = and = and BC=B’C’ then, triangles are congruent.Angle-Angle-Side (AAS) Congruent criteria :If two angles of the two triangles are equal and the length of other side is same in both triangle then the triangles are said to be congruent by the property of Angle-Angle-Side (AAS). In above triangle ABC and A’B’C’ if, = and = and CA=C’A’ then, triangles are congruent.Hypotenuse-Leg (HL) Congruent criteria :If the hypotenuse of the two triangles are equal and the length of any other one side is same in both triangle then the triangles are said to be congruent by the property of Hypotenuse-Leg (HL)." }, { "code": null, "e": 28844, "s": 28544, "text": "Side-Side-Side (SSS) Congruency criteria: If all the sides of a triangle are equal to the sides of another triangle then the triangles are said to be congruent by the property of Side-Side-Side (SSS).In above triangle ABC and A’B’C’ if, AB=A’B’ and BC=B’C’ and CA=C’A’ then, triangles are congruent." }, { "code": null, "e": 29158, "s": 28844, "text": "Side-Angle-Side (SAS) Congruent criteria: If two sides of the two triangles are equal and the angle between them is same in both triangle then the triangles are said to be congruent by the property of Side-Angle-Side (SAS). In above triangle ABC and A’B’C’ if, AB=A’B’ and BC=B’C’ and = triangles are congruent." }, { "code": null, "e": 29484, "s": 29158, "text": "Angle-Side-Angle (ASA) Congruent criteria :If two angles of the two triangles are equal and the length of side between them is same in both triangle then the triangles are said to be congruent by the property of Angle-Side-Angle (ASA).In above triangle ABC and A’B’C’ if, = and = and BC=B’C’ then, triangles are congruent." }, { "code": null, "e": 29805, "s": 29484, "text": "Angle-Angle-Side (AAS) Congruent criteria :If two angles of the two triangles are equal and the length of other side is same in both triangle then the triangles are said to be congruent by the property of Angle-Angle-Side (AAS). In above triangle ABC and A’B’C’ if, = and = and CA=C’A’ then, triangles are congruent." }, { "code": null, "e": 30040, "s": 29805, "text": "Hypotenuse-Leg (HL) Congruent criteria :If the hypotenuse of the two triangles are equal and the length of any other one side is same in both triangle then the triangles are said to be congruent by the property of Hypotenuse-Leg (HL)." }, { "code": null, "e": 30091, "s": 30040, "text": "Below is the implementation of the above theorems." }, { "code": "# Python program to check # similarity between two triangles. # Function for SAS congruencydef cong_sas(s1, s2, a1, a2): s1 = [float(i) for i in s1] s2 = [float(i) for i in s2] a1 = [float(i) for i in a1] a2 = [float(i) for i in a2] s1.sort() s2.sort() a1.sort() a2.sort() # Check for SAS # angle b / w two smallest sides is largest. if s1[0] == s2[0] and s1[1] == s2[1]: # since we take angle b / w the sides. if a1[2] == a2[2]: return 1 if s1[1] == s2[1] and s1[2] == s2[2]: if a1[0] == a2[0]: return 1 if s1[2] == s2[2] and s1[0] == s2[0]: if a1[1] == a2[1]: return 1 return 0 # Function for ASA congruencydef cong_asa(s1, s2, a1, a2): s1 = [float(i) for i in s1] s2 = [float(i) for i in s2] a1 = [float(i) for i in a1] a2 = [float(i) for i in a2] s1.sort() s2.sort() a1.sort() a2.sort() # Check for ASA # side b / w two smallest angle is largest. if a1[0] == a2[0] and a1[1] == a2[1]: # since we take side b / w the angle. if s1[2] == s2[2]: return 1 if a1[1] == a2[1] and a1[2] == a2[2]: if s1[0] == s2[0]: return 1 if a1[2] == a2[2] and a1[0] == a2[0]: if s1[1] == s2[1]: return 1 return 0 # Function for AAS congruencydef cong_aas(s1, s2, a1, a2): s1 = [float(i) for i in s1] s2 = [float(i) for i in s2] a1 = [float(i) for i in a1] a2 = [float(i) for i in a2] s1.sort() s2.sort() a1.sort() a2.sort() # Check for AAS # side other two smallest angle is smallest or 2nd smallest. if a1[0] == a2[0] and a1[1] == a2[1]: # since we take side other than angles. if s1[0] == s2[0] or s1[1] == s2[1]: return 1 if a1[1] == a2[1] and a1[2] == a2[2]: if s1[1] == s2[1] or s1[2] == s2[2]: return 1 if a1[2] == a2[2] and a1[0] == a2[0]: if s1[0] == s2[0] or s1[2] == s2[2]: return 1 return 0 # Function for HL congruencydef cong_hl(s1, s2): s1 = [float(i) for i in s1] s2 = [float(i) for i in s2] s1.sort() s2.sort() # Check for HL if s1[2] == s2[2]: if s1[1] == s2[1] or s1[0] == s2[0]: return 1 return 0 # Function for SSS congruencydef cong_sss(s1, s2): s1 = [float(i) for i in s1] s2 = [float(i) for i in s2] s1.sort() s2.sort() # Check for SSS if(s1[0] == s2[0] and s1[1] == s2[1] and s1[2] == s2[2]): return 1 return 0 # Driver Code s1 = [3, 4, 5]s2 = [4, 3, 5] a1 = [90, 60, 30]a2 = [60, 30, 90] # function call for SSS congruencysss = cong_sss(s1, s2) # function call for SAS congruency sas = cong_sas(s1, s2, a1, a2) # function call for ASA congruency asa = cong_asa(s1, s2, a1, a2) # function call for AAS congruencyaas = cong_aas(s1, s2, a1, a2) # function call for HL congruencyhl = cong_hl(s1, s2, ) # Check if triangles are congruent or not if sss or sas or asa or aas or hl : print \"Triangles are congruent by\", if sss: print \"SSS\", if sas: print \"SAS\", if asa: print \"ASA\", if aas: print \"AAS\", if hl: print \"HL\",else: print \"Triangles are not congruent\"", "e": 33609, "s": 30091, "text": null }, { "code": null, "e": 33656, "s": 33609, "text": "Triangles are congruent by SSS SAS ASA AAS HL\n" }, { "code": null, "e": 33661, "s": 33656, "text": "math" }, { "code": null, "e": 33680, "s": 33661, "text": "school-programming" }, { "code": null, "e": 33689, "s": 33680, "text": "triangle" }, { "code": null, "e": 33699, "s": 33689, "text": "Geometric" }, { "code": null, "e": 33718, "s": 33699, "text": "School Programming" }, { "code": null, "e": 33728, "s": 33718, "text": "Geometric" }, { "code": null, "e": 33826, "s": 33728, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33875, "s": 33826, "text": "Program for distance between two points on earth" }, { "code": null, "e": 33926, "s": 33875, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 33979, "s": 33926, "text": "Optimum location of point to minimize total distance" }, { "code": null, "e": 34037, "s": 33979, "text": "Check whether a given point lies inside a triangle or not" }, { "code": null, "e": 34086, "s": 34037, "text": "Closest Pair of Points | O(nlogn) Implementation" }, { "code": null, "e": 34104, "s": 34086, "text": "Python Dictionary" }, { "code": null, "e": 34120, "s": 34104, "text": "Arrays in C/C++" }, { "code": null, "e": 34139, "s": 34120, "text": "Inheritance in C++" }, { "code": null, "e": 34164, "s": 34139, "text": "Reverse a string in Java" } ]
Java Program to Blur Images using OpenCV - GeeksforGeeks
17 May, 2021 Blurring is a simple and frequently used image processing operation. It is also called as Smoothing. OpenCV library provides many functions to apply diverse linear filters to smooth images or blur images. Smoothing of an image removes noisy pixels from the image and applying a low-pass filter to an image. A low-pass filter means removing noise from an image while leaving the majority of the image undamaged. The most common type of filter is linear. In a linear filter, the weighted sum of the input pixels value determines the output pixels value. OpenCV functions which can be used to blur an image are as follows: blur() GaussianBlur() medianBlur() bilateralFilter() Return type of above functions is modified image of the same directory which is supposed to be taken as sample input image. All functions described above are as follows Method1. Blur() : This function performs smoothing using normalized block filter. Syntax: Imgproc.blur(src, dst, new Size(i, i), new Point(-1, -1)); Parameters: This function requires 4 arguments src: Source image dst: Destination image Size( w, h ): Size of the kernel of width w pixels and height h pixels Point(-1, -1): Indicates the anchor point location with respect to the neighborhood. The center of the kernel is considered the anchor point if there is a negative value. Method 2. GaussianBlur(): This function performs smoothing using a Gaussian filter. Syntax: Imgproc.GaussianBlur(src, dst, new Size(i, i), 0, 0); Parameters: This function requires 4 arguments src: Source image dst: Destination image Size(w, h): The size of the kernel to be used. The size will be calculated using the σx and σy arguments if w and h are not odd and positive numbers. σx, σy: The standard deviation in x and y. Writing 0 implies that σx and σy is calculated using kernel size. Method 3. medianBlur(): This function performs smoothing using a Median filter. Syntax: Imgproc.medianBlur(src, dst, i); Parameters: This function requires 3 arguments src: Source image dst: Destination image i: Size of the kernel. It must be odd. Method 4. bilateralFilter(): This function performs smoothing using a Bilateral filter. Syntax: Imgproc.bilateralFilter(src, dst, i, i * 2, i / 2); Parameters: This function requires 5 arguments src: Source image dst: Destination image d: The diameter of each pixel neighborhood. σColor: Standard deviation in the color space. σSpace: Standard deviation in the coordinate space (in pixel terms) Implementation: Input image is as follows which is supposed to be blurred out. Input Image Java // Importing OpenCV libraries// to use inbuilt methodsimport org.opencv.core.*;import org.opencv.highgui.HighGui;import org.opencv.imgcodecs.Imgcodecs;import org.opencv.imgproc.Imgproc; class GFG { int DELAY_BLUR = 100; int MAX_KERNEL_LENGTH = 31; // Source Image by creating Matlab object Mat src = new Mat(); // Destination Image by creating Matlab object Mat dst = new Mat(); // Main driver code public static void main(String[] args) { // Load the native library System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // Taking input image from directory String filename = "D:\\InputImage.jpg"; src = Imgcodecs.imread(filename, Imgcodecs.IMREAD_COLOR); // 4 different methods of Imgproc class // to blur out input image // Method 1. Standard blur method // using blur() for (int i = 1; i < MAX_KERNEL_LENGTH; i = i + 2) { Imgproc.blur(src, dst, new Size(i, i), new Point(-1, -1)); // Display blurred input image displayDst(DELAY_BLUR); } // Method 2. Gaussian blur method // using GaussianBlur() for (int i = 1; i < MAX_KERNEL_LENGTH; i = i + 2) { Imgproc.GaussianBlur(src, dst, new Size(i, i), 0, 0); // Display blurred input image displayDst(DELAY_BLUR); } // Method 3. Median blur method // using medianBlur() for (int i = 1; i < MAX_KERNEL_LENGTH; i = i + 2) { Imgproc.medianBlur(src, dst, i); // Display blurred input image displayDst(DELAY_BLUR); } // Method 4. Bilateral filter Method // using bilateralFilter() for (int i = 1; i < MAX_KERNEL_LENGTH; i = i + 2) { Imgproc.bilateralFilter(src, dst, i, i * 2, i / 2); // Display blurred input image displayDst(DELAY_BLUR); } }} Output: The output image is a blurred image of the corresponding input image: Output Image simmytarika5 Java-OpenCV OpenCV Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Program to print ASCII Value of a character
[ { "code": null, "e": 25225, "s": 25197, "text": "\n17 May, 2021" }, { "code": null, "e": 25430, "s": 25225, "text": "Blurring is a simple and frequently used image processing operation. It is also called as Smoothing. OpenCV library provides many functions to apply diverse linear filters to smooth images or blur images." }, { "code": null, "e": 25777, "s": 25430, "text": "Smoothing of an image removes noisy pixels from the image and applying a low-pass filter to an image. A low-pass filter means removing noise from an image while leaving the majority of the image undamaged. The most common type of filter is linear. In a linear filter, the weighted sum of the input pixels value determines the output pixels value." }, { "code": null, "e": 25845, "s": 25777, "text": "OpenCV functions which can be used to blur an image are as follows:" }, { "code": null, "e": 25852, "s": 25845, "text": "blur()" }, { "code": null, "e": 25867, "s": 25852, "text": "GaussianBlur()" }, { "code": null, "e": 25880, "s": 25867, "text": "medianBlur()" }, { "code": null, "e": 25898, "s": 25880, "text": "bilateralFilter()" }, { "code": null, "e": 26067, "s": 25898, "text": "Return type of above functions is modified image of the same directory which is supposed to be taken as sample input image. All functions described above are as follows" }, { "code": null, "e": 26150, "s": 26067, "text": "Method1. Blur() : This function performs smoothing using normalized block filter. " }, { "code": null, "e": 26158, "s": 26150, "text": "Syntax:" }, { "code": null, "e": 26217, "s": 26158, "text": "Imgproc.blur(src, dst, new Size(i, i), new Point(-1, -1));" }, { "code": null, "e": 26264, "s": 26217, "text": "Parameters: This function requires 4 arguments" }, { "code": null, "e": 26282, "s": 26264, "text": "src: Source image" }, { "code": null, "e": 26305, "s": 26282, "text": "dst: Destination image" }, { "code": null, "e": 26376, "s": 26305, "text": "Size( w, h ): Size of the kernel of width w pixels and height h pixels" }, { "code": null, "e": 26547, "s": 26376, "text": "Point(-1, -1): Indicates the anchor point location with respect to the neighborhood. The center of the kernel is considered the anchor point if there is a negative value." }, { "code": null, "e": 26632, "s": 26547, "text": "Method 2. GaussianBlur(): This function performs smoothing using a Gaussian filter. " }, { "code": null, "e": 26640, "s": 26632, "text": "Syntax:" }, { "code": null, "e": 26694, "s": 26640, "text": "Imgproc.GaussianBlur(src, dst, new Size(i, i), 0, 0);" }, { "code": null, "e": 26741, "s": 26694, "text": "Parameters: This function requires 4 arguments" }, { "code": null, "e": 26759, "s": 26741, "text": "src: Source image" }, { "code": null, "e": 26782, "s": 26759, "text": "dst: Destination image" }, { "code": null, "e": 26932, "s": 26782, "text": "Size(w, h): The size of the kernel to be used. The size will be calculated using the σx and σy arguments if w and h are not odd and positive numbers." }, { "code": null, "e": 27041, "s": 26932, "text": "σx, σy: The standard deviation in x and y. Writing 0 implies that σx and σy is calculated using kernel size." }, { "code": null, "e": 27122, "s": 27041, "text": "Method 3. medianBlur(): This function performs smoothing using a Median filter. " }, { "code": null, "e": 27130, "s": 27122, "text": "Syntax:" }, { "code": null, "e": 27163, "s": 27130, "text": "Imgproc.medianBlur(src, dst, i);" }, { "code": null, "e": 27210, "s": 27163, "text": "Parameters: This function requires 3 arguments" }, { "code": null, "e": 27228, "s": 27210, "text": "src: Source image" }, { "code": null, "e": 27251, "s": 27228, "text": "dst: Destination image" }, { "code": null, "e": 27290, "s": 27251, "text": "i: Size of the kernel. It must be odd." }, { "code": null, "e": 27379, "s": 27290, "text": "Method 4. bilateralFilter(): This function performs smoothing using a Bilateral filter. " }, { "code": null, "e": 27388, "s": 27379, "text": "Syntax: " }, { "code": null, "e": 27440, "s": 27388, "text": "Imgproc.bilateralFilter(src, dst, i, i * 2, i / 2);" }, { "code": null, "e": 27487, "s": 27440, "text": "Parameters: This function requires 5 arguments" }, { "code": null, "e": 27505, "s": 27487, "text": "src: Source image" }, { "code": null, "e": 27528, "s": 27505, "text": "dst: Destination image" }, { "code": null, "e": 27572, "s": 27528, "text": "d: The diameter of each pixel neighborhood." }, { "code": null, "e": 27619, "s": 27572, "text": "σColor: Standard deviation in the color space." }, { "code": null, "e": 27687, "s": 27619, "text": "σSpace: Standard deviation in the coordinate space (in pixel terms)" }, { "code": null, "e": 27766, "s": 27687, "text": "Implementation: Input image is as follows which is supposed to be blurred out." }, { "code": null, "e": 27778, "s": 27766, "text": "Input Image" }, { "code": null, "e": 27783, "s": 27778, "text": "Java" }, { "code": "// Importing OpenCV libraries// to use inbuilt methodsimport org.opencv.core.*;import org.opencv.highgui.HighGui;import org.opencv.imgcodecs.Imgcodecs;import org.opencv.imgproc.Imgproc; class GFG { int DELAY_BLUR = 100; int MAX_KERNEL_LENGTH = 31; // Source Image by creating Matlab object Mat src = new Mat(); // Destination Image by creating Matlab object Mat dst = new Mat(); // Main driver code public static void main(String[] args) { // Load the native library System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // Taking input image from directory String filename = \"D:\\\\InputImage.jpg\"; src = Imgcodecs.imread(filename, Imgcodecs.IMREAD_COLOR); // 4 different methods of Imgproc class // to blur out input image // Method 1. Standard blur method // using blur() for (int i = 1; i < MAX_KERNEL_LENGTH; i = i + 2) { Imgproc.blur(src, dst, new Size(i, i), new Point(-1, -1)); // Display blurred input image displayDst(DELAY_BLUR); } // Method 2. Gaussian blur method // using GaussianBlur() for (int i = 1; i < MAX_KERNEL_LENGTH; i = i + 2) { Imgproc.GaussianBlur(src, dst, new Size(i, i), 0, 0); // Display blurred input image displayDst(DELAY_BLUR); } // Method 3. Median blur method // using medianBlur() for (int i = 1; i < MAX_KERNEL_LENGTH; i = i + 2) { Imgproc.medianBlur(src, dst, i); // Display blurred input image displayDst(DELAY_BLUR); } // Method 4. Bilateral filter Method // using bilateralFilter() for (int i = 1; i < MAX_KERNEL_LENGTH; i = i + 2) { Imgproc.bilateralFilter(src, dst, i, i * 2, i / 2); // Display blurred input image displayDst(DELAY_BLUR); } }}", "e": 29818, "s": 27783, "text": null }, { "code": null, "e": 29900, "s": 29822, "text": "Output: The output image is a blurred image of the corresponding input image:" }, { "code": null, "e": 29915, "s": 29902, "text": "Output Image" }, { "code": null, "e": 29930, "s": 29917, "text": "simmytarika5" }, { "code": null, "e": 29942, "s": 29930, "text": "Java-OpenCV" }, { "code": null, "e": 29949, "s": 29942, "text": "OpenCV" }, { "code": null, "e": 29956, "s": 29949, "text": "Picked" }, { "code": null, "e": 29961, "s": 29956, "text": "Java" }, { "code": null, "e": 29975, "s": 29961, "text": "Java Programs" }, { "code": null, "e": 29980, "s": 29975, "text": "Java" }, { "code": null, "e": 30078, "s": 29980, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30093, "s": 30078, "text": "Stream In Java" }, { "code": null, "e": 30114, "s": 30093, "text": "Constructors in Java" }, { "code": null, "e": 30133, "s": 30114, "text": "Exceptions in Java" }, { "code": null, "e": 30163, "s": 30133, "text": "Functional Interfaces in Java" }, { "code": null, "e": 30209, "s": 30163, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 30235, "s": 30209, "text": "Java Programming Examples" }, { "code": null, "e": 30269, "s": 30235, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 30316, "s": 30269, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 30348, "s": 30316, "text": "How to Iterate HashMap in Java?" } ]
Median of two sorted arrays of different sizes - GeeksforGeeks
19 Feb, 2022 Given two sorted arrays, a[] and b[], the task is to find the median of these sorted arrays, in O(log n + log m) time complexity, when n is the number of elements in the first array, and m is the number of elements in the second array. This is an extension of median of two sorted arrays of equal size problem. Here we handle arrays of unequal size also. Example: Input: ar1[] = {-5, 3, 6, 12, 15} ar2[] = {-12, -10, -6, -3, 4, 10} Output : The median is 3. Explanation : The merged array is : ar3[] = {-12, -10, -6, -5 , -3, 3, 4, 6, 10, 12, 15}, So the median of the merged array is 3 Input: ar1[] = {2, 3, 5, 8} ar2[] = {10, 12, 14, 16, 18, 20} Output : The median is 11. Explanation : The merged array is : ar3[] = {2, 3, 5, 8, 10, 12, 14, 16, 18, 20} if the number of the elements are even, so there are two middle elements, take the average between the two : (10 + 12) / 2 = 11. Method 1: This method uses a linear and simpler approach. Approach: The given arrays are sorted, so merge the sorted arrays in an efficient way and keep the count of elements inserted in the output array or printed form. So when the elements in the output array are half the original size of the given array print the element as a median element. There are two cases: Case 1: m+n is odd, the median is at (m+n)/2 th index in the array obtained after merging both the arrays.Case 2: m+n is even, the median will be average of elements at index ((m+n)/2 – 1) and (m+n)/2 in the array obtained after merging both the arrays Case 1: m+n is odd, the median is at (m+n)/2 th index in the array obtained after merging both the arrays. Case 2: m+n is even, the median will be average of elements at index ((m+n)/2 – 1) and (m+n)/2 in the array obtained after merging both the arrays Algorithm: Given two arrays are sorted. So they can be merged in O(m+n) time. Create a variable count to have a count of elements in the output array.If the value of (m+n) is odd then there is only one median else the median is the average of elements at index (m+n)/2 and ((m+n)/2 – 1).To merge the both arrays, keep two indices i and j initially assigned to 0. Compare the ith index of 1st array and jth index of second, increase the index of the smallest element and increase the count.Store (m+n)/2 and (m+n)/2-1 in two variables (In the below C++ code, m1 and m2 are used for this purpose).Check if the count reached (m+n) / 2. If (m+n) is odd return m1, If even return (m1+m2)/2. Given two arrays are sorted. So they can be merged in O(m+n) time. Create a variable count to have a count of elements in the output array. If the value of (m+n) is odd then there is only one median else the median is the average of elements at index (m+n)/2 and ((m+n)/2 – 1). To merge the both arrays, keep two indices i and j initially assigned to 0. Compare the ith index of 1st array and jth index of second, increase the index of the smallest element and increase the count. Store (m+n)/2 and (m+n)/2-1 in two variables (In the below C++ code, m1 and m2 are used for this purpose). Check if the count reached (m+n) / 2. If (m+n) is odd return m1, If even return (m1+m2)/2. Implementation: C++ C Java Python3 C# Javascript // A Simple Merge based O(n) solution to find// median of two sorted arrays#include <bits/stdc++.h>using namespace std; /* This function returns median of ar1[] and ar2[].Assumption in this function:Both ar1[] and ar2[] are sorted arrays */int getMedian(int ar1[], int ar2[], int n, int m){ int i = 0; /* Current index of input array ar1[] */ int j = 0; /* Current index of input array ar2[] */ int count; int m1 = -1, m2 = -1; /*loop till (m+n)/2*/ for (count = 0; count <= (m + n)/2; count++) { //store (n+m)/2-1 in m2 m2=m1; if(i != n && j != m) { m1 = (ar1[i] > ar2[j]) ? ar2[j++] : ar1[i++]; } else if(i < n) { m1 = ar1[i++]; } // for case when j<m, else { m1 = ar2[j++]; } } // Since there are (n+m) elements, // There are following two cases // if n+m is odd then the middle // index is median i.e. (m+n)/2 // other wise median will be average of elements // at index ((m+n)/2 - 1) and (m+n)/2 // in the array obtained after merging ar1 and ar2 if((m + n) % 2 == 1){ return m1; } else{ return (m1+m2)/2; }}/* Driver code */int main(){ int ar1[] = {900}; int ar2[] = {5,8,10,20}; int n1 = sizeof(ar1)/sizeof(ar1[0]); int n2 = sizeof(ar2)/sizeof(ar2[0]); cout << getMedian(ar1, ar2, n1, n2);} // This is code is contributed by rathbhupendra, modified by rajesh999 // A Simple Merge based O(n) solution to find// median of two sorted arrays#include <stdio.h> /* This function returns median of ar1[] and ar2[].Assumption in this function:Both ar1[] and ar2[] are sorted arrays */int getMedian(int ar1[], int ar2[], int n, int m){ int i = 0; /* Current index of input array ar1[] */ int j = 0; /* Current index of input array ar2[] */ int count; int m1 = -1, m2 = -1; // Since there are (n+m) elements, // There are following two cases // if n+m is odd then the middle //index is median i.e. (m+n)/2 if((m + n) % 2 == 1) { for (count = 0; count <= (n + m)/2; count++) { if(i != n && j != m){ m1 = (ar1[i] > ar2[j]) ? ar2[j++] : ar1[i++]; } else if(i < n){ m1 = ar1[i++]; } // for case when j<m, else{ m1 = ar2[j++]; } } return m1; } // median will be average of elements // at index ((m+n)/2 - 1) and (m+n)/2 // in the array obtained after merging ar1 and ar2 else { for (count = 0; count <= (n + m)/2; count++) { m2 = m1; if(i != n && j != m){ m1 = (ar1[i] > ar2[j]) ? ar2[j++] : ar1[i++]; } else if(i < n){ m1 = ar1[i++]; } // for case when j<m, else{ m1 = ar1[j++]; } } return (m1 + m2)/2; }} /* Driver program to test above function */int main(){ int ar1[] = {900}; int ar2[] = {5, 8, 10, 20}; int n1 = sizeof(ar1)/sizeof(ar1[0]); int n2 = sizeof(ar2)/sizeof(ar2[0]); printf("%d", getMedian(ar1, ar2, n1, n2)); getchar(); return 0;}// This code is uploaded by Pratil // A Simple Merge based O(n) solution// to find median of two sorted arraysclass GFG{ // Function to calculate medianstatic int getMedian(int ar1[], int ar2[], int n, int m){ // Current index of input array ar1[] int i = 0; // Current index of input array ar2[] int j = 0; int count; int m1 = -1, m2 = -1; // Since there are (n+m) elements, // There are following two cases // if n+m is odd then the middle //index is median i.e. (m+n)/2 if ((m + n) % 2 == 1) { for(count = 0; count <= (n + m) / 2; count++) { if (i != n && j != m) { m1 = (ar1[i] > ar2[j]) ? ar2[j++] : ar1[i++]; } else if (i < n) { m1 = ar1[i++]; } // for case when j<m, else { m1 = ar2[j++]; } } return m1; } // median will be average of elements // at index ((m+n)/2 - 1) and (m+n)/2 // in the array obtained after merging // ar1 and ar2 else { for(count = 0; count <= (n + m) / 2; count++) { m2 = m1; if (i != n && j != m) { m1 = (ar1[i] > ar2[j]) ? ar2[j++] : ar1[i++]; } else if (i < n) { m1 = ar1[i++]; } // for case when j<m, else { m1 = ar2[j++]; } } return (m1 + m2) / 2; }} // Driver codepublic static void main(String[] args){ int ar1[] = { 900 }; int ar2[] = { 5, 8, 10, 20 }; int n1 = ar1.length; int n2 = ar2.length; System.out.println(getMedian(ar1, ar2, n1, n2));}} // This code is contributed by Yash Singhal # A Simple Merge based O(n) solution to find# median of two sorted arrays """ This function returns median of ar1[] and ar2[].Assumption in this function:Both ar1[] and ar2[] are sorted arrays """def getMedian(ar1, ar2, n, m) : i = 0 # Current index of input array ar1[] j = 0 # Current index of input array ar2[] m1, m2 = -1, -1 # Since there are (n+m) elements, # There are following two cases # if n+m is odd then the middle # index is median i.e. (m+n)/2 if((m + n) % 2 == 1) : for count in range(((n + m) // 2) + 1) : if(i != n and j != m) : if ar1[i] > ar2[j] : m1 = ar2[j] j += 1 else : m1 = ar1[i] i += 1 elif(i < n) : m1 = ar1[i] i += 1 # for case when j<m, else : m1 = ar2[j] j += 1 return m1 # median will be average of elements # at index ((m + n)/2 - 1) and (m + n)/2 # in the array obtained after merging ar1 and ar2 else : for count in range(((n + m) // 2) + 1) : m2 = m1 if(i != n and j != m) : if ar1[i] > ar2[j] : m1 = ar2[j] j += 1 else : m1 = ar1[i] i += 1 elif(i < n) : m1 = ar1[i] i += 1 # for case when j<m, else : m1 = ar2[j] j += 1 return (m1 + m2)//2 # Driver code ar1 = [900]ar2 = [5, 8, 10, 20] n1 = len(ar1)n2 = len(ar2)print(getMedian(ar1, ar2, n1, n2)) # This code is contributed by divyesh072019 // A Simple Merge based O(n) solution// to find median of two sorted arraysusing System; class GFG{ // Function to calculate medianstatic int getMedian(int []ar1, int []ar2, int n, int m){ // Current index of input array ar1[] int i = 0; // Current index of input array ar2[] int j = 0; int count; int m1 = -1, m2 = -1; // Since there are (n+m) elements, // There are following two cases // if n+m is odd then the middle //index is median i.e. (m+n)/2 if ((m + n) % 2 == 1) { for(count = 0; count <= (n + m) / 2; count++) { if (i != n && j != m) { m1 = (ar1[i] > ar2[j]) ? ar2[j++] : ar1[i++]; } else if (i < n) { m1 = ar1[i++]; } // for case when j<m, else { m1 = ar2[j++]; } } return m1; } // median will be average of elements // at index ((m+n)/2 - 1) and (m+n)/2 // in the array obtained after merging // ar1 and ar2 else { for(count = 0; count <= (n + m) / 2; count++) { m2 = m1; if (i != n && j != m) { m1 = (ar1[i] > ar2[j]) ? ar2[j++] : ar1[i++]; } else if (i < n) { m1 = ar1[i++]; } // for case when j<m, else { m1 = ar2[j++]; } } return (m1 + m2) / 2; }} // Driver codepublic static void Main(String[] args){ int []ar1 = { 900 }; int []ar2 = { 5, 8, 10, 20 }; int n1 = ar1.Length; int n2 = ar2.Length; Console.WriteLine(getMedian(ar1, ar2, n1, n2));}} // This code is contributed by Princi Singh <script> // A Simple Merge based O(n) solution to find// median of two sorted arrays // This function returns median of ar1[] and ar2[].// Assumption in this function:// Both ar1[] and ar2[] are sorted arraysfunction getMedian(ar1, ar2, n, m){ // Current index of input array ar1[] let i = 0; // Current index of input array ar2[] let j = 0; let count; let m1 = -1, m2 = -1; // Since there are (n+m) elements, // There are following two cases // if n+m is odd then the middle // index is median i.e. (m+n)/2 if ((m + n) % 2 == 1) { for(count = 0; count <= (n + m) / 2; count++) { if (i != n && j != m) { m1 = (ar1[i] > ar2[j]) ? ar2[j++] : ar1[i++]; } else if(i < n) { m1 = ar1[i++]; } // For case when j<m, else { m1 = ar2[j++]; } } return m1; } // Median will be average of elements // at index ((m+n)/2 - 1) and (m+n)/2 // in the array obtained after merging // ar1 and ar2 else { for(count = 0; count <= (n + m) / 2; count++) { m2 = m1; if (i != n && j != m) { m1 = (ar1[i] > ar2[j]) ? ar2[j++] : ar1[i++]; } else if(i < n) { m1 = ar1[i++]; } // For case when j<m, else { m1 = ar2[j++]; } } return (m1 + m2) / 2; }} // Driver codelet ar1 = [900];let ar2 = [5, 8, 10, 20]; let n1 = ar1.length;let n2 = ar2.length;document.write(getMedian(ar1, ar2, n1, n2)); // This code is contributed by divyeshrabadiya07 </script> 10 Complexity Analysis: Time Complexity: O(m + n). To merge both the arrays O(m+n) time is needed. Space Complexity: O(1). No extra space is required. Efficient solution: Approach:The idea is simple, calculate the median of both the arrays and discard one half of each array. Now, there are some basic corner cases. For array size less than or equal to 2 Suppose there are two arrays and the size of both the arrays is greater than 2. Find the middle element of the first array and middle element of the second array (the first array is smaller than the second) if the middle element of the smaller array is less than the second array, then it can be said that all elements of the first half of smaller array will be in the first half of the output (merged array). So, reduce the search space by ignoring the first half of the smaller array and the second half of the larger array. Else ignore the second half of the smaller array and first half of a larger array. In addition to that there are more basic corner cases: If the size of smaller array is 0. Return the median of a larger array.if the size of smaller array is 1. The size of the larger array is also 1. Return the median of two elements.If the size of the larger array is odd. Then after adding the element from 2nd array, it will be even so the median will be an average of two mid elements. So the element from the smaller array will affect the median if and only if it lies between (m/2 – 1)th and (m/2 + 1)th element of the larger array. So, find the median in between the four elements, the element of the smaller array and (m/2)th, (m/2 – 1)th and (m/2 + 1)th element of a larger arraySimilarly, if the size is even, then check for the median of three elements, the element of the smaller array and (m/2)th, (m/2 – 1)th element of a larger arrayIf the size of smaller array is 2 If the larger array also has two elements, find the median of four elements.If the larger array has an odd number of elements, then the median will be one of the following 3 elements Middle element of larger arrayMax of the second element of smaller array and element just before the middle, i.e M/2-1th element in a bigger arrayMin of the first element of smaller array and element just after the middle in the bigger array, i.e M/2 + 1th element in the bigger arrayIf the larger array has even number of elements, then the median will be one of the following 4 elements The middle two elements of the larger arrayMax of the first element of smaller array and element just before the first middle element in the bigger array, i.e M/2 – 2nd elementMin of the second element of smaller array and element just after the second middle in the bigger array, M/2 + 1th element If the size of smaller array is 0. Return the median of a larger array. if the size of smaller array is 1. The size of the larger array is also 1. Return the median of two elements.If the size of the larger array is odd. Then after adding the element from 2nd array, it will be even so the median will be an average of two mid elements. So the element from the smaller array will affect the median if and only if it lies between (m/2 – 1)th and (m/2 + 1)th element of the larger array. So, find the median in between the four elements, the element of the smaller array and (m/2)th, (m/2 – 1)th and (m/2 + 1)th element of a larger arraySimilarly, if the size is even, then check for the median of three elements, the element of the smaller array and (m/2)th, (m/2 – 1)th element of a larger array The size of the larger array is also 1. Return the median of two elements.If the size of the larger array is odd. Then after adding the element from 2nd array, it will be even so the median will be an average of two mid elements. So the element from the smaller array will affect the median if and only if it lies between (m/2 – 1)th and (m/2 + 1)th element of the larger array. So, find the median in between the four elements, the element of the smaller array and (m/2)th, (m/2 – 1)th and (m/2 + 1)th element of a larger arraySimilarly, if the size is even, then check for the median of three elements, the element of the smaller array and (m/2)th, (m/2 – 1)th element of a larger array The size of the larger array is also 1. Return the median of two elements. If the size of the larger array is odd. Then after adding the element from 2nd array, it will be even so the median will be an average of two mid elements. So the element from the smaller array will affect the median if and only if it lies between (m/2 – 1)th and (m/2 + 1)th element of the larger array. So, find the median in between the four elements, the element of the smaller array and (m/2)th, (m/2 – 1)th and (m/2 + 1)th element of a larger array Similarly, if the size is even, then check for the median of three elements, the element of the smaller array and (m/2)th, (m/2 – 1)th element of a larger array If the size of smaller array is 2 If the larger array also has two elements, find the median of four elements.If the larger array has an odd number of elements, then the median will be one of the following 3 elements Middle element of larger arrayMax of the second element of smaller array and element just before the middle, i.e M/2-1th element in a bigger arrayMin of the first element of smaller array and element just after the middle in the bigger array, i.e M/2 + 1th element in the bigger arrayIf the larger array has even number of elements, then the median will be one of the following 4 elements The middle two elements of the larger arrayMax of the first element of smaller array and element just before the first middle element in the bigger array, i.e M/2 – 2nd elementMin of the second element of smaller array and element just after the second middle in the bigger array, M/2 + 1th element If the larger array also has two elements, find the median of four elements.If the larger array has an odd number of elements, then the median will be one of the following 3 elements Middle element of larger arrayMax of the second element of smaller array and element just before the middle, i.e M/2-1th element in a bigger arrayMin of the first element of smaller array and element just after the middle in the bigger array, i.e M/2 + 1th element in the bigger arrayIf the larger array has even number of elements, then the median will be one of the following 4 elements The middle two elements of the larger arrayMax of the first element of smaller array and element just before the first middle element in the bigger array, i.e M/2 – 2nd elementMin of the second element of smaller array and element just after the second middle in the bigger array, M/2 + 1th element If the larger array also has two elements, find the median of four elements. If the larger array has an odd number of elements, then the median will be one of the following 3 elements Middle element of larger arrayMax of the second element of smaller array and element just before the middle, i.e M/2-1th element in a bigger arrayMin of the first element of smaller array and element just after the middle in the bigger array, i.e M/2 + 1th element in the bigger array Middle element of larger arrayMax of the second element of smaller array and element just before the middle, i.e M/2-1th element in a bigger arrayMin of the first element of smaller array and element just after the middle in the bigger array, i.e M/2 + 1th element in the bigger array Middle element of larger array Max of the second element of smaller array and element just before the middle, i.e M/2-1th element in a bigger array Min of the first element of smaller array and element just after the middle in the bigger array, i.e M/2 + 1th element in the bigger array If the larger array has even number of elements, then the median will be one of the following 4 elements The middle two elements of the larger arrayMax of the first element of smaller array and element just before the first middle element in the bigger array, i.e M/2 – 2nd elementMin of the second element of smaller array and element just after the second middle in the bigger array, M/2 + 1th element The middle two elements of the larger arrayMax of the first element of smaller array and element just before the first middle element in the bigger array, i.e M/2 – 2nd elementMin of the second element of smaller array and element just after the second middle in the bigger array, M/2 + 1th element The middle two elements of the larger array Max of the first element of smaller array and element just before the first middle element in the bigger array, i.e M/2 – 2nd element Min of the second element of smaller array and element just after the second middle in the bigger array, M/2 + 1th element How can one half of each array be discarded? Let’s take an example to understand thisInput :arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10},brr[] = { 11, 12, 13, 14, 15, 16, 17, 18, 19 }Dry Run of the code:Recursive call 1:smaller array[] = 1 2 3 4 5 6 7 8 9 10, mid = 5larger array[] = 11 12 13 14 15 16 17 18 19 , mid = 15 5 < 15Discard first half of the first array and second half of the second array Recursive call 2:smaller array[] = 11 12 13 14 15, mid = 13larger array[] = 5 6 7 8 9 10, mid = 7 7 < 13Discard first half of the second array and second half of the first array Recursive call 3:smaller array[] = 11 12 13 , mid = 12larger array[] = 7 8 9 10 , mid = 8 8 < 12Discard first half of the second array and second half of the first array Recursive call 4:smaller array[] = 11 12larger array[] = 8 9 10 Size of the smaller array is 2 and the size of the larger array is oddso, the median will be the median of max( 11, 8), 9, min( 10, 12)that is 9, 10, 11, so the median is 10. Output:10.000000 Algorithm: Create a recursive function that takes two arrays and the sizes of both the arrays.Take care of the base cases for the size of arrays less than 2. (previously discussed in Approach).Note: The first array is always the smaller array.Find the middle elements of both the arrays. i.e element at (n – 1)/2 and (m – 1)/2 of first and second array respectively. Compare both the elements.If the middle element of the smaller array is less than the middle element of the larger array then the first half of the smaller array is bound to lie strictly in the first half of the merged array. It can also be stated that there is an element in the first half of the larger array and the second half of the smaller array which is the median. So, reduce the search space to the first half of the larger array and the second half of the smaller array.Similarly, If the middle element of the smaller array is greater than the middle element of the larger array then reduce the search space to the first half of the smaller array and second half of the larger array. Create a recursive function that takes two arrays and the sizes of both the arrays. Take care of the base cases for the size of arrays less than 2. (previously discussed in Approach).Note: The first array is always the smaller array. Find the middle elements of both the arrays. i.e element at (n – 1)/2 and (m – 1)/2 of first and second array respectively. Compare both the elements. If the middle element of the smaller array is less than the middle element of the larger array then the first half of the smaller array is bound to lie strictly in the first half of the merged array. It can also be stated that there is an element in the first half of the larger array and the second half of the smaller array which is the median. So, reduce the search space to the first half of the larger array and the second half of the smaller array. Similarly, If the middle element of the smaller array is greater than the middle element of the larger array then reduce the search space to the first half of the smaller array and second half of the larger array. Implementation: C++ Java Python3 C# PHP Javascript // A C++ program to find median of two sorted arrays of// unequal sizes#include <bits/stdc++.h>using namespace std; // A utility function to find median of two integersfloat MO2(int a, int b){ return ( a + b ) / 2.0; } // A utility function to find median of three integersfloat MO3(int a, int b, int c){ return a + b + c - max(a, max(b, c)) - min(a, min(b, c));} // A utility function to find a median of four integersfloat MO4(int a, int b, int c, int d){ int Max = max( a, max( b, max( c, d ) ) ); int Min = min( a, min( b, min( c, d ) ) ); return ( a + b + c + d - Max - Min ) / 2.0;} // Utility function to find median of single arrayfloat medianSingle(int arr[], int n){ if (n == 0) return -1; if (n%2 == 0) return (double)(arr[n/2] + arr[n/2-1])/2; return arr[n/2];} // This function assumes that N is smaller than or equal to M// This function returns -1 if both arrays are emptyfloat findMedianUtil( int A[], int N, int B[], int M ){ // If smaller array is empty, return median from second array if (N == 0) return medianSingle(B, M); // If the smaller array has only one element if (N == 1) { // Case 1: If the larger array also has one element, // simply call MO2() if (M == 1) return MO2(A[0], B[0]); // Case 2: If the larger array has odd number of elements, // then consider the middle 3 elements of larger array and // the only element of smaller array. Take few examples // like following // A = {9}, B[] = {5, 8, 10, 20, 30} and // A[] = {1}, B[] = {5, 8, 10, 20, 30} if (M & 1) return MO2( B[M/2], MO3(A[0], B[M/2 - 1], B[M/2 + 1]) ); // Case 3: If the larger array has even number of element, // then median will be one of the following 3 elements // ... The middle two elements of larger array // ... The only element of smaller array return MO3( B[M/2], B[M/2 - 1], A[0] ); } // If the smaller array has two elements else if (N == 2) { // Case 4: If the larger array also has two elements, // simply call MO4() if (M == 2) return MO4(A[0], A[1], B[0], B[1]); // Case 5: If the larger array has odd number of elements, // then median will be one of the following 3 elements // 1. Middle element of larger array // 2. Max of first element of smaller array and element // just before the middle in bigger array // 3. Min of second element of smaller array and element // just after the middle in bigger array if (M & 1) return MO3 ( B[M/2], max(A[0], B[M/2 - 1]), min(A[1], B[M/2 + 1]) ); // Case 6: If the larger array has even number of elements, // then median will be one of the following 4 elements // 1) & 2) The middle two elements of larger array // 3) Max of first element of smaller array and element // just before the first middle element in bigger array // 4. Min of second element of smaller array and element // just after the second middle in bigger array return MO4 ( B[M/2], B[M/2 - 1], max( A[0], B[M/2 - 2] ), min( A[1], B[M/2 + 1] ) ); } int idxA = ( N - 1 ) / 2; int idxB = ( M - 1 ) / 2; /* if A[idxA] <= B[idxB], then median must exist in A[idxA....] and B[....idxB] */ if (A[idxA] <= B[idxB] ) return findMedianUtil(A + idxA, N/2 + 1, B, M - idxA ); /* if A[idxA] > B[idxB], then median must exist in A[...idxA] and B[idxB....] */ return findMedianUtil(A, N/2 + 1, B + idxA, M - idxA );} // A wrapper function around findMedianUtil(). This function// makes sure that smaller array is passed as first argument// to findMedianUtilfloat findMedian( int A[], int N, int B[], int M ){ if (N > M) return findMedianUtil( B, M, A, N ); return findMedianUtil( A, N, B, M );} // Driver program to test above functionsint main(){ int A[] = {900}; int B[] = {5, 8, 10, 20}; int N = sizeof(A) / sizeof(A[0]); int M = sizeof(B) / sizeof(B[0]); printf("%f", findMedian( A, N, B, M ) ); return 0;} // A Java program to find median of two sorted arrays of// unequal sizesimport java.util.*; class GFG { // A utility function to find median of two integers static float MO2(int a, int b) { return (float) ((a + b) / 2.0); } // A utility function to find median of three integers static float MO3(int a, int b, int c) { return a + b + c - Math.max(a, Math.max(b, c)) - Math.min(a, Math.min(b, c)); } // A utility function to find a median of four integers static float MO4(int a, int b, int c, int d) { int Max = Math.max(a, Math.max(b, Math.max(c, d))); int Min = Math.min(a, Math.min(b, Math.min(c, d))); return (float) ((a + b + c + d - Max - Min) / 2.0); } // Utility function to find median of single array static float medianSingle(int arr[], int n) { if (n == 0) return -1; if (n % 2 == 0) return (float) ((double) (arr[n / 2] + arr[n / 2 - 1]) / 2); return arr[n / 2]; } // This function assumes that N is smaller than or equal to M // This function returns -1 if both arrays are empty static float findMedianUtil(int A[], int N, int B[], int M) { // If smaller array is empty, return median from second array if (N == 0) return medianSingle(B, M); // If the smaller array has only one element if (N == 1) { // Case 1: If the larger array also has one element, // simply call MO2() if (M == 1) return MO2(A[0], B[0]); // Case 2: If the larger array has odd number of elements, // then consider the middle 3 elements of larger array and // the only element of smaller array. Take few examples // like following // A = {9}, B[] = {5, 8, 10, 20, 30} and // A[] = {1}, B[] = {5, 8, 10, 20, 30} if (M % 2 == 1) return MO2(B[M / 2], (int) MO3(A[0], B[M / 2 - 1], B[M / 2 + 1])); // Case 3: If the larger array has even number of element, // then median will be one of the following 3 elements // ... The middle two elements of larger array // ... The only element of smaller array return MO3(B[M / 2], B[M / 2 - 1], A[0]); } // If the smaller array has two elements else if (N == 2) { // Case 4: If the larger array also has two elements, // simply call MO4() if (M == 2) return MO4(A[0], A[1], B[0], B[1]); // Case 5: If the larger array has odd number of elements, // then median will be one of the following 3 elements // 1. Middle element of larger array // 2. Max of first element of smaller array and element // just before the middle in bigger array // 3. Min of second element of smaller array and element // just after the middle in bigger array if (M % 2 == 1) return MO3(B[M / 2], Math.max(A[0], B[M / 2 - 1]), Math.min(A[1], B[M / 2 + 1])); // Case 6: If the larger array has even number of elements, // then median will be one of the following 4 elements // 1) & 2) The middle two elements of larger array // 3) Max of first element of smaller array and element // just before the first middle element in bigger array // 4. Min of second element of smaller array and element // just after the second middle in bigger array return MO4(B[M / 2], B[M / 2 - 1], Math.max(A[0], B[M / 2 - 2]), Math.min(A[1], B[M / 2 + 1])); } int idxA = (N - 1) / 2; int idxB = (M - 1) / 2; /* * if A[idxA] <= B[idxB], then median must exist in A[idxA....] and B[....idxB] */ if (A[idxA] <= B[idxB]) return findMedianUtil(Arrays.copyOfRange(A, idxA, A.length), N / 2 + 1, B, M - idxA); /* * if A[idxA] > B[idxB], then median must exist in A[...idxA] and B[idxB....] */ return findMedianUtil(A, N / 2 + 1, Arrays.copyOfRange(B, idxB, B.length), M - idxA); } // A wrapper function around findMedianUtil(). This function // makes sure that smaller array is passed as first argument // to findMedianUtil static float findMedian(int A[], int N, int B[], int M) { if (N > M) return findMedianUtil(B, M, A, N); return findMedianUtil(A, N, B, M); } // Driver program to test above functions public static void main(String[] args) { int A[] = { 900 }; int B[] = { 5, 8, 10, 20 }; int N = A.length; int M = B.length; System.out.printf("%f", findMedian(A, N, B, M)); }} // This code is contributed by Princi Singh. # A Python3 program to find median of two sorted arrays of# unequal sizes # A utility function to find median of two integersdef MO2(a, b) : return ( a + b ) / 2 # A utility function to find median of three integersdef MO3(a, b, c) : return a + b + c - max(a, max(b, c)) - min(a, min(b, c)) # A utility function to find a median of four integersdef MO4(a, b, c, d) : Max = max( a, max( b, max( c, d ) ) ) Min = min( a, min( b, min( c, d ) ) ) return ( a + b + c + d - Max - Min ) / 2 # Utility function to find median of single arraydef medianSingle(arr, n) : if (n == 0) : return -1 if (n % 2 == 0) : return (arr[n / 2] + arr[n / 2 - 1]) / 2 return arr[n / 2] # This function assumes that N is smaller than or equal to M# This function returns -1 if both arrays are emptydef findMedianUtil(A, N, B, M) : # If smaller array is empty, return median from second array if (N == 0) : return medianSingle(B, M) # If the smaller array has only one element if (N == 1) : # Case 1: If the larger array also has one element, # simply call MO2() if (M == 1) : return MO2(A[0], B[0]) # Case 2: If the larger array has odd number of elements, # then consider the middle 3 elements of larger array and # the only element of smaller array. Take few examples # like following # A = {9}, B[] = {5, 8, 10, 20, 30} and # A[] = {1}, B[] = {5, 8, 10, 20, 30} if (M & 1 != 0) : return MO2( B[M / 2], MO3(A[0], B[M / 2 - 1], B[M / 2 + 1]) ) # Case 3: If the larger array has even number of element, # then median will be one of the following 3 elements # ... The middle two elements of larger array # ... The only element of smaller array return MO3(B[M // 2], B[M // 2 - 1], A[0]) # If the smaller array has two elements elif (N == 2) : # Case 4: If the larger array also has two elements, # simply call MO4() if (M == 2) : return MO4(A[0], A[1], B[0], B[1]) # Case 5: If the larger array has odd number of elements, # then median will be one of the following 3 elements # 1. Middle element of larger array # 2. Max of first element of smaller array and element # just before the middle in bigger array # 3. Min of second element of smaller array and element # just after the middle in bigger array if (M & 1 != 0) : return MO3 (B[M / 2], max(A[0], B[M / 2 - 1]), min(A[1], B[M / 2 + 1])) # Case 6: If the larger array has even number of elements, # then median will be one of the following 4 elements # 1) & 2) The middle two elements of larger array # 3) Max of first element of smaller array and element # just before the first middle element in bigger array # 4. Min of second element of smaller array and element # just after the second middle in bigger array return MO4 (B[M / 2], B[M / 2 - 1], max( A[0], B[M / 2 - 2] ), min( A[1], B[M / 2 + 1] )) idxA = ( N - 1 ) / 2 idxB = ( M - 1 ) / 2 ''' if A[idxA] <= B[idxB], then median must exist in A[idxA....] and B[....idxB] ''' if (A[idxA] <= B[idxB] ) : return findMedianUtil(A + idxA, N / 2 + 1, B, M - idxA ) ''' if A[idxA] > B[idxB], then median must exist in A[...idxA] and B[idxB....] ''' return findMedianUtil(A, N / 2 + 1, B + idxA, M - idxA ) # A wrapper function around findMedianUtil(). This function# makes sure that smaller array is passed as first argument# to findMedianUtildef findMedian(A, N, B, M) : if (N > M) : return findMedianUtil( B, M, A, N ); return findMedianUtil( A, N, B, M ) # Driver codeA = [900]B = [5, 8, 10, 20] N = len(A)M = len(B) print(findMedian(A, N, B, M )) # This code is contributed by divyesh072019 // A C# program to find median of two sorted arrays of// unequal sizesusing System;class GFG{ // A utility function to find median of two integers static float MO2(int a, int b) { return (float) ((a + b) / 2.0); } // A utility function to find median of three integers static float MO3(int a, int b, int c) { return a + b + c - Math.Max(a, Math.Max(b, c)) - Math.Min(a, Math.Min(b, c)); } // A utility function to find a median of four integers static float MO4(int a, int b, int c, int d) { int Max = Math.Max(a, Math.Max(b, Math.Max(c, d))); int Min = Math.Min(a, Math.Min(b, Math.Min(c, d))); return (float) ((a + b + c + d - Max - Min) / 2.0); } // Utility function to find median of single array static float medianSingle(int[] arr, int n) { if (n == 0) return -1; if (n % 2 == 0) return (float) ((double) (arr[n / 2] + arr[n / 2 - 1]) / 2); return arr[n / 2]; } static int[] copyOfRange (int[] src, int start, int end) { int len = end - start; int[] dest = new int[len]; Array.Copy(src, start, dest, 0, len); return dest; } // This function assumes that N is smaller than or equal to M // This function returns -1 if both arrays are empty static float findMedianUtil(int[] A, int N, int[] B, int M) { // If smaller array is empty, // return median from second array if (N == 0) return medianSingle(B, M); // If the smaller array has only one element if (N == 1) { // Case 1: If the larger array also has one element, // simply call MO2() if (M == 1) return MO2(A[0], B[0]); // Case 2: If the larger array has odd number of elements, // then consider the middle 3 elements of larger array and // the only element of smaller array. Take few examples // like following // A = {9}, B[] = {5, 8, 10, 20, 30} and // A[] = {1}, B[] = {5, 8, 10, 20, 30} if (M % 2 == 1) return MO2(B[M / 2], (int) MO3(A[0], B[M / 2 - 1], B[M / 2 + 1])); // Case 3: If the larger array has even number of element, // then median will be one of the following 3 elements // ... The middle two elements of larger array // ... The only element of smaller array return MO3(B[M / 2], B[M / 2 - 1], A[0]); } // If the smaller array has two elements else if (N == 2) { // Case 4: If the larger array also has two elements, // simply call MO4() if (M == 2) return MO4(A[0], A[1], B[0], B[1]); // Case 5: If the larger array has odd number of elements, // then median will be one of the following 3 elements // 1. Middle element of larger array // 2. Max of first element of smaller array and element // just before the middle in bigger array // 3. Min of second element of smaller array and element // just after the middle in bigger array if (M % 2 == 1) return MO3(B[M / 2], Math.Max(A[0], B[M / 2 - 1]), Math.Min(A[1], B[M / 2 + 1])); // Case 6: If the larger array has even number of elements, // then median will be one of the following 4 elements // 1) & 2) The middle two elements of larger array // 3) Max of first element of smaller array and element // just before the first middle element in bigger array // 4. Min of second element of smaller array and element // just after the second middle in bigger array return MO4(B[M / 2], B[M / 2 - 1], Math.Max(A[0], B[M / 2 - 2]), Math.Min(A[1], B[M / 2 + 1])); } int idxA = (N - 1) / 2; int idxB = (M - 1) / 2; /* * if A[idxA] <= B[idxB], then median must exist in A[idxA....] and B[....idxB] */ if (A[idxA] <= B[idxB]) return findMedianUtil(copyOfRange(A, idxA, A.Length), N / 2 + 1, B, M - idxA); /* * if A[idxA] > B[idxB], then median must exist in A[...idxA] and B[idxB....] */ return findMedianUtil(A, N / 2 + 1, copyOfRange(B, idxB, B.Length), M - idxA); } // A wrapper function around findMedianUtil(). This function // makes sure that smaller array is passed as first argument // to findMedianUtil static float findMedian(int[] A, int N, int[] B, int M) { if (N > M) return findMedianUtil(B, M, A, N); return findMedianUtil(A, N, B, M); } // Driver code static void Main() { int[] A = { 900 }; int[] B = { 5, 8, 10, 20 }; int N = A.Length; int M = B.Length; Console.WriteLine(findMedian(A, N, B, M)); }} // This code is contributed by divyeshrabadiya07 <?php// A PHP program to find median// of two sorted arrays of// unequal sizes // A utility function to// find median of two integersfunction MO2($a, $b){ return ($a + $b) / 2.0;} // A utility function to// find median of three integersfunction MO3($a, $b, $c){ return $a + $b + $c - max($a, max($b, $c)) - min($a, min($b, $c));} // A utility function to find// median of four integersfunction MO4($a, $b, $c, $d){ $Max = max($a, max($b, max($c, $d))); $Min = min($a, min($b, min( $c, $d))); return ($a + $b + $c + $d - $Max - $Min) / 2.0;} // Utility function to// find median of single arrayfunction medianSingle($arr, $n){if ($n == 0) return -1;if ($n % 2 == 0) return ($arr[$n / 2] + $arr[$n / 2 - 1]) / 2;return $arr[$n / 2];} // This function assumes that N// is smaller than or equal to M// This function returns -1 if// both arrays are emptyfunction findMedianUtil(&$A, $N, &$B, $M ){ // If smaller array is empty, // return median from second array if ($N == 0) return medianSingle($B, $M); // If the smaller array // has only one element if ($N == 1) { // Case 1: If the larger // array also has one // element, simply call MO2() if ($M == 1) return MO2($A[0], $B[0]); // Case 2: If the larger array // has odd number of elements, // then consider the middle 3 // elements of larger array and // the only element of smaller // array. Take few examples // like following // $A = array(9), // $B = array(5, 8, 10, 20, 30) // and $A = array(1), // $B = array(5, 8, 10, 20, 30) if ($M & 1) return MO2($B[$M / 2], $MO3($A[0], $B[$M / 2 - 1], $B[$M / 2 + 1])); // Case 3: If the larger array // has even number of element, // then median will be one of // the following 3 elements // ... The middle two elements // of larger array // ... The only element of // smaller array return MO3($B[$M / 2], $B[$M / 2 - 1], $A[0]); } // If the smaller array // has two elements else if ($N == 2) { // Case 4: If the larger // array also has two elements, // simply call MO4() if ($M == 2) return MO4($A[0], $A[1], $B[0], $B[1]); // Case 5: If the larger array // has odd number of elements, // then median will be one of // the following 3 elements // 1. Middle element of // larger array // 2. Max of first element of // smaller array and element // just before the middle // in bigger array // 3. Min of second element // of smaller array and element // just after the middle // in bigger array if ($M & 1) return MO3 ($B[$M / 2], max($A[0], $B[$M / 2 - 1]), min($A[1], $B[$M / 2 + 1])); // Case 6: If the larger array // has even number of elements, // then median will be one of // the following 4 elements // 1) & 2) The middle two // elements of larger array // 3) Max of first element of // smaller array and element // just before the first middle // element in bigger array // 4. Min of second element of // smaller array and element // just after the second // middle in bigger array return MO4 ($B[$M / 2], $B[$M / 2 - 1], max($A[0], $B[$M / 2 - 2]), min($A[1], $B[$M / 2 + 1])); } $idxA = ($N - 1 ) / 2; $idxB = ($M - 1 ) / 2; /* if $A[$idxA] <= $B[$idxB], then median must exist in $A[$idxA....] and $B[....$idxB] */ if ($A[$idxA] <= $B[$idxB] ) return findMedianUtil($A + $idxA, $N / 2 + 1, $B, $M - $idxA ); /* if $A[$idxA] > $B[$idxB], then median must exist in $A[...$idxA] and $B[$idxB....] */ return findMedianUtil($A, $N/2 + 1, $B + $idxA, $M - $idxA );} // A wrapper function around// findMedianUtil(). This// function makes sure that// smaller array is passed as// first argument to findMedianUtilfunction findMedian(&$A, $N, &$B, $M ){ if ($N > $M) return findMedianUtil($B, $M, $A, $N ); return findMedianUtil($A, $N, $B, $M );} // Driver Code$A = array(900);$B = array(5, 8, 10, 20); $N = sizeof($A);$M = sizeof($B); echo findMedian( $A, $N, $B, $M ); // This code is contributed// by ChitraNayal?> <script>// A Javascript program to find median of two sorted arrays of// unequal sizes // A utility function to find median of two integersfunction MO2(a,b){ return ((a + b) / 2.0);} // A utility function to find median of three integersfunction MO3(a, b, c){ return a + b + c - Math.max(a, Math.max(b, c)) - Math.min(a, Math.min(b, c));} // A utility function to find a median of four integersfunction MO4(a, b, c, d){ let Max = Math.max(a, Math.max(b, Math.max(c, d))); let Min = Math.min(a, Math.min(b, Math.min(c, d))); return ((a + b + c + d - Max - Min) / 2.0);} // Utility function to find median of single arrayfunction medianSingle(arr, n){ if (n == 0) return -1; if (n % 2 == 0) return ( (arr[n / 2] + arr[n / 2 - 1]) / 2); return arr[n / 2];} // This function assumes that N is smaller than or equal to M // This function returns -1 if both arrays are emptyfunction findMedianUtil(A, N, B, M){ // If smaller array is empty, return median from second array if (N == 0) return medianSingle(B, M); // If the smaller array has only one element if (N == 1) { // Case 1: If the larger array also has one element, // simply call MO2() if (M == 1) return MO2(A[0], B[0]); // Case 2: If the larger array has odd number of elements, // then consider the middle 3 elements of larger array and // the only element of smaller array. Take few examples // like following // A = {9}, B[] = {5, 8, 10, 20, 30} and // A[] = {1}, B[] = {5, 8, 10, 20, 30} if (M % 2 == 1) return MO2(B[M / 2], MO3(A[0], B[M / 2 - 1], B[M / 2 + 1])); // Case 3: If the larger array has even number of element, // then median will be one of the following 3 elements // ... The middle two elements of larger array // ... The only element of smaller array return MO3(B[M / 2], B[M / 2 - 1], A[0]); } // If the smaller array has two elements else if (N == 2) { // Case 4: If the larger array also has two elements, // simply call MO4() if (M == 2) return MO4(A[0], A[1], B[0], B[1]); // Case 5: If the larger array has odd number of elements, // then median will be one of the following 3 elements // 1. Middle element of larger array // 2. Max of first element of smaller array and element // just before the middle in bigger array // 3. Min of second element of smaller array and element // just after the middle in bigger array if (M % 2 == 1) return MO3(B[M / 2], Math.max(A[0], B[M / 2 - 1]), Math.min(A[1], B[M / 2 + 1])); // Case 6: If the larger array has even number of elements, // then median will be one of the following 4 elements // 1) & 2) The middle two elements of larger array // 3) Max of first element of smaller array and element // just before the first middle element in bigger array // 4. Min of second element of smaller array and element // just after the second middle in bigger array return MO4(B[M / 2], B[M / 2 - 1], Math.max(A[0], B[M / 2 - 2]), Math.min(A[1], B[M / 2 + 1])); } let idxA = (N - 1) / 2; let idxB = (M - 1) / 2; /* * if A[idxA] <= B[idxB], then median must exist in A[idxA....] and B[....idxB] */ if (A[idxA] <= B[idxB]) return findMedianUtil(A.slice(idxA, A.length), N / 2 + 1, B, M - idxA); /* * if A[idxA] > B[idxB], then median must exist in A[...idxA] and B[idxB....] */ return findMedianUtil(A, N / 2 + 1, B.slice( idxB, B.length), M - idxA);} // A wrapper function around findMedianUtil(). This function // makes sure that smaller array is passed as first argument // to findMedianUtilfunction findMedian(A,N,B,M){ if (N > M) return findMedianUtil(B, M, A, N); return findMedianUtil(A, N, B, M);} // Driver program to test above functionslet A = [ 900];let B = [5, 8, 10, 20];let N = A.length;let M = B.length;document.write(findMedian(A, N, B, M)); // This code is contributed by avanitrachhadiya2155</script> 10.000000 Complexity Analysis: Time Complexity: O(min(log m, log n)). In each step one half of each array is discarded. So the algorithm takes O(min(log m, log n)) time to reach the median value. Space Complexity: O(1). No extra space is required. Solution 3 : Simple Mathematical Approach Approach: The given two arrays are sorted, so we need to merge them into a third array using the method System.arraycopy(src, srcPos, dest, destPos, length) and then sort the third array using Arrays.sort(array) method. 1. Case 1: If the length of the third array is odd, then the median is at (length)/2 th index in the array obtained after merging both the arrays. 2. Case 2: If the length of the third array is even, then the median will be the average of elements at index ((length)/2 ) and ((length)/2 – 1) in the array obtained after merging both the arrays. 1. Merge the two given arrays into one array. 2. Then sort the third(merged) array 3. If the length of the third array is even then : divide the length of array by 2 return arr[value] + arr[value - 1] / 2 4. If the length of the third array is odd then : divide the length of array by 2 round that value return the arr[value] C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; int Solution(int arr[], int n){ // If length of array is even if (n % 2 == 0) { int z = n / 2; int e = arr[z]; int q = arr[z - 1]; int ans = (e + q) / 2; return ans; } // If length if array is odd else { int z = round(n / 2); return arr[z]; }} // Driver Codeint main() { // TODO Auto-generated method stub int arr1[] = { -5, 3, 6, 12, 15 }; int arr2[] = { -12, -10, -6, -3, 4, 10 }; int i = sizeof(arr1) / sizeof(arr1[0]); int j = sizeof(arr2) / sizeof(arr2[0]); int arr3[i+j]; int l = i+j; // Merge two array into one array for(int k=0;k<i;k++) { arr3[k]=arr1[k]; } int a=0; for(int k=i;k<l;k++) { arr3[k]=arr2[a++]; } // Sort the merged array sort(arr3,arr3+l); // calling the method cout<<"Median = " << Solution(arr3, l);} // This code is contributed by SoumikMondal // Java program for the above approachimport java.io.*;import java.util.Arrays; public class GFG { public static int Solution(int[] arr) { int n = arr.length; // If length of array is even if (n % 2 == 0) { int z = n / 2; int e = arr[z]; int q = arr[z - 1]; int ans = (e + q) / 2; return ans; } // If length if array is odd else { int z = Math.round(n / 2); return arr[z]; } } // Driver Code public static void main(String[] args) { // TODO Auto-generated method stub int[] arr1 = { -5, 3, 6, 12, 15 }; int[] arr2 = { -12, -10, -6, -3, 4, 10 }; int i = arr1.length; int j = arr2.length; int[] arr3 = new int[i + j]; // Merge two array into one array System.arraycopy(arr1, 0, arr3, 0, i); System.arraycopy(arr2, 0, arr3, i, j); // Sort the merged array Arrays.sort(arr3); // calling the method System.out.print("Median = " + Solution(arr3)); }}// This code is contributed by Manas Tole # Python3 program for the above approachdef Solution(arr): n = len(arr) # If length of array is even if n % 2 == 0: z = n // 2 e = arr[z] q = arr[z - 1] ans = (e + q) / 2 return ans # If length of array is odd else: z = n // 2 ans = arr[z] return ans # Driver codeif __name__ == "__main__": arr1 = [ -5, 3, 6, 12, 15 ] arr2 = [ -12, -10, -6, -3, 4, 10 ] # Concatenating the two arrays arr3 = arr1 + arr2 # Sorting the resultant array arr3.sort() print("Median = ", Solution(arr3)) # This code is contributed by kush11 // C# program for the above approachusing System;using System.Collections.Generic; public class GFG { public static int Solution(int[] arr) { int n = arr.Length; // If length of array is even if (n % 2 == 0) { int z = n / 2; int e = arr[z]; int q = arr[z - 1]; int ans = (e + q) / 2; return ans; } // If length if array is odd else { int z = n / 2; return arr[z]; } } // Driver Code static public void Main (){ // TODO Auto-generated method stub int[] arr1 = { -5, 3, 6, 12, 15 }; int[] arr2 = { -12, -10, -6, -3, 4, 10 }; // Merge two array into one array var myList = new List<int>(); myList.AddRange(arr1); myList.AddRange(arr2); int[] arr3 = myList.ToArray(); // Sort the merged array Array.Sort(arr3); // calling the method Console.Write("Median = " + Solution(arr3)); }} // This code is contributed by Shubhamsingh10 <script>// Javascript program for the above approach function Solution(arr, n){ // If length of array is even if (n % 2 == 0) { var z = n / 2; var e = arr[z]; var q = arr[z - 1]; var ans = (e + q) / 2; return ans; } // If length if array is odd else { var z = Math.floor(n / 2); return arr[z]; }} // Driver Code // TODO Auto-generated method stubvar arr1 = [ -5, 3, 6, 12, 15 ];var arr2 = [ -12, -10, -6, -3, 4, 10 ]; var i = arr1.length;var j = arr2.length; var l = i+j;// Merge two array into one arrayconst arr3 = arr1.concat(arr2); // Sort the merged arrayarr3.sort(function(a, b) { return a - b;}); // calling the methoddocument.write("Median = " + Solution(arr3, l)); // This code is contributed by Shubham Singh</script> Median = 3 Complexity Analysis : Time Complexity: O((n+m) Log (n+m)) Space Complexity: O(n+m). Since we are creating a new array of size n+m. Solution 4 : Binary Search Approach: The given two arrays are sorted, so we can utilize the ability of Binary Search to divide the array and find the median. Median means the point at which the whole array is divide into two parts. Hence since the two arrays are not merged so to get the median we require merging which is costly. Hence instead of merging we will use below given algorithm to efficiently find median. Algorithm: 1. Lets assume that there are two arrays A and B with array A having the minimum number of elements. If this is not the case then swap A and B to make A having small size. 2. The edge cases like one array is empty or both are empty will be handled. 3. let n be the size of A and m be the size of B. Now think of an idea that if we have to find the median than we have to divide the whole merged array into two parts namely left and right parts. Now since we are given the size of left part (i.e (n+m+1)/2), Now look at below given example. A-> 1,2,3,4,5 n = 5 B-> 1,2,3,4,5,6 m = 6 Here merged array will look like :- 1,1,2,2,3,3,4,4,5,5,6 and median then is 3 Now we can see our left part which is underlined. We divide A and B into two parts such that the sum of left part of both A and B will result in left part of merged array. A-> 1,2,3,4,5 // pointers l =0 and r = n-1 hence mid = (l+r)/2; B -> 1,2,3,4,5,6 we can see that left part of A is given as n/2 and since total length of left part in merged array is (m+n+1)/2, so left part of B = (m+n+1)/2-n/2; Now we just have to confirm if our left and right partitions in A and B are correct or not. 4. Now we have 4 variables indicating four values two from array A and two from array B. leftA -> Rightmost element in left part of A = 2 leftb -> Rightmost element in left part of B = 4 rightA -> Leftmost element in right part of A = 3 rightB -> Leftmost element in right part of B = 5 Hence to confirm that partition is correct we have to check the following conditions. leftA<=rightB and leftB<=rightA // This is the case when the sum of two parts of A and B results in left part of merged array if our partition not works that means we have to find other mid point in A and then left part in B This is seen when leftA > rightB //means we have to dec size of A's partition so do r = mid-1; else do l =mid+1; Hence repeat the above steps with new partitions till we get the answers. 5. If leftA<=rightB and leftB<=rightA then we get correct partition and our answer depends on the total size of merged array (i.e. m+n) If (m+n)%2==0 ans is max(leftA,leftB)+min(rightA,rightB)/2; // max of left part is nearest to median and min of right part is nearest to medain else ans is max(leftA,leftB); Hence the above algorithm can be coded as C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; // Method to find mediandouble Median(vector<int>& A, vector<int>& B){ int n = A.size(); int m = B.size(); if (n > m) return Median(B, A); // Swapping to make A smaller int start = 0; int end = n; int realmidinmergedarray = (n + m + 1) / 2; while (start <= end) { int mid = (start + end) / 2; int leftAsize = mid; int leftBsize = realmidinmergedarray - mid; int leftA = (leftAsize > 0) ? A[leftAsize - 1] : INT_MIN; // checking overflow of indices int leftB = (leftBsize > 0) ? B[leftBsize - 1] : INT_MIN; int rightA = (leftAsize < n) ? A[leftAsize] : INT_MAX; int rightB = (leftBsize < m) ? B[leftBsize] : INT_MAX; // if correct partition is done if (leftA <= rightB and leftB <= rightA) { if ((m + n) % 2 == 0) return (max(leftA, leftB) + min(rightA, rightB)) / 2.0; return max(leftA, leftB); } else if (leftA > rightB) { end = mid - 1; } else start = mid + 1; } return 0.0;} // Driver codeint main(){ vector<int> arr1 = { -5, 3, 6, 12, 15 }; vector<int> arr2 = { -12, -10, -6, -3, 4, 10 }; cout << "Median of the two arrays are" << endl; cout << Median(arr1, arr2); return 0;} public class GFG { // Method to find median static double Median(int[] A, int[] B) { int n = A.length; int m = B.length; if (n > m) return Median(B, A); // Swapping to make A smaller int start = 0; int end = n; int realmidinmergedarray = (n + m + 1) / 2; while (start <= end) { int mid = (start + end) / 2; int leftAsize = mid; int leftBsize = realmidinmergedarray - mid; int leftA = (leftAsize > 0) ? A[leftAsize - 1] : Integer.MIN_VALUE; // checking overflow of indices int leftB = (leftBsize > 0) ? B[leftBsize - 1] : Integer.MIN_VALUE; int rightA = (leftAsize < n) ? A[leftAsize] : Integer.MAX_VALUE; int rightB = (leftBsize < m) ? B[leftBsize] : Integer.MAX_VALUE; // if correct partition is done if (leftA <= rightB && leftB <= rightA) { if ((m + n) % 2 == 0) return (Math.max(leftA, leftB) + Math.min(rightA, rightB)) / 2.0; return Math.max(leftA, leftB); } else if (leftA > rightB) { end = mid - 1; } else start = mid + 1; } return 0.0; } // Driver code public static void main(String[] args) { int[] arr1 = { -5, 3, 6, 12, 15 }; int[] arr2 = { -12, -10, -6, -3, 4, 10 }; System.out.println("Median of the two arrays are"); System.out.println(Median(arr1, arr2)); }} // This code is contributed by Hritik class Solution: # Method to find median def Median(self, A, B): # Assumption both A and B cannot be empty n = len(A) m = len(B) if (n > m): return self.Median(B, A) # Swapping to make A smaller start = 0 end = n realmidinmergedarray = (n + m + 1) // 2 while (start <= end): mid = (start + end) // 2 leftAsize = mid leftBsize = realmidinmergedarray - mid # checking overflow of indices leftA = A[leftAsize - 1] if (leftAsize > 0) else float('-inf') leftB = B[leftBsize - 1] if (leftBsize > 0) else float('-inf') rightA = A[leftAsize] if (leftAsize < n) else float('inf') rightB = B[leftBsize] if (leftBsize < m) else float('inf') # if correct partition is done if leftA <= rightB and leftB <= rightA: if ((m + n) % 2 == 0): return (max(leftA, leftB) + min(rightA, rightB)) / 2.0 return max(leftA, leftB) elif (leftA > rightB): end = mid - 1 else: start = mid + 1 # Driver codeans = Solution()arr1 = [-5, 3, 6, 12, 15]arr2 = [-12, -10, -6, -3, 4, 10]print("Median of the two arrays is {}".format(ans.Median(arr1, arr2))) # This code is contributed by Arpan using System; public class GFG { // Method to find median static double Median(int[] A, int[] B) { int n = A.Length; int m = B.Length; if (n > m) return Median(B, A); // Swapping to make A smaller int start = 0; int end = n; int realmidinmergedarray = (n + m + 1) / 2; while (start <= end) { int mid = (start + end) / 2; int leftAsize = mid; int leftBsize = realmidinmergedarray - mid; int leftA = (leftAsize > 0) ? A[leftAsize - 1] : Int32.MinValue; // checking overflow of indices int leftB = (leftBsize > 0) ? B[leftBsize - 1] : Int32.MinValue; int rightA = (leftAsize < n) ? A[leftAsize] : Int32.MaxValue; int rightB = (leftBsize < m) ? B[leftBsize] : Int32.MaxValue; // if correct partition is done if (leftA <= rightB && leftB <= rightA) { if ((m + n) % 2 == 0) return (Math.Max(leftA, leftB) + Math.Min(rightA, rightB)) / 2.0; return Math.Max(leftA, leftB); } else if (leftA > rightB) { end = mid - 1; } else start = mid + 1; } return 0.0; } // Driver code public static void Main() { int[] arr1 = { -5, 3, 6, 12, 15 }; int[] arr2 = { -12, -10, -6, -3, 4, 10 }; Console.WriteLine("Median of the two arrays are"); Console.WriteLine(Median(arr1, arr2)); }} // This code is contributed by Shubham Singh <script> // JavaScript Program to implement // the above approach // Method to find median function Median(A, B) { let n = A.length; let m = B.length; if (n > m) return Median(B, A); // Swapping to make A smaller let start = 0; let end = n; let realmidinmergedarray = Math.floor((n + m + 1) / 2); while (start <= end) { let mid = Math.floor((start + end) / 2); let leftAsize = mid; let leftBsize = realmidinmergedarray - mid; let leftA = (leftAsize > 0) ? A[leftAsize - 1] : Number.MIN_VALUE; // checking overflow of indices let leftB = (leftBsize > 0) ? B[leftBsize - 1] : INT_MIN; let rightA = (leftAsize < n) ? A[leftAsize] : INT_MAX; let rightB = (leftBsize < m) ? B[leftBsize] : INT_MAX; // if correct partition is done if (leftA <= rightB && leftB <= rightA) { if ((m + n) % 2 == 0) return Math.floor((Math.max(leftA, leftB) + Math.min(rightA, rightB)) / 2.0); return Math.max(leftA, leftB); } else if (leftA > rightB) { end = mid - 1; } else start = mid + 1; } return 0.0; } // Driver code let arr1 = [-5, 3, 6, 12, 15]; let arr2 = [-12, -10, -6, -3, 4, 10]; document.write("Median of the two arrays are" + "<br>"); document.write(Median(arr1, arr2)) // This code is contributed by Potta Lokesh </script> Median of the two arrays are 3 Time Complexity: O(min(log m, log n)) : Since binary search is being applied on the smaller of the 2 arraysAuxiliary Space: O(1) ukasp pratil Raj Bansal AkshAyMore2 rathbhupendra ankush_953 andrew1234 Akanksha_Rai nsit_changeable ysinghal555 princi singh divyeshrabadiya07 divyesh072019 manastole01 saipraveenm99 mukesh07 SoumikMondal vilajaxmyai kush11 avanitrachhadiya2155 SHUBHAMSINGH10 harshkumarchoudhary144 hritikrommie ruhelaa48 namanbansal4 arpansheetal lokeshpotta20 rajesh999 anuragncp architgwl2000 Binary Search median-finding statistical-algorithms Divide and Conquer Searching Searching Divide and Conquer Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for Tower of Hanoi Divide and Conquer Algorithm | Introduction Write a program to calculate pow(x,n) Count number of occurrences (or frequency) in a sorted array Quick Sort vs Merge Sort Linear Search Search an element in a sorted and rotated array Find the Missing Number K'th Smallest/Largest Element in Unsorted Array | Set 1 Program to find largest element in an array
[ { "code": null, "e": 26555, "s": 26527, "text": "\n19 Feb, 2022" }, { "code": null, "e": 26910, "s": 26555, "text": "Given two sorted arrays, a[] and b[], the task is to find the median of these sorted arrays, in O(log n + log m) time complexity, when n is the number of elements in the first array, and m is the number of elements in the second array. This is an extension of median of two sorted arrays of equal size problem. Here we handle arrays of unequal size also." }, { "code": null, "e": 26920, "s": 26910, "text": "Example: " }, { "code": null, "e": 27531, "s": 26920, "text": "Input: ar1[] = {-5, 3, 6, 12, 15}\n ar2[] = {-12, -10, -6, -3, 4, 10}\nOutput : The median is 3.\nExplanation : The merged array is :\n ar3[] = {-12, -10, -6, -5 , -3,\n 3, 4, 6, 10, 12, 15},\n So the median of the merged array is 3\n\nInput: ar1[] = {2, 3, 5, 8}\n ar2[] = {10, 12, 14, 16, 18, 20}\nOutput : The median is 11.\nExplanation : The merged array is :\n ar3[] = {2, 3, 5, 8, 10, 12, 14, 16, 18, 20}\n if the number of the elements are even, \n so there are two middle elements,\n take the average between the two :\n (10 + 12) / 2 = 11." }, { "code": null, "e": 27590, "s": 27531, "text": "Method 1: This method uses a linear and simpler approach. " }, { "code": null, "e": 27901, "s": 27590, "text": "Approach: The given arrays are sorted, so merge the sorted arrays in an efficient way and keep the count of elements inserted in the output array or printed form. So when the elements in the output array are half the original size of the given array print the element as a median element. There are two cases: " }, { "code": null, "e": 28154, "s": 27901, "text": "Case 1: m+n is odd, the median is at (m+n)/2 th index in the array obtained after merging both the arrays.Case 2: m+n is even, the median will be average of elements at index ((m+n)/2 – 1) and (m+n)/2 in the array obtained after merging both the arrays" }, { "code": null, "e": 28261, "s": 28154, "text": "Case 1: m+n is odd, the median is at (m+n)/2 th index in the array obtained after merging both the arrays." }, { "code": null, "e": 28408, "s": 28261, "text": "Case 2: m+n is even, the median will be average of elements at index ((m+n)/2 – 1) and (m+n)/2 in the array obtained after merging both the arrays" }, { "code": null, "e": 28420, "s": 28408, "text": "Algorithm: " }, { "code": null, "e": 29095, "s": 28420, "text": "Given two arrays are sorted. So they can be merged in O(m+n) time. Create a variable count to have a count of elements in the output array.If the value of (m+n) is odd then there is only one median else the median is the average of elements at index (m+n)/2 and ((m+n)/2 – 1).To merge the both arrays, keep two indices i and j initially assigned to 0. Compare the ith index of 1st array and jth index of second, increase the index of the smallest element and increase the count.Store (m+n)/2 and (m+n)/2-1 in two variables (In the below C++ code, m1 and m2 are used for this purpose).Check if the count reached (m+n) / 2. If (m+n) is odd return m1, If even return (m1+m2)/2." }, { "code": null, "e": 29235, "s": 29095, "text": "Given two arrays are sorted. So they can be merged in O(m+n) time. Create a variable count to have a count of elements in the output array." }, { "code": null, "e": 29373, "s": 29235, "text": "If the value of (m+n) is odd then there is only one median else the median is the average of elements at index (m+n)/2 and ((m+n)/2 – 1)." }, { "code": null, "e": 29576, "s": 29373, "text": "To merge the both arrays, keep two indices i and j initially assigned to 0. Compare the ith index of 1st array and jth index of second, increase the index of the smallest element and increase the count." }, { "code": null, "e": 29683, "s": 29576, "text": "Store (m+n)/2 and (m+n)/2-1 in two variables (In the below C++ code, m1 and m2 are used for this purpose)." }, { "code": null, "e": 29774, "s": 29683, "text": "Check if the count reached (m+n) / 2. If (m+n) is odd return m1, If even return (m1+m2)/2." }, { "code": null, "e": 29791, "s": 29774, "text": "Implementation: " }, { "code": null, "e": 29795, "s": 29791, "text": "C++" }, { "code": null, "e": 29797, "s": 29795, "text": "C" }, { "code": null, "e": 29802, "s": 29797, "text": "Java" }, { "code": null, "e": 29810, "s": 29802, "text": "Python3" }, { "code": null, "e": 29813, "s": 29810, "text": "C#" }, { "code": null, "e": 29824, "s": 29813, "text": "Javascript" }, { "code": "// A Simple Merge based O(n) solution to find// median of two sorted arrays#include <bits/stdc++.h>using namespace std; /* This function returns median of ar1[] and ar2[].Assumption in this function:Both ar1[] and ar2[] are sorted arrays */int getMedian(int ar1[], int ar2[], int n, int m){ int i = 0; /* Current index of input array ar1[] */ int j = 0; /* Current index of input array ar2[] */ int count; int m1 = -1, m2 = -1; /*loop till (m+n)/2*/ for (count = 0; count <= (m + n)/2; count++) { //store (n+m)/2-1 in m2 m2=m1; if(i != n && j != m) { m1 = (ar1[i] > ar2[j]) ? ar2[j++] : ar1[i++]; } else if(i < n) { m1 = ar1[i++]; } // for case when j<m, else { m1 = ar2[j++]; } } // Since there are (n+m) elements, // There are following two cases // if n+m is odd then the middle // index is median i.e. (m+n)/2 // other wise median will be average of elements // at index ((m+n)/2 - 1) and (m+n)/2 // in the array obtained after merging ar1 and ar2 if((m + n) % 2 == 1){ return m1; } else{ return (m1+m2)/2; }}/* Driver code */int main(){ int ar1[] = {900}; int ar2[] = {5,8,10,20}; int n1 = sizeof(ar1)/sizeof(ar1[0]); int n2 = sizeof(ar2)/sizeof(ar2[0]); cout << getMedian(ar1, ar2, n1, n2);} // This is code is contributed by rathbhupendra, modified by rajesh999", "e": 31298, "s": 29824, "text": null }, { "code": "// A Simple Merge based O(n) solution to find// median of two sorted arrays#include <stdio.h> /* This function returns median of ar1[] and ar2[].Assumption in this function:Both ar1[] and ar2[] are sorted arrays */int getMedian(int ar1[], int ar2[], int n, int m){ int i = 0; /* Current index of input array ar1[] */ int j = 0; /* Current index of input array ar2[] */ int count; int m1 = -1, m2 = -1; // Since there are (n+m) elements, // There are following two cases // if n+m is odd then the middle //index is median i.e. (m+n)/2 if((m + n) % 2 == 1) { for (count = 0; count <= (n + m)/2; count++) { if(i != n && j != m){ m1 = (ar1[i] > ar2[j]) ? ar2[j++] : ar1[i++]; } else if(i < n){ m1 = ar1[i++]; } // for case when j<m, else{ m1 = ar2[j++]; } } return m1; } // median will be average of elements // at index ((m+n)/2 - 1) and (m+n)/2 // in the array obtained after merging ar1 and ar2 else { for (count = 0; count <= (n + m)/2; count++) { m2 = m1; if(i != n && j != m){ m1 = (ar1[i] > ar2[j]) ? ar2[j++] : ar1[i++]; } else if(i < n){ m1 = ar1[i++]; } // for case when j<m, else{ m1 = ar1[j++]; } } return (m1 + m2)/2; }} /* Driver program to test above function */int main(){ int ar1[] = {900}; int ar2[] = {5, 8, 10, 20}; int n1 = sizeof(ar1)/sizeof(ar1[0]); int n2 = sizeof(ar2)/sizeof(ar2[0]); printf(\"%d\", getMedian(ar1, ar2, n1, n2)); getchar(); return 0;}// This code is uploaded by Pratil", "e": 33049, "s": 31298, "text": null }, { "code": "// A Simple Merge based O(n) solution// to find median of two sorted arraysclass GFG{ // Function to calculate medianstatic int getMedian(int ar1[], int ar2[], int n, int m){ // Current index of input array ar1[] int i = 0; // Current index of input array ar2[] int j = 0; int count; int m1 = -1, m2 = -1; // Since there are (n+m) elements, // There are following two cases // if n+m is odd then the middle //index is median i.e. (m+n)/2 if ((m + n) % 2 == 1) { for(count = 0; count <= (n + m) / 2; count++) { if (i != n && j != m) { m1 = (ar1[i] > ar2[j]) ? ar2[j++] : ar1[i++]; } else if (i < n) { m1 = ar1[i++]; } // for case when j<m, else { m1 = ar2[j++]; } } return m1; } // median will be average of elements // at index ((m+n)/2 - 1) and (m+n)/2 // in the array obtained after merging // ar1 and ar2 else { for(count = 0; count <= (n + m) / 2; count++) { m2 = m1; if (i != n && j != m) { m1 = (ar1[i] > ar2[j]) ? ar2[j++] : ar1[i++]; } else if (i < n) { m1 = ar1[i++]; } // for case when j<m, else { m1 = ar2[j++]; } } return (m1 + m2) / 2; }} // Driver codepublic static void main(String[] args){ int ar1[] = { 900 }; int ar2[] = { 5, 8, 10, 20 }; int n1 = ar1.length; int n2 = ar2.length; System.out.println(getMedian(ar1, ar2, n1, n2));}} // This code is contributed by Yash Singhal", "e": 34953, "s": 33049, "text": null }, { "code": "# A Simple Merge based O(n) solution to find# median of two sorted arrays \"\"\" This function returns median of ar1[] and ar2[].Assumption in this function:Both ar1[] and ar2[] are sorted arrays \"\"\"def getMedian(ar1, ar2, n, m) : i = 0 # Current index of input array ar1[] j = 0 # Current index of input array ar2[] m1, m2 = -1, -1 # Since there are (n+m) elements, # There are following two cases # if n+m is odd then the middle # index is median i.e. (m+n)/2 if((m + n) % 2 == 1) : for count in range(((n + m) // 2) + 1) : if(i != n and j != m) : if ar1[i] > ar2[j] : m1 = ar2[j] j += 1 else : m1 = ar1[i] i += 1 elif(i < n) : m1 = ar1[i] i += 1 # for case when j<m, else : m1 = ar2[j] j += 1 return m1 # median will be average of elements # at index ((m + n)/2 - 1) and (m + n)/2 # in the array obtained after merging ar1 and ar2 else : for count in range(((n + m) // 2) + 1) : m2 = m1 if(i != n and j != m) : if ar1[i] > ar2[j] : m1 = ar2[j] j += 1 else : m1 = ar1[i] i += 1 elif(i < n) : m1 = ar1[i] i += 1 # for case when j<m, else : m1 = ar2[j] j += 1 return (m1 + m2)//2 # Driver code ar1 = [900]ar2 = [5, 8, 10, 20] n1 = len(ar1)n2 = len(ar2)print(getMedian(ar1, ar2, n1, n2)) # This code is contributed by divyesh072019", "e": 36826, "s": 34953, "text": null }, { "code": "// A Simple Merge based O(n) solution// to find median of two sorted arraysusing System; class GFG{ // Function to calculate medianstatic int getMedian(int []ar1, int []ar2, int n, int m){ // Current index of input array ar1[] int i = 0; // Current index of input array ar2[] int j = 0; int count; int m1 = -1, m2 = -1; // Since there are (n+m) elements, // There are following two cases // if n+m is odd then the middle //index is median i.e. (m+n)/2 if ((m + n) % 2 == 1) { for(count = 0; count <= (n + m) / 2; count++) { if (i != n && j != m) { m1 = (ar1[i] > ar2[j]) ? ar2[j++] : ar1[i++]; } else if (i < n) { m1 = ar1[i++]; } // for case when j<m, else { m1 = ar2[j++]; } } return m1; } // median will be average of elements // at index ((m+n)/2 - 1) and (m+n)/2 // in the array obtained after merging // ar1 and ar2 else { for(count = 0; count <= (n + m) / 2; count++) { m2 = m1; if (i != n && j != m) { m1 = (ar1[i] > ar2[j]) ? ar2[j++] : ar1[i++]; } else if (i < n) { m1 = ar1[i++]; } // for case when j<m, else { m1 = ar2[j++]; } } return (m1 + m2) / 2; }} // Driver codepublic static void Main(String[] args){ int []ar1 = { 900 }; int []ar2 = { 5, 8, 10, 20 }; int n1 = ar1.Length; int n2 = ar2.Length; Console.WriteLine(getMedian(ar1, ar2, n1, n2));}} // This code is contributed by Princi Singh", "e": 38748, "s": 36826, "text": null }, { "code": "<script> // A Simple Merge based O(n) solution to find// median of two sorted arrays // This function returns median of ar1[] and ar2[].// Assumption in this function:// Both ar1[] and ar2[] are sorted arraysfunction getMedian(ar1, ar2, n, m){ // Current index of input array ar1[] let i = 0; // Current index of input array ar2[] let j = 0; let count; let m1 = -1, m2 = -1; // Since there are (n+m) elements, // There are following two cases // if n+m is odd then the middle // index is median i.e. (m+n)/2 if ((m + n) % 2 == 1) { for(count = 0; count <= (n + m) / 2; count++) { if (i != n && j != m) { m1 = (ar1[i] > ar2[j]) ? ar2[j++] : ar1[i++]; } else if(i < n) { m1 = ar1[i++]; } // For case when j<m, else { m1 = ar2[j++]; } } return m1; } // Median will be average of elements // at index ((m+n)/2 - 1) and (m+n)/2 // in the array obtained after merging // ar1 and ar2 else { for(count = 0; count <= (n + m) / 2; count++) { m2 = m1; if (i != n && j != m) { m1 = (ar1[i] > ar2[j]) ? ar2[j++] : ar1[i++]; } else if(i < n) { m1 = ar1[i++]; } // For case when j<m, else { m1 = ar2[j++]; } } return (m1 + m2) / 2; }} // Driver codelet ar1 = [900];let ar2 = [5, 8, 10, 20]; let n1 = ar1.length;let n2 = ar2.length;document.write(getMedian(ar1, ar2, n1, n2)); // This code is contributed by divyeshrabadiya07 </script>", "e": 40629, "s": 38748, "text": null }, { "code": null, "e": 40635, "s": 40632, "text": "10" }, { "code": null, "e": 40659, "s": 40637, "text": "Complexity Analysis: " }, { "code": null, "e": 40736, "s": 40661, "text": "Time Complexity: O(m + n). To merge both the arrays O(m+n) time is needed." }, { "code": null, "e": 40788, "s": 40736, "text": "Space Complexity: O(1). No extra space is required." }, { "code": null, "e": 40811, "s": 40790, "text": "Efficient solution: " }, { "code": null, "e": 40998, "s": 40813, "text": "Approach:The idea is simple, calculate the median of both the arrays and discard one half of each array. Now, there are some basic corner cases. For array size less than or equal to 2 " }, { "code": null, "e": 41610, "s": 41000, "text": "Suppose there are two arrays and the size of both the arrays is greater than 2. Find the middle element of the first array and middle element of the second array (the first array is smaller than the second) if the middle element of the smaller array is less than the second array, then it can be said that all elements of the first half of smaller array will be in the first half of the output (merged array). So, reduce the search space by ignoring the first half of the smaller array and the second half of the larger array. Else ignore the second half of the smaller array and first half of a larger array." }, { "code": null, "e": 41668, "s": 41612, "text": "In addition to that there are more basic corner cases: " }, { "code": null, "e": 43369, "s": 41670, "text": "If the size of smaller array is 0. Return the median of a larger array.if the size of smaller array is 1. The size of the larger array is also 1. Return the median of two elements.If the size of the larger array is odd. Then after adding the element from 2nd array, it will be even so the median will be an average of two mid elements. So the element from the smaller array will affect the median if and only if it lies between (m/2 – 1)th and (m/2 + 1)th element of the larger array. So, find the median in between the four elements, the element of the smaller array and (m/2)th, (m/2 – 1)th and (m/2 + 1)th element of a larger arraySimilarly, if the size is even, then check for the median of three elements, the element of the smaller array and (m/2)th, (m/2 – 1)th element of a larger arrayIf the size of smaller array is 2 If the larger array also has two elements, find the median of four elements.If the larger array has an odd number of elements, then the median will be one of the following 3 elements Middle element of larger arrayMax of the second element of smaller array and element just before the middle, i.e M/2-1th element in a bigger arrayMin of the first element of smaller array and element just after the middle in the bigger array, i.e M/2 + 1th element in the bigger arrayIf the larger array has even number of elements, then the median will be one of the following 4 elements The middle two elements of the larger arrayMax of the first element of smaller array and element just before the first middle element in the bigger array, i.e M/2 – 2nd elementMin of the second element of smaller array and element just after the second middle in the bigger array, M/2 + 1th element" }, { "code": null, "e": 43441, "s": 43369, "text": "If the size of smaller array is 0. Return the median of a larger array." }, { "code": null, "e": 44165, "s": 43441, "text": "if the size of smaller array is 1. The size of the larger array is also 1. Return the median of two elements.If the size of the larger array is odd. Then after adding the element from 2nd array, it will be even so the median will be an average of two mid elements. So the element from the smaller array will affect the median if and only if it lies between (m/2 – 1)th and (m/2 + 1)th element of the larger array. So, find the median in between the four elements, the element of the smaller array and (m/2)th, (m/2 – 1)th and (m/2 + 1)th element of a larger arraySimilarly, if the size is even, then check for the median of three elements, the element of the smaller array and (m/2)th, (m/2 – 1)th element of a larger array" }, { "code": null, "e": 44854, "s": 44165, "text": "The size of the larger array is also 1. Return the median of two elements.If the size of the larger array is odd. Then after adding the element from 2nd array, it will be even so the median will be an average of two mid elements. So the element from the smaller array will affect the median if and only if it lies between (m/2 – 1)th and (m/2 + 1)th element of the larger array. So, find the median in between the four elements, the element of the smaller array and (m/2)th, (m/2 – 1)th and (m/2 + 1)th element of a larger arraySimilarly, if the size is even, then check for the median of three elements, the element of the smaller array and (m/2)th, (m/2 – 1)th element of a larger array" }, { "code": null, "e": 44929, "s": 44854, "text": "The size of the larger array is also 1. Return the median of two elements." }, { "code": null, "e": 45384, "s": 44929, "text": "If the size of the larger array is odd. Then after adding the element from 2nd array, it will be even so the median will be an average of two mid elements. So the element from the smaller array will affect the median if and only if it lies between (m/2 – 1)th and (m/2 + 1)th element of the larger array. So, find the median in between the four elements, the element of the smaller array and (m/2)th, (m/2 – 1)th and (m/2 + 1)th element of a larger array" }, { "code": null, "e": 45545, "s": 45384, "text": "Similarly, if the size is even, then check for the median of three elements, the element of the smaller array and (m/2)th, (m/2 – 1)th element of a larger array" }, { "code": null, "e": 46450, "s": 45545, "text": "If the size of smaller array is 2 If the larger array also has two elements, find the median of four elements.If the larger array has an odd number of elements, then the median will be one of the following 3 elements Middle element of larger arrayMax of the second element of smaller array and element just before the middle, i.e M/2-1th element in a bigger arrayMin of the first element of smaller array and element just after the middle in the bigger array, i.e M/2 + 1th element in the bigger arrayIf the larger array has even number of elements, then the median will be one of the following 4 elements The middle two elements of the larger arrayMax of the first element of smaller array and element just before the first middle element in the bigger array, i.e M/2 – 2nd elementMin of the second element of smaller array and element just after the second middle in the bigger array, M/2 + 1th element" }, { "code": null, "e": 47321, "s": 46450, "text": "If the larger array also has two elements, find the median of four elements.If the larger array has an odd number of elements, then the median will be one of the following 3 elements Middle element of larger arrayMax of the second element of smaller array and element just before the middle, i.e M/2-1th element in a bigger arrayMin of the first element of smaller array and element just after the middle in the bigger array, i.e M/2 + 1th element in the bigger arrayIf the larger array has even number of elements, then the median will be one of the following 4 elements The middle two elements of the larger arrayMax of the first element of smaller array and element just before the first middle element in the bigger array, i.e M/2 – 2nd elementMin of the second element of smaller array and element just after the second middle in the bigger array, M/2 + 1th element" }, { "code": null, "e": 47398, "s": 47321, "text": "If the larger array also has two elements, find the median of four elements." }, { "code": null, "e": 47790, "s": 47398, "text": "If the larger array has an odd number of elements, then the median will be one of the following 3 elements Middle element of larger arrayMax of the second element of smaller array and element just before the middle, i.e M/2-1th element in a bigger arrayMin of the first element of smaller array and element just after the middle in the bigger array, i.e M/2 + 1th element in the bigger array" }, { "code": null, "e": 48075, "s": 47790, "text": "Middle element of larger arrayMax of the second element of smaller array and element just before the middle, i.e M/2-1th element in a bigger arrayMin of the first element of smaller array and element just after the middle in the bigger array, i.e M/2 + 1th element in the bigger array" }, { "code": null, "e": 48106, "s": 48075, "text": "Middle element of larger array" }, { "code": null, "e": 48223, "s": 48106, "text": "Max of the second element of smaller array and element just before the middle, i.e M/2-1th element in a bigger array" }, { "code": null, "e": 48362, "s": 48223, "text": "Min of the first element of smaller array and element just after the middle in the bigger array, i.e M/2 + 1th element in the bigger array" }, { "code": null, "e": 48766, "s": 48362, "text": "If the larger array has even number of elements, then the median will be one of the following 4 elements The middle two elements of the larger arrayMax of the first element of smaller array and element just before the first middle element in the bigger array, i.e M/2 – 2nd elementMin of the second element of smaller array and element just after the second middle in the bigger array, M/2 + 1th element" }, { "code": null, "e": 49065, "s": 48766, "text": "The middle two elements of the larger arrayMax of the first element of smaller array and element just before the first middle element in the bigger array, i.e M/2 – 2nd elementMin of the second element of smaller array and element just after the second middle in the bigger array, M/2 + 1th element" }, { "code": null, "e": 49109, "s": 49065, "text": "The middle two elements of the larger array" }, { "code": null, "e": 49243, "s": 49109, "text": "Max of the first element of smaller array and element just before the first middle element in the bigger array, i.e M/2 – 2nd element" }, { "code": null, "e": 49366, "s": 49243, "text": "Min of the second element of smaller array and element just after the second middle in the bigger array, M/2 + 1th element" }, { "code": null, "e": 49413, "s": 49368, "text": "How can one half of each array be discarded?" }, { "code": null, "e": 49687, "s": 49415, "text": "Let’s take an example to understand thisInput :arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10},brr[] = { 11, 12, 13, 14, 15, 16, 17, 18, 19 }Dry Run of the code:Recursive call 1:smaller array[] = 1 2 3 4 5 6 7 8 9 10, mid = 5larger array[] = 11 12 13 14 15 16 17 18 19 , mid = 15" }, { "code": null, "e": 49767, "s": 49687, "text": "5 < 15Discard first half of the first array and second half of the second array" }, { "code": null, "e": 49865, "s": 49767, "text": "Recursive call 2:smaller array[] = 11 12 13 14 15, mid = 13larger array[] = 5 6 7 8 9 10, mid = 7" }, { "code": null, "e": 49945, "s": 49865, "text": "7 < 13Discard first half of the second array and second half of the first array" }, { "code": null, "e": 50035, "s": 49945, "text": "Recursive call 3:smaller array[] = 11 12 13 , mid = 12larger array[] = 7 8 9 10 , mid = 8" }, { "code": null, "e": 50115, "s": 50035, "text": "8 < 12Discard first half of the second array and second half of the first array" }, { "code": null, "e": 50179, "s": 50115, "text": "Recursive call 4:smaller array[] = 11 12larger array[] = 8 9 10" }, { "code": null, "e": 50354, "s": 50179, "text": "Size of the smaller array is 2 and the size of the larger array is oddso, the median will be the median of max( 11, 8), 9, min( 10, 12)that is 9, 10, 11, so the median is 10." }, { "code": null, "e": 50371, "s": 50354, "text": "Output:10.000000" }, { "code": null, "e": 50385, "s": 50373, "text": "Algorithm: " }, { "code": null, "e": 51437, "s": 50387, "text": "Create a recursive function that takes two arrays and the sizes of both the arrays.Take care of the base cases for the size of arrays less than 2. (previously discussed in Approach).Note: The first array is always the smaller array.Find the middle elements of both the arrays. i.e element at (n – 1)/2 and (m – 1)/2 of first and second array respectively. Compare both the elements.If the middle element of the smaller array is less than the middle element of the larger array then the first half of the smaller array is bound to lie strictly in the first half of the merged array. It can also be stated that there is an element in the first half of the larger array and the second half of the smaller array which is the median. So, reduce the search space to the first half of the larger array and the second half of the smaller array.Similarly, If the middle element of the smaller array is greater than the middle element of the larger array then reduce the search space to the first half of the smaller array and second half of the larger array." }, { "code": null, "e": 51521, "s": 51437, "text": "Create a recursive function that takes two arrays and the sizes of both the arrays." }, { "code": null, "e": 51671, "s": 51521, "text": "Take care of the base cases for the size of arrays less than 2. (previously discussed in Approach).Note: The first array is always the smaller array." }, { "code": null, "e": 51822, "s": 51671, "text": "Find the middle elements of both the arrays. i.e element at (n – 1)/2 and (m – 1)/2 of first and second array respectively. Compare both the elements." }, { "code": null, "e": 52277, "s": 51822, "text": "If the middle element of the smaller array is less than the middle element of the larger array then the first half of the smaller array is bound to lie strictly in the first half of the merged array. It can also be stated that there is an element in the first half of the larger array and the second half of the smaller array which is the median. So, reduce the search space to the first half of the larger array and the second half of the smaller array." }, { "code": null, "e": 52491, "s": 52277, "text": "Similarly, If the middle element of the smaller array is greater than the middle element of the larger array then reduce the search space to the first half of the smaller array and second half of the larger array." }, { "code": null, "e": 52510, "s": 52493, "text": "Implementation: " }, { "code": null, "e": 52516, "s": 52512, "text": "C++" }, { "code": null, "e": 52521, "s": 52516, "text": "Java" }, { "code": null, "e": 52529, "s": 52521, "text": "Python3" }, { "code": null, "e": 52532, "s": 52529, "text": "C#" }, { "code": null, "e": 52536, "s": 52532, "text": "PHP" }, { "code": null, "e": 52547, "s": 52536, "text": "Javascript" }, { "code": "// A C++ program to find median of two sorted arrays of// unequal sizes#include <bits/stdc++.h>using namespace std; // A utility function to find median of two integersfloat MO2(int a, int b){ return ( a + b ) / 2.0; } // A utility function to find median of three integersfloat MO3(int a, int b, int c){ return a + b + c - max(a, max(b, c)) - min(a, min(b, c));} // A utility function to find a median of four integersfloat MO4(int a, int b, int c, int d){ int Max = max( a, max( b, max( c, d ) ) ); int Min = min( a, min( b, min( c, d ) ) ); return ( a + b + c + d - Max - Min ) / 2.0;} // Utility function to find median of single arrayfloat medianSingle(int arr[], int n){ if (n == 0) return -1; if (n%2 == 0) return (double)(arr[n/2] + arr[n/2-1])/2; return arr[n/2];} // This function assumes that N is smaller than or equal to M// This function returns -1 if both arrays are emptyfloat findMedianUtil( int A[], int N, int B[], int M ){ // If smaller array is empty, return median from second array if (N == 0) return medianSingle(B, M); // If the smaller array has only one element if (N == 1) { // Case 1: If the larger array also has one element, // simply call MO2() if (M == 1) return MO2(A[0], B[0]); // Case 2: If the larger array has odd number of elements, // then consider the middle 3 elements of larger array and // the only element of smaller array. Take few examples // like following // A = {9}, B[] = {5, 8, 10, 20, 30} and // A[] = {1}, B[] = {5, 8, 10, 20, 30} if (M & 1) return MO2( B[M/2], MO3(A[0], B[M/2 - 1], B[M/2 + 1]) ); // Case 3: If the larger array has even number of element, // then median will be one of the following 3 elements // ... The middle two elements of larger array // ... The only element of smaller array return MO3( B[M/2], B[M/2 - 1], A[0] ); } // If the smaller array has two elements else if (N == 2) { // Case 4: If the larger array also has two elements, // simply call MO4() if (M == 2) return MO4(A[0], A[1], B[0], B[1]); // Case 5: If the larger array has odd number of elements, // then median will be one of the following 3 elements // 1. Middle element of larger array // 2. Max of first element of smaller array and element // just before the middle in bigger array // 3. Min of second element of smaller array and element // just after the middle in bigger array if (M & 1) return MO3 ( B[M/2], max(A[0], B[M/2 - 1]), min(A[1], B[M/2 + 1]) ); // Case 6: If the larger array has even number of elements, // then median will be one of the following 4 elements // 1) & 2) The middle two elements of larger array // 3) Max of first element of smaller array and element // just before the first middle element in bigger array // 4. Min of second element of smaller array and element // just after the second middle in bigger array return MO4 ( B[M/2], B[M/2 - 1], max( A[0], B[M/2 - 2] ), min( A[1], B[M/2 + 1] ) ); } int idxA = ( N - 1 ) / 2; int idxB = ( M - 1 ) / 2; /* if A[idxA] <= B[idxB], then median must exist in A[idxA....] and B[....idxB] */ if (A[idxA] <= B[idxB] ) return findMedianUtil(A + idxA, N/2 + 1, B, M - idxA ); /* if A[idxA] > B[idxB], then median must exist in A[...idxA] and B[idxB....] */ return findMedianUtil(A, N/2 + 1, B + idxA, M - idxA );} // A wrapper function around findMedianUtil(). This function// makes sure that smaller array is passed as first argument// to findMedianUtilfloat findMedian( int A[], int N, int B[], int M ){ if (N > M) return findMedianUtil( B, M, A, N ); return findMedianUtil( A, N, B, M );} // Driver program to test above functionsint main(){ int A[] = {900}; int B[] = {5, 8, 10, 20}; int N = sizeof(A) / sizeof(A[0]); int M = sizeof(B) / sizeof(B[0]); printf(\"%f\", findMedian( A, N, B, M ) ); return 0;}", "e": 56878, "s": 52547, "text": null }, { "code": "// A Java program to find median of two sorted arrays of// unequal sizesimport java.util.*; class GFG { // A utility function to find median of two integers static float MO2(int a, int b) { return (float) ((a + b) / 2.0); } // A utility function to find median of three integers static float MO3(int a, int b, int c) { return a + b + c - Math.max(a, Math.max(b, c)) - Math.min(a, Math.min(b, c)); } // A utility function to find a median of four integers static float MO4(int a, int b, int c, int d) { int Max = Math.max(a, Math.max(b, Math.max(c, d))); int Min = Math.min(a, Math.min(b, Math.min(c, d))); return (float) ((a + b + c + d - Max - Min) / 2.0); } // Utility function to find median of single array static float medianSingle(int arr[], int n) { if (n == 0) return -1; if (n % 2 == 0) return (float) ((double) (arr[n / 2] + arr[n / 2 - 1]) / 2); return arr[n / 2]; } // This function assumes that N is smaller than or equal to M // This function returns -1 if both arrays are empty static float findMedianUtil(int A[], int N, int B[], int M) { // If smaller array is empty, return median from second array if (N == 0) return medianSingle(B, M); // If the smaller array has only one element if (N == 1) { // Case 1: If the larger array also has one element, // simply call MO2() if (M == 1) return MO2(A[0], B[0]); // Case 2: If the larger array has odd number of elements, // then consider the middle 3 elements of larger array and // the only element of smaller array. Take few examples // like following // A = {9}, B[] = {5, 8, 10, 20, 30} and // A[] = {1}, B[] = {5, 8, 10, 20, 30} if (M % 2 == 1) return MO2(B[M / 2], (int) MO3(A[0], B[M / 2 - 1], B[M / 2 + 1])); // Case 3: If the larger array has even number of element, // then median will be one of the following 3 elements // ... The middle two elements of larger array // ... The only element of smaller array return MO3(B[M / 2], B[M / 2 - 1], A[0]); } // If the smaller array has two elements else if (N == 2) { // Case 4: If the larger array also has two elements, // simply call MO4() if (M == 2) return MO4(A[0], A[1], B[0], B[1]); // Case 5: If the larger array has odd number of elements, // then median will be one of the following 3 elements // 1. Middle element of larger array // 2. Max of first element of smaller array and element // just before the middle in bigger array // 3. Min of second element of smaller array and element // just after the middle in bigger array if (M % 2 == 1) return MO3(B[M / 2], Math.max(A[0], B[M / 2 - 1]), Math.min(A[1], B[M / 2 + 1])); // Case 6: If the larger array has even number of elements, // then median will be one of the following 4 elements // 1) & 2) The middle two elements of larger array // 3) Max of first element of smaller array and element // just before the first middle element in bigger array // 4. Min of second element of smaller array and element // just after the second middle in bigger array return MO4(B[M / 2], B[M / 2 - 1], Math.max(A[0], B[M / 2 - 2]), Math.min(A[1], B[M / 2 + 1])); } int idxA = (N - 1) / 2; int idxB = (M - 1) / 2; /* * if A[idxA] <= B[idxB], then median must exist in A[idxA....] and B[....idxB] */ if (A[idxA] <= B[idxB]) return findMedianUtil(Arrays.copyOfRange(A, idxA, A.length), N / 2 + 1, B, M - idxA); /* * if A[idxA] > B[idxB], then median must exist in A[...idxA] and B[idxB....] */ return findMedianUtil(A, N / 2 + 1, Arrays.copyOfRange(B, idxB, B.length), M - idxA); } // A wrapper function around findMedianUtil(). This function // makes sure that smaller array is passed as first argument // to findMedianUtil static float findMedian(int A[], int N, int B[], int M) { if (N > M) return findMedianUtil(B, M, A, N); return findMedianUtil(A, N, B, M); } // Driver program to test above functions public static void main(String[] args) { int A[] = { 900 }; int B[] = { 5, 8, 10, 20 }; int N = A.length; int M = B.length; System.out.printf(\"%f\", findMedian(A, N, B, M)); }} // This code is contributed by Princi Singh.", "e": 61930, "s": 56878, "text": null }, { "code": "# A Python3 program to find median of two sorted arrays of# unequal sizes # A utility function to find median of two integersdef MO2(a, b) : return ( a + b ) / 2 # A utility function to find median of three integersdef MO3(a, b, c) : return a + b + c - max(a, max(b, c)) - min(a, min(b, c)) # A utility function to find a median of four integersdef MO4(a, b, c, d) : Max = max( a, max( b, max( c, d ) ) ) Min = min( a, min( b, min( c, d ) ) ) return ( a + b + c + d - Max - Min ) / 2 # Utility function to find median of single arraydef medianSingle(arr, n) : if (n == 0) : return -1 if (n % 2 == 0) : return (arr[n / 2] + arr[n / 2 - 1]) / 2 return arr[n / 2] # This function assumes that N is smaller than or equal to M# This function returns -1 if both arrays are emptydef findMedianUtil(A, N, B, M) : # If smaller array is empty, return median from second array if (N == 0) : return medianSingle(B, M) # If the smaller array has only one element if (N == 1) : # Case 1: If the larger array also has one element, # simply call MO2() if (M == 1) : return MO2(A[0], B[0]) # Case 2: If the larger array has odd number of elements, # then consider the middle 3 elements of larger array and # the only element of smaller array. Take few examples # like following # A = {9}, B[] = {5, 8, 10, 20, 30} and # A[] = {1}, B[] = {5, 8, 10, 20, 30} if (M & 1 != 0) : return MO2( B[M / 2], MO3(A[0], B[M / 2 - 1], B[M / 2 + 1]) ) # Case 3: If the larger array has even number of element, # then median will be one of the following 3 elements # ... The middle two elements of larger array # ... The only element of smaller array return MO3(B[M // 2], B[M // 2 - 1], A[0]) # If the smaller array has two elements elif (N == 2) : # Case 4: If the larger array also has two elements, # simply call MO4() if (M == 2) : return MO4(A[0], A[1], B[0], B[1]) # Case 5: If the larger array has odd number of elements, # then median will be one of the following 3 elements # 1. Middle element of larger array # 2. Max of first element of smaller array and element # just before the middle in bigger array # 3. Min of second element of smaller array and element # just after the middle in bigger array if (M & 1 != 0) : return MO3 (B[M / 2], max(A[0], B[M / 2 - 1]), min(A[1], B[M / 2 + 1])) # Case 6: If the larger array has even number of elements, # then median will be one of the following 4 elements # 1) & 2) The middle two elements of larger array # 3) Max of first element of smaller array and element # just before the first middle element in bigger array # 4. Min of second element of smaller array and element # just after the second middle in bigger array return MO4 (B[M / 2], B[M / 2 - 1], max( A[0], B[M / 2 - 2] ), min( A[1], B[M / 2 + 1] )) idxA = ( N - 1 ) / 2 idxB = ( M - 1 ) / 2 ''' if A[idxA] <= B[idxB], then median must exist in A[idxA....] and B[....idxB] ''' if (A[idxA] <= B[idxB] ) : return findMedianUtil(A + idxA, N / 2 + 1, B, M - idxA ) ''' if A[idxA] > B[idxB], then median must exist in A[...idxA] and B[idxB....] ''' return findMedianUtil(A, N / 2 + 1, B + idxA, M - idxA ) # A wrapper function around findMedianUtil(). This function# makes sure that smaller array is passed as first argument# to findMedianUtildef findMedian(A, N, B, M) : if (N > M) : return findMedianUtil( B, M, A, N ); return findMedianUtil( A, N, B, M ) # Driver codeA = [900]B = [5, 8, 10, 20] N = len(A)M = len(B) print(findMedian(A, N, B, M )) # This code is contributed by divyesh072019", "e": 65823, "s": 61930, "text": null }, { "code": "// A C# program to find median of two sorted arrays of// unequal sizesusing System;class GFG{ // A utility function to find median of two integers static float MO2(int a, int b) { return (float) ((a + b) / 2.0); } // A utility function to find median of three integers static float MO3(int a, int b, int c) { return a + b + c - Math.Max(a, Math.Max(b, c)) - Math.Min(a, Math.Min(b, c)); } // A utility function to find a median of four integers static float MO4(int a, int b, int c, int d) { int Max = Math.Max(a, Math.Max(b, Math.Max(c, d))); int Min = Math.Min(a, Math.Min(b, Math.Min(c, d))); return (float) ((a + b + c + d - Max - Min) / 2.0); } // Utility function to find median of single array static float medianSingle(int[] arr, int n) { if (n == 0) return -1; if (n % 2 == 0) return (float) ((double) (arr[n / 2] + arr[n / 2 - 1]) / 2); return arr[n / 2]; } static int[] copyOfRange (int[] src, int start, int end) { int len = end - start; int[] dest = new int[len]; Array.Copy(src, start, dest, 0, len); return dest; } // This function assumes that N is smaller than or equal to M // This function returns -1 if both arrays are empty static float findMedianUtil(int[] A, int N, int[] B, int M) { // If smaller array is empty, // return median from second array if (N == 0) return medianSingle(B, M); // If the smaller array has only one element if (N == 1) { // Case 1: If the larger array also has one element, // simply call MO2() if (M == 1) return MO2(A[0], B[0]); // Case 2: If the larger array has odd number of elements, // then consider the middle 3 elements of larger array and // the only element of smaller array. Take few examples // like following // A = {9}, B[] = {5, 8, 10, 20, 30} and // A[] = {1}, B[] = {5, 8, 10, 20, 30} if (M % 2 == 1) return MO2(B[M / 2], (int) MO3(A[0], B[M / 2 - 1], B[M / 2 + 1])); // Case 3: If the larger array has even number of element, // then median will be one of the following 3 elements // ... The middle two elements of larger array // ... The only element of smaller array return MO3(B[M / 2], B[M / 2 - 1], A[0]); } // If the smaller array has two elements else if (N == 2) { // Case 4: If the larger array also has two elements, // simply call MO4() if (M == 2) return MO4(A[0], A[1], B[0], B[1]); // Case 5: If the larger array has odd number of elements, // then median will be one of the following 3 elements // 1. Middle element of larger array // 2. Max of first element of smaller array and element // just before the middle in bigger array // 3. Min of second element of smaller array and element // just after the middle in bigger array if (M % 2 == 1) return MO3(B[M / 2], Math.Max(A[0], B[M / 2 - 1]), Math.Min(A[1], B[M / 2 + 1])); // Case 6: If the larger array has even number of elements, // then median will be one of the following 4 elements // 1) & 2) The middle two elements of larger array // 3) Max of first element of smaller array and element // just before the first middle element in bigger array // 4. Min of second element of smaller array and element // just after the second middle in bigger array return MO4(B[M / 2], B[M / 2 - 1], Math.Max(A[0], B[M / 2 - 2]), Math.Min(A[1], B[M / 2 + 1])); } int idxA = (N - 1) / 2; int idxB = (M - 1) / 2; /* * if A[idxA] <= B[idxB], then median must exist in A[idxA....] and B[....idxB] */ if (A[idxA] <= B[idxB]) return findMedianUtil(copyOfRange(A, idxA, A.Length), N / 2 + 1, B, M - idxA); /* * if A[idxA] > B[idxB], then median must exist in A[...idxA] and B[idxB....] */ return findMedianUtil(A, N / 2 + 1, copyOfRange(B, idxB, B.Length), M - idxA); } // A wrapper function around findMedianUtil(). This function // makes sure that smaller array is passed as first argument // to findMedianUtil static float findMedian(int[] A, int N, int[] B, int M) { if (N > M) return findMedianUtil(B, M, A, N); return findMedianUtil(A, N, B, M); } // Driver code static void Main() { int[] A = { 900 }; int[] B = { 5, 8, 10, 20 }; int N = A.Length; int M = B.Length; Console.WriteLine(findMedian(A, N, B, M)); }} // This code is contributed by divyeshrabadiya07", "e": 71104, "s": 65823, "text": null }, { "code": "<?php// A PHP program to find median// of two sorted arrays of// unequal sizes // A utility function to// find median of two integersfunction MO2($a, $b){ return ($a + $b) / 2.0;} // A utility function to// find median of three integersfunction MO3($a, $b, $c){ return $a + $b + $c - max($a, max($b, $c)) - min($a, min($b, $c));} // A utility function to find// median of four integersfunction MO4($a, $b, $c, $d){ $Max = max($a, max($b, max($c, $d))); $Min = min($a, min($b, min( $c, $d))); return ($a + $b + $c + $d - $Max - $Min) / 2.0;} // Utility function to// find median of single arrayfunction medianSingle($arr, $n){if ($n == 0) return -1;if ($n % 2 == 0) return ($arr[$n / 2] + $arr[$n / 2 - 1]) / 2;return $arr[$n / 2];} // This function assumes that N// is smaller than or equal to M// This function returns -1 if// both arrays are emptyfunction findMedianUtil(&$A, $N, &$B, $M ){ // If smaller array is empty, // return median from second array if ($N == 0) return medianSingle($B, $M); // If the smaller array // has only one element if ($N == 1) { // Case 1: If the larger // array also has one // element, simply call MO2() if ($M == 1) return MO2($A[0], $B[0]); // Case 2: If the larger array // has odd number of elements, // then consider the middle 3 // elements of larger array and // the only element of smaller // array. Take few examples // like following // $A = array(9), // $B = array(5, 8, 10, 20, 30) // and $A = array(1), // $B = array(5, 8, 10, 20, 30) if ($M & 1) return MO2($B[$M / 2], $MO3($A[0], $B[$M / 2 - 1], $B[$M / 2 + 1])); // Case 3: If the larger array // has even number of element, // then median will be one of // the following 3 elements // ... The middle two elements // of larger array // ... The only element of // smaller array return MO3($B[$M / 2], $B[$M / 2 - 1], $A[0]); } // If the smaller array // has two elements else if ($N == 2) { // Case 4: If the larger // array also has two elements, // simply call MO4() if ($M == 2) return MO4($A[0], $A[1], $B[0], $B[1]); // Case 5: If the larger array // has odd number of elements, // then median will be one of // the following 3 elements // 1. Middle element of // larger array // 2. Max of first element of // smaller array and element // just before the middle // in bigger array // 3. Min of second element // of smaller array and element // just after the middle // in bigger array if ($M & 1) return MO3 ($B[$M / 2], max($A[0], $B[$M / 2 - 1]), min($A[1], $B[$M / 2 + 1])); // Case 6: If the larger array // has even number of elements, // then median will be one of // the following 4 elements // 1) & 2) The middle two // elements of larger array // 3) Max of first element of // smaller array and element // just before the first middle // element in bigger array // 4. Min of second element of // smaller array and element // just after the second // middle in bigger array return MO4 ($B[$M / 2], $B[$M / 2 - 1], max($A[0], $B[$M / 2 - 2]), min($A[1], $B[$M / 2 + 1])); } $idxA = ($N - 1 ) / 2; $idxB = ($M - 1 ) / 2; /* if $A[$idxA] <= $B[$idxB], then median must exist in $A[$idxA....] and $B[....$idxB] */ if ($A[$idxA] <= $B[$idxB] ) return findMedianUtil($A + $idxA, $N / 2 + 1, $B, $M - $idxA ); /* if $A[$idxA] > $B[$idxB], then median must exist in $A[...$idxA] and $B[$idxB....] */ return findMedianUtil($A, $N/2 + 1, $B + $idxA, $M - $idxA );} // A wrapper function around// findMedianUtil(). This// function makes sure that// smaller array is passed as// first argument to findMedianUtilfunction findMedian(&$A, $N, &$B, $M ){ if ($N > $M) return findMedianUtil($B, $M, $A, $N ); return findMedianUtil($A, $N, $B, $M );} // Driver Code$A = array(900);$B = array(5, 8, 10, 20); $N = sizeof($A);$M = sizeof($B); echo findMedian( $A, $N, $B, $M ); // This code is contributed// by ChitraNayal?>", "e": 75881, "s": 71104, "text": null }, { "code": "<script>// A Javascript program to find median of two sorted arrays of// unequal sizes // A utility function to find median of two integersfunction MO2(a,b){ return ((a + b) / 2.0);} // A utility function to find median of three integersfunction MO3(a, b, c){ return a + b + c - Math.max(a, Math.max(b, c)) - Math.min(a, Math.min(b, c));} // A utility function to find a median of four integersfunction MO4(a, b, c, d){ let Max = Math.max(a, Math.max(b, Math.max(c, d))); let Min = Math.min(a, Math.min(b, Math.min(c, d))); return ((a + b + c + d - Max - Min) / 2.0);} // Utility function to find median of single arrayfunction medianSingle(arr, n){ if (n == 0) return -1; if (n % 2 == 0) return ( (arr[n / 2] + arr[n / 2 - 1]) / 2); return arr[n / 2];} // This function assumes that N is smaller than or equal to M // This function returns -1 if both arrays are emptyfunction findMedianUtil(A, N, B, M){ // If smaller array is empty, return median from second array if (N == 0) return medianSingle(B, M); // If the smaller array has only one element if (N == 1) { // Case 1: If the larger array also has one element, // simply call MO2() if (M == 1) return MO2(A[0], B[0]); // Case 2: If the larger array has odd number of elements, // then consider the middle 3 elements of larger array and // the only element of smaller array. Take few examples // like following // A = {9}, B[] = {5, 8, 10, 20, 30} and // A[] = {1}, B[] = {5, 8, 10, 20, 30} if (M % 2 == 1) return MO2(B[M / 2], MO3(A[0], B[M / 2 - 1], B[M / 2 + 1])); // Case 3: If the larger array has even number of element, // then median will be one of the following 3 elements // ... The middle two elements of larger array // ... The only element of smaller array return MO3(B[M / 2], B[M / 2 - 1], A[0]); } // If the smaller array has two elements else if (N == 2) { // Case 4: If the larger array also has two elements, // simply call MO4() if (M == 2) return MO4(A[0], A[1], B[0], B[1]); // Case 5: If the larger array has odd number of elements, // then median will be one of the following 3 elements // 1. Middle element of larger array // 2. Max of first element of smaller array and element // just before the middle in bigger array // 3. Min of second element of smaller array and element // just after the middle in bigger array if (M % 2 == 1) return MO3(B[M / 2], Math.max(A[0], B[M / 2 - 1]), Math.min(A[1], B[M / 2 + 1])); // Case 6: If the larger array has even number of elements, // then median will be one of the following 4 elements // 1) & 2) The middle two elements of larger array // 3) Max of first element of smaller array and element // just before the first middle element in bigger array // 4. Min of second element of smaller array and element // just after the second middle in bigger array return MO4(B[M / 2], B[M / 2 - 1], Math.max(A[0], B[M / 2 - 2]), Math.min(A[1], B[M / 2 + 1])); } let idxA = (N - 1) / 2; let idxB = (M - 1) / 2; /* * if A[idxA] <= B[idxB], then median must exist in A[idxA....] and B[....idxB] */ if (A[idxA] <= B[idxB]) return findMedianUtil(A.slice(idxA, A.length), N / 2 + 1, B, M - idxA); /* * if A[idxA] > B[idxB], then median must exist in A[...idxA] and B[idxB....] */ return findMedianUtil(A, N / 2 + 1, B.slice( idxB, B.length), M - idxA);} // A wrapper function around findMedianUtil(). This function // makes sure that smaller array is passed as first argument // to findMedianUtilfunction findMedian(A,N,B,M){ if (N > M) return findMedianUtil(B, M, A, N); return findMedianUtil(A, N, B, M);} // Driver program to test above functionslet A = [ 900];let B = [5, 8, 10, 20];let N = A.length;let M = B.length;document.write(findMedian(A, N, B, M)); // This code is contributed by avanitrachhadiya2155</script>", "e": 80533, "s": 75881, "text": null }, { "code": null, "e": 80543, "s": 80533, "text": "10.000000" }, { "code": null, "e": 80565, "s": 80543, "text": "Complexity Analysis: " }, { "code": null, "e": 80730, "s": 80565, "text": "Time Complexity: O(min(log m, log n)). In each step one half of each array is discarded. So the algorithm takes O(min(log m, log n)) time to reach the median value." }, { "code": null, "e": 80782, "s": 80730, "text": "Space Complexity: O(1). No extra space is required." }, { "code": null, "e": 80825, "s": 80782, "text": "Solution 3 : Simple Mathematical Approach " }, { "code": null, "e": 81045, "s": 80825, "text": "Approach: The given two arrays are sorted, so we need to merge them into a third array using the method System.arraycopy(src, srcPos, dest, destPos, length) and then sort the third array using Arrays.sort(array) method." }, { "code": null, "e": 81192, "s": 81045, "text": "1. Case 1: If the length of the third array is odd, then the median is at (length)/2 th index in the array obtained after merging both the arrays." }, { "code": null, "e": 81390, "s": 81192, "text": "2. Case 2: If the length of the third array is even, then the median will be the average of elements at index ((length)/2 ) and ((length)/2 – 1) in the array obtained after merging both the arrays." }, { "code": null, "e": 81744, "s": 81390, "text": "1. Merge the two given arrays into one array.\n2. Then sort the third(merged) array\n3. If the length of the third array is even then :\n divide the length of array by 2\n return arr[value] + arr[value - 1] / 2\n \n4. If the length of the third array is odd then :\n divide the length of array by 2\n round that value \n return the arr[value] " }, { "code": null, "e": 81748, "s": 81744, "text": "C++" }, { "code": null, "e": 81753, "s": 81748, "text": "Java" }, { "code": null, "e": 81761, "s": 81753, "text": "Python3" }, { "code": null, "e": 81764, "s": 81761, "text": "C#" }, { "code": null, "e": 81775, "s": 81764, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; int Solution(int arr[], int n){ // If length of array is even if (n % 2 == 0) { int z = n / 2; int e = arr[z]; int q = arr[z - 1]; int ans = (e + q) / 2; return ans; } // If length if array is odd else { int z = round(n / 2); return arr[z]; }} // Driver Codeint main() { // TODO Auto-generated method stub int arr1[] = { -5, 3, 6, 12, 15 }; int arr2[] = { -12, -10, -6, -3, 4, 10 }; int i = sizeof(arr1) / sizeof(arr1[0]); int j = sizeof(arr2) / sizeof(arr2[0]); int arr3[i+j]; int l = i+j; // Merge two array into one array for(int k=0;k<i;k++) { arr3[k]=arr1[k]; } int a=0; for(int k=i;k<l;k++) { arr3[k]=arr2[a++]; } // Sort the merged array sort(arr3,arr3+l); // calling the method cout<<\"Median = \" << Solution(arr3, l);} // This code is contributed by SoumikMondal", "e": 82884, "s": 81775, "text": null }, { "code": "// Java program for the above approachimport java.io.*;import java.util.Arrays; public class GFG { public static int Solution(int[] arr) { int n = arr.length; // If length of array is even if (n % 2 == 0) { int z = n / 2; int e = arr[z]; int q = arr[z - 1]; int ans = (e + q) / 2; return ans; } // If length if array is odd else { int z = Math.round(n / 2); return arr[z]; } } // Driver Code public static void main(String[] args) { // TODO Auto-generated method stub int[] arr1 = { -5, 3, 6, 12, 15 }; int[] arr2 = { -12, -10, -6, -3, 4, 10 }; int i = arr1.length; int j = arr2.length; int[] arr3 = new int[i + j]; // Merge two array into one array System.arraycopy(arr1, 0, arr3, 0, i); System.arraycopy(arr2, 0, arr3, i, j); // Sort the merged array Arrays.sort(arr3); // calling the method System.out.print(\"Median = \" + Solution(arr3)); }}// This code is contributed by Manas Tole", "e": 84052, "s": 82884, "text": null }, { "code": "# Python3 program for the above approachdef Solution(arr): n = len(arr) # If length of array is even if n % 2 == 0: z = n // 2 e = arr[z] q = arr[z - 1] ans = (e + q) / 2 return ans # If length of array is odd else: z = n // 2 ans = arr[z] return ans # Driver codeif __name__ == \"__main__\": arr1 = [ -5, 3, 6, 12, 15 ] arr2 = [ -12, -10, -6, -3, 4, 10 ] # Concatenating the two arrays arr3 = arr1 + arr2 # Sorting the resultant array arr3.sort() print(\"Median = \", Solution(arr3)) # This code is contributed by kush11", "e": 84685, "s": 84052, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; public class GFG { public static int Solution(int[] arr) { int n = arr.Length; // If length of array is even if (n % 2 == 0) { int z = n / 2; int e = arr[z]; int q = arr[z - 1]; int ans = (e + q) / 2; return ans; } // If length if array is odd else { int z = n / 2; return arr[z]; } } // Driver Code static public void Main (){ // TODO Auto-generated method stub int[] arr1 = { -5, 3, 6, 12, 15 }; int[] arr2 = { -12, -10, -6, -3, 4, 10 }; // Merge two array into one array var myList = new List<int>(); myList.AddRange(arr1); myList.AddRange(arr2); int[] arr3 = myList.ToArray(); // Sort the merged array Array.Sort(arr3); // calling the method Console.Write(\"Median = \" + Solution(arr3)); }} // This code is contributed by Shubhamsingh10", "e": 85794, "s": 84685, "text": null }, { "code": "<script>// Javascript program for the above approach function Solution(arr, n){ // If length of array is even if (n % 2 == 0) { var z = n / 2; var e = arr[z]; var q = arr[z - 1]; var ans = (e + q) / 2; return ans; } // If length if array is odd else { var z = Math.floor(n / 2); return arr[z]; }} // Driver Code // TODO Auto-generated method stubvar arr1 = [ -5, 3, 6, 12, 15 ];var arr2 = [ -12, -10, -6, -3, 4, 10 ]; var i = arr1.length;var j = arr2.length; var l = i+j;// Merge two array into one arrayconst arr3 = arr1.concat(arr2); // Sort the merged arrayarr3.sort(function(a, b) { return a - b;}); // calling the methoddocument.write(\"Median = \" + Solution(arr3, l)); // This code is contributed by Shubham Singh</script>", "e": 86605, "s": 85794, "text": null }, { "code": null, "e": 86619, "s": 86608, "text": "Median = 3" }, { "code": null, "e": 86643, "s": 86621, "text": "Complexity Analysis :" }, { "code": null, "e": 86681, "s": 86645, "text": "Time Complexity: O((n+m) Log (n+m))" }, { "code": null, "e": 86754, "s": 86681, "text": "Space Complexity: O(n+m). Since we are creating a new array of size n+m." }, { "code": null, "e": 86783, "s": 86756, "text": "Solution 4 : Binary Search" }, { "code": null, "e": 86916, "s": 86785, "text": "Approach: The given two arrays are sorted, so we can utilize the ability of Binary Search to divide the array and find the median." }, { "code": null, "e": 87178, "s": 86918, "text": "Median means the point at which the whole array is divide into two parts. Hence since the two arrays are not merged so to get the median we require merging which is costly. Hence instead of merging we will use below given algorithm to efficiently find median." }, { "code": null, "e": 87191, "s": 87180, "text": "Algorithm:" }, { "code": null, "e": 89652, "s": 87193, "text": "1. Lets assume that there are two arrays A and B with array A having the minimum number of elements.\n If this is not the case then swap A and B to make A having small size.\n2. The edge cases like one array is empty or both are empty will be handled.\n3. let n be the size of A and m be the size of B.\n Now think of an idea that if we have to find the median than we have to divide the whole merged array into two parts\n namely left and right parts.\n Now since we are given the size of left part (i.e (n+m+1)/2), Now look at below given example.\n \n A-> 1,2,3,4,5 n = 5\n B-> 1,2,3,4,5,6 m = 6\n \n Here merged array will look like :- 1,1,2,2,3,3,4,4,5,5,6 and median then is 3\n \n Now we can see our left part which is underlined. We divide A and B into two parts such that the \n sum of left part of both A and B will result in left part of merged array.\n \n A-> 1,2,3,4,5 // pointers l =0 and r = n-1 hence mid = (l+r)/2;\n B -> 1,2,3,4,5,6\n\n we can see that left part of A is given as n/2 and since total length of left part in merged array\n is (m+n+1)/2, so left part of B = (m+n+1)/2-n/2;\n \n Now we just have to confirm if our left and right partitions in A and B are correct or not.\n \n4. Now we have 4 variables indicating four values two from array A and two from array B.\n leftA -> Rightmost element in left part of A = 2\n leftb -> Rightmost element in left part of B = 4\n rightA -> Leftmost element in right part of A = 3\n rightB -> Leftmost element in right part of B = 5\n \n Hence to confirm that partition is correct we have to check the following conditions.\n leftA<=rightB and leftB<=rightA // This is the case when the sum of two parts of A and B results in left part of merged array\n \n if our partition not works that means we have to find other mid point in A and then left part in B\n This is seen when\n \n leftA > rightB //means we have to dec size of A's partition\n so do r = mid-1;\n else\n do l =mid+1;\n \n Hence repeat the above steps with new partitions till we get the answers.\n5. If leftA<=rightB and leftB<=rightA\n then we get correct partition and our answer depends on the total size of merged array (i.e. m+n)\n \n If (m+n)%2==0\n ans is max(leftA,leftB)+min(rightA,rightB)/2; // max of left part is nearest to median and min of right part is nearest to medain\n else\n ans is max(leftA,leftB);" }, { "code": null, "e": 89696, "s": 89654, "text": "Hence the above algorithm can be coded as" }, { "code": null, "e": 89702, "s": 89698, "text": "C++" }, { "code": null, "e": 89707, "s": 89702, "text": "Java" }, { "code": null, "e": 89715, "s": 89707, "text": "Python3" }, { "code": null, "e": 89718, "s": 89715, "text": "C#" }, { "code": null, "e": 89729, "s": 89718, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // Method to find mediandouble Median(vector<int>& A, vector<int>& B){ int n = A.size(); int m = B.size(); if (n > m) return Median(B, A); // Swapping to make A smaller int start = 0; int end = n; int realmidinmergedarray = (n + m + 1) / 2; while (start <= end) { int mid = (start + end) / 2; int leftAsize = mid; int leftBsize = realmidinmergedarray - mid; int leftA = (leftAsize > 0) ? A[leftAsize - 1] : INT_MIN; // checking overflow of indices int leftB = (leftBsize > 0) ? B[leftBsize - 1] : INT_MIN; int rightA = (leftAsize < n) ? A[leftAsize] : INT_MAX; int rightB = (leftBsize < m) ? B[leftBsize] : INT_MAX; // if correct partition is done if (leftA <= rightB and leftB <= rightA) { if ((m + n) % 2 == 0) return (max(leftA, leftB) + min(rightA, rightB)) / 2.0; return max(leftA, leftB); } else if (leftA > rightB) { end = mid - 1; } else start = mid + 1; } return 0.0;} // Driver codeint main(){ vector<int> arr1 = { -5, 3, 6, 12, 15 }; vector<int> arr2 = { -12, -10, -6, -3, 4, 10 }; cout << \"Median of the two arrays are\" << endl; cout << Median(arr1, arr2); return 0;}", "e": 91179, "s": 89729, "text": null }, { "code": "public class GFG { // Method to find median static double Median(int[] A, int[] B) { int n = A.length; int m = B.length; if (n > m) return Median(B, A); // Swapping to make A smaller int start = 0; int end = n; int realmidinmergedarray = (n + m + 1) / 2; while (start <= end) { int mid = (start + end) / 2; int leftAsize = mid; int leftBsize = realmidinmergedarray - mid; int leftA = (leftAsize > 0) ? A[leftAsize - 1] : Integer.MIN_VALUE; // checking overflow of indices int leftB = (leftBsize > 0) ? B[leftBsize - 1] : Integer.MIN_VALUE; int rightA = (leftAsize < n) ? A[leftAsize] : Integer.MAX_VALUE; int rightB = (leftBsize < m) ? B[leftBsize] : Integer.MAX_VALUE; // if correct partition is done if (leftA <= rightB && leftB <= rightA) { if ((m + n) % 2 == 0) return (Math.max(leftA, leftB) + Math.min(rightA, rightB)) / 2.0; return Math.max(leftA, leftB); } else if (leftA > rightB) { end = mid - 1; } else start = mid + 1; } return 0.0; } // Driver code public static void main(String[] args) { int[] arr1 = { -5, 3, 6, 12, 15 }; int[] arr2 = { -12, -10, -6, -3, 4, 10 }; System.out.println(\"Median of the two arrays are\"); System.out.println(Median(arr1, arr2)); }} // This code is contributed by Hritik", "e": 92904, "s": 91179, "text": null }, { "code": "class Solution: # Method to find median def Median(self, A, B): # Assumption both A and B cannot be empty n = len(A) m = len(B) if (n > m): return self.Median(B, A) # Swapping to make A smaller start = 0 end = n realmidinmergedarray = (n + m + 1) // 2 while (start <= end): mid = (start + end) // 2 leftAsize = mid leftBsize = realmidinmergedarray - mid # checking overflow of indices leftA = A[leftAsize - 1] if (leftAsize > 0) else float('-inf') leftB = B[leftBsize - 1] if (leftBsize > 0) else float('-inf') rightA = A[leftAsize] if (leftAsize < n) else float('inf') rightB = B[leftBsize] if (leftBsize < m) else float('inf') # if correct partition is done if leftA <= rightB and leftB <= rightA: if ((m + n) % 2 == 0): return (max(leftA, leftB) + min(rightA, rightB)) / 2.0 return max(leftA, leftB) elif (leftA > rightB): end = mid - 1 else: start = mid + 1 # Driver codeans = Solution()arr1 = [-5, 3, 6, 12, 15]arr2 = [-12, -10, -6, -3, 4, 10]print(\"Median of the two arrays is {}\".format(ans.Median(arr1, arr2))) # This code is contributed by Arpan", "e": 94271, "s": 92904, "text": null }, { "code": "using System; public class GFG { // Method to find median static double Median(int[] A, int[] B) { int n = A.Length; int m = B.Length; if (n > m) return Median(B, A); // Swapping to make A smaller int start = 0; int end = n; int realmidinmergedarray = (n + m + 1) / 2; while (start <= end) { int mid = (start + end) / 2; int leftAsize = mid; int leftBsize = realmidinmergedarray - mid; int leftA = (leftAsize > 0) ? A[leftAsize - 1] : Int32.MinValue; // checking overflow of indices int leftB = (leftBsize > 0) ? B[leftBsize - 1] : Int32.MinValue; int rightA = (leftAsize < n) ? A[leftAsize] : Int32.MaxValue; int rightB = (leftBsize < m) ? B[leftBsize] : Int32.MaxValue; // if correct partition is done if (leftA <= rightB && leftB <= rightA) { if ((m + n) % 2 == 0) return (Math.Max(leftA, leftB) + Math.Min(rightA, rightB)) / 2.0; return Math.Max(leftA, leftB); } else if (leftA > rightB) { end = mid - 1; } else start = mid + 1; } return 0.0; } // Driver code public static void Main() { int[] arr1 = { -5, 3, 6, 12, 15 }; int[] arr2 = { -12, -10, -6, -3, 4, 10 }; Console.WriteLine(\"Median of the two arrays are\"); Console.WriteLine(Median(arr1, arr2)); }} // This code is contributed by Shubham Singh", "e": 95704, "s": 94271, "text": null }, { "code": "<script> // JavaScript Program to implement // the above approach // Method to find median function Median(A, B) { let n = A.length; let m = B.length; if (n > m) return Median(B, A); // Swapping to make A smaller let start = 0; let end = n; let realmidinmergedarray = Math.floor((n + m + 1) / 2); while (start <= end) { let mid = Math.floor((start + end) / 2); let leftAsize = mid; let leftBsize = realmidinmergedarray - mid; let leftA = (leftAsize > 0) ? A[leftAsize - 1] : Number.MIN_VALUE; // checking overflow of indices let leftB = (leftBsize > 0) ? B[leftBsize - 1] : INT_MIN; let rightA = (leftAsize < n) ? A[leftAsize] : INT_MAX; let rightB = (leftBsize < m) ? B[leftBsize] : INT_MAX; // if correct partition is done if (leftA <= rightB && leftB <= rightA) { if ((m + n) % 2 == 0) return Math.floor((Math.max(leftA, leftB) + Math.min(rightA, rightB)) / 2.0); return Math.max(leftA, leftB); } else if (leftA > rightB) { end = mid - 1; } else start = mid + 1; } return 0.0; } // Driver code let arr1 = [-5, 3, 6, 12, 15]; let arr2 = [-12, -10, -6, -3, 4, 10]; document.write(\"Median of the two arrays are\" + \"<br>\"); document.write(Median(arr1, arr2)) // This code is contributed by Potta Lokesh </script>", "e": 97578, "s": 95704, "text": null }, { "code": null, "e": 97612, "s": 97581, "text": "Median of the two arrays are\n3" }, { "code": null, "e": 97743, "s": 97614, "text": "Time Complexity: O(min(log m, log n)) : Since binary search is being applied on the smaller of the 2 arraysAuxiliary Space: O(1)" }, { "code": null, "e": 97751, "s": 97745, "text": "ukasp" }, { "code": null, "e": 97758, "s": 97751, "text": "pratil" }, { "code": null, "e": 97769, "s": 97758, "text": "Raj Bansal" }, { "code": null, "e": 97781, "s": 97769, "text": "AkshAyMore2" }, { "code": null, "e": 97795, "s": 97781, "text": "rathbhupendra" }, { "code": null, "e": 97806, "s": 97795, "text": "ankush_953" }, { "code": null, "e": 97817, "s": 97806, "text": "andrew1234" }, { "code": null, "e": 97830, "s": 97817, "text": "Akanksha_Rai" }, { "code": null, "e": 97846, "s": 97830, "text": "nsit_changeable" }, { "code": null, "e": 97858, "s": 97846, "text": "ysinghal555" }, { "code": null, "e": 97871, "s": 97858, "text": "princi singh" }, { "code": null, "e": 97889, "s": 97871, "text": "divyeshrabadiya07" }, { "code": null, "e": 97903, "s": 97889, "text": "divyesh072019" }, { "code": null, "e": 97915, "s": 97903, "text": "manastole01" }, { "code": null, "e": 97929, "s": 97915, "text": "saipraveenm99" }, { "code": null, "e": 97938, "s": 97929, "text": "mukesh07" }, { "code": null, "e": 97951, "s": 97938, "text": "SoumikMondal" }, { "code": null, "e": 97963, "s": 97951, "text": "vilajaxmyai" }, { "code": null, "e": 97970, "s": 97963, "text": "kush11" }, { "code": null, "e": 97991, "s": 97970, "text": "avanitrachhadiya2155" }, { "code": null, "e": 98006, "s": 97991, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 98029, "s": 98006, "text": "harshkumarchoudhary144" }, { "code": null, "e": 98042, "s": 98029, "text": "hritikrommie" }, { "code": null, "e": 98052, "s": 98042, "text": "ruhelaa48" }, { "code": null, "e": 98065, "s": 98052, "text": "namanbansal4" }, { "code": null, "e": 98078, "s": 98065, "text": "arpansheetal" }, { "code": null, "e": 98092, "s": 98078, "text": "lokeshpotta20" }, { "code": null, "e": 98102, "s": 98092, "text": "rajesh999" }, { "code": null, "e": 98112, "s": 98102, "text": "anuragncp" }, { "code": null, "e": 98126, "s": 98112, "text": "architgwl2000" }, { "code": null, "e": 98140, "s": 98126, "text": "Binary Search" }, { "code": null, "e": 98155, "s": 98140, "text": "median-finding" }, { "code": null, "e": 98178, "s": 98155, "text": "statistical-algorithms" }, { "code": null, "e": 98197, "s": 98178, "text": "Divide and Conquer" }, { "code": null, "e": 98207, "s": 98197, "text": "Searching" }, { "code": null, "e": 98217, "s": 98207, "text": "Searching" }, { "code": null, "e": 98236, "s": 98217, "text": "Divide and Conquer" }, { "code": null, "e": 98250, "s": 98236, "text": "Binary Search" }, { "code": null, "e": 98348, "s": 98250, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 98375, "s": 98348, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 98419, "s": 98375, "text": "Divide and Conquer Algorithm | Introduction" }, { "code": null, "e": 98457, "s": 98419, "text": "Write a program to calculate pow(x,n)" }, { "code": null, "e": 98518, "s": 98457, "text": "Count number of occurrences (or frequency) in a sorted array" }, { "code": null, "e": 98543, "s": 98518, "text": "Quick Sort vs Merge Sort" }, { "code": null, "e": 98557, "s": 98543, "text": "Linear Search" }, { "code": null, "e": 98605, "s": 98557, "text": "Search an element in a sorted and rotated array" }, { "code": null, "e": 98629, "s": 98605, "text": "Find the Missing Number" }, { "code": null, "e": 98685, "s": 98629, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" } ]
Extract images from video in Python - GeeksforGeeks
29 Aug, 2018 OpenCV comes with many powerful video editing functions. In current scenario, techniques such as image scanning, face recognition can be accomplished using OpenCV. Image Analysis is a very common field in the area of Computer Vision. It is the extraction of meaningful information from videos or images. OpenCv library can be used to perform multiple operations on videos. Modules Needed: import cv2 import os Function Used : VideoCapture(File_path) : Read the video(.mp4 format) read() : Read data depending upon the type of object that calls imwrite(filename, img[, params]) : Saves an image to a specified file. Below is the implementation: # Importing all necessary librariesimport cv2import os # Read the video from specified pathcam = cv2.VideoCapture("C:\\Users\\Admin\\PycharmProjects\\project_1\\openCV.mp4") try: # creating a folder named data if not os.path.exists('data'): os.makedirs('data') # if not created then raise errorexcept OSError: print ('Error: Creating directory of data') # framecurrentframe = 0 while(True): # reading from frame ret,frame = cam.read() if ret: # if video is still left continue creating images name = './data/frame' + str(currentframe) + '.jpg' print ('Creating...' + name) # writing the extracted images cv2.imwrite(name, frame) # increasing counter so that it will # show how many frames are created currentframe += 1 else: break # Release all space and windows once donecam.release()cv2.destroyAllWindows() Output: All the extracted images will be saved in a folder named “data” on the system. Image-Processing OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace()
[ { "code": null, "e": 42714, "s": 42686, "text": "\n29 Aug, 2018" }, { "code": null, "e": 42878, "s": 42714, "text": "OpenCV comes with many powerful video editing functions. In current scenario, techniques such as image scanning, face recognition can be accomplished using OpenCV." }, { "code": null, "e": 43087, "s": 42878, "text": "Image Analysis is a very common field in the area of Computer Vision. It is the extraction of meaningful information from videos or images. OpenCv library can be used to perform multiple operations on videos." }, { "code": null, "e": 43103, "s": 43087, "text": "Modules Needed:" }, { "code": null, "e": 43125, "s": 43103, "text": "import cv2\nimport os\n" }, { "code": null, "e": 43141, "s": 43125, "text": "Function Used :" }, { "code": null, "e": 43195, "s": 43141, "text": "VideoCapture(File_path) : Read the video(.mp4 format)" }, { "code": null, "e": 43259, "s": 43195, "text": "read() : Read data depending upon the type of object that calls" }, { "code": null, "e": 43330, "s": 43259, "text": "imwrite(filename, img[, params]) : Saves an image to a specified file." }, { "code": null, "e": 43359, "s": 43330, "text": "Below is the implementation:" }, { "code": "# Importing all necessary librariesimport cv2import os # Read the video from specified pathcam = cv2.VideoCapture(\"C:\\\\Users\\\\Admin\\\\PycharmProjects\\\\project_1\\\\openCV.mp4\") try: # creating a folder named data if not os.path.exists('data'): os.makedirs('data') # if not created then raise errorexcept OSError: print ('Error: Creating directory of data') # framecurrentframe = 0 while(True): # reading from frame ret,frame = cam.read() if ret: # if video is still left continue creating images name = './data/frame' + str(currentframe) + '.jpg' print ('Creating...' + name) # writing the extracted images cv2.imwrite(name, frame) # increasing counter so that it will # show how many frames are created currentframe += 1 else: break # Release all space and windows once donecam.release()cv2.destroyAllWindows()", "e": 44283, "s": 43359, "text": null }, { "code": null, "e": 44291, "s": 44283, "text": "Output:" }, { "code": null, "e": 44370, "s": 44291, "text": "All the extracted images will be saved in a folder named “data” on the system." }, { "code": null, "e": 44387, "s": 44370, "text": "Image-Processing" }, { "code": null, "e": 44394, "s": 44387, "text": "OpenCV" }, { "code": null, "e": 44401, "s": 44394, "text": "Python" }, { "code": null, "e": 44499, "s": 44401, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44527, "s": 44499, "text": "Read JSON file using Python" }, { "code": null, "e": 44577, "s": 44527, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 44599, "s": 44577, "text": "Python map() function" }, { "code": null, "e": 44643, "s": 44599, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 44678, "s": 44643, "text": "Read a file line by line in Python" }, { "code": null, "e": 44710, "s": 44678, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 44732, "s": 44710, "text": "Enumerate() in Python" }, { "code": null, "e": 44774, "s": 44732, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 44804, "s": 44774, "text": "Iterate over a list in Python" } ]
Check if an Object is of Type Integer in R Programming - is.integer() Function - GeeksforGeeks
16 Jun, 2020 is.integer() function in R Language is used to check if the object passed to it as argument is of integer type. Syntax: is.integer(x) Parameters:x: Object to be checked Example 1: # R program to check if # object is an integer # Creating a vectorx1 <- 4Lx2 <- c(1:6)x3 <- c("a", "b", "c", "d")x4 <- c(1, 2, "a", 3, "b") # Calling is.integer() functionis.integer(x1)is.integer(x2)is.integer(x3)is.integer(x4) Output: [1] TRUE [1] TRUE [1] FALSE [1] FALSE Example 2: # R program to check if # object is an integer # Creating a matrixx1 <- matrix(c(1:9), 3, 3) # Calling is.integer() functionis.integer(x1) Output: [1] TRUE R List-Function R Math-Function R Matrix-Function R Object-Function R Vector-Function 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? R - if statement How to filter R dataframe by multiple conditions? Plot mean and standard deviation using ggplot2 in R How to import an Excel File into R ?
[ { "code": null, "e": 26487, "s": 26459, "text": "\n16 Jun, 2020" }, { "code": null, "e": 26599, "s": 26487, "text": "is.integer() function in R Language is used to check if the object passed to it as argument is of integer type." }, { "code": null, "e": 26621, "s": 26599, "text": "Syntax: is.integer(x)" }, { "code": null, "e": 26656, "s": 26621, "text": "Parameters:x: Object to be checked" }, { "code": null, "e": 26667, "s": 26656, "text": "Example 1:" }, { "code": "# R program to check if # object is an integer # Creating a vectorx1 <- 4Lx2 <- c(1:6)x3 <- c(\"a\", \"b\", \"c\", \"d\")x4 <- c(1, 2, \"a\", 3, \"b\") # Calling is.integer() functionis.integer(x1)is.integer(x2)is.integer(x3)is.integer(x4)", "e": 26897, "s": 26667, "text": null }, { "code": null, "e": 26905, "s": 26897, "text": "Output:" }, { "code": null, "e": 26944, "s": 26905, "text": "[1] TRUE\n[1] TRUE\n[1] FALSE\n[1] FALSE\n" }, { "code": null, "e": 26955, "s": 26944, "text": "Example 2:" }, { "code": "# R program to check if # object is an integer # Creating a matrixx1 <- matrix(c(1:9), 3, 3) # Calling is.integer() functionis.integer(x1)", "e": 27096, "s": 26955, "text": null }, { "code": null, "e": 27104, "s": 27096, "text": "Output:" }, { "code": null, "e": 27114, "s": 27104, "text": "[1] TRUE\n" }, { "code": null, "e": 27130, "s": 27114, "text": "R List-Function" }, { "code": null, "e": 27146, "s": 27130, "text": "R Math-Function" }, { "code": null, "e": 27164, "s": 27146, "text": "R Matrix-Function" }, { "code": null, "e": 27182, "s": 27164, "text": "R Object-Function" }, { "code": null, "e": 27200, "s": 27182, "text": "R Vector-Function" }, { "code": null, "e": 27211, "s": 27200, "text": "R Language" }, { "code": null, "e": 27309, "s": 27211, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27361, "s": 27309, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27396, "s": 27361, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27434, "s": 27396, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27492, "s": 27434, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27535, "s": 27492, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 27584, "s": 27535, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27601, "s": 27584, "text": "R - if statement" }, { "code": null, "e": 27651, "s": 27601, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 27703, "s": 27651, "text": "Plot mean and standard deviation using ggplot2 in R" } ]
Image Classification of PCBs and its Web Application (Flask) | by Utkarsh Ankit | Towards Data Science
Hello, This blog is about creating an Image Classification model for PCBs(Printed Circuit boards) to detect defective PCBs and classify them as Good or Bad. So for that, we will create a Deep Learning Model and try to get the best possible results along with proper visualisation of each step. After creating the working model, we will create a Web Application for the same using Flask. You can find the code for this project on my GitHub along with the setup instruction file below. So, let’s go ahead and flex. Requirements Jupyter NotebookPython 3.5 or Later. (3.7 preferable)Libraries — Tensorflow, Keras, Pandas, Numpy, Matplotlib, OpenCV, Pillow, Flask. [all latest version] Jupyter Notebook Python 3.5 or Later. (3.7 preferable) Libraries — Tensorflow, Keras, Pandas, Numpy, Matplotlib, OpenCV, Pillow, Flask. [all latest version] Understanding the Dataset PCBs (Printed Circuit Boards) is a widely used electronic component, used almost in any electronic device. Sometimes during its mass production in factories leads to some anomalies which lead to a defective product. Electronic companies have to bear that loss. So this deep learning Image Classification model helps to identify Good and Bad Circuits at production time only. So, the dataset we are using is a binary image of PCB, in which the Black part denotes the circuit and the white parts signify the empty circuit areas. The dots or noise in the image shows the anomalies. As we can see the image has no anomalies and defects in it. Now, we will see another image of a PCB with defects. As here the defects are marked, it is an example of a defective PCB. You can download the dataset from here. Data Preparation/Preprocessing Now after we download the dataset, we can see the dimension of each image is 640x640. It will be better if we reduce the dimension of them so that it will be easy for training the data, but to make sure the quality of the image didn’t get affected, we will compress the image using the Anti-Aliasing technique. Here is my link to my GitHub repo which helps to do the same. Use the Image Resizer tool there and you will get the desired result. So, after resizing the image to 224x224, we save them into a different folder. I saved 1,095 images of somewhat equally mixed good and bad PCBs. So, that folder is going to be your Training Data set. Pick some other images (different from the training set) and put them into a separate folder to work as your Test Data set. Make sure the test folder is a good mixture of good and bad images with a proper ratio maintained. Now I will check my training dataset that it has a proper ratio of both types of images or in other words, to check the possible “class imbalance”. Well for my reference, I named the good PCB image as Good().jpeg and bad as Bad().jpeg. Then I labelled the good images as ‘0’ and bad images as ‘1’. And then we plot their graph:- So, we can observe from the graph that our classes are pretty balance. Now for Cross-Validation, we will split out the training dataset into training and validation sets. As I mentioned earlier I took 1,095 images. I split them as 80% training data and 20% validation set. train_df, validate_df = train_test_split(df, test_size=0.20, random_state=42)train_df = train_df.reset_index(drop=True)validate_df = validate_df.reset_index(drop=True) And then we plot both training and testing image ratios:- ⇙ This is the plotted graph of the final “training dataset”, i.e. approximately 400+ images in both classes. ⇖ ⇙ This is the plotted graph of the “validation dataset”, i.e. approximately 100+ images in both classes. ⇖ ___ Now I am going to apply one of the greatest tools according to me i.e. Keras ImageDataGenerator. It is a very useful tool as it helps to do Data Augmentation in real-time while training the model. As we know our training data is already less, so applying augmentation not only helps us to make our model robust but also saves memory. Now, we add the path and load the images in the generator. So, now we can say that our Data Preparation/Preprocessing part is complete. Model Implementation Now it’s time to design the brain. Here I used the “MobileNet” model which is pre-trained on the ImageNet dataset. Well, MobileNet is a Deep Learning based Convolution Neural Network Architecture. It is a lightweight architecture and uses depthwise separable convolutions. You can learn more about it from its paper here. As I mentioned we are using the MobileNet model pre-trained of ImageNet Dataset, so here we are using the concept of Transfer Learning. Therefore instead of training the whole model, we will freeze the base layer and add some other layers according to our requirements. As we are using pre-trained weights, we will make sure that all the weights are non-trainable except the last few dense layers. Well, I set the first 20 layers to be non-trainable. for layer in model.layers[:20]: layer.trainable=Falsefor layer in model.layers[20:]: layer.trainable=True But if you want to set all layers to be non-trainable, you can use this instead. for layer in model.layers: layer.trainable=False So, we are done with the Model Implementation part now. Training So, our data preparation is done along with model implementation. Now, it’s time to train our model. Before I proceed further, I want to mention that I used two Callbacks named “Early Stopping” and “Learning Rate Reduction”. We need to consider the number of Epochs carefully as too many of them lead to overfitting the data, whereas too few leads to underfitting. Early Stopping allows you to specify an arbitrarily large number of training epochs and stop training when the model stops improving on a hold out validation dataset. Here is a link if you want to learn more about it. ReduceLROnPlateau reduces the Learning Rate when a metric is stopped improving. Models often benefit from reducing the learning rate by a factor of 2–10 once learning stagnates. This callback monitors a quantity and if no improvement is seen for a ‘patience’ number of epochs, the learning rate is reduced. You can check this from here. Now, we will start training our model. Well, I trained my model on Google Colab as it gives certain advantages, I will advise everyone to try to use Google Colab, you just need to upload or link the dataset on google drive and then mount it on colab using this simple call by giving right folder location:- from google.colab import drivedrive.mount('/content/drive') Now we will set all the variables in the model.fit.generator() and then we will start to train our model. Well, I set my epoch as 50 but it stopped it at 42 as it stops improving. I plotted two graphs from the data we extracted while training the model. . ⇙ “Loss vs Epochs” graph. ⇖ . ⇙ “Accuracy vs Epochs” graph. ⇖ . Note:- The Blue line denotes the training and Red line denotes the validation variable respectively in both the graphs. So, after training the model, I got a Validation Accuracy of 95.71%. Now, we save the trained weights in the .h5 or .hdf5 file (both are the same). model.save_weights("model.h5") If you trained it via Google Colab, you can save the weights in the drive directly like this:- model.save('/content/drive/My Drive/folder (1)/model.h5') Therefore our training is complete, now it’s time to check the results. Prediction and Results So first, we will load our model. model = load_model(r'C:/Users/nEW u/Flask/model.h5') Then we will use ImagedataGenerator to get to the test folder and call the image files collectively. And will call the predict function and set it with the image generator function. Now, we will plot our results along with the images. I took the help of the Matplotlib library. And here comes our result:- Note:- As I mentioned earlier, I named the images files as good and bad for my reference. So, the initial part is the name of the image file and the result is in the Bracket. Therefore you can compare the Result with the actual Image quality as per the image name. So, here our Image Classification model is complete successfully. Now, it's time to create a Web Application. I am going to use Flask for it. Flask is a Python’s API used to create web applications. So, for start, I am gonna give you a basic code snippet that we usually follow while using Flask. Hope you got a bit idea, Now let’s start implementing. Functions First, we must write functions to call the model, for processing the image before we pass it to our model and prediction function which let our image pass the model and return the result. For calling the model:- For processing the image:- Prediction function (it uses the“load_image” function):- Design As we are done with our functions, we will proceed forward to design our web pages. So, here we will need two pages, On the first page, it will ask to select and upload the image. The second page will show the image along with the result. Important Note:- While using Flask we must be very attentive as we need to create a separate folder. In that folder, we will create our python file in which we use flask, and we also need to create two subfolders named “Templates” and “Static”. Templates are where we save our HTML files, and in the Static folder, we save images and other stuff. You must follow this convention if you want to save yourself from the error cycle. So, as we need two pages, I designed two HTML pages accordingly. For design purposes, I used “Bootstrap”. Well, Bootstrap is an open-source Front-End framework used to create websites and web apps. It contains various HTML, CSS and JavaScript-based design templates for UI interface elements such as Buttons and Forms etc. So, here is my first web page HTML file named home.html:- Notice on the third line, bootstrap link for the design is used (CSS based template). And here is the second page HTML file, saved as predict.html:- Here both CSS and JavaScript templates are used. Compilation and Deployment Our model is ready, functions are ready, templates are also ready. Now it’s time to compile all those things and enjoy the magic. First, we run the Flask:- app = Flask(__name__) Then we load the model by calling the function:- get_model() And now we call both the pages along with functions and templates:- Well, now its time for the final step i.e. to run everything and to generate URL:- Now a URL is generated (notice in blue). Click on it and we will get our first page like this:- Then we choose the image file which we want to check and then click upload. After pressing the upload button, it redirects to the next page with url+”/predict”. It will show the image with the result:- Here we are with the final result. So, the implementation of a Deep Learning model-based Web Application for defect detection in PCB is hereby successful. You can clone the repository by:- git clone https://github.com/utk-ink/Defect-Detection-of-PCB.git Or Here is my GitHub’s link for the whole code:- github.com Hope you liked it!!! Well, this blog is not monetized, I just wanted to share my knowledge in the best possible way. Please do give Claps, Follow and Share as it motivates me to write more. Thank You!!
[ { "code": null, "e": 684, "s": 171, "text": "Hello, This blog is about creating an Image Classification model for PCBs(Printed Circuit boards) to detect defective PCBs and classify them as Good or Bad. So for that, we will create a Deep Learning Model and try to get the best possible results along with proper visualisation of each step. After creating the working model, we will create a Web Application for the same using Flask. You can find the code for this project on my GitHub along with the setup instruction file below. So, let’s go ahead and flex." }, { "code": null, "e": 697, "s": 684, "text": "Requirements" }, { "code": null, "e": 852, "s": 697, "text": "Jupyter NotebookPython 3.5 or Later. (3.7 preferable)Libraries — Tensorflow, Keras, Pandas, Numpy, Matplotlib, OpenCV, Pillow, Flask. [all latest version]" }, { "code": null, "e": 869, "s": 852, "text": "Jupyter Notebook" }, { "code": null, "e": 907, "s": 869, "text": "Python 3.5 or Later. (3.7 preferable)" }, { "code": null, "e": 1009, "s": 907, "text": "Libraries — Tensorflow, Keras, Pandas, Numpy, Matplotlib, OpenCV, Pillow, Flask. [all latest version]" }, { "code": null, "e": 1035, "s": 1009, "text": "Understanding the Dataset" }, { "code": null, "e": 1410, "s": 1035, "text": "PCBs (Printed Circuit Boards) is a widely used electronic component, used almost in any electronic device. Sometimes during its mass production in factories leads to some anomalies which lead to a defective product. Electronic companies have to bear that loss. So this deep learning Image Classification model helps to identify Good and Bad Circuits at production time only." }, { "code": null, "e": 1614, "s": 1410, "text": "So, the dataset we are using is a binary image of PCB, in which the Black part denotes the circuit and the white parts signify the empty circuit areas. The dots or noise in the image shows the anomalies." }, { "code": null, "e": 1728, "s": 1614, "text": "As we can see the image has no anomalies and defects in it. Now, we will see another image of a PCB with defects." }, { "code": null, "e": 1837, "s": 1728, "text": "As here the defects are marked, it is an example of a defective PCB. You can download the dataset from here." }, { "code": null, "e": 1868, "s": 1837, "text": "Data Preparation/Preprocessing" }, { "code": null, "e": 2179, "s": 1868, "text": "Now after we download the dataset, we can see the dimension of each image is 640x640. It will be better if we reduce the dimension of them so that it will be easy for training the data, but to make sure the quality of the image didn’t get affected, we will compress the image using the Anti-Aliasing technique." }, { "code": null, "e": 2311, "s": 2179, "text": "Here is my link to my GitHub repo which helps to do the same. Use the Image Resizer tool there and you will get the desired result." }, { "code": null, "e": 2734, "s": 2311, "text": "So, after resizing the image to 224x224, we save them into a different folder. I saved 1,095 images of somewhat equally mixed good and bad PCBs. So, that folder is going to be your Training Data set. Pick some other images (different from the training set) and put them into a separate folder to work as your Test Data set. Make sure the test folder is a good mixture of good and bad images with a proper ratio maintained." }, { "code": null, "e": 3032, "s": 2734, "text": "Now I will check my training dataset that it has a proper ratio of both types of images or in other words, to check the possible “class imbalance”. Well for my reference, I named the good PCB image as Good().jpeg and bad as Bad().jpeg. Then I labelled the good images as ‘0’ and bad images as ‘1’." }, { "code": null, "e": 3063, "s": 3032, "text": "And then we plot their graph:-" }, { "code": null, "e": 3336, "s": 3063, "text": "So, we can observe from the graph that our classes are pretty balance. Now for Cross-Validation, we will split out the training dataset into training and validation sets. As I mentioned earlier I took 1,095 images. I split them as 80% training data and 20% validation set." }, { "code": null, "e": 3504, "s": 3336, "text": "train_df, validate_df = train_test_split(df, test_size=0.20, random_state=42)train_df = train_df.reset_index(drop=True)validate_df = validate_df.reset_index(drop=True)" }, { "code": null, "e": 3562, "s": 3504, "text": "And then we plot both training and testing image ratios:-" }, { "code": null, "e": 3564, "s": 3562, "text": "⇙" }, { "code": null, "e": 3671, "s": 3564, "text": "This is the plotted graph of the final “training dataset”, i.e. approximately 400+ images in both classes." }, { "code": null, "e": 3673, "s": 3671, "text": "⇖" }, { "code": null, "e": 3675, "s": 3673, "text": "⇙" }, { "code": null, "e": 3778, "s": 3675, "text": "This is the plotted graph of the “validation dataset”, i.e. approximately 100+ images in both classes." }, { "code": null, "e": 3780, "s": 3778, "text": "⇖" }, { "code": null, "e": 3784, "s": 3780, "text": "___" }, { "code": null, "e": 4118, "s": 3784, "text": "Now I am going to apply one of the greatest tools according to me i.e. Keras ImageDataGenerator. It is a very useful tool as it helps to do Data Augmentation in real-time while training the model. As we know our training data is already less, so applying augmentation not only helps us to make our model robust but also saves memory." }, { "code": null, "e": 4177, "s": 4118, "text": "Now, we add the path and load the images in the generator." }, { "code": null, "e": 4254, "s": 4177, "text": "So, now we can say that our Data Preparation/Preprocessing part is complete." }, { "code": null, "e": 4275, "s": 4254, "text": "Model Implementation" }, { "code": null, "e": 4597, "s": 4275, "text": "Now it’s time to design the brain. Here I used the “MobileNet” model which is pre-trained on the ImageNet dataset. Well, MobileNet is a Deep Learning based Convolution Neural Network Architecture. It is a lightweight architecture and uses depthwise separable convolutions. You can learn more about it from its paper here." }, { "code": null, "e": 4867, "s": 4597, "text": "As I mentioned we are using the MobileNet model pre-trained of ImageNet Dataset, so here we are using the concept of Transfer Learning. Therefore instead of training the whole model, we will freeze the base layer and add some other layers according to our requirements." }, { "code": null, "e": 5048, "s": 4867, "text": "As we are using pre-trained weights, we will make sure that all the weights are non-trainable except the last few dense layers. Well, I set the first 20 layers to be non-trainable." }, { "code": null, "e": 5160, "s": 5048, "text": "for layer in model.layers[:20]: layer.trainable=Falsefor layer in model.layers[20:]: layer.trainable=True" }, { "code": null, "e": 5241, "s": 5160, "text": "But if you want to set all layers to be non-trainable, you can use this instead." }, { "code": null, "e": 5297, "s": 5241, "text": "for layer in model.layers: layer.trainable=False" }, { "code": null, "e": 5353, "s": 5297, "text": "So, we are done with the Model Implementation part now." }, { "code": null, "e": 5362, "s": 5353, "text": "Training" }, { "code": null, "e": 5587, "s": 5362, "text": "So, our data preparation is done along with model implementation. Now, it’s time to train our model. Before I proceed further, I want to mention that I used two Callbacks named “Early Stopping” and “Learning Rate Reduction”." }, { "code": null, "e": 5945, "s": 5587, "text": "We need to consider the number of Epochs carefully as too many of them lead to overfitting the data, whereas too few leads to underfitting. Early Stopping allows you to specify an arbitrarily large number of training epochs and stop training when the model stops improving on a hold out validation dataset. Here is a link if you want to learn more about it." }, { "code": null, "e": 6282, "s": 5945, "text": "ReduceLROnPlateau reduces the Learning Rate when a metric is stopped improving. Models often benefit from reducing the learning rate by a factor of 2–10 once learning stagnates. This callback monitors a quantity and if no improvement is seen for a ‘patience’ number of epochs, the learning rate is reduced. You can check this from here." }, { "code": null, "e": 6589, "s": 6282, "text": "Now, we will start training our model. Well, I trained my model on Google Colab as it gives certain advantages, I will advise everyone to try to use Google Colab, you just need to upload or link the dataset on google drive and then mount it on colab using this simple call by giving right folder location:-" }, { "code": null, "e": 6649, "s": 6589, "text": "from google.colab import drivedrive.mount('/content/drive')" }, { "code": null, "e": 6755, "s": 6649, "text": "Now we will set all the variables in the model.fit.generator() and then we will start to train our model." }, { "code": null, "e": 6903, "s": 6755, "text": "Well, I set my epoch as 50 but it stopped it at 42 as it stops improving. I plotted two graphs from the data we extracted while training the model." }, { "code": null, "e": 6905, "s": 6903, "text": "." }, { "code": null, "e": 6907, "s": 6905, "text": "⇙" }, { "code": null, "e": 6931, "s": 6907, "text": "“Loss vs Epochs” graph." }, { "code": null, "e": 6933, "s": 6931, "text": "⇖" }, { "code": null, "e": 6935, "s": 6933, "text": "." }, { "code": null, "e": 6937, "s": 6935, "text": "⇙" }, { "code": null, "e": 6965, "s": 6937, "text": "“Accuracy vs Epochs” graph." }, { "code": null, "e": 6967, "s": 6965, "text": "⇖" }, { "code": null, "e": 6969, "s": 6967, "text": "." }, { "code": null, "e": 7089, "s": 6969, "text": "Note:- The Blue line denotes the training and Red line denotes the validation variable respectively in both the graphs." }, { "code": null, "e": 7158, "s": 7089, "text": "So, after training the model, I got a Validation Accuracy of 95.71%." }, { "code": null, "e": 7237, "s": 7158, "text": "Now, we save the trained weights in the .h5 or .hdf5 file (both are the same)." }, { "code": null, "e": 7268, "s": 7237, "text": "model.save_weights(\"model.h5\")" }, { "code": null, "e": 7363, "s": 7268, "text": "If you trained it via Google Colab, you can save the weights in the drive directly like this:-" }, { "code": null, "e": 7421, "s": 7363, "text": "model.save('/content/drive/My Drive/folder (1)/model.h5')" }, { "code": null, "e": 7493, "s": 7421, "text": "Therefore our training is complete, now it’s time to check the results." }, { "code": null, "e": 7516, "s": 7493, "text": "Prediction and Results" }, { "code": null, "e": 7550, "s": 7516, "text": "So first, we will load our model." }, { "code": null, "e": 7603, "s": 7550, "text": "model = load_model(r'C:/Users/nEW u/Flask/model.h5')" }, { "code": null, "e": 7785, "s": 7603, "text": "Then we will use ImagedataGenerator to get to the test folder and call the image files collectively. And will call the predict function and set it with the image generator function." }, { "code": null, "e": 7881, "s": 7785, "text": "Now, we will plot our results along with the images. I took the help of the Matplotlib library." }, { "code": null, "e": 7909, "s": 7881, "text": "And here comes our result:-" }, { "code": null, "e": 8174, "s": 7909, "text": "Note:- As I mentioned earlier, I named the images files as good and bad for my reference. So, the initial part is the name of the image file and the result is in the Bracket. Therefore you can compare the Result with the actual Image quality as per the image name." }, { "code": null, "e": 8316, "s": 8174, "text": "So, here our Image Classification model is complete successfully. Now, it's time to create a Web Application. I am going to use Flask for it." }, { "code": null, "e": 8471, "s": 8316, "text": "Flask is a Python’s API used to create web applications. So, for start, I am gonna give you a basic code snippet that we usually follow while using Flask." }, { "code": null, "e": 8526, "s": 8471, "text": "Hope you got a bit idea, Now let’s start implementing." }, { "code": null, "e": 8536, "s": 8526, "text": "Functions" }, { "code": null, "e": 8724, "s": 8536, "text": "First, we must write functions to call the model, for processing the image before we pass it to our model and prediction function which let our image pass the model and return the result." }, { "code": null, "e": 8748, "s": 8724, "text": "For calling the model:-" }, { "code": null, "e": 8775, "s": 8748, "text": "For processing the image:-" }, { "code": null, "e": 8832, "s": 8775, "text": "Prediction function (it uses the“load_image” function):-" }, { "code": null, "e": 8839, "s": 8832, "text": "Design" }, { "code": null, "e": 9078, "s": 8839, "text": "As we are done with our functions, we will proceed forward to design our web pages. So, here we will need two pages, On the first page, it will ask to select and upload the image. The second page will show the image along with the result." }, { "code": null, "e": 9508, "s": 9078, "text": "Important Note:- While using Flask we must be very attentive as we need to create a separate folder. In that folder, we will create our python file in which we use flask, and we also need to create two subfolders named “Templates” and “Static”. Templates are where we save our HTML files, and in the Static folder, we save images and other stuff. You must follow this convention if you want to save yourself from the error cycle." }, { "code": null, "e": 9831, "s": 9508, "text": "So, as we need two pages, I designed two HTML pages accordingly. For design purposes, I used “Bootstrap”. Well, Bootstrap is an open-source Front-End framework used to create websites and web apps. It contains various HTML, CSS and JavaScript-based design templates for UI interface elements such as Buttons and Forms etc." }, { "code": null, "e": 9889, "s": 9831, "text": "So, here is my first web page HTML file named home.html:-" }, { "code": null, "e": 9975, "s": 9889, "text": "Notice on the third line, bootstrap link for the design is used (CSS based template)." }, { "code": null, "e": 10038, "s": 9975, "text": "And here is the second page HTML file, saved as predict.html:-" }, { "code": null, "e": 10087, "s": 10038, "text": "Here both CSS and JavaScript templates are used." }, { "code": null, "e": 10114, "s": 10087, "text": "Compilation and Deployment" }, { "code": null, "e": 10244, "s": 10114, "text": "Our model is ready, functions are ready, templates are also ready. Now it’s time to compile all those things and enjoy the magic." }, { "code": null, "e": 10270, "s": 10244, "text": "First, we run the Flask:-" }, { "code": null, "e": 10292, "s": 10270, "text": "app = Flask(__name__)" }, { "code": null, "e": 10341, "s": 10292, "text": "Then we load the model by calling the function:-" }, { "code": null, "e": 10353, "s": 10341, "text": "get_model()" }, { "code": null, "e": 10421, "s": 10353, "text": "And now we call both the pages along with functions and templates:-" }, { "code": null, "e": 10504, "s": 10421, "text": "Well, now its time for the final step i.e. to run everything and to generate URL:-" }, { "code": null, "e": 10600, "s": 10504, "text": "Now a URL is generated (notice in blue). Click on it and we will get our first page like this:-" }, { "code": null, "e": 10802, "s": 10600, "text": "Then we choose the image file which we want to check and then click upload. After pressing the upload button, it redirects to the next page with url+”/predict”. It will show the image with the result:-" }, { "code": null, "e": 10957, "s": 10802, "text": "Here we are with the final result. So, the implementation of a Deep Learning model-based Web Application for defect detection in PCB is hereby successful." }, { "code": null, "e": 10991, "s": 10957, "text": "You can clone the repository by:-" }, { "code": null, "e": 11056, "s": 10991, "text": "git clone https://github.com/utk-ink/Defect-Detection-of-PCB.git" }, { "code": null, "e": 11059, "s": 11056, "text": "Or" }, { "code": null, "e": 11105, "s": 11059, "text": "Here is my GitHub’s link for the whole code:-" }, { "code": null, "e": 11116, "s": 11105, "text": "github.com" }, { "code": null, "e": 11137, "s": 11116, "text": "Hope you liked it!!!" } ]
Restricted cubic splines. A spline is a drafting tool for drawing... | by Peter Flom | Towards Data Science
A spline is a drafting tool for drawing curves. In statistics, splines are a broad class of methods for transforming variables. I first introduce the concept via linear splines and work my way to restricted cubic splines which is what I (and many others) recommend. You should be aware that there are a huge variety of splines and each has its proponents. The pathway is as follows: 1. Dummy variables 2. Unrestricted linear splines 3. Restricted linear splines 4. Restricted cubic splines In an earlier article I showed that categorizing (which is the dummy variable method) isn’t a good method. There are two basic problems with it: The relationship is flat within each segment and it jumps between segments. In spline terminology, letting a curve jump is called “unrestricted”. Step 2 gets rid of the flatness (but leaves us with straight lines that jump). Step 3 gets rid of the jumps (but keeps the straight lines). Step 4 lets the relationship in each section curve. The result is a very flexible curve that has no jumps. Restricted cubic splines (RCS) have many advantages but they have one big disadvantage: The resultant output is not always easy to interpret. Two aspects of splines that we have not touched on is the number of knots to allow and how to place them. Various proposals have been made, but Frank Harrell recommends using 4 knots if N < 100 and 5 for larger data sets and placing them at the 5th, 35th, 65th and 95th percentiles for k = 4 and the 5th, 27.5th, 50th, 72.5th and 95th for k = 5 (where k is the number of knots). All this may be clearer by example. I will start with a sine regression(as in my previous post) For comparison purposes, we should follow the above advice about knots for the dummy variable plot. This yields: The first step is to allow the lines between each not to have nonzero slope. Somewhat messy code (dammit Jim, I’m a data analyst, not a programmer!) is: mUnresLin1 <- lm(y~x, subset = (x6int == 1)) mUnresLin2 <- lm(y~x, subset = (x6int == 2)) mUnresLin3 <- lm(y~x, subset = (x6int == 3)) mUnresLin4 <- lm(y~x, subset = (x6int == 4)) mUnresLin5 <- lm(y~x, subset = (x6int == 5)) mUnresLin6 <- lm(y~x, subset = (x6int == 6)) plot(x[x6int == 1],mUnresLin1$fitted.values, las = 1, xlab = "x", ylab = "y", col = "red", xlim = c(min(x),max(x)), ylim = c(min(y),max(y))) points(x[x6int == 2],mUnresLin2$fitted.values, col = "red") points(x[x6int == 3],mUnresLin3$fitted.values, col = "red") points(x[x6int == 4],mUnresLin4$fitted.values, col = "red") points(x[x6int == 5],mUnresLin5$fitted.values, col = "red") points(x[x6int == 6],mUnresLin6$fitted.values, col = "red") points(x,y, pch = 20, cex = .5) this yields which is already a major improvement, but has jumps (one of them fairly large) and sudden shifts in direction that are probably as hard to justify as the jumps in the earlier model. Next, we can force the lines to match up with a restricted linear spline. There is already an R function for this, so the code is straightforward: install.packages("lspline") library(lspline)mlinspline <- lm(y ~ lspline(x, quantile(x, c(0, .05, .275, .5, .775, .95, 1), include.lowest = TRUE)))plot(x,mlinspline$fitted.values, las = 1, xlab = "x", ylab = "y", col = "red", xlim = c(min(x),max(x)), ylim = c(min(y),max(y)))points(x,y, pch = 20, cex = .5) This produces: The final step is to allow the lines within each segment to curve. We can do this with restricted cubic splines; again, there is an R package making this easy. library(Hmisc)library(rms)mRCS <- ols(y~rcs(x, quantile(x, c(0, .05, .275, .5, .775, .95, 1), include.lowest = TRUE)))plot(x,mRCS$fitted.values, col = "red", xlim = c(min(x),max(x)), ylim = c(min(y),max(y)))points(x,y) which produces: which matches the original sine curve very well.
[ { "code": null, "e": 554, "s": 171, "text": "A spline is a drafting tool for drawing curves. In statistics, splines are a broad class of methods for transforming variables. I first introduce the concept via linear splines and work my way to restricted cubic splines which is what I (and many others) recommend. You should be aware that there are a huge variety of splines and each has its proponents. The pathway is as follows:" }, { "code": null, "e": 573, "s": 554, "text": "1. Dummy variables" }, { "code": null, "e": 604, "s": 573, "text": "2. Unrestricted linear splines" }, { "code": null, "e": 633, "s": 604, "text": "3. Restricted linear splines" }, { "code": null, "e": 661, "s": 633, "text": "4. Restricted cubic splines" }, { "code": null, "e": 1341, "s": 661, "text": "In an earlier article I showed that categorizing (which is the dummy variable method) isn’t a good method. There are two basic problems with it: The relationship is flat within each segment and it jumps between segments. In spline terminology, letting a curve jump is called “unrestricted”. Step 2 gets rid of the flatness (but leaves us with straight lines that jump). Step 3 gets rid of the jumps (but keeps the straight lines). Step 4 lets the relationship in each section curve. The result is a very flexible curve that has no jumps. Restricted cubic splines (RCS) have many advantages but they have one big disadvantage: The resultant output is not always easy to interpret." }, { "code": null, "e": 1720, "s": 1341, "text": "Two aspects of splines that we have not touched on is the number of knots to allow and how to place them. Various proposals have been made, but Frank Harrell recommends using 4 knots if N < 100 and 5 for larger data sets and placing them at the 5th, 35th, 65th and 95th percentiles for k = 4 and the 5th, 27.5th, 50th, 72.5th and 95th for k = 5 (where k is the number of knots)." }, { "code": null, "e": 1929, "s": 1720, "text": "All this may be clearer by example. I will start with a sine regression(as in my previous post) For comparison purposes, we should follow the above advice about knots for the dummy variable plot. This yields:" }, { "code": null, "e": 2082, "s": 1929, "text": "The first step is to allow the lines between each not to have nonzero slope. Somewhat messy code (dammit Jim, I’m a data analyst, not a programmer!) is:" }, { "code": null, "e": 2935, "s": 2082, "text": "mUnresLin1 <- lm(y~x, subset = (x6int == 1)) mUnresLin2 <- lm(y~x, subset = (x6int == 2)) mUnresLin3 <- lm(y~x, subset = (x6int == 3)) mUnresLin4 <- lm(y~x, subset = (x6int == 4)) mUnresLin5 <- lm(y~x, subset = (x6int == 5)) mUnresLin6 <- lm(y~x, subset = (x6int == 6)) plot(x[x6int == 1],mUnresLin1$fitted.values, las = 1, xlab = \"x\", ylab = \"y\", col = \"red\", xlim = c(min(x),max(x)), ylim = c(min(y),max(y))) points(x[x6int == 2],mUnresLin2$fitted.values, col = \"red\") points(x[x6int == 3],mUnresLin3$fitted.values, col = \"red\") points(x[x6int == 4],mUnresLin4$fitted.values, col = \"red\") points(x[x6int == 5],mUnresLin5$fitted.values, col = \"red\") points(x[x6int == 6],mUnresLin6$fitted.values, col = \"red\") points(x,y, pch = 20, cex = .5)" }, { "code": null, "e": 2947, "s": 2935, "text": "this yields" }, { "code": null, "e": 3129, "s": 2947, "text": "which is already a major improvement, but has jumps (one of them fairly large) and sudden shifts in direction that are probably as hard to justify as the jumps in the earlier model." }, { "code": null, "e": 3276, "s": 3129, "text": "Next, we can force the lines to match up with a restricted linear spline. There is already an R function for this, so the code is straightforward:" }, { "code": null, "e": 3638, "s": 3276, "text": "install.packages(\"lspline\") library(lspline)mlinspline <- lm(y ~ lspline(x, quantile(x, c(0, .05, .275, .5, .775, .95, 1), include.lowest = TRUE)))plot(x,mlinspline$fitted.values, las = 1, xlab = \"x\", ylab = \"y\", col = \"red\", xlim = c(min(x),max(x)), ylim = c(min(y),max(y)))points(x,y, pch = 20, cex = .5)" }, { "code": null, "e": 3653, "s": 3638, "text": "This produces:" }, { "code": null, "e": 3813, "s": 3653, "text": "The final step is to allow the lines within each segment to curve. We can do this with restricted cubic splines; again, there is an R package making this easy." }, { "code": null, "e": 4073, "s": 3813, "text": "library(Hmisc)library(rms)mRCS <- ols(y~rcs(x, quantile(x, c(0, .05, .275, .5, .775, .95, 1), include.lowest = TRUE)))plot(x,mRCS$fitted.values, col = \"red\", xlim = c(min(x),max(x)), ylim = c(min(y),max(y)))points(x,y)" }, { "code": null, "e": 4089, "s": 4073, "text": "which produces:" } ]
NER For Stock Mentions on Reddit | Towards Data Science
Reddit has been at the epicenter of one of the biggest movements in the world of finance, and although it seemed like an unlikely source of such a movement — it’s hardly surprising in hindsight. The trading-focused subreddits of Reddit are the backdrop for a huge amount of discussion about what is happening in the markets — so it is only logical to tap into this huge data source. When building a data extraction tool like this, one of the first things we need to do is identify what the data we’re extracting is actually about — and for that we will be using named entity recognition (NER). We will be identifying which organizations are being discussed. In short, we will cover: > Reddit Data> NER - SpaCy> Identifying Entities - DisplaCy Visualization - Extracting Entities> Processing The Dataset - Extracting Entities - Pruning Entities> Building a Frequency Table Watch the video tutorial here: First, we need to extract information from Reddit — for this, we have two options. We can use the requests library to interface directly with the Reddit API, or we use the PRAW library which adds an extra layer of abstraction in accessing the Reddit API. In this project, we will be interfacing directly with the Reddit API through requests — but feel free to use whichever approach you prefer. You can find a guide to interfacing through requests here: towardsdatascience.com We will be using this script to extract the Reddit data. You can find the data we use here (if you’d like to skip this part). Using this we can easily switch which subreddits we’re looking at — but we will be focusing on /r/investing. Once we have our data we need to process it and extract organization names so that any further analysis is automatically classified and results assigned to the correct stocks. Organizations are mentioned in each subreddit in a variety of formats. Typically we will find two formats: Organization name, eg Tesla/Tesla Motors Ticker symbol, eg TSLA, tsla, or $TSLA We also need to be able to differentiate between tickers and other abbreviations/slang —some of these are unclear like AI (AI can mean both artificial intelligence and refer to the ticker symbol for C3.ai). So, we need a reasonable competent NER process to accurately classify our data. The spaCy library is one of the most popular packages for natural language processing in Python — and it comes with an excellent set of tools for NER, including some really cool visualization tools in displaCy — which we will explore soon. To install spaCy, open CMD/Bash/etc and type pip install spacy. After installation, we can download any of the SpaCy models by entering python -m spacy download <MODEL-NAME> into our command line. Once downloaded we can initialize the model in our Python code like so: nlp = spacy.load('en_core_web_sm') The spaCy model names are broken into four parts, [lang]_[type]_[genre]_[size]: Lang — the language of the model (eg en for English). Type — model type, core is general purpose and supports vocabulary, syntax, entities, and word vectors. Genre — type of text model is trained on (eg web or news). Size — model package size — sm, md, or lg. In our case we will be using an English model, which will need to support NER (entities) — so it will be a general-purpose core model. Reddit threads align well with the web genre, and we will stick with the small model size sm. All of this gives us our model en_core_web_sm! We will begin with this extract from a thread on ARK in /r/investing: Given the recent downturn in stocks especially in tech which is likely to persist as yields keep going up, I thought it would be prudent to share the risks of investing in ARK ETFs, written up very nicely by [The Bear Cave](https://...). The risks comes primarily from ARK's illiquid and very large holdings in small cap companies. ARK is forced to sell its holdings whenever its liquid ETF gets hit with outflows as is especially the case in market downturns. This could force very painful liquidations at unfavorable prices and the ensuing crash goes into a positive feedback loop leading into a death spiral enticing even more outflows and predatory shorts. From here we want to extract ARK as the only relevant organization for this extract. To do this we will return to our initialized nlp model: txt = ("Given the recent downturn in stocks especially in tech which is likely to persist as yields keep going up, " "I thought it would be prudent to share the risks of investing in ARK ETFs, written up very nicely by " "[The Bear Cave](https://thebearcave.substack.com/p/special-edition-will-ark-invest-blow). The risks comes " "primarily from ARK's illiquid and very large holdings in small cap companies. ARK is forced to sell its " "holdings whenever its liquid ETF gets hit with outflows as is especially the case in market downturns. " "This could force very painful liquidations at unfavorable prices and the ensuing crash goes into a " "positive feedback loop leading into a death spiral enticing even more outflows and predatory shorts.") doc = nlp(txt) doc Given the recent downturn in stocks especially in tech which is likely to persist as yields keep going up, I thought it would be prudent to share the risks of investing in ARK ETFs, written up very nicely by [The Bear Cave](https://thebearcave.substack.com/p/special-edition-will-ark-invest-blow). The risks comes primarily from ARK's illiquid and very large holdings in small cap companies. ARK is forced to sell its holdings whenever its liquid ETF gets hit with outflows as is especially the case in market downturns. This could force very painful liquidations at unfavorable prices and the ensuing crash goes into a positive feedback loop leading into a death spiral enticing even more outflows and predatory shorts. Although it doesn’t look like it, doc does in fact contain our NER-tagged text. We just need to access it. There are two ways that we are going to take a look at, via a displaCy visualization — and programmatically via the ents attribute. DisplaCy allows us to conveniently visualize our text with spaCy identified entities highlighted like so: This method is great for quickly visualizing the results of our model — immediately it’s clear that the model is identifying ETF as an organization (which we may want to remove), and also identifying an article link The Bear Cave as a WORK_OF_ART. For me, it’s not inherently clear what the WORK_OF_ART tag means (Picasso maybe?). Fortunately, we can get a tag description using spacy.explain(<TAG>): spacy.explain('WORK_OF_ART') 'Titles of books, songs, etc.' From this description, the article — although not quite a book — seems to make sense. Visualizing with displaCy is great, but we also need a more programmatic way to pull out organization entities. Here is where ents comes in. The ents attribute of doc contains a list of entities and their respective tags — which we can then loop through to view our data. Here we’re accessing the tag type through entity.label_ and the respective text via entity.text. We will filter for ORG labels only. Additionally, we are identifying ARK three times in this slice of text — ideally we only want to return each unique organization once, which we will do by converting our output list into a set. And there we have it, we’ve extracted our organization entities from the text. Now, all we need to do is refactor what we’ve done so far and apply it to all of our extracted data. Our dataset looks like this: We are focusing on the selftext column which contains the text content of each post to /r/investing. To process this and output our organization entities, all we do is rewrite the code we’ve already built into a function that takes a single selftext string as input — and returns a list of identified entities: We add these identified entities to a new column in our dataframe called organizations. Again, we’re pulling in a few entities that we don’t want to include. To avoid these we add an additional condition to the if-statement in our get_orgs function: Now, if the organization is contained within the BLACKLIST it will be ignored — which we can see in our dataframe: Now all of our data is prepared, we can move on to building a frequency table. To do this we will be extracting all of our organization labels into a single list, which we will then process using collections to create a Counter object (the frequency table). Now we have our frequency table wrapped within Counter. This object is structured much like a Python dictionary, where we have our labels as keys and their frequency as values. However, unlike a Python dictionary, Counter comes with several useful methods — in particular, the most_common(n) method — which returns the n most frequently mentioned organizations for us! And there we have it, all of the most frequently mentioned organizations from /r/investing! That’s all for this article, we’ve covered a lot including: A quick glance at pulling data from the Reddit API (more here if you need it). SpaCy models — how to download them and understand what they are for. Entity extraction with our spaCy model. Visualization NER using displaCy. Adapting this to work with a full dataset. Building a mentions frequency table using collections. I hope you enjoyed this article! If you have any questions, let me know via Twitter or in the comments below. If you’d like more content like this, I post on YouTube too. Thanks for reading! SpaCy, Visualizers — DisplaCy Docs 🤖 NLP With Transformers Course Full Script *All images are by the author except where stated otherwise
[ { "code": null, "e": 366, "s": 171, "text": "Reddit has been at the epicenter of one of the biggest movements in the world of finance, and although it seemed like an unlikely source of such a movement — it’s hardly surprising in hindsight." }, { "code": null, "e": 554, "s": 366, "text": "The trading-focused subreddits of Reddit are the backdrop for a huge amount of discussion about what is happening in the markets — so it is only logical to tap into this huge data source." }, { "code": null, "e": 765, "s": 554, "text": "When building a data extraction tool like this, one of the first things we need to do is identify what the data we’re extracting is actually about — and for that we will be using named entity recognition (NER)." }, { "code": null, "e": 854, "s": 765, "text": "We will be identifying which organizations are being discussed. In short, we will cover:" }, { "code": null, "e": 1048, "s": 854, "text": "> Reddit Data> NER - SpaCy> Identifying Entities - DisplaCy Visualization - Extracting Entities> Processing The Dataset - Extracting Entities - Pruning Entities> Building a Frequency Table" }, { "code": null, "e": 1079, "s": 1048, "text": "Watch the video tutorial here:" }, { "code": null, "e": 1334, "s": 1079, "text": "First, we need to extract information from Reddit — for this, we have two options. We can use the requests library to interface directly with the Reddit API, or we use the PRAW library which adds an extra layer of abstraction in accessing the Reddit API." }, { "code": null, "e": 1533, "s": 1334, "text": "In this project, we will be interfacing directly with the Reddit API through requests — but feel free to use whichever approach you prefer. You can find a guide to interfacing through requests here:" }, { "code": null, "e": 1556, "s": 1533, "text": "towardsdatascience.com" }, { "code": null, "e": 1682, "s": 1556, "text": "We will be using this script to extract the Reddit data. You can find the data we use here (if you’d like to skip this part)." }, { "code": null, "e": 1791, "s": 1682, "text": "Using this we can easily switch which subreddits we’re looking at — but we will be focusing on /r/investing." }, { "code": null, "e": 1967, "s": 1791, "text": "Once we have our data we need to process it and extract organization names so that any further analysis is automatically classified and results assigned to the correct stocks." }, { "code": null, "e": 2074, "s": 1967, "text": "Organizations are mentioned in each subreddit in a variety of formats. Typically we will find two formats:" }, { "code": null, "e": 2115, "s": 2074, "text": "Organization name, eg Tesla/Tesla Motors" }, { "code": null, "e": 2154, "s": 2115, "text": "Ticker symbol, eg TSLA, tsla, or $TSLA" }, { "code": null, "e": 2361, "s": 2154, "text": "We also need to be able to differentiate between tickers and other abbreviations/slang —some of these are unclear like AI (AI can mean both artificial intelligence and refer to the ticker symbol for C3.ai)." }, { "code": null, "e": 2441, "s": 2361, "text": "So, we need a reasonable competent NER process to accurately classify our data." }, { "code": null, "e": 2681, "s": 2441, "text": "The spaCy library is one of the most popular packages for natural language processing in Python — and it comes with an excellent set of tools for NER, including some really cool visualization tools in displaCy — which we will explore soon." }, { "code": null, "e": 2745, "s": 2681, "text": "To install spaCy, open CMD/Bash/etc and type pip install spacy." }, { "code": null, "e": 2950, "s": 2745, "text": "After installation, we can download any of the SpaCy models by entering python -m spacy download <MODEL-NAME> into our command line. Once downloaded we can initialize the model in our Python code like so:" }, { "code": null, "e": 2985, "s": 2950, "text": "nlp = spacy.load('en_core_web_sm')" }, { "code": null, "e": 3065, "s": 2985, "text": "The spaCy model names are broken into four parts, [lang]_[type]_[genre]_[size]:" }, { "code": null, "e": 3119, "s": 3065, "text": "Lang — the language of the model (eg en for English)." }, { "code": null, "e": 3223, "s": 3119, "text": "Type — model type, core is general purpose and supports vocabulary, syntax, entities, and word vectors." }, { "code": null, "e": 3282, "s": 3223, "text": "Genre — type of text model is trained on (eg web or news)." }, { "code": null, "e": 3325, "s": 3282, "text": "Size — model package size — sm, md, or lg." }, { "code": null, "e": 3554, "s": 3325, "text": "In our case we will be using an English model, which will need to support NER (entities) — so it will be a general-purpose core model. Reddit threads align well with the web genre, and we will stick with the small model size sm." }, { "code": null, "e": 3601, "s": 3554, "text": "All of this gives us our model en_core_web_sm!" }, { "code": null, "e": 3671, "s": 3601, "text": "We will begin with this extract from a thread on ARK in /r/investing:" }, { "code": null, "e": 4332, "s": 3671, "text": "Given the recent downturn in stocks especially in tech which is likely to persist as yields keep going up, I thought it would be prudent to share the risks of investing in ARK ETFs, written up very nicely by [The Bear Cave](https://...). The risks comes primarily from ARK's illiquid and very large holdings in small cap companies. ARK is forced to sell its holdings whenever its liquid ETF gets hit with outflows as is especially the case in market downturns. This could force very painful liquidations at unfavorable prices and the ensuing crash goes into a positive feedback loop leading into a death spiral enticing even more outflows and predatory shorts." }, { "code": null, "e": 4473, "s": 4332, "text": "From here we want to extract ARK as the only relevant organization for this extract. To do this we will return to our initialized nlp model:" }, { "code": null, "e": 5265, "s": 4473, "text": "txt = (\"Given the recent downturn in stocks especially in tech which is likely to persist as yields keep going up, \"\n \"I thought it would be prudent to share the risks of investing in ARK ETFs, written up very nicely by \"\n \"[The Bear Cave](https://thebearcave.substack.com/p/special-edition-will-ark-invest-blow). The risks comes \"\n \"primarily from ARK's illiquid and very large holdings in small cap companies. ARK is forced to sell its \"\n \"holdings whenever its liquid ETF gets hit with outflows as is especially the case in market downturns. \"\n \"This could force very painful liquidations at unfavorable prices and the ensuing crash goes into a \"\n \"positive feedback loop leading into a death spiral enticing even more outflows and predatory shorts.\")\n" }, { "code": null, "e": 5281, "s": 5265, "text": "doc = nlp(txt)\n" }, { "code": null, "e": 5286, "s": 5281, "text": "doc\n" }, { "code": null, "e": 6007, "s": 5286, "text": "Given the recent downturn in stocks especially in tech which is likely to persist as yields keep going up, I thought it would be prudent to share the risks of investing in ARK ETFs, written up very nicely by [The Bear Cave](https://thebearcave.substack.com/p/special-edition-will-ark-invest-blow). The risks comes primarily from ARK's illiquid and very large holdings in small cap companies. ARK is forced to sell its holdings whenever its liquid ETF gets hit with outflows as is especially the case in market downturns. This could force very painful liquidations at unfavorable prices and the ensuing crash goes into a positive feedback loop leading into a death spiral enticing even more outflows and predatory shorts." }, { "code": null, "e": 6114, "s": 6007, "text": "Although it doesn’t look like it, doc does in fact contain our NER-tagged text. We just need to access it." }, { "code": null, "e": 6246, "s": 6114, "text": "There are two ways that we are going to take a look at, via a displaCy visualization — and programmatically via the ents attribute." }, { "code": null, "e": 6352, "s": 6246, "text": "DisplaCy allows us to conveniently visualize our text with spaCy identified entities highlighted like so:" }, { "code": null, "e": 6600, "s": 6352, "text": "This method is great for quickly visualizing the results of our model — immediately it’s clear that the model is identifying ETF as an organization (which we may want to remove), and also identifying an article link The Bear Cave as a WORK_OF_ART." }, { "code": null, "e": 6753, "s": 6600, "text": "For me, it’s not inherently clear what the WORK_OF_ART tag means (Picasso maybe?). Fortunately, we can get a tag description using spacy.explain(<TAG>):" }, { "code": null, "e": 6783, "s": 6753, "text": "spacy.explain('WORK_OF_ART')\n" }, { "code": null, "e": 6814, "s": 6783, "text": "'Titles of books, songs, etc.'" }, { "code": null, "e": 6900, "s": 6814, "text": "From this description, the article — although not quite a book — seems to make sense." }, { "code": null, "e": 7041, "s": 6900, "text": "Visualizing with displaCy is great, but we also need a more programmatic way to pull out organization entities. Here is where ents comes in." }, { "code": null, "e": 7172, "s": 7041, "text": "The ents attribute of doc contains a list of entities and their respective tags — which we can then loop through to view our data." }, { "code": null, "e": 7305, "s": 7172, "text": "Here we’re accessing the tag type through entity.label_ and the respective text via entity.text. We will filter for ORG labels only." }, { "code": null, "e": 7499, "s": 7305, "text": "Additionally, we are identifying ARK three times in this slice of text — ideally we only want to return each unique organization once, which we will do by converting our output list into a set." }, { "code": null, "e": 7679, "s": 7499, "text": "And there we have it, we’ve extracted our organization entities from the text. Now, all we need to do is refactor what we’ve done so far and apply it to all of our extracted data." }, { "code": null, "e": 7708, "s": 7679, "text": "Our dataset looks like this:" }, { "code": null, "e": 7809, "s": 7708, "text": "We are focusing on the selftext column which contains the text content of each post to /r/investing." }, { "code": null, "e": 8019, "s": 7809, "text": "To process this and output our organization entities, all we do is rewrite the code we’ve already built into a function that takes a single selftext string as input — and returns a list of identified entities:" }, { "code": null, "e": 8107, "s": 8019, "text": "We add these identified entities to a new column in our dataframe called organizations." }, { "code": null, "e": 8269, "s": 8107, "text": "Again, we’re pulling in a few entities that we don’t want to include. To avoid these we add an additional condition to the if-statement in our get_orgs function:" }, { "code": null, "e": 8384, "s": 8269, "text": "Now, if the organization is contained within the BLACKLIST it will be ignored — which we can see in our dataframe:" }, { "code": null, "e": 8642, "s": 8384, "text": "Now all of our data is prepared, we can move on to building a frequency table. To do this we will be extracting all of our organization labels into a single list, which we will then process using collections to create a Counter object (the frequency table)." }, { "code": null, "e": 8819, "s": 8642, "text": "Now we have our frequency table wrapped within Counter. This object is structured much like a Python dictionary, where we have our labels as keys and their frequency as values." }, { "code": null, "e": 9011, "s": 8819, "text": "However, unlike a Python dictionary, Counter comes with several useful methods — in particular, the most_common(n) method — which returns the n most frequently mentioned organizations for us!" }, { "code": null, "e": 9103, "s": 9011, "text": "And there we have it, all of the most frequently mentioned organizations from /r/investing!" }, { "code": null, "e": 9163, "s": 9103, "text": "That’s all for this article, we’ve covered a lot including:" }, { "code": null, "e": 9242, "s": 9163, "text": "A quick glance at pulling data from the Reddit API (more here if you need it)." }, { "code": null, "e": 9312, "s": 9242, "text": "SpaCy models — how to download them and understand what they are for." }, { "code": null, "e": 9352, "s": 9312, "text": "Entity extraction with our spaCy model." }, { "code": null, "e": 9386, "s": 9352, "text": "Visualization NER using displaCy." }, { "code": null, "e": 9429, "s": 9386, "text": "Adapting this to work with a full dataset." }, { "code": null, "e": 9484, "s": 9429, "text": "Building a mentions frequency table using collections." }, { "code": null, "e": 9655, "s": 9484, "text": "I hope you enjoyed this article! If you have any questions, let me know via Twitter or in the comments below. If you’d like more content like this, I post on YouTube too." }, { "code": null, "e": 9675, "s": 9655, "text": "Thanks for reading!" }, { "code": null, "e": 9710, "s": 9675, "text": "SpaCy, Visualizers — DisplaCy Docs" }, { "code": null, "e": 9741, "s": 9710, "text": "🤖 NLP With Transformers Course" }, { "code": null, "e": 9753, "s": 9741, "text": "Full Script" } ]
HTML | DOM oncontextmenu Event - GeeksforGeeks
22 Jul, 2019 The HTML DOM oncontextmenu event occurs when an element is right-clicked to open the context menu. Note: The oncontextmenu event is supported in all browsers but the contextmenu attribute is currently only supported in Firefox. Syntax: HTML: <element oncontextmenu="myScript"> JavaScript: object.oncontextmenu = function(){myScript}; In JavaScript, using the addEventListener() method: object.addEventListener("contextmenu", myScript); Example 1: Using HTML <!DOCTYPE html><html> <head> <style> div { background: green; border: 1px solid black; padding: 10px; } </style></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <h2>HTML DOM oncontextmenu Event</h2> <div oncontextmenu="myFunction()" contextmenu="mymenu"> <p>Right-click inside the box </div> <script> function myFunction() { alert("right-clicked"); } </script> </center></body> </html> Output:Before:After:Example 2: Using JavaScript <!DOCTYPE html><html> <head> <style> div { background: green; border: 1px solid black; padding: 10px; } </style></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <h2>HTML DOM oncontextmenu Event</h2> <div id="myDIV" contextmenu="mymenu"> <p>Right-click inside the box </div> <p id="try"></p> <script> document.getElementById( "myDIV").oncontextmenu = function() { GFGfun() }; function GFGfun() { var gfg = document.getElementById("try"); gfg.innerHTML = "right-clicked"; } </script> </center></body> </html> Output:Before:After:Example: In JavaScript, using the addEventListener() method: <!DOCTYPE html><html> <head> <style> div { background: green; border: 1px solid black; padding: 10px; } </style></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <h2>HTML DOM oncontextmenu Event</h2> <div id="myDIV" contextmenu="mymenu"> <p>Right-click inside the box </div> <p id="try"></p> <script> document.getElementById( "myDIV").addEventListener("contextmenu", GFGfun); function GFGfun() { var gfg = document.getElementById("try"); gfg.innerHTML = "right-clicked"; } </script> </center></body> </html> Output:Before:After: Supported Browsers: The browsers supported by DOM oncontextmenu Event are listed below: Google Chrome Internet Explorer Firefox 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. Akanksha_Rai HTML-DOM HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Types of CSS (Cascading Style Sheet) How to Insert Form Data into Database using PHP ? REST API (Introduction) Design a web page using HTML and CSS Form validation using HTML and JavaScript Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript
[ { "code": null, "e": 24709, "s": 24681, "text": "\n22 Jul, 2019" }, { "code": null, "e": 24808, "s": 24709, "text": "The HTML DOM oncontextmenu event occurs when an element is right-clicked to open the context menu." }, { "code": null, "e": 24937, "s": 24808, "text": "Note: The oncontextmenu event is supported in all browsers but the contextmenu attribute is currently only supported in Firefox." }, { "code": null, "e": 24945, "s": 24937, "text": "Syntax:" }, { "code": null, "e": 24951, "s": 24945, "text": "HTML:" }, { "code": null, "e": 24986, "s": 24951, "text": "<element oncontextmenu=\"myScript\">" }, { "code": null, "e": 24998, "s": 24986, "text": "JavaScript:" }, { "code": null, "e": 25043, "s": 24998, "text": "object.oncontextmenu = function(){myScript};" }, { "code": null, "e": 25095, "s": 25043, "text": "In JavaScript, using the addEventListener() method:" }, { "code": null, "e": 25145, "s": 25095, "text": "object.addEventListener(\"contextmenu\", myScript);" }, { "code": null, "e": 25167, "s": 25145, "text": "Example 1: Using HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> div { background: green; border: 1px solid black; padding: 10px; } </style></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h2>HTML DOM oncontextmenu Event</h2> <div oncontextmenu=\"myFunction()\" contextmenu=\"mymenu\"> <p>Right-click inside the box </div> <script> function myFunction() { alert(\"right-clicked\"); } </script> </center></body> </html>", "e": 25754, "s": 25167, "text": null }, { "code": null, "e": 25802, "s": 25754, "text": "Output:Before:After:Example 2: Using JavaScript" }, { "code": "<!DOCTYPE html><html> <head> <style> div { background: green; border: 1px solid black; padding: 10px; } </style></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h2>HTML DOM oncontextmenu Event</h2> <div id=\"myDIV\" contextmenu=\"mymenu\"> <p>Right-click inside the box </div> <p id=\"try\"></p> <script> document.getElementById( \"myDIV\").oncontextmenu = function() { GFGfun() }; function GFGfun() { var gfg = document.getElementById(\"try\"); gfg.innerHTML = \"right-clicked\"; } </script> </center></body> </html>", "e": 26573, "s": 25802, "text": null }, { "code": null, "e": 26654, "s": 26573, "text": "Output:Before:After:Example: In JavaScript, using the addEventListener() method:" }, { "code": "<!DOCTYPE html><html> <head> <style> div { background: green; border: 1px solid black; padding: 10px; } </style></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h2>HTML DOM oncontextmenu Event</h2> <div id=\"myDIV\" contextmenu=\"mymenu\"> <p>Right-click inside the box </div> <p id=\"try\"></p> <script> document.getElementById( \"myDIV\").addEventListener(\"contextmenu\", GFGfun); function GFGfun() { var gfg = document.getElementById(\"try\"); gfg.innerHTML = \"right-clicked\"; } </script> </center></body> </html>", "e": 27401, "s": 26654, "text": null }, { "code": null, "e": 27422, "s": 27401, "text": "Output:Before:After:" }, { "code": null, "e": 27510, "s": 27422, "text": "Supported Browsers: The browsers supported by DOM oncontextmenu Event are listed below:" }, { "code": null, "e": 27524, "s": 27510, "text": "Google Chrome" }, { "code": null, "e": 27542, "s": 27524, "text": "Internet Explorer" }, { "code": null, "e": 27550, "s": 27542, "text": "Firefox" }, { "code": null, "e": 27563, "s": 27550, "text": "Apple Safari" }, { "code": null, "e": 27569, "s": 27563, "text": "Opera" }, { "code": null, "e": 27706, "s": 27569, "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": 27719, "s": 27706, "text": "Akanksha_Rai" }, { "code": null, "e": 27728, "s": 27719, "text": "HTML-DOM" }, { "code": null, "e": 27733, "s": 27728, "text": "HTML" }, { "code": null, "e": 27750, "s": 27733, "text": "Web Technologies" }, { "code": null, "e": 27755, "s": 27750, "text": "HTML" }, { "code": null, "e": 27853, "s": 27755, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27862, "s": 27853, "text": "Comments" }, { "code": null, "e": 27875, "s": 27862, "text": "Old Comments" }, { "code": null, "e": 27912, "s": 27875, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 27962, "s": 27912, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27986, "s": 27962, "text": "REST API (Introduction)" }, { "code": null, "e": 28023, "s": 27986, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28065, "s": 28023, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 28121, "s": 28065, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 28154, "s": 28121, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28197, "s": 28154, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28258, "s": 28197, "text": "Difference between var, let and const keywords in JavaScript" } ]
Simulate Images for ML in PyBullet — The Quick & Easy Way | by Mason McGough | Towards Data Science
When applying deep Reinforcement Learning (RL) to robotics, we are faced with a conundrum: how do we train a robot to do a task when deep learning requires hundreds of thousands, even millions, of examples? To achieve 96% grasp success on never-before-seen objects, researchers at Google and Berkeley trained a robotic agent through 580,000 real-world grasp attempts. This feat took seven robots and several weeks to accomplish. Without Google resources, it may seem hopeless for the average ML practitioner. We cannot expect to easily run hundreds of thousands of iterations of training using a physical robot, which is subject to wear-and-tear and requires human supervision, neither of which comes cheap. It would be much more feasible if we could pretrain such RL algorithms to drastically reduce the number of real world attempts needed. With the advent of deep learning, RL techniques have matured but so has the demand for data. In an attempt to bridge this gap, many researchers are exploring the synthetic generation of training data, utilizing 3D rendering techniques to produce mock-ups of the task environment. While this technique works wonders in the simulated environment, it does not generalize well to the real world. Anyone who has worked closely with deep learning has learned how effective it is at exploiting nuances in training data to “cheat” a task. In practice, the real world is out-of-sample for these models trained in simulation and, unsurprisingly, they fail. Recent research is focused towards reducing the “reality gap,” those noticeable differences between the real world and 3D-rendered facsimiles, to pretrain robotic agents in simulation and thus drastically reduce the amount of real-world training needed. By aggressively randomizing the appearance and dynamics of a simulation, models learn features that in theory should generalize to the real world. This can even reduce the number of training sessions needed to train a robot by 99% according to recent research. For computer vision tasks where producing hundreds of thousands, or even millions, of training images is infeasible, this method is highly appealing. Let’s say for example we wish to generate synthetic training data to pretrain a classifier that can distinguish between a collection of small objects. We wish to select an object, drop it into a virtual “bin,” and render a screenshot. Ideally, we want to repeat this process thousands of times with randomization to create a rich dataset of images of objects. To this end (and inspired by the work done at OpenAI and Google), I recently began my journey to generate training data for my own applications. This led me to PyBullet, a Python module designed for robotics and machine learning applications based on the Bullet Physics SDK. Unlike other 3D rendering solutions like Maya or Blender, PyBullet is focused on robotics and has native implementations for concepts like joints, dynamics simulation, forward and inverse kinematics, and more. In addition, it can be easily installed with a package manager, allowing you to seamlessly integrate other Python packages, like NumPy and TensorFlow, into your simulations. While similar to proprietary physics simulation software MuJoCo, PyBullet is both free and easy to install, so it is a great choice for someone looking to experiment with simulation and robotics. This guide is meant as an introduction for those wishing to generate training images, but the official PyBullet quick start guide can be found here. Note that this tutorial assumes you are using Python version ≥3.6 (if you are using an older version, try creating a virtual environment for this tutorial). First things first, we will install PyBullet to our Python environment. pip install numpypip install pybullet Note that installing NumPy first is optional, but recommended when rendering images, due to the overhead of copying image buffers between C/C++ and Python. Now that you have everything successfully installed, let us dive right into a PyBullet session. PyBullet relies on a client-server model, where your Python session sends and receives data from a simulation server. There are chiefly two types of servers: DIRECT and GUI. As the name implies, GUI allows you to see the physical simulation in a GUI. DIRECT is useful for rendering headlessly and can be used for efficient rendering without a GPU. DIRECT will be the mode of choice when we are ready to render thousands of images as training data, but for now we will select GUI. Let us begin by initializing a PyBullet server. Start by launching a python interactive session and then enter the following: import pybullet as pbphysicsClient = pb.connect(pb.GUI) This step is necessary, as it instantiates the world simulation that you will work with. The physicsClient variable holds a unique ID for that server. This makes it possible in PyBullet to run multiple servers, even across multiple machines, and manage them from a single script by keeping track of these IDs. Many entities in PyBullet are similarly referred to by their IDs, including objects, colliders, and textures. Now you should see a simulation window pop up. That’s great! It means your simulation is working. You should see a primary viewport with additional windows for RGB, depth, and segmentation data. The world should be completely empty. Let’s first create a plane for our simulation. This plane comes with the pybullet_data package and can be easily loaded into any simulation. import pybullet_datapb.setAdditionalSearchPath(pybullet_data.getDataPath())planeId = pb.loadURDF(‘plane.urdf’) This does a few things. First, it loads another module called pybullet_data, which contains placeholder URDFs for many useful things. This is added to the path, so that when we finally call loadURDF it knows where to find ‘plane.urdf’ and loads it into our scene. Now we should have a plane that spans our scene. The most supported file formats in PyBullet are URDF, SDF, and MJCF. These formats are very easy to load and configure and have their own specialized loading functions. However, many of the 3D models we find on the web are in the simple and popular Wavefront OBJ file format. It is possible to load these, but requires knowing a bit more about the nuts-and-bolts of models in PyBullet, so we will bite the bullet and learn to load our own models with OBJ files. We will be using a dataset of procedurally generated objects for simulation tasks. This set consists of 1000 OBJ files which include corresponding colliders, materials, and URDF versions. Download those here and extract them into a folder called “random_urdfs” in your project folder. Every typical 3D object in a physical simulation consists of a visual mesh to describe the way an object appears and a collider mesh that describes an object’s physical dimensions and how it will interact with the world, such as how it collides with other physical objects. Collider meshes, or simply colliders, are typically simplified representations of our visual mesh that are computationally much cheaper to calculate collisions with. Using the two types of meshes together enables our physical simulations to run efficiently while still being visually appealing. Let us start by loading the visual shape for an object using the createVisualShape function. We can start with an object from our procedurally generated objects dataset. visualShapeId = pb.createVisualShape( shapeType=pb.GEOM_MESH, fileName='random_urdfs/000/000.obj', rgbaColor=None, meshScale=[0.1, 0.1, 0.1]) The first parameter shapeType tells PyBullet what kind of shape we are loading. These include spheres, boxes, cylinders, planes, capsules, and meshes. In our case, we wish to load a custom mesh described in our OBJ file. You can also describe the RGB color (as a length-4 list describing red, green, blue, and alpha channels), which we set to None here. We will replace the object’s texture later. Lastly, OBJ files do not intrinsically have units, so we may need to specify a mesh scale to ensure that our object is not too large or too small. Now we have a visual shape to reference for our object, but no physical shape. Let us load this using the createCollisionShape function. collisionShapeId = pb.createCollisionShape( shapeType=pb.GEOM_MESH, fileName='random_urdfs/000/000_coll.obj', meshScale=[0.1, 0.1, 0.1]) Similar to the createVisualShape function, we need to specify that we want a mesh using shapeType and where to find the mesh data with fileName. We can and should also specify the mesh scale so that the collider has the same shape as the visual shape. At this point, we have references to a visual shape and a collider, but the two aren’t connected and we have no object yet. That is where createMultiBody comes in. This function unites these two and creates an instance of an object. multiBodyId = pb.createMultiBody( baseMass=1.0, baseCollisionShapeIndex=collisionShapeId, baseVisualShapeIndex=visualShapeId, basePosition=[0, 0, 1], baseOrientation=pb.getQuaternionFromEuler([0, 0, 0])) We pass the IDs of our collider and visual shapes to createMultiBody to create a new object. This object needs a position and orientation to know where to place it in the physical world and a mass to know how it should interact with other objects. Set position with a length-3 list of x, y, z coordinates. For simplicity, we set mass to 1.0 for now. Orientation is a little trickier and requires that we specify it in a length-4 list of quaternions. Quaternions are a useful 4-dimensional representation for rotation in 3D spaces that are crucially used in computer graphics software like Blender, Maya, and Unity to avoid rotational artifacts such as gimbal lock. PyBullet has a convenience function called getQuaternionFromEuler that allows us to describe rotation in rotations about the x, y, and z axes, which are easier for human beings to visualize and understand. This representation of rotation is called Euler angles. Note: if you receive a message like “Unsupported texture image format [random_urdfs/000/000.png],” then ignore it. We will override the default texture in the next step anyways. Success! We have generated a physical object and placed it in our world. Recall from earlier that we want to randomize the appearance and dynamics of our 3D models. Let us start with the appearance and download and extract the Describable Textures Dataset here. This contains thousands of images comprised of 47 texture categories. Extract these into a folder called “dtd”. Let us pick one of these textures at random and apply it to our model. import os, glob, randomtexture_paths = glob.glob(os.path.join('dtd', '**', '*.jpg'), recursive=True)random_texture_path = texture_paths[random.randint(0, len(texture_paths) - 1)]textureId = pb.loadTexture(random_texture_path)pb.changeVisualShape(multiBodyId, -1, textureUniqueId=textureId) This snippet recursively grabs a list of paths to all of the textures in folder “dtd” with extension “.jpg” and randomly samples a single one. Then it passes it to function loadTexture to load a texture and create an ID. It then uses the changeVisualShape function to apply the texture with textureId to object with multiBodyId. Now your object should have the texture applied to it. You can also apply this same method to attach a texture to the plane if you wish. Note that the -1 is necessary for required parameter jointIndex, which specifies the link you wish to apply the texture to. Links are useful for creating objects with hierarchies of moving parts, like robots with many joints. This is an important concept in PyBullet, but is out of the scope of this tutorial, so we supply a value “-1” to tell it to apply it to the base object rather than any link. So far, we have created our simulation, but nothing is moving. There are a few reasons for this. First of all, we haven’t applied any gravity to the scene, so our object is floating in space. Let us do that real quick. pb.setGravity(0, 0, -9.8) That applies a downward negative acceleration of -9.8 m/s2 to our objects in the scene, just like we experience on the surface of planet Earth. However, your object still is not falling like you would expect. That is because the simulation is not stepping. There are two ways to step through your simulation: manually call stepSimulation to proceed the simulation by one time step or call setRealTimeSimulation to render in real time. For demonstration purposes, we will use the latter, but you will probably wish to use stepSimulation once we start rendering batches of objects in a loop. pb.setRealTimeSimulation(1) Set to “1” to enable or “0” to disable. Now your object should fall and hit the ground. By the way, the default time step is 1/240 seconds, but you can override this default if desired using the setTimeStep function. We now have a method to load a plane, place an OBJ file on our plane, apply a texture to the object, and render the scene. The last piece of the puzzle is rendering an image of our object. Essentially, we want to place a virtual camera over our object, point it downward at our object, and take a picture. Whether we are looking to solve a classification or segmentation task, PyBullet makes taking pictures of our simulation fairly straightforward with the getCameraImage function, which renders an RGB image, a segmentation mask, and a depth buffer simultaneously. However, we need to first specify the extrinsic and intrinsic properties of our camera, a process that is a bit more involved than it may seem. The camera extrinsic properties essentially describe how our camera is positioned in the world, such as its orientation and position. The camera intrinsic properties describe properties of the camera itself, such as the field-of-view (FOV) and the aspect ratio of its sensor (e.g. 4:3, 16:9, etc.). In PyBullet, we describe these properties with a view matrix and a projection matrix, respectively. The PyBullet quick start guide links to a great resource to learn more about the camera extrinsic and intrinsic properties and their corresponding matrices. The camera view matrix is a complicated 4x4 matrix, but in simplest terms it describes where the camera is and in what direction it is pointing. There are some useful helper functions for creating this matrix by specifying position and rotation more directly. The function computeViewMatrix can create this matrix in exchange for three vectors. viewMatrix = pb.computeViewMatrix( cameraEyePosition=[0, 0, 3], cameraTargetPosition=[0, 0, 0], cameraUpVector=[0, 1, 0]) As the name implies, cameraEyePosition describes the physical location of the camera in x, y, and z coordinates. We will place it 3 units directly above the plane, centered over our object. Next we describe the point that we wish the camera to face with cameraTargetPosition. We want it to look straight down at our object, so we point it at the origin. Lastly, we need to describe the orientation of the camera. We do this with cameraUpVector, which is a vector that points out of the top of our camera. We point this out along the y axis. Our camera should now be pointing directly downward so that the image plane that it renders is perfectly parallel with the plane we generated. The projection matrix, much like the view matrix, can be created using a few helper functions. In this case, the computeProjectionMatrixFOV function describes our camera’s intrinsic properties in the simplest and most pertinent ways to our use case. projectionMatrix = pb.computeProjectionMatrixFOV( fov=45.0, aspect=1.0, nearVal=0.1, farVal=3.1) The fov parameter specifies the camera FOV in degrees. It describes how “wide” the camera’s visual field is and is similar in principle to the focal length of a real camera. The aspect parameter describes the camera aspect ratio, which we set to 1.0 here for simplicity. The nearVal and farVal parameters describe the minimum and maximum distance, respectively, at which the camera will render objects. Since our camera is 3 units above the plane, we set farVal to 3.1 to just include that plane. These parameters are defined in the OpenGL documentation and you can read more about them here. We have described our camera’s properties and are now ready to render some images. Let us do that with getCameraImage. This function returns three image buffers: rgbImg, depthImg, and segImg. rgbImg is a uint8 image with red, green, blue, and alpha channels of the camera’s visuals. depthImg is a floating-point grayscale image that describes the distance of individual rendered pixels from the camera. It can be used to model the field-of-view of a real-world depth sensor, such as a Microsoft Kinect. Lastly, segImg is a segmentation mask of the image where pixels each contain unique integers with object IDs. These are invaluable for training segmentation algorithms for robotic agents, such as a robotic arm that needs to identify objects to sort into respective bins or for a driverless car that wants to identify pedestrians, street signs, and roads. width, height, rgbImg, depthImg, segImg = pb.getCameraImage( width=224, height=224, viewMatrix=viewMatrix, projectionMatrix=projectionMatrix) Once you call this function, you should see the images that you rendered in the three windows in your viewer. If that is the case, then congrats! You have rendered your first object. You would probably want to convert these image buffers to NumPy vectors and save them with an imaging library such as PIL or imageio. PyBullet makes our task of creating a virtual scene to generate training images fairly simple. With the concepts discussed in this tutorial, you should be able to generate your own datasets for classification or segmentation. Additional augmentations might be worth exploring, such as adding noise to the position and orientation of the camera and rendered objects. One might also wish to replace the plane with a mock-up of the real-world environment you wish to train for. Hopefully this tutorial is a solid launching point for you to develop your own physical simulations for machine learning.
[ { "code": null, "e": 1015, "s": 172, "text": "When applying deep Reinforcement Learning (RL) to robotics, we are faced with a conundrum: how do we train a robot to do a task when deep learning requires hundreds of thousands, even millions, of examples? To achieve 96% grasp success on never-before-seen objects, researchers at Google and Berkeley trained a robotic agent through 580,000 real-world grasp attempts. This feat took seven robots and several weeks to accomplish. Without Google resources, it may seem hopeless for the average ML practitioner. We cannot expect to easily run hundreds of thousands of iterations of training using a physical robot, which is subject to wear-and-tear and requires human supervision, neither of which comes cheap. It would be much more feasible if we could pretrain such RL algorithms to drastically reduce the number of real world attempts needed." }, { "code": null, "e": 1662, "s": 1015, "text": "With the advent of deep learning, RL techniques have matured but so has the demand for data. In an attempt to bridge this gap, many researchers are exploring the synthetic generation of training data, utilizing 3D rendering techniques to produce mock-ups of the task environment. While this technique works wonders in the simulated environment, it does not generalize well to the real world. Anyone who has worked closely with deep learning has learned how effective it is at exploiting nuances in training data to “cheat” a task. In practice, the real world is out-of-sample for these models trained in simulation and, unsurprisingly, they fail." }, { "code": null, "e": 2327, "s": 1662, "text": "Recent research is focused towards reducing the “reality gap,” those noticeable differences between the real world and 3D-rendered facsimiles, to pretrain robotic agents in simulation and thus drastically reduce the amount of real-world training needed. By aggressively randomizing the appearance and dynamics of a simulation, models learn features that in theory should generalize to the real world. This can even reduce the number of training sessions needed to train a robot by 99% according to recent research. For computer vision tasks where producing hundreds of thousands, or even millions, of training images is infeasible, this method is highly appealing." }, { "code": null, "e": 2962, "s": 2327, "text": "Let’s say for example we wish to generate synthetic training data to pretrain a classifier that can distinguish between a collection of small objects. We wish to select an object, drop it into a virtual “bin,” and render a screenshot. Ideally, we want to repeat this process thousands of times with randomization to create a rich dataset of images of objects. To this end (and inspired by the work done at OpenAI and Google), I recently began my journey to generate training data for my own applications. This led me to PyBullet, a Python module designed for robotics and machine learning applications based on the Bullet Physics SDK." }, { "code": null, "e": 3848, "s": 2962, "text": "Unlike other 3D rendering solutions like Maya or Blender, PyBullet is focused on robotics and has native implementations for concepts like joints, dynamics simulation, forward and inverse kinematics, and more. In addition, it can be easily installed with a package manager, allowing you to seamlessly integrate other Python packages, like NumPy and TensorFlow, into your simulations. While similar to proprietary physics simulation software MuJoCo, PyBullet is both free and easy to install, so it is a great choice for someone looking to experiment with simulation and robotics. This guide is meant as an introduction for those wishing to generate training images, but the official PyBullet quick start guide can be found here. Note that this tutorial assumes you are using Python version ≥3.6 (if you are using an older version, try creating a virtual environment for this tutorial)." }, { "code": null, "e": 3920, "s": 3848, "text": "First things first, we will install PyBullet to our Python environment." }, { "code": null, "e": 3958, "s": 3920, "text": "pip install numpypip install pybullet" }, { "code": null, "e": 4114, "s": 3958, "text": "Note that installing NumPy first is optional, but recommended when rendering images, due to the overhead of copying image buffers between C/C++ and Python." }, { "code": null, "e": 4816, "s": 4114, "text": "Now that you have everything successfully installed, let us dive right into a PyBullet session. PyBullet relies on a client-server model, where your Python session sends and receives data from a simulation server. There are chiefly two types of servers: DIRECT and GUI. As the name implies, GUI allows you to see the physical simulation in a GUI. DIRECT is useful for rendering headlessly and can be used for efficient rendering without a GPU. DIRECT will be the mode of choice when we are ready to render thousands of images as training data, but for now we will select GUI. Let us begin by initializing a PyBullet server. Start by launching a python interactive session and then enter the following:" }, { "code": null, "e": 4872, "s": 4816, "text": "import pybullet as pbphysicsClient = pb.connect(pb.GUI)" }, { "code": null, "e": 5292, "s": 4872, "text": "This step is necessary, as it instantiates the world simulation that you will work with. The physicsClient variable holds a unique ID for that server. This makes it possible in PyBullet to run multiple servers, even across multiple machines, and manage them from a single script by keeping track of these IDs. Many entities in PyBullet are similarly referred to by their IDs, including objects, colliders, and textures." }, { "code": null, "e": 5666, "s": 5292, "text": "Now you should see a simulation window pop up. That’s great! It means your simulation is working. You should see a primary viewport with additional windows for RGB, depth, and segmentation data. The world should be completely empty. Let’s first create a plane for our simulation. This plane comes with the pybullet_data package and can be easily loaded into any simulation." }, { "code": null, "e": 5777, "s": 5666, "text": "import pybullet_datapb.setAdditionalSearchPath(pybullet_data.getDataPath())planeId = pb.loadURDF(‘plane.urdf’)" }, { "code": null, "e": 6090, "s": 5777, "text": "This does a few things. First, it loads another module called pybullet_data, which contains placeholder URDFs for many useful things. This is added to the path, so that when we finally call loadURDF it knows where to find ‘plane.urdf’ and loads it into our scene. Now we should have a plane that spans our scene." }, { "code": null, "e": 6552, "s": 6090, "text": "The most supported file formats in PyBullet are URDF, SDF, and MJCF. These formats are very easy to load and configure and have their own specialized loading functions. However, many of the 3D models we find on the web are in the simple and popular Wavefront OBJ file format. It is possible to load these, but requires knowing a bit more about the nuts-and-bolts of models in PyBullet, so we will bite the bullet and learn to load our own models with OBJ files." }, { "code": null, "e": 6837, "s": 6552, "text": "We will be using a dataset of procedurally generated objects for simulation tasks. This set consists of 1000 OBJ files which include corresponding colliders, materials, and URDF versions. Download those here and extract them into a folder called “random_urdfs” in your project folder." }, { "code": null, "e": 7406, "s": 6837, "text": "Every typical 3D object in a physical simulation consists of a visual mesh to describe the way an object appears and a collider mesh that describes an object’s physical dimensions and how it will interact with the world, such as how it collides with other physical objects. Collider meshes, or simply colliders, are typically simplified representations of our visual mesh that are computationally much cheaper to calculate collisions with. Using the two types of meshes together enables our physical simulations to run efficiently while still being visually appealing." }, { "code": null, "e": 7576, "s": 7406, "text": "Let us start by loading the visual shape for an object using the createVisualShape function. We can start with an object from our procedurally generated objects dataset." }, { "code": null, "e": 7730, "s": 7576, "text": "visualShapeId = pb.createVisualShape( shapeType=pb.GEOM_MESH, fileName='random_urdfs/000/000.obj', rgbaColor=None, meshScale=[0.1, 0.1, 0.1])" }, { "code": null, "e": 8275, "s": 7730, "text": "The first parameter shapeType tells PyBullet what kind of shape we are loading. These include spheres, boxes, cylinders, planes, capsules, and meshes. In our case, we wish to load a custom mesh described in our OBJ file. You can also describe the RGB color (as a length-4 list describing red, green, blue, and alpha channels), which we set to None here. We will replace the object’s texture later. Lastly, OBJ files do not intrinsically have units, so we may need to specify a mesh scale to ensure that our object is not too large or too small." }, { "code": null, "e": 8412, "s": 8275, "text": "Now we have a visual shape to reference for our object, but no physical shape. Let us load this using the createCollisionShape function." }, { "code": null, "e": 8558, "s": 8412, "text": "collisionShapeId = pb.createCollisionShape( shapeType=pb.GEOM_MESH, fileName='random_urdfs/000/000_coll.obj', meshScale=[0.1, 0.1, 0.1])" }, { "code": null, "e": 8810, "s": 8558, "text": "Similar to the createVisualShape function, we need to specify that we want a mesh using shapeType and where to find the mesh data with fileName. We can and should also specify the mesh scale so that the collider has the same shape as the visual shape." }, { "code": null, "e": 9043, "s": 8810, "text": "At this point, we have references to a visual shape and a collider, but the two aren’t connected and we have no object yet. That is where createMultiBody comes in. This function unites these two and creates an instance of an object." }, { "code": null, "e": 9263, "s": 9043, "text": "multiBodyId = pb.createMultiBody( baseMass=1.0, baseCollisionShapeIndex=collisionShapeId, baseVisualShapeIndex=visualShapeId, basePosition=[0, 0, 1], baseOrientation=pb.getQuaternionFromEuler([0, 0, 0]))" }, { "code": null, "e": 9613, "s": 9263, "text": "We pass the IDs of our collider and visual shapes to createMultiBody to create a new object. This object needs a position and orientation to know where to place it in the physical world and a mass to know how it should interact with other objects. Set position with a length-3 list of x, y, z coordinates. For simplicity, we set mass to 1.0 for now." }, { "code": null, "e": 10190, "s": 9613, "text": "Orientation is a little trickier and requires that we specify it in a length-4 list of quaternions. Quaternions are a useful 4-dimensional representation for rotation in 3D spaces that are crucially used in computer graphics software like Blender, Maya, and Unity to avoid rotational artifacts such as gimbal lock. PyBullet has a convenience function called getQuaternionFromEuler that allows us to describe rotation in rotations about the x, y, and z axes, which are easier for human beings to visualize and understand. This representation of rotation is called Euler angles." }, { "code": null, "e": 10368, "s": 10190, "text": "Note: if you receive a message like “Unsupported texture image format [random_urdfs/000/000.png],” then ignore it. We will override the default texture in the next step anyways." }, { "code": null, "e": 10813, "s": 10368, "text": "Success! We have generated a physical object and placed it in our world. Recall from earlier that we want to randomize the appearance and dynamics of our 3D models. Let us start with the appearance and download and extract the Describable Textures Dataset here. This contains thousands of images comprised of 47 texture categories. Extract these into a folder called “dtd”. Let us pick one of these textures at random and apply it to our model." }, { "code": null, "e": 11103, "s": 10813, "text": "import os, glob, randomtexture_paths = glob.glob(os.path.join('dtd', '**', '*.jpg'), recursive=True)random_texture_path = texture_paths[random.randint(0, len(texture_paths) - 1)]textureId = pb.loadTexture(random_texture_path)pb.changeVisualShape(multiBodyId, -1, textureUniqueId=textureId)" }, { "code": null, "e": 11569, "s": 11103, "text": "This snippet recursively grabs a list of paths to all of the textures in folder “dtd” with extension “.jpg” and randomly samples a single one. Then it passes it to function loadTexture to load a texture and create an ID. It then uses the changeVisualShape function to apply the texture with textureId to object with multiBodyId. Now your object should have the texture applied to it. You can also apply this same method to attach a texture to the plane if you wish." }, { "code": null, "e": 11969, "s": 11569, "text": "Note that the -1 is necessary for required parameter jointIndex, which specifies the link you wish to apply the texture to. Links are useful for creating objects with hierarchies of moving parts, like robots with many joints. This is an important concept in PyBullet, but is out of the scope of this tutorial, so we supply a value “-1” to tell it to apply it to the base object rather than any link." }, { "code": null, "e": 12188, "s": 11969, "text": "So far, we have created our simulation, but nothing is moving. There are a few reasons for this. First of all, we haven’t applied any gravity to the scene, so our object is floating in space. Let us do that real quick." }, { "code": null, "e": 12214, "s": 12188, "text": "pb.setGravity(0, 0, -9.8)" }, { "code": null, "e": 12471, "s": 12214, "text": "That applies a downward negative acceleration of -9.8 m/s2 to our objects in the scene, just like we experience on the surface of planet Earth. However, your object still is not falling like you would expect. That is because the simulation is not stepping." }, { "code": null, "e": 12804, "s": 12471, "text": "There are two ways to step through your simulation: manually call stepSimulation to proceed the simulation by one time step or call setRealTimeSimulation to render in real time. For demonstration purposes, we will use the latter, but you will probably wish to use stepSimulation once we start rendering batches of objects in a loop." }, { "code": null, "e": 12832, "s": 12804, "text": "pb.setRealTimeSimulation(1)" }, { "code": null, "e": 13049, "s": 12832, "text": "Set to “1” to enable or “0” to disable. Now your object should fall and hit the ground. By the way, the default time step is 1/240 seconds, but you can override this default if desired using the setTimeStep function." }, { "code": null, "e": 13355, "s": 13049, "text": "We now have a method to load a plane, place an OBJ file on our plane, apply a texture to the object, and render the scene. The last piece of the puzzle is rendering an image of our object. Essentially, we want to place a virtual camera over our object, point it downward at our object, and take a picture." }, { "code": null, "e": 13760, "s": 13355, "text": "Whether we are looking to solve a classification or segmentation task, PyBullet makes taking pictures of our simulation fairly straightforward with the getCameraImage function, which renders an RGB image, a segmentation mask, and a depth buffer simultaneously. However, we need to first specify the extrinsic and intrinsic properties of our camera, a process that is a bit more involved than it may seem." }, { "code": null, "e": 14316, "s": 13760, "text": "The camera extrinsic properties essentially describe how our camera is positioned in the world, such as its orientation and position. The camera intrinsic properties describe properties of the camera itself, such as the field-of-view (FOV) and the aspect ratio of its sensor (e.g. 4:3, 16:9, etc.). In PyBullet, we describe these properties with a view matrix and a projection matrix, respectively. The PyBullet quick start guide links to a great resource to learn more about the camera extrinsic and intrinsic properties and their corresponding matrices." }, { "code": null, "e": 14661, "s": 14316, "text": "The camera view matrix is a complicated 4x4 matrix, but in simplest terms it describes where the camera is and in what direction it is pointing. There are some useful helper functions for creating this matrix by specifying position and rotation more directly. The function computeViewMatrix can create this matrix in exchange for three vectors." }, { "code": null, "e": 14792, "s": 14661, "text": "viewMatrix = pb.computeViewMatrix( cameraEyePosition=[0, 0, 3], cameraTargetPosition=[0, 0, 0], cameraUpVector=[0, 1, 0])" }, { "code": null, "e": 15476, "s": 14792, "text": "As the name implies, cameraEyePosition describes the physical location of the camera in x, y, and z coordinates. We will place it 3 units directly above the plane, centered over our object. Next we describe the point that we wish the camera to face with cameraTargetPosition. We want it to look straight down at our object, so we point it at the origin. Lastly, we need to describe the orientation of the camera. We do this with cameraUpVector, which is a vector that points out of the top of our camera. We point this out along the y axis. Our camera should now be pointing directly downward so that the image plane that it renders is perfectly parallel with the plane we generated." }, { "code": null, "e": 15726, "s": 15476, "text": "The projection matrix, much like the view matrix, can be created using a few helper functions. In this case, the computeProjectionMatrixFOV function describes our camera’s intrinsic properties in the simplest and most pertinent ways to our use case." }, { "code": null, "e": 15835, "s": 15726, "text": "projectionMatrix = pb.computeProjectionMatrixFOV( fov=45.0, aspect=1.0, nearVal=0.1, farVal=3.1)" }, { "code": null, "e": 16428, "s": 15835, "text": "The fov parameter specifies the camera FOV in degrees. It describes how “wide” the camera’s visual field is and is similar in principle to the focal length of a real camera. The aspect parameter describes the camera aspect ratio, which we set to 1.0 here for simplicity. The nearVal and farVal parameters describe the minimum and maximum distance, respectively, at which the camera will render objects. Since our camera is 3 units above the plane, we set farVal to 3.1 to just include that plane. These parameters are defined in the OpenGL documentation and you can read more about them here." }, { "code": null, "e": 16547, "s": 16428, "text": "We have described our camera’s properties and are now ready to render some images. Let us do that with getCameraImage." }, { "code": null, "e": 17286, "s": 16547, "text": "This function returns three image buffers: rgbImg, depthImg, and segImg. rgbImg is a uint8 image with red, green, blue, and alpha channels of the camera’s visuals. depthImg is a floating-point grayscale image that describes the distance of individual rendered pixels from the camera. It can be used to model the field-of-view of a real-world depth sensor, such as a Microsoft Kinect. Lastly, segImg is a segmentation mask of the image where pixels each contain unique integers with object IDs. These are invaluable for training segmentation algorithms for robotic agents, such as a robotic arm that needs to identify objects to sort into respective bins or for a driverless car that wants to identify pedestrians, street signs, and roads." }, { "code": null, "e": 17441, "s": 17286, "text": "width, height, rgbImg, depthImg, segImg = pb.getCameraImage( width=224, height=224, viewMatrix=viewMatrix, projectionMatrix=projectionMatrix)" }, { "code": null, "e": 17758, "s": 17441, "text": "Once you call this function, you should see the images that you rendered in the three windows in your viewer. If that is the case, then congrats! You have rendered your first object. You would probably want to convert these image buffers to NumPy vectors and save them with an imaging library such as PIL or imageio." } ]
Insert values in a table by MySQL SELECT from another table in MySQL?
Fir this, use INSERT INTO SELECT statement. Let us first create a table − mysql> create table DemoTable1 -> ( -> Id int, -> Name varchar(20), -> Age int -> ); Query OK, 0 rows affected (1.72 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1 values(100,'Chris',24); Query OK, 1 row affected (0.61 sec) mysql> insert into DemoTable1 values(101,'Adam',23); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable1 values(102,'John',25); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1 values(103,'Carol',26); Query OK, 1 row affected (0.26 sec) Display all records from the table using select statement − mysql> select * from DemoTable1; This will produce the following output − +------+-------+------+ | Id | Name | Age | +------+-------+------+ | 100 | Chris | 24 | | 101 | Adam | 23 | | 102 | John | 25 | | 103 | Carol | 26 | +------+-------+------+ 4 rows in set (0.00 sec) Here is the query to create second table − mysql> create table DemoTable2 -> ( -> EmployeeId int, -> EmployeeFirstName varchar(20), -> EmployeeAge int -> ); Query OK, 0 rows affected (1.63 sec) Here is the query to insert values in DemoTable2 from MySQL select from DemoTable1 − mysql> insert into DemoTable2(EmployeeId,EmployeeFirstName,EmployeeAge) select Id,Name,Age from DemoTable1 where Id=101; Query OK, 1 row affected (0.17 sec) Records: 1 Duplicates: 0 Warnings: 0 Let us check the table records − mysql> select * from DemoTable2; Here is the query to create second table − +------------+-------------------+-------------+ | EmployeeId | EmployeeFirstName | EmployeeAge | +------------+-------------------+-------------+ | 101 | Adam | 23 | +------------+-------------------+-------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1136, "s": 1062, "text": "Fir this, use INSERT INTO SELECT statement. Let us first create a table −" }, { "code": null, "e": 1273, "s": 1136, "text": "mysql> create table DemoTable1\n -> (\n -> Id int,\n -> Name varchar(20),\n -> Age int\n -> );\nQuery OK, 0 rows affected (1.72 sec)" }, { "code": null, "e": 1329, "s": 1273, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1687, "s": 1329, "text": "mysql> insert into DemoTable1 values(100,'Chris',24);\nQuery OK, 1 row affected (0.61 sec)\nmysql> insert into DemoTable1 values(101,'Adam',23);\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable1 values(102,'John',25);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable1 values(103,'Carol',26);\nQuery OK, 1 row affected (0.26 sec)" }, { "code": null, "e": 1747, "s": 1687, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1780, "s": 1747, "text": "mysql> select * from DemoTable1;" }, { "code": null, "e": 1821, "s": 1780, "text": "This will produce the following output −" }, { "code": null, "e": 2036, "s": 1821, "text": "+------+-------+------+\n| Id | Name | Age |\n+------+-------+------+\n| 100 | Chris | 24 |\n| 101 | Adam | 23 |\n| 102 | John | 25 |\n| 103 | Carol | 26 |\n+------+-------+------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2079, "s": 2036, "text": "Here is the query to create second table −" }, { "code": null, "e": 2245, "s": 2079, "text": "mysql> create table DemoTable2\n -> (\n -> EmployeeId int,\n -> EmployeeFirstName varchar(20),\n -> EmployeeAge int\n -> );\nQuery OK, 0 rows affected (1.63 sec)" }, { "code": null, "e": 2330, "s": 2245, "text": "Here is the query to insert values in DemoTable2 from MySQL select from DemoTable1 −" }, { "code": null, "e": 2524, "s": 2330, "text": "mysql> insert into DemoTable2(EmployeeId,EmployeeFirstName,EmployeeAge) select Id,Name,Age from DemoTable1 where Id=101;\nQuery OK, 1 row affected (0.17 sec)\nRecords: 1 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 2557, "s": 2524, "text": "Let us check the table records −" }, { "code": null, "e": 2590, "s": 2557, "text": "mysql> select * from DemoTable2;" }, { "code": null, "e": 2633, "s": 2590, "text": "Here is the query to create second table −" }, { "code": null, "e": 2902, "s": 2633, "text": "+------------+-------------------+-------------+\n| EmployeeId | EmployeeFirstName | EmployeeAge |\n+------------+-------------------+-------------+\n| 101 | Adam | 23 |\n+------------+-------------------+-------------+\n1 row in set (0.00 sec)" } ]
A Deep Dive into Neo4j Link Prediction Pipeline and FastRP Embedding Algorithm | by Tomaz Bratanic | Towards Data Science
In my previous blog post, I introduced the newly available Link Prediction pipeline in the Neo4j Graph Data Science library. Since the post, I took more time to dig deeper and learn the inner workings of the pipeline. I’ve learned a couple of things along the way that I want to share with you. At first, I intended to show how the Link Prediction pipeline combines node properties to generate input features of the Link Prediction model. However, when I was developing the content, I noticed a couple of insights about using the FastRP embedding algorithm. Therefore, by the end of this blog post, you will hopefully learn more about the FastRP embedding model and how you can combine multiple node features as an input to the Link Prediction model. The code used in this post is available on GitHub. I had to find a small network so I easily visualize results as we go along. I decided to use the interaction network from the first season of the Game of Thrones TV show made available by Andrew Beveridge. The graph model consists of characters and their interactions. We will treat the interaction relationship as undirected, where is character A interacts with character B, this directly implies that character B also interacted with character A. We also know how many times two characters interacted, and we store that information as the relationship property. If you want to follow along with examples in this post, I recommend using a Blank project in Neo4j Sandbox. It is a free cloud instance of Neo4j database that comes pre-installed with both APOC and Graph Data Science plugins. The dataset is available on GitHub, so we can easily import it into Neo4j with the following Cypher query: LOAD CSV WITH HEADERS FROM "https://raw.githubusercontent.com/mathbeveridge/gameofthrones/master/data/got-s1-edges.csv" as rowMERGE (s:Character{name:row.Source})MERGE (t:Character{name:row.Target})MERGE (s)-[i:INTERACTS]-(t)SET i.weight = toInteger(row.Weight) Under the hood, the link prediction model in Neo4j uses a logistic regression classifier. We are dealing with a binary classification problem, where we want to predict if a link exists between a pair of nodes or not. On a high level, the link prediction pipeline follows the following steps: In this post, we will focus on the first two steps, so let’s take a closer look at what is happening there. As a first step, you have to define node features. For example, you could use custom node properties such as age or gender. You can also use graph algorithms such as PageRank or Betweenness centrality as initial node features. In this blog post, we will start by using FastRP node embeddings to define initial node features. The nice thing about the FastRP embedding algorithm is that it captures the network information and preserves the similarity in embedding space between neighboring nodes that are close in a graph. At the moment, you can’t use pairwise information such as the number of common neighbors or the length of the shortest path between a pair of nodes as input features. In the second step, the link feature combiner creates a single feature from a pair of node properties. Currently, there are three techniques that you can use to combine a pair of node properties into a single link feature vector: Cosine distance L2 or Euclidian distance Hadamard product In the above example, I have used the Hadamard product to combine a pair of node properties into a single link feature vector. All the available link feature combiner techniques are order-invariant as the Link Prediction pipeline supports predicting only undirected relationships at the moment. You can use multiple link feature combiners in a single pipeline to define several feature vectors, which are then concatenated as an input to the Link Prediction model. I’ll walk you through an example later in the post. Once the node features and link feature combiner are defined, you can train the model to predict new connections. You can preprocess node features before defining the Link Prediction pipeline. You can also include them directly in the pipeline definition if you only use graph algorithms such as node embeddings or centrality measures as node features. In the first example, we will use the FastRP embeddings as our Link Prediction model node features. Therefore, we could potentially include them in the pipeline definition. However, we will first do a short analysis of the node embedding results, so we need to store the node embeddings to the graph before diving into the pipeline definition. We start by projecting an undirected named graph. Take a look at the documentation for more information about the inner workings of the Graph Data Science library. CALL gds.graph.create('gots1', 'Character', {INTERACTS:{orientation:'UNDIRECTED', properties:'weight'}}) We will use Louvain, a community detection algorithm, to help us better understand the results of the FastRP embedding algorithm. You can use the following Cypher query to store the community structure information back to the database. CALL gds.louvain.write('gots1', {writeProperty:'louvain', relationshipWeightProperty:'weight'}) Throughout this blog post, I will be using Neo4j Bloom to visualize the results of algorithms and link predictions. Take a look at this guide if you want to learn how to visualize networks with Bloom. Now we can go ahead and execute the FastRP embedding algorithm. The algorithm will produce an embedding or a fixed-size vector for every node in the graph. My friend CJ Sullivan wrote an excellent article explaining the inner working of the FastRP algorithm. CALL gds.fastRP.write('gots1', {writeProperty:'embedding', embeddingDimension:56, relationshipWeightProperty:'weight'}) First, we will evaluate FastRP embeddings with a t-SNE scatter plot visualization. The stored node embeddings are vectors with a length of 56, as defined by the embeddingDimension parameter. The t-SNE algorithm is a dimensionality reduction algorithm, which we can use to reduce the embedding dimension to two. Having vectors with length two allows us to visualize them with a scatter plot. The Python code I used for dimensionality reduction and scatter plot visualization is: This code produces the following visualization: FastRP embeddings and the Louvain algorithm were executed independently, and yet, we can observe that FastRP embeddings cluster nodes in the same community close in the embedding space. This is no surprise as FastRP is a community-based node embedding algorithm, meaning that nodes close in the graph will be also close in the embedding space. Next, we will evaluate the cosine similarity between nodes in the graph. MATCH (c:Character)WITH {item:id(c), weights: c.embedding} AS userDataWITH collect(userData) AS dataCALL gds.alpha.similarity.cosine.stats({ data: data, topK: 1000, similarityCutoff: 0.1})YIELD nodes, similarityPairs, min, max, mean, p25, p50, p75, p90, p95, p99RETURN nodes, similarityPairs, min, max, mean, p25, p50, p75, p90, p95, p99 Results An average cosine similarity coefficient between all nodes in the graph is around 0.5. Around 25% of the node pairs have a cosine similarity greater than 0.81. Nodes are so similar in the embedding space because we have a tiny graph of only 126 nodes. Next, we will evaluate the cosine and euclidian distance between pairs of nodes connected by a relationship. Results Most node pairs that are connected with a relationship have a high cosine similarity. Again, this is expected as the FastRP is designed to translate the network topology structure into embedding space. Therefore, we expect the neighboring nodes in the graph to be very similar in the embedding space. We will examine the node pairs connected in the network with a cosine similarity of less than 0.5 as this is a bit more unexpected. First, we have to tag them with Cypher: MATCH p=(c1:Character)-[i:INTERACTS]->(c2:Character)WHERE gds.alpha.similarity.cosine(c1.embedding, c2.embedding) < 0.5SET i.show = True And now, we can go ahead and visualize them with Neo4j Bloom. It seems that pairs of connected nodes with a lower cosine similarity mainly occur when we have connections between various clusters or communities in the network. If you remember the t-SNE visualization, the nodes in the same community are nicely grouped in the embedding space. However, we have a couple of relationships between nodes from different communities. When we have connections between nodes from various communities, their similarity decreases. It also seems that these nodes have a higher degree, meaning they have many links within their community and then a couple of links to other communities. Therefore, they are more similar to neighbors within their community and then less similar to neighbors from other clusters. We’ve got the embeddings ready, and we know that pairs of connected nodes are highly likely to have a high cosine similarity in the embedding space. Now, we will evaluate how different link feature combiners affect the output of the link prediction model. Cosine combiner Interestingly enough, the first combiner we will take a look at is the Cosine similarity combiner. The Link Feature combiner takes pairs of node features and combines them into a single link feature, which is then used as training data to the logistic regression model that will predict new links. We have already done the cosine similarity analysis, so we know that node pairs with a high cosine similarity are likely to be connected. Therefore, you might imagine that new predicted links will be between pairs of not yet connected nodes with high cosine similarity, as this is precisely how our training data looks. The Python script we will be using to produce link predictions is: It is a bit lengthy script as we need to define the entire Link Prediction pipeline for each link feature combiner option. Finally, the predicted links are stored to Neo4j so that we can visualize them with Bloom. In my previous blog post, I did a step-by-step explanation of the pipeline. As mentioned, I have prepared a Jupyter Notebook with all the code, so you don’t have to copy it from the blog post directly. Let’s examine the predicted links using the Cosine Link Feature combiner. The average Euclidian and Cosine similarity of node pairs that have predicted links is: As we might imagine, the cosine similarity between nodes of predicted links is on average 0.999. Thus, the results agree with our training data. Furthermore, we can learn a bit about FastRP embeddings from the results. Peripheral nodes with a low degree are very similar in the embedding space, even if they are not directly connected. For example, the blue nodes in the bottom-left part of the visualizations are all very similar. All four nodes have only a single relationship, and they share their only neighbor nodes. L2 link feature combiner Next, we will take a look at the L2 link feature combiner. L2 link feature combiner calculates the Euclidian distance between two node features. The results are almost identical to the Cosine Link Feature combiner. Seems that the FastRP embedding algorithm optimizes both Cosine and Euclidian distance similarities between neighboring nodes in the network. Hadamard link feature combiner The Hadamard link feature combiner uses the Hadamard product to produce a link feature. The Hadamard product is simply entrywise multiplication. Let’s examine the predicted links using the Hadamard link feature combiner. The average Euclidian and Cosine similarity of node pairs that have predicted links is: Some of the predicted links are similar to the Cosine and Euclidian link feature combiner results. For example, the predicted links in the red community are almost identical. On the other hand, the model predicted more links in the center instead of the periphery of the blue cluster. In the previous example, we have only used a single link feature combiner. In the case of Cosine or L2 link feature combiner, we have effectively only used a single input feature to the logistic regression model. In practice, it makes sense to have multiple input features that best describe your domain. As a demonstration, we will add the Preferential attachment input as the second link feature. Looking at the documentation in Neo4j, the Preferential attachment is defined as multiplying node degrees between a pair of nodes. In practice, the preferential attachment model assumes that nodes with a higher node degree are more likely to form new connections. Unfortunately, we can’t automatically add the preferential attachment link feature just yet, but we can add it manually. To add the preferential attachment input feature, we will first calculate the node degree values for all nodes. You sometimes want to normalize the input features with logistic regression models, so I will show you how to scale features directly in the Link Prediction pipeline. Then we just need to add the Hadamard link feature combiner, which multiplies the input matrices, in this case, node degrees. So if I understand the math correctly, the resulting link feature should represent preferential attachment as we effectively multiply node degrees between pairs of nodes. In the Link Prediction pipeline, you can have as many link feature combiners as you wish. The results of all link feature combiners are then concatenated into a single vector that is used as an input to the Link Prediction logistic regression model. We can add the degree calculation and scaling directly into the pipeline and don’t have to prepare the degree features beforehand. We need to add the following three steps into our pipeline. The first query mutates the degree value to the named graph. The second step will scale the degree value using the MinMax scaler and mutate it as the scaledDegree property. Lastly, we use the Hadamard link feature combiner that combines node degrees. In the end, we’ll quickly evaluate how adding a secondary link feature affects the link prediction results. We get the following results using the Cosine link feature combiner with FastRP embeddings and Hadamard combiner with scaled node degrees. Adding the secondary link feature shifted predicted links from the network periphery to the center. In some way, it makes sense because the preferential attachment prefers links between nodes with a higher degree, and those nodes are usually located in the center of the network. We get the following results using the Euclidian link feature combiner with FastRP embeddings and Hadamard combiner with scaled node degrees. The secondary link feature didn’t really affect the results. I’ve also tried not scaling the node degree values and then the predicted links shift strongly towards the center. If we don’t scale the node degrees before using the Hadamard combiner, the preferential attachment feature becomes dominant. Therefore, the predicted links are between nodes with a high degree instead of the low degree nodes on the periphery. I have really enjoyed writing this blog post and learned a lot about FastRP embedding algorithm and Link Prediction pipeline along the way. A quick summary would be: FastRP is more likely to assign high similarity between neighboring nodes with a low degree On the other hand, the cosine similarity between connected nodes of different communities could be lower than 0.5 Using multiple link feature combiners can help you better describe your domain Scaling node features influences the result of Link Prediction logistic regression model I encourage you to start a free Neo4j Sandbox project and start predicting new connections in your graphs. Let me know how it goes! As always, the code is available on GitHub.
[ { "code": null, "e": 922, "s": 171, "text": "In my previous blog post, I introduced the newly available Link Prediction pipeline in the Neo4j Graph Data Science library. Since the post, I took more time to dig deeper and learn the inner workings of the pipeline. I’ve learned a couple of things along the way that I want to share with you. At first, I intended to show how the Link Prediction pipeline combines node properties to generate input features of the Link Prediction model. However, when I was developing the content, I noticed a couple of insights about using the FastRP embedding algorithm. Therefore, by the end of this blog post, you will hopefully learn more about the FastRP embedding model and how you can combine multiple node features as an input to the Link Prediction model." }, { "code": null, "e": 973, "s": 922, "text": "The code used in this post is available on GitHub." }, { "code": null, "e": 1179, "s": 973, "text": "I had to find a small network so I easily visualize results as we go along. I decided to use the interaction network from the first season of the Game of Thrones TV show made available by Andrew Beveridge." }, { "code": null, "e": 1537, "s": 1179, "text": "The graph model consists of characters and their interactions. We will treat the interaction relationship as undirected, where is character A interacts with character B, this directly implies that character B also interacted with character A. We also know how many times two characters interacted, and we store that information as the relationship property." }, { "code": null, "e": 1763, "s": 1537, "text": "If you want to follow along with examples in this post, I recommend using a Blank project in Neo4j Sandbox. It is a free cloud instance of Neo4j database that comes pre-installed with both APOC and Graph Data Science plugins." }, { "code": null, "e": 1870, "s": 1763, "text": "The dataset is available on GitHub, so we can easily import it into Neo4j with the following Cypher query:" }, { "code": null, "e": 2132, "s": 1870, "text": "LOAD CSV WITH HEADERS FROM \"https://raw.githubusercontent.com/mathbeveridge/gameofthrones/master/data/got-s1-edges.csv\" as rowMERGE (s:Character{name:row.Source})MERGE (t:Character{name:row.Target})MERGE (s)-[i:INTERACTS]-(t)SET i.weight = toInteger(row.Weight)" }, { "code": null, "e": 2424, "s": 2132, "text": "Under the hood, the link prediction model in Neo4j uses a logistic regression classifier. We are dealing with a binary classification problem, where we want to predict if a link exists between a pair of nodes or not. On a high level, the link prediction pipeline follows the following steps:" }, { "code": null, "e": 2532, "s": 2424, "text": "In this post, we will focus on the first two steps, so let’s take a closer look at what is happening there." }, { "code": null, "e": 3221, "s": 2532, "text": "As a first step, you have to define node features. For example, you could use custom node properties such as age or gender. You can also use graph algorithms such as PageRank or Betweenness centrality as initial node features. In this blog post, we will start by using FastRP node embeddings to define initial node features. The nice thing about the FastRP embedding algorithm is that it captures the network information and preserves the similarity in embedding space between neighboring nodes that are close in a graph. At the moment, you can’t use pairwise information such as the number of common neighbors or the length of the shortest path between a pair of nodes as input features." }, { "code": null, "e": 3451, "s": 3221, "text": "In the second step, the link feature combiner creates a single feature from a pair of node properties. Currently, there are three techniques that you can use to combine a pair of node properties into a single link feature vector:" }, { "code": null, "e": 3467, "s": 3451, "text": "Cosine distance" }, { "code": null, "e": 3492, "s": 3467, "text": "L2 or Euclidian distance" }, { "code": null, "e": 3509, "s": 3492, "text": "Hadamard product" }, { "code": null, "e": 4026, "s": 3509, "text": "In the above example, I have used the Hadamard product to combine a pair of node properties into a single link feature vector. All the available link feature combiner techniques are order-invariant as the Link Prediction pipeline supports predicting only undirected relationships at the moment. You can use multiple link feature combiners in a single pipeline to define several feature vectors, which are then concatenated as an input to the Link Prediction model. I’ll walk you through an example later in the post." }, { "code": null, "e": 4140, "s": 4026, "text": "Once the node features and link feature combiner are defined, you can train the model to predict new connections." }, { "code": null, "e": 4887, "s": 4140, "text": "You can preprocess node features before defining the Link Prediction pipeline. You can also include them directly in the pipeline definition if you only use graph algorithms such as node embeddings or centrality measures as node features. In the first example, we will use the FastRP embeddings as our Link Prediction model node features. Therefore, we could potentially include them in the pipeline definition. However, we will first do a short analysis of the node embedding results, so we need to store the node embeddings to the graph before diving into the pipeline definition. We start by projecting an undirected named graph. Take a look at the documentation for more information about the inner workings of the Graph Data Science library." }, { "code": null, "e": 4994, "s": 4887, "text": "CALL gds.graph.create('gots1', 'Character', {INTERACTS:{orientation:'UNDIRECTED', properties:'weight'}})" }, { "code": null, "e": 5230, "s": 4994, "text": "We will use Louvain, a community detection algorithm, to help us better understand the results of the FastRP embedding algorithm. You can use the following Cypher query to store the community structure information back to the database." }, { "code": null, "e": 5328, "s": 5230, "text": "CALL gds.louvain.write('gots1', {writeProperty:'louvain', relationshipWeightProperty:'weight'})" }, { "code": null, "e": 5529, "s": 5328, "text": "Throughout this blog post, I will be using Neo4j Bloom to visualize the results of algorithms and link predictions. Take a look at this guide if you want to learn how to visualize networks with Bloom." }, { "code": null, "e": 5788, "s": 5529, "text": "Now we can go ahead and execute the FastRP embedding algorithm. The algorithm will produce an embedding or a fixed-size vector for every node in the graph. My friend CJ Sullivan wrote an excellent article explaining the inner working of the FastRP algorithm." }, { "code": null, "e": 5910, "s": 5788, "text": "CALL gds.fastRP.write('gots1', {writeProperty:'embedding', embeddingDimension:56, relationshipWeightProperty:'weight'})" }, { "code": null, "e": 6388, "s": 5910, "text": "First, we will evaluate FastRP embeddings with a t-SNE scatter plot visualization. The stored node embeddings are vectors with a length of 56, as defined by the embeddingDimension parameter. The t-SNE algorithm is a dimensionality reduction algorithm, which we can use to reduce the embedding dimension to two. Having vectors with length two allows us to visualize them with a scatter plot. The Python code I used for dimensionality reduction and scatter plot visualization is:" }, { "code": null, "e": 6436, "s": 6388, "text": "This code produces the following visualization:" }, { "code": null, "e": 6853, "s": 6436, "text": "FastRP embeddings and the Louvain algorithm were executed independently, and yet, we can observe that FastRP embeddings cluster nodes in the same community close in the embedding space. This is no surprise as FastRP is a community-based node embedding algorithm, meaning that nodes close in the graph will be also close in the embedding space. Next, we will evaluate the cosine similarity between nodes in the graph." }, { "code": null, "e": 7194, "s": 6853, "text": "MATCH (c:Character)WITH {item:id(c), weights: c.embedding} AS userDataWITH collect(userData) AS dataCALL gds.alpha.similarity.cosine.stats({ data: data, topK: 1000, similarityCutoff: 0.1})YIELD nodes, similarityPairs, min, max, mean, p25, p50, p75, p90, p95, p99RETURN nodes, similarityPairs, min, max, mean, p25, p50, p75, p90, p95, p99" }, { "code": null, "e": 7202, "s": 7194, "text": "Results" }, { "code": null, "e": 7563, "s": 7202, "text": "An average cosine similarity coefficient between all nodes in the graph is around 0.5. Around 25% of the node pairs have a cosine similarity greater than 0.81. Nodes are so similar in the embedding space because we have a tiny graph of only 126 nodes. Next, we will evaluate the cosine and euclidian distance between pairs of nodes connected by a relationship." }, { "code": null, "e": 7571, "s": 7563, "text": "Results" }, { "code": null, "e": 8044, "s": 7571, "text": "Most node pairs that are connected with a relationship have a high cosine similarity. Again, this is expected as the FastRP is designed to translate the network topology structure into embedding space. Therefore, we expect the neighboring nodes in the graph to be very similar in the embedding space. We will examine the node pairs connected in the network with a cosine similarity of less than 0.5 as this is a bit more unexpected. First, we have to tag them with Cypher:" }, { "code": null, "e": 8181, "s": 8044, "text": "MATCH p=(c1:Character)-[i:INTERACTS]->(c2:Character)WHERE gds.alpha.similarity.cosine(c1.embedding, c2.embedding) < 0.5SET i.show = True" }, { "code": null, "e": 8243, "s": 8181, "text": "And now, we can go ahead and visualize them with Neo4j Bloom." }, { "code": null, "e": 8980, "s": 8243, "text": "It seems that pairs of connected nodes with a lower cosine similarity mainly occur when we have connections between various clusters or communities in the network. If you remember the t-SNE visualization, the nodes in the same community are nicely grouped in the embedding space. However, we have a couple of relationships between nodes from different communities. When we have connections between nodes from various communities, their similarity decreases. It also seems that these nodes have a higher degree, meaning they have many links within their community and then a couple of links to other communities. Therefore, they are more similar to neighbors within their community and then less similar to neighbors from other clusters." }, { "code": null, "e": 9236, "s": 8980, "text": "We’ve got the embeddings ready, and we know that pairs of connected nodes are highly likely to have a high cosine similarity in the embedding space. Now, we will evaluate how different link feature combiners affect the output of the link prediction model." }, { "code": null, "e": 9252, "s": 9236, "text": "Cosine combiner" }, { "code": null, "e": 9351, "s": 9252, "text": "Interestingly enough, the first combiner we will take a look at is the Cosine similarity combiner." }, { "code": null, "e": 9870, "s": 9351, "text": "The Link Feature combiner takes pairs of node features and combines them into a single link feature, which is then used as training data to the logistic regression model that will predict new links. We have already done the cosine similarity analysis, so we know that node pairs with a high cosine similarity are likely to be connected. Therefore, you might imagine that new predicted links will be between pairs of not yet connected nodes with high cosine similarity, as this is precisely how our training data looks." }, { "code": null, "e": 9937, "s": 9870, "text": "The Python script we will be using to produce link predictions is:" }, { "code": null, "e": 10353, "s": 9937, "text": "It is a bit lengthy script as we need to define the entire Link Prediction pipeline for each link feature combiner option. Finally, the predicted links are stored to Neo4j so that we can visualize them with Bloom. In my previous blog post, I did a step-by-step explanation of the pipeline. As mentioned, I have prepared a Jupyter Notebook with all the code, so you don’t have to copy it from the blog post directly." }, { "code": null, "e": 10427, "s": 10353, "text": "Let’s examine the predicted links using the Cosine Link Feature combiner." }, { "code": null, "e": 10515, "s": 10427, "text": "The average Euclidian and Cosine similarity of node pairs that have predicted links is:" }, { "code": null, "e": 11037, "s": 10515, "text": "As we might imagine, the cosine similarity between nodes of predicted links is on average 0.999. Thus, the results agree with our training data. Furthermore, we can learn a bit about FastRP embeddings from the results. Peripheral nodes with a low degree are very similar in the embedding space, even if they are not directly connected. For example, the blue nodes in the bottom-left part of the visualizations are all very similar. All four nodes have only a single relationship, and they share their only neighbor nodes." }, { "code": null, "e": 11062, "s": 11037, "text": "L2 link feature combiner" }, { "code": null, "e": 11207, "s": 11062, "text": "Next, we will take a look at the L2 link feature combiner. L2 link feature combiner calculates the Euclidian distance between two node features." }, { "code": null, "e": 11419, "s": 11207, "text": "The results are almost identical to the Cosine Link Feature combiner. Seems that the FastRP embedding algorithm optimizes both Cosine and Euclidian distance similarities between neighboring nodes in the network." }, { "code": null, "e": 11450, "s": 11419, "text": "Hadamard link feature combiner" }, { "code": null, "e": 11595, "s": 11450, "text": "The Hadamard link feature combiner uses the Hadamard product to produce a link feature. The Hadamard product is simply entrywise multiplication." }, { "code": null, "e": 11671, "s": 11595, "text": "Let’s examine the predicted links using the Hadamard link feature combiner." }, { "code": null, "e": 11759, "s": 11671, "text": "The average Euclidian and Cosine similarity of node pairs that have predicted links is:" }, { "code": null, "e": 12044, "s": 11759, "text": "Some of the predicted links are similar to the Cosine and Euclidian link feature combiner results. For example, the predicted links in the red community are almost identical. On the other hand, the model predicted more links in the center instead of the periphery of the blue cluster." }, { "code": null, "e": 13404, "s": 12044, "text": "In the previous example, we have only used a single link feature combiner. In the case of Cosine or L2 link feature combiner, we have effectively only used a single input feature to the logistic regression model. In practice, it makes sense to have multiple input features that best describe your domain. As a demonstration, we will add the Preferential attachment input as the second link feature. Looking at the documentation in Neo4j, the Preferential attachment is defined as multiplying node degrees between a pair of nodes. In practice, the preferential attachment model assumes that nodes with a higher node degree are more likely to form new connections. Unfortunately, we can’t automatically add the preferential attachment link feature just yet, but we can add it manually. To add the preferential attachment input feature, we will first calculate the node degree values for all nodes. You sometimes want to normalize the input features with logistic regression models, so I will show you how to scale features directly in the Link Prediction pipeline. Then we just need to add the Hadamard link feature combiner, which multiplies the input matrices, in this case, node degrees. So if I understand the math correctly, the resulting link feature should represent preferential attachment as we effectively multiply node degrees between pairs of nodes." }, { "code": null, "e": 13785, "s": 13404, "text": "In the Link Prediction pipeline, you can have as many link feature combiners as you wish. The results of all link feature combiners are then concatenated into a single vector that is used as an input to the Link Prediction logistic regression model. We can add the degree calculation and scaling directly into the pipeline and don’t have to prepare the degree features beforehand." }, { "code": null, "e": 14204, "s": 13785, "text": "We need to add the following three steps into our pipeline. The first query mutates the degree value to the named graph. The second step will scale the degree value using the MinMax scaler and mutate it as the scaledDegree property. Lastly, we use the Hadamard link feature combiner that combines node degrees. In the end, we’ll quickly evaluate how adding a secondary link feature affects the link prediction results." }, { "code": null, "e": 14343, "s": 14204, "text": "We get the following results using the Cosine link feature combiner with FastRP embeddings and Hadamard combiner with scaled node degrees." }, { "code": null, "e": 14623, "s": 14343, "text": "Adding the secondary link feature shifted predicted links from the network periphery to the center. In some way, it makes sense because the preferential attachment prefers links between nodes with a higher degree, and those nodes are usually located in the center of the network." }, { "code": null, "e": 14765, "s": 14623, "text": "We get the following results using the Euclidian link feature combiner with FastRP embeddings and Hadamard combiner with scaled node degrees." }, { "code": null, "e": 14941, "s": 14765, "text": "The secondary link feature didn’t really affect the results. I’ve also tried not scaling the node degree values and then the predicted links shift strongly towards the center." }, { "code": null, "e": 15184, "s": 14941, "text": "If we don’t scale the node degrees before using the Hadamard combiner, the preferential attachment feature becomes dominant. Therefore, the predicted links are between nodes with a high degree instead of the low degree nodes on the periphery." }, { "code": null, "e": 15350, "s": 15184, "text": "I have really enjoyed writing this blog post and learned a lot about FastRP embedding algorithm and Link Prediction pipeline along the way. A quick summary would be:" }, { "code": null, "e": 15442, "s": 15350, "text": "FastRP is more likely to assign high similarity between neighboring nodes with a low degree" }, { "code": null, "e": 15556, "s": 15442, "text": "On the other hand, the cosine similarity between connected nodes of different communities could be lower than 0.5" }, { "code": null, "e": 15635, "s": 15556, "text": "Using multiple link feature combiners can help you better describe your domain" }, { "code": null, "e": 15724, "s": 15635, "text": "Scaling node features influences the result of Link Prediction logistic regression model" }, { "code": null, "e": 15856, "s": 15724, "text": "I encourage you to start a free Neo4j Sandbox project and start predicting new connections in your graphs. Let me know how it goes!" } ]
How do we create a string from the contents of a file in java?
In Java you can read the contents of a file in several ways one way is to read it to a string using the java.util.Scanner class, to do so, Instantiate the Scanner class, with the path of the file to be read, as a parameter to its constructor. Instantiate the Scanner class, with the path of the file to be read, as a parameter to its constructor. Create an empty String buffer. Create an empty String buffer. Start a while loop with condition, if the Scanner has next line. i.e. hasNextLine() at while. Start a while loop with condition, if the Scanner has next line. i.e. hasNextLine() at while. Within the loop append each line of the file to the StringBuffer object using the append() method. Within the loop append each line of the file to the StringBuffer object using the append() method. Convert the contents of the contents of the buffer to String using the toString() method. Convert the contents of the contents of the buffer to String using the toString() method. Create a file with name sample.txt in the C directory in your system, copy and paste the following content in it. Tutorials Point is an E-learning company that set out on its journey to provide knowledge to that class of readers that responds better to online content. With Tutorials Point, you can learn at your own pace, in your own space. After a successful journey of providing the best learning content at tutorialspoint.com, we created our subscription based premium product called Tutorix to provide Simply Easy Learning in the best personalized way for K-12 students, and aspirants of competitive exams like IIT/JEE and NEET. Following Java program reads the contents of the file sample.txt in to a String and prints it. import java.io.File; import java.io.IOException; import java.util.Scanner; public class FileToString { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(new File("E://test//sample.txt")); String input; StringBuffer sb = new StringBuffer(); while (sc.hasNextLine()) { input = sc.nextLine(); sb.append(" "+input); } System.out.println("Contents of the file are: "+sb.toString()); } } Contents of the file are: Tutorials Point is an E-learning company that set out on its journey to provide knowledge to that class of readers that responds better to online content. With Tutorials Point, you can learn at your own pace, in your own space. After a successful journey of providing the best learning content at tutorialspoint.com, we created our subscription based premium product called Tutorix to provide Simply Easy Learning in the best personalized way for K-12 students, and aspirants of competitive exams like IIT/JEE and NEET.
[ { "code": null, "e": 1201, "s": 1062, "text": "In Java you can read the contents of a file in several ways one way is to read it to a string using the java.util.Scanner class, to do so," }, { "code": null, "e": 1305, "s": 1201, "text": "Instantiate the Scanner class, with the path of the file to be read, as a parameter to its constructor." }, { "code": null, "e": 1409, "s": 1305, "text": "Instantiate the Scanner class, with the path of the file to be read, as a parameter to its constructor." }, { "code": null, "e": 1440, "s": 1409, "text": "Create an empty String buffer." }, { "code": null, "e": 1471, "s": 1440, "text": "Create an empty String buffer." }, { "code": null, "e": 1565, "s": 1471, "text": "Start a while loop with condition, if the Scanner has next line. i.e. hasNextLine() at while." }, { "code": null, "e": 1659, "s": 1565, "text": "Start a while loop with condition, if the Scanner has next line. i.e. hasNextLine() at while." }, { "code": null, "e": 1758, "s": 1659, "text": "Within the loop append each line of the file to the StringBuffer object using the append() method." }, { "code": null, "e": 1857, "s": 1758, "text": "Within the loop append each line of the file to the StringBuffer object using the append() method." }, { "code": null, "e": 1947, "s": 1857, "text": "Convert the contents of the contents of the buffer to String using the toString() method." }, { "code": null, "e": 2037, "s": 1947, "text": "Convert the contents of the contents of the buffer to String using the toString() method." }, { "code": null, "e": 2151, "s": 2037, "text": "Create a file with name sample.txt in the C directory in your system, copy and paste the following content in it." }, { "code": null, "e": 2676, "s": 2151, "text": "Tutorials Point is an E-learning company that set out on its journey to provide knowledge to that class \nof readers that responds better to online content. With Tutorials Point, you can learn at your own pace, \nin your own space.\n\nAfter a successful journey of providing the best learning content at tutorialspoint.com, we created \nour subscription based premium product called Tutorix to provide Simply Easy Learning in the best \npersonalized way for K-12 students, and aspirants of competitive exams like IIT/JEE and NEET." }, { "code": null, "e": 2771, "s": 2676, "text": "Following Java program reads the contents of the file sample.txt in to a String and prints it." }, { "code": null, "e": 3248, "s": 2771, "text": "import java.io.File;\nimport java.io.IOException;\nimport java.util.Scanner;\npublic class FileToString {\n public static void main(String[] args) throws IOException {\n Scanner sc = new Scanner(new File(\"E://test//sample.txt\"));\n String input;\n StringBuffer sb = new StringBuffer();\n while (sc.hasNextLine()) {\n input = sc.nextLine();\n sb.append(\" \"+input);\n }\n System.out.println(\"Contents of the file are: \"+sb.toString());\n }\n}" }, { "code": null, "e": 3799, "s": 3248, "text": "Contents of the file are: Tutorials Point is an E-learning company that set out on its journey to \nprovide knowledge to that class of readers that responds better to online content. With Tutorials Point, \nyou can learn at your own pace, in your own space. After a successful journey of providing the best \nlearning content at tutorialspoint.com, we created our subscription based premium product called \nTutorix to provide Simply Easy Learning in the best personalized way for K-12 students, and aspirants \nof competitive exams like IIT/JEE and NEET." } ]
Java Generics - Raw Types
A raw type is an object of a generic class or interface if its type arguments are not passed during its creation. Following example will showcase above mentioned concept. Create the following java program using any editor of your choice. GenericsTester.java package com.tutorialspoint; public class GenericsTester { public static void main(String[] args) { Box<Integer> box = new Box<Integer>(); box.set(Integer.valueOf(10)); System.out.printf("Integer Value :%d\n", box.getData()); Box rawBox = new Box(); //No warning rawBox = box; System.out.printf("Integer Value :%d\n", rawBox.getData()); //Warning for unchecked invocation to set(T) rawBox.set(Integer.valueOf(10)); System.out.printf("Integer Value :%d\n", rawBox.getData()); //Warning for unchecked conversion box = rawBox; System.out.printf("Integer Value :%d\n", box.getData()); } } class Box<T> { private T t; public void set(T t) { this.t = t; } public T getData() { return t; } } This will produce the following result. Integer Value :10 Integer Value :10 Integer Value :10 Integer Value :10 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2811, "s": 2640, "text": "A raw type is an object of a generic class or interface if its type arguments are not passed during its creation. Following example will showcase above mentioned concept." }, { "code": null, "e": 2878, "s": 2811, "text": "Create the following java program using any editor of your choice." }, { "code": null, "e": 2898, "s": 2878, "text": "GenericsTester.java" }, { "code": null, "e": 3741, "s": 2898, "text": "package com.tutorialspoint;\n\npublic class GenericsTester {\n public static void main(String[] args) {\n Box<Integer> box = new Box<Integer>();\n \n box.set(Integer.valueOf(10));\n System.out.printf(\"Integer Value :%d\\n\", box.getData());\n \n \n Box rawBox = new Box();\n \n //No warning\n rawBox = box;\n System.out.printf(\"Integer Value :%d\\n\", rawBox.getData());\n \n //Warning for unchecked invocation to set(T)\n rawBox.set(Integer.valueOf(10));\n System.out.printf(\"Integer Value :%d\\n\", rawBox.getData());\n \n //Warning for unchecked conversion\n box = rawBox;\n System.out.printf(\"Integer Value :%d\\n\", box.getData());\n }\n}\n\nclass Box<T> {\n private T t; \n\n public void set(T t) {\n this.t = t;\n }\n\n public T getData() {\n return t;\n } \n}" }, { "code": null, "e": 3781, "s": 3741, "text": "This will produce the following result." }, { "code": null, "e": 3854, "s": 3781, "text": "Integer Value :10\nInteger Value :10\nInteger Value :10\nInteger Value :10\n" }, { "code": null, "e": 3887, "s": 3854, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 3903, "s": 3887, "text": " Malhar Lathkar" }, { "code": null, "e": 3936, "s": 3903, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 3952, "s": 3936, "text": " Malhar Lathkar" }, { "code": null, "e": 3987, "s": 3952, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4001, "s": 3987, "text": " Anadi Sharma" }, { "code": null, "e": 4035, "s": 4001, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 4049, "s": 4035, "text": " Tushar Kale" }, { "code": null, "e": 4086, "s": 4049, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4101, "s": 4086, "text": " Monica Mittal" }, { "code": null, "e": 4134, "s": 4101, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 4153, "s": 4134, "text": " Arnab Chakraborty" }, { "code": null, "e": 4160, "s": 4153, "text": " Print" }, { "code": null, "e": 4171, "s": 4160, "text": " Add Notes" } ]
Sum of cubes of first n odd natural numbers - GeeksforGeeks
24 Mar, 2021 Given a number n, find sum of first n odd natural numbers. Input : 2 Output : 28 1^3 + 3^3 = 28 Input : 4 Output : 496 1^3 + 3^3 + 5^3 + 7^3 = 496 A simple solution is to traverse through n odd numbers and find the sum of cubes. C++ Java Python3 C# PHP Javascript // Simple C++ method to find sum of cubes of// first n odd numbers.#include <iostream>using namespace std; int cubeSum(int n){ int sum = 0; for (int i = 0; i < n; i++) sum += (2*i + 1)*(2*i + 1)*(2*i + 1); return sum;} int main(){ cout << cubeSum(2); return 0;} // Java program to perform sum of// cubes of first n odd natural numbers public class GFG{ public static int cubesum(int n) { int sum = 0; for(int i = 0; i < n; i++) sum += (2 * i + 1) * (2 * i +1) * (2 * i + 1); return sum; } // Driver function public static void main(String args[]) { int a = 5; System.out.println(cubesum(a)); }} // This article is published Akansh Gupta # Python3 program to find sum of# cubes of first n odd numbers. def cubeSum(n): sum = 0 for i in range(0, n) : sum += (2 * i + 1) * (2 * i + 1) * (2 * i + 1) return sum # Driven codeprint(cubeSum(2)) # This code is contributed by Shariq Raza // C# program to perform sum of// cubes of first n odd natural numbersusing System; public class GFG{ public static int cubesum(int n) { int sum = 0; for(int i = 0; i < n; i++) sum += (2 * i + 1) * (2 * i +1) * (2 * i + 1); return sum; } // Driver function public static void Main() { int a = 5; Console.WriteLine(cubesum(a)); }} // This code is published vt_m <?php// Simple PHP method to find sum of// cubes of first n odd numbers. function cubeSum($n){ $sum = 0; for ($i = 0; $i < $n; $i++) $sum += (2 * $i + 1) * (2 * $i + 1) * (2 * $i + 1); return $sum;} // Driver Codeecho cubeSum(2); // This code is contributed by vt_m.?> <script>// Simple javascript method to find sum of cubes of// first n odd numbers.function cubeSum( n){ let sum = 0; for (let i = 0; i < n; i++) sum += (2*i + 1)*(2*i + 1)*(2*i + 1); return sum;} document.write(cubeSum(2)); // This code is contributed by Rajput-Ji </script> Output : 28 An efficient solution is to apply below formula. sum = n2(2n2 - 1) How does it work? We know that sum of cubes of first n natural numbers is = n2(n+1)2 / 4 Sum of first n even numbers is 2 * n2(n+1)2 Sum of cubes of first n odd natural numbers = Sum of cubes of first 2n natural numbers - Sum of cubes of first n even natural numbers = (2n)2(2n+1)2 / 4 - 2 * n2(n+1)2 = n2(2n+1)2 - 2 * n2(n+1)2 = n2[(2n+1)2 - 2*(n+1)2] = n2(2n2 - 1) C++ Java Python3 C# PHP Javascript // Efficient C++ method to find sum of cubes of// first n odd numbers.#include <iostream>using namespace std; int cubeSum(int n){ return n * n * (2 * n * n - 1);} int main(){ cout << cubeSum(4); return 0;} // Java program to perform sum of// cubes of first n odd natural numbers public class GFG{ public static int cubesum(int n) { return (n) * (n) * (2 * n * n - 1); } // Driver function public static void main(String args[]) { int a = 4; System.out.println(cubesum(a)); }} // This code is contributed by Akansh Gupta. # Python3 program to find sum of# cubes of first n odd numbers. # Function to find sum of cubes# of first n odd numberdef cubeSum(n): return (n * n * (2 * n * n - 1)) # Driven codeprint(cubeSum(4)) # This code is contributed by Shariq Raza // C# program to perform sum of// cubes of first n odd natural numbersusing System; public class GFG{ public static int cubesum(int n) { return (n) * (n) * (2 * n * n - 1); } // Driver function public static void Main() { int a = 4; Console.WriteLine(cubesum(a)); }} // This code is published vt_m. <?php// Efficient PHP method to// find sum of cubes of// first n odd numbers. function cubeSum($n){ return $n * $n * (2 * $n * $n - 1);} // Driver Codeecho cubeSum(4); // This code is contributed by vt_m.?> <script>// javascript program to perform sum of// cubes of first n odd natural numbers function cubesum(n){ return (n) * (n) * (2 * n * n - 1);} // Driver functionvar a = 4;document.write(cubesum(a)); // This code is contributed by Amit Katiyar</script> Output: 496 This article is contributed by Dharmendra kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m Rajput-Ji amit143katiyar maths-cube number-theory series series-sum Mathematical School Programming number-theory Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Merge two sorted arrays Program to find GCD or HCF of two numbers Modulo Operator (%) in C/C++ with Examples Prime Numbers Sieve of Eratosthenes Python Dictionary Inheritance in C++ Overriding in Java Arrays in C/C++ Copy Constructor in C++
[ { "code": null, "e": 24695, "s": 24667, "text": "\n24 Mar, 2021" }, { "code": null, "e": 24755, "s": 24695, "text": "Given a number n, find sum of first n odd natural numbers. " }, { "code": null, "e": 24846, "s": 24755, "text": "Input : 2\nOutput : 28\n1^3 + 3^3 = 28\n\nInput : 4\nOutput : 496\n1^3 + 3^3 + 5^3 + 7^3 = 496" }, { "code": null, "e": 24932, "s": 24848, "text": "A simple solution is to traverse through n odd numbers and find the sum of cubes. " }, { "code": null, "e": 24936, "s": 24932, "text": "C++" }, { "code": null, "e": 24941, "s": 24936, "text": "Java" }, { "code": null, "e": 24949, "s": 24941, "text": "Python3" }, { "code": null, "e": 24952, "s": 24949, "text": "C#" }, { "code": null, "e": 24956, "s": 24952, "text": "PHP" }, { "code": null, "e": 24967, "s": 24956, "text": "Javascript" }, { "code": "// Simple C++ method to find sum of cubes of// first n odd numbers.#include <iostream>using namespace std; int cubeSum(int n){ int sum = 0; for (int i = 0; i < n; i++) sum += (2*i + 1)*(2*i + 1)*(2*i + 1); return sum;} int main(){ cout << cubeSum(2); return 0;}", "e": 25251, "s": 24967, "text": null }, { "code": "// Java program to perform sum of// cubes of first n odd natural numbers public class GFG{ public static int cubesum(int n) { int sum = 0; for(int i = 0; i < n; i++) sum += (2 * i + 1) * (2 * i +1) * (2 * i + 1); return sum; } // Driver function public static void main(String args[]) { int a = 5; System.out.println(cubesum(a)); }} // This article is published Akansh Gupta", "e": 25744, "s": 25251, "text": null }, { "code": "# Python3 program to find sum of# cubes of first n odd numbers. def cubeSum(n): sum = 0 for i in range(0, n) : sum += (2 * i + 1) * (2 * i + 1) * (2 * i + 1) return sum # Driven codeprint(cubeSum(2)) # This code is contributed by Shariq Raza", "e": 26007, "s": 25744, "text": null }, { "code": "// C# program to perform sum of// cubes of first n odd natural numbersusing System; public class GFG{ public static int cubesum(int n) { int sum = 0; for(int i = 0; i < n; i++) sum += (2 * i + 1) * (2 * i +1) * (2 * i + 1); return sum; } // Driver function public static void Main() { int a = 5; Console.WriteLine(cubesum(a)); }} // This code is published vt_m", "e": 26486, "s": 26007, "text": null }, { "code": "<?php// Simple PHP method to find sum of// cubes of first n odd numbers. function cubeSum($n){ $sum = 0; for ($i = 0; $i < $n; $i++) $sum += (2 * $i + 1) * (2 * $i + 1) * (2 * $i + 1); return $sum;} // Driver Codeecho cubeSum(2); // This code is contributed by vt_m.?>", "e": 26801, "s": 26486, "text": null }, { "code": "<script>// Simple javascript method to find sum of cubes of// first n odd numbers.function cubeSum( n){ let sum = 0; for (let i = 0; i < n; i++) sum += (2*i + 1)*(2*i + 1)*(2*i + 1); return sum;} document.write(cubeSum(2)); // This code is contributed by Rajput-Ji </script>", "e": 27096, "s": 26801, "text": null }, { "code": null, "e": 27107, "s": 27096, "text": "Output : " }, { "code": null, "e": 27110, "s": 27107, "text": "28" }, { "code": null, "e": 27160, "s": 27110, "text": "An efficient solution is to apply below formula. " }, { "code": null, "e": 27626, "s": 27160, "text": "sum = n2(2n2 - 1) \n\nHow does it work? \n\nWe know that sum of cubes of first \nn natural numbers is = n2(n+1)2 / 4\n\nSum of first n even numbers is 2 * n2(n+1)2 \n\nSum of cubes of first n odd natural numbers = \n Sum of cubes of first 2n natural numbers - \n Sum of cubes of first n even natural numbers \n\n = (2n)2(2n+1)2 / 4 - 2 * n2(n+1)2 \n = n2(2n+1)2 - 2 * n2(n+1)2 \n = n2[(2n+1)2 - 2*(n+1)2]\n = n2(2n2 - 1)" }, { "code": null, "e": 27632, "s": 27628, "text": "C++" }, { "code": null, "e": 27637, "s": 27632, "text": "Java" }, { "code": null, "e": 27645, "s": 27637, "text": "Python3" }, { "code": null, "e": 27648, "s": 27645, "text": "C#" }, { "code": null, "e": 27652, "s": 27648, "text": "PHP" }, { "code": null, "e": 27663, "s": 27652, "text": "Javascript" }, { "code": "// Efficient C++ method to find sum of cubes of// first n odd numbers.#include <iostream>using namespace std; int cubeSum(int n){ return n * n * (2 * n * n - 1);} int main(){ cout << cubeSum(4); return 0;}", "e": 27878, "s": 27663, "text": null }, { "code": "// Java program to perform sum of// cubes of first n odd natural numbers public class GFG{ public static int cubesum(int n) { return (n) * (n) * (2 * n * n - 1); } // Driver function public static void main(String args[]) { int a = 4; System.out.println(cubesum(a)); }} // This code is contributed by Akansh Gupta.", "e": 28267, "s": 27878, "text": null }, { "code": "# Python3 program to find sum of# cubes of first n odd numbers. # Function to find sum of cubes# of first n odd numberdef cubeSum(n): return (n * n * (2 * n * n - 1)) # Driven codeprint(cubeSum(4)) # This code is contributed by Shariq Raza", "e": 28510, "s": 28267, "text": null }, { "code": "// C# program to perform sum of// cubes of first n odd natural numbersusing System; public class GFG{ public static int cubesum(int n) { return (n) * (n) * (2 * n * n - 1); } // Driver function public static void Main() { int a = 4; Console.WriteLine(cubesum(a)); }} // This code is published vt_m.", "e": 28883, "s": 28510, "text": null }, { "code": "<?php// Efficient PHP method to// find sum of cubes of// first n odd numbers. function cubeSum($n){ return $n * $n * (2 * $n * $n - 1);} // Driver Codeecho cubeSum(4); // This code is contributed by vt_m.?>", "e": 29093, "s": 28883, "text": null }, { "code": "<script>// javascript program to perform sum of// cubes of first n odd natural numbers function cubesum(n){ return (n) * (n) * (2 * n * n - 1);} // Driver functionvar a = 4;document.write(cubesum(a)); // This code is contributed by Amit Katiyar</script>", "e": 29363, "s": 29093, "text": null }, { "code": null, "e": 29373, "s": 29363, "text": "Output: " }, { "code": null, "e": 29377, "s": 29373, "text": "496" }, { "code": null, "e": 29806, "s": 29377, "text": "This article is contributed by Dharmendra kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 29811, "s": 29806, "text": "vt_m" }, { "code": null, "e": 29821, "s": 29811, "text": "Rajput-Ji" }, { "code": null, "e": 29836, "s": 29821, "text": "amit143katiyar" }, { "code": null, "e": 29847, "s": 29836, "text": "maths-cube" }, { "code": null, "e": 29861, "s": 29847, "text": "number-theory" }, { "code": null, "e": 29868, "s": 29861, "text": "series" }, { "code": null, "e": 29879, "s": 29868, "text": "series-sum" }, { "code": null, "e": 29892, "s": 29879, "text": "Mathematical" }, { "code": null, "e": 29911, "s": 29892, "text": "School Programming" }, { "code": null, "e": 29925, "s": 29911, "text": "number-theory" }, { "code": null, "e": 29938, "s": 29925, "text": "Mathematical" }, { "code": null, "e": 29945, "s": 29938, "text": "series" }, { "code": null, "e": 30043, "s": 29945, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30052, "s": 30043, "text": "Comments" }, { "code": null, "e": 30065, "s": 30052, "text": "Old Comments" }, { "code": null, "e": 30089, "s": 30065, "text": "Merge two sorted arrays" }, { "code": null, "e": 30131, "s": 30089, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 30174, "s": 30131, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 30188, "s": 30174, "text": "Prime Numbers" }, { "code": null, "e": 30210, "s": 30188, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 30228, "s": 30210, "text": "Python Dictionary" }, { "code": null, "e": 30247, "s": 30228, "text": "Inheritance in C++" }, { "code": null, "e": 30266, "s": 30247, "text": "Overriding in Java" }, { "code": null, "e": 30282, "s": 30266, "text": "Arrays in C/C++" } ]
Intuition Behind Transformers Architecture in NLP. | by Oleg Borisov | Towards Data Science
One of the most impactful breakthroughs in NLP happened just couple of years ago, when Ashish Vaswani and his team introduced Transformers architecture in 2017. Simplicity and efficiency of the presented architecture, allowed other researchers to create very big and very impressive Language Models like BERT and GPT. Surely, there are a lot of sources that try to explain how transformers work, unfortunately, some intuitive aspects of the explanation are often missed and not presented. Thus, it is unclear: how people came up with this idea? What was the inspiration? What are the Key, Query and Values matrices in the context of transformers? How can we interpret all components? Of course, implementation of Transformers in some libraries like Huggingface does not require us to know how the model works and it could be treated like a blackbox, but as with many things it could be very useful to understand all underlying mechanisms in order to be able to either: create something new, improve previous solution or understand which task is suitable for which operation. In this article, I would like to explain transformers architecture on a very basic and intuitive level, so that even a reader who has never heard of transformers will be able to follow though and understand every single detail. I also believe that people who are familiar with this architecture will gain a new perspective on transformers by reading this article. So without further ado, let’s begin. As we all know, language has a sequential nature, and order of the words matters. Similarly to the language, time series also have this importance of the order in which data points occur. So, let’s take a look at one time-series analysis example and check if we could apply similar ideas to the NLP task. Say we have some time-series data as shown below: In this example, we have some stock price and its value changes over the time, we would like to analyse the trend, unfortunately, our data is noisy, and hence it is a bit hard to extract the trend. In statistics, it is known that we could apply convolution operation using some Kernel in order to reduce the noise. It could be done as shown below for some point x_i. After the convolution we will get a denoised representation y_i of our initial data point x_i. If we apply convolution to our example graph, using the Kernel [0.25, 0.5, 0.25] we will get. As you can clearly see, the overall trend is that the stock price is raising. Ok, sounds great, shall we apply some similar idea in NLP domain? In fact, yes, we can do it, and Convolutional Neural Networks have been using this approach while learning the values for the kernel matrix, but there is a huge drawback! In the time-series example we have considered the neighbouring points are correlated with each-other thus we could smoothen the graph, unfortunately , the same thing does not apply to the language (at least not always). Consider example below: When Ben and I were playing football, John called me and asked to help him on the weekend to assemble his new furniture. In this case, if we do not use a large window size, there is no possibility for the system to understand to whom the words: “him/his”, are referring to. In some languages like german, it could happen that you would have a very large sentence, and the verb is going to be in the end, so sometimes you would only guess what is happening in the sentence until you read the verb in the end. Therefore, while, the idea of moving to the representation space is very good, using convolution/window/kernel approach to do that is not applicable for the NLP tasks. So let’s think if there exists some other approach that we could use, and let’s focus on idea of so called self-attention. In self-attention, the main goal is to understand, how the words in a sentence are interconnected with each other. In the example sentence we considered earlier, if we were to ask question “Doing what?” then word Ben should be connected (using terminology attend) to the phrase playing football. similarly words him/his are connected to the word John, as he was the one to ask for help and his furniture needs to be assembled. As we have seen window approach is not applicable here, so let us take a look at some other approach. In one of my previous articles, I have talked about a very cool and useful way of representing the words called Embeddings. One of the nice properties of word embeddings is that if two words are similar than their cosine similarity is going to be equal to 1. For simplicity, consider that we have a 4 word sentence (hence we work with 4 tokens). Let us, first convert our tokens to the vector representation using some embedding so that we get tokens x_i. Now, for the sake of simplicity of an example, let’s convert vector x_2 to the representation space y_2, using all our word-vectors x_1, x_2, x_3, x_4. Similarly as in the time-series example we are going to do as shown below: Where we know what the x_i values are, and need to figure out how to compute weights w_{ij} as we do not want to use any hardcoded values and want to make sure that weights can reflect similarities of words given the context of the sentence. One of the possible ways to do that could be dot product between two vectors (if two vectors are independent dot product would be zero, if they are similar dot product will be a large positive number). So, let’s do it this way and define weight w_{ij} as: And, since in this example we are working with vector x_2, I will update our schematic diagram as shown below Now, some weights are going turn out to be super large, some of them will turn out to be relatively small, so to make our model consistent, we can normalise the weights to make sure that they sum to 1. And now, after the normalisation, exactly these weights w_{i2} are going to be used to compute representation vector y_2. And thus the final diagram would look like: Now we have found y_2, by querying x_2 and we can apply similar procedure to find representation vectors for other tokens: y_1, y_3, y_4. And to align out graph with Transformers terminology in this case: Query, Key Values are marked as in figure below. As you could have noticed, this is a very robust and easy to perform method, which did not even include any Neural Network and learning parameters at all (Even though I used word weights to make analogy with time-series example, they are not connected with NN weights). But... aren’t we a little bit naive by just using this simple architecture to reflect self-attention? Probably yes, as in this case it is still might be complicated for us to say wether word “him” refers to Bob or to John. Therefore, in this architecture, we only rely on the quality of our Embedding, and if it is bad, then so are our results going to be. So, what could be done in this case? How about we would introduce some simple Feedforward Neural Network at the points of our Key, Query and Value parts. Thus our original architecture could be slightly updated as follows: And this is what actually happens behind the Transformer’s so called “Scaled Dot-Product Attention”. Which in paper is shown like below. Where above, Q is matrix that contains queries, K — keys, and V — values. Which we get by passing words embeddings from our sentence through the respective Feedforward NN. The only things that were not discussed so far are: the scaling part and the mask. The scaling part is needed just to stabilise the gradients. Mask is used in the decoding part during the training process, to prevent us from attending the words that the is not supposed to see yet (If you still do not understand it don’t worry, for now it is not that important). And what is the beauty of it, is that the whole computation could be completely done in a parallel manner, as we can supply the entire sentence to the model which is going to perform all the computation simultaneously! And in fact this complicated diagram can be easily simplified and shown as formula: There is another question that one could ask: is having one attention enough for us? Unfortunately, no, that is why we need multiple attention mechanisms. Consider the following sentence: Today my friend John bought a car. From this sentence, let’s consider what words could be related/connected to the word “bought”: Bought what? --> carWho bought? --> JohnWhen? --> today As you can see we in the language we usually have different words related to the query word depending on the “question” that we might be asking. Having only one self-attention is going to oversaturate our mechanism and it might become too complicated for us to find what word matters the most. To make analogy with Convolutional Neural Networks, we have multiple kernels in each layer, where each of the kernels learns their own unique features. So, instead of using one self-attention, let’s use multiple of those, and this combined block is called called Multi-Headed Attention. Let’s now take a moment and see how that works, as it also has some important details that one needs to understand. As you can see from the image above, we have sentence X (which is a matrix that contains stacked word embeddings x_1, x_2, ...). Which we pass through the Linear layer and get our Key, Query and Value matrices, which we then supply to the Scaled Dot-Product Attention as described. The only difference now, is that we need to perform all those operations h times, where h corresponds to the number of heads that we define. Now, there is one important part that I would like to focus our attention on. Each Head does not process the whole embedding vector, it processes just a part of the vector. Let me illustrate: Assume that our embedding is of size d, and that we have h heads, that means that the first head is going to process the first d/h dimensions of the vector, the second head is going to process the next d/h dimensions, and we continue in the same pattern Why is this done? As we know from the embeddings article each dimension of the embedding space could represent some special information (if a word represented has wings or is a type of bird) or some abstract information information like: what part of speech the word belongs to what hyperplane between two axis represents, etc. So it is possible also that the embedding could also learn to reflect different type of information that is going to help us to distinguish the connection between different words in a sentence. And using this approach, for example one of the Heads will be able to answer the question “who?”, the other Head will answer question “did what?”, some other Head will learn connection to the question “when?” etc. After the split of embeddings is done and all the words are passed through the Scaled Dot-Product Attention layer, we will concatenate the output vectors from all our heads, to make sure that for each word in our sentence we can answer a particular question (that head has managed to learn). In the end we make another pass through the Linear FF layer to make sure that our output has some particular dimension. This is what the Multi-Head attention is about, which is actually the main, the hardest and the most confusing part of transformer, which turned out to be not too complicated! Now, let’s look at the global picture, focus on the encoder architecture of the transformer (In this article I am not going to touch on decoder, as it has a similar structure, with some little differences which could be omitted for this article). As the first step, our original text is passed through the Input Embedding which is straight forward word-vector representation part. Then we need to sum it up with the Positional Encoding, which is crucial for transformer as we process all tokens all together at the same time, so this allows the transformer to know the order of the tokens inside of the sentence We can either train it from scratch or use a deterministic approach by using some special formula After that, we just our vectors to the Transformer block which on the figure shown as the grey box. This Transformer block is repeated N times to allow us to have deeper architecture, so output of block 1 is used as input for the block 2. As you can see when the input enters the transformer block, it passes through the Multi-Headed Attention mechanism (which we now understand very well), but you notice that there is a residual connection, that also passes our input vector around the Multi-Headed Attention block. Why is it there? Think about the training process for a second. Imagine that we are now in a process of updating the weights of the NN and a gradient signal comes in The main problem here is that since we have N transformer blocks, h Multi-Headed Attention blocks in each transformer blocks, then we risk having a vanishing gradient problem, and which might result in a problem of not training our NN at all. So we can consider those residual connections to be very important optimisation approach as well as the trick that helps us to avoid vanishing gradients problem. So as we have seen in this article is that Transformer architecture is a very neat and beautiful solution that allowed to make some incredible progress in NLP. I really like to think about Transformers as of the undirectional architecture as we can directly supply to it the whole sentence, and the NN will be able to use its Self-Attention mechanism to find the dependencies between the words in a sentence no matter how far apart those words are located in the sentence. LSTMs and Bi-LSTMs might have hard time to catch on those word relationships in the sentence, because of the sequential nature of training them. Transformers are much easier and much faster to train as the batch-wise operations are very natural using this architecture. While with RNNs to do some similar operations would require one to implement some special tricks which might be quite complex and sometimes counterintuitive. I hope after reading this article you have managed to understand that Transformer is a quite simple architecture once you understand the Self-Attention part, and that there is nothing to be afraid of! Stay tuned for more NLP and Machine Learning articles, stay safe and enjoy your holidays!
[ { "code": null, "e": 490, "s": 172, "text": "One of the most impactful breakthroughs in NLP happened just couple of years ago, when Ashish Vaswani and his team introduced Transformers architecture in 2017. Simplicity and efficiency of the presented architecture, allowed other researchers to create very big and very impressive Language Models like BERT and GPT." }, { "code": null, "e": 856, "s": 490, "text": "Surely, there are a lot of sources that try to explain how transformers work, unfortunately, some intuitive aspects of the explanation are often missed and not presented. Thus, it is unclear: how people came up with this idea? What was the inspiration? What are the Key, Query and Values matrices in the context of transformers? How can we interpret all components?" }, { "code": null, "e": 1247, "s": 856, "text": "Of course, implementation of Transformers in some libraries like Huggingface does not require us to know how the model works and it could be treated like a blackbox, but as with many things it could be very useful to understand all underlying mechanisms in order to be able to either: create something new, improve previous solution or understand which task is suitable for which operation." }, { "code": null, "e": 1648, "s": 1247, "text": "In this article, I would like to explain transformers architecture on a very basic and intuitive level, so that even a reader who has never heard of transformers will be able to follow though and understand every single detail. I also believe that people who are familiar with this architecture will gain a new perspective on transformers by reading this article. So without further ado, let’s begin." }, { "code": null, "e": 2003, "s": 1648, "text": "As we all know, language has a sequential nature, and order of the words matters. Similarly to the language, time series also have this importance of the order in which data points occur. So, let’s take a look at one time-series analysis example and check if we could apply similar ideas to the NLP task. Say we have some time-series data as shown below:" }, { "code": null, "e": 2201, "s": 2003, "text": "In this example, we have some stock price and its value changes over the time, we would like to analyse the trend, unfortunately, our data is noisy, and hence it is a bit hard to extract the trend." }, { "code": null, "e": 2370, "s": 2201, "text": "In statistics, it is known that we could apply convolution operation using some Kernel in order to reduce the noise. It could be done as shown below for some point x_i." }, { "code": null, "e": 2559, "s": 2370, "text": "After the convolution we will get a denoised representation y_i of our initial data point x_i. If we apply convolution to our example graph, using the Kernel [0.25, 0.5, 0.25] we will get." }, { "code": null, "e": 2637, "s": 2559, "text": "As you can clearly see, the overall trend is that the stock price is raising." }, { "code": null, "e": 2874, "s": 2637, "text": "Ok, sounds great, shall we apply some similar idea in NLP domain? In fact, yes, we can do it, and Convolutional Neural Networks have been using this approach while learning the values for the kernel matrix, but there is a huge drawback!" }, { "code": null, "e": 3118, "s": 2874, "text": "In the time-series example we have considered the neighbouring points are correlated with each-other thus we could smoothen the graph, unfortunately , the same thing does not apply to the language (at least not always). Consider example below:" }, { "code": null, "e": 3239, "s": 3118, "text": "When Ben and I were playing football, John called me and asked to help him on the weekend to assemble his new furniture." }, { "code": null, "e": 3626, "s": 3239, "text": "In this case, if we do not use a large window size, there is no possibility for the system to understand to whom the words: “him/his”, are referring to. In some languages like german, it could happen that you would have a very large sentence, and the verb is going to be in the end, so sometimes you would only guess what is happening in the sentence until you read the verb in the end." }, { "code": null, "e": 3917, "s": 3626, "text": "Therefore, while, the idea of moving to the representation space is very good, using convolution/window/kernel approach to do that is not applicable for the NLP tasks. So let’s think if there exists some other approach that we could use, and let’s focus on idea of so called self-attention." }, { "code": null, "e": 4446, "s": 3917, "text": "In self-attention, the main goal is to understand, how the words in a sentence are interconnected with each other. In the example sentence we considered earlier, if we were to ask question “Doing what?” then word Ben should be connected (using terminology attend) to the phrase playing football. similarly words him/his are connected to the word John, as he was the one to ask for help and his furniture needs to be assembled. As we have seen window approach is not applicable here, so let us take a look at some other approach." }, { "code": null, "e": 4705, "s": 4446, "text": "In one of my previous articles, I have talked about a very cool and useful way of representing the words called Embeddings. One of the nice properties of word embeddings is that if two words are similar than their cosine similarity is going to be equal to 1." }, { "code": null, "e": 4902, "s": 4705, "text": "For simplicity, consider that we have a 4 word sentence (hence we work with 4 tokens). Let us, first convert our tokens to the vector representation using some embedding so that we get tokens x_i." }, { "code": null, "e": 5054, "s": 4902, "text": "Now, for the sake of simplicity of an example, let’s convert vector x_2 to the representation space y_2, using all our word-vectors x_1, x_2, x_3, x_4." }, { "code": null, "e": 5129, "s": 5054, "text": "Similarly as in the time-series example we are going to do as shown below:" }, { "code": null, "e": 5627, "s": 5129, "text": "Where we know what the x_i values are, and need to figure out how to compute weights w_{ij} as we do not want to use any hardcoded values and want to make sure that weights can reflect similarities of words given the context of the sentence. One of the possible ways to do that could be dot product between two vectors (if two vectors are independent dot product would be zero, if they are similar dot product will be a large positive number). So, let’s do it this way and define weight w_{ij} as:" }, { "code": null, "e": 5737, "s": 5627, "text": "And, since in this example we are working with vector x_2, I will update our schematic diagram as shown below" }, { "code": null, "e": 5939, "s": 5737, "text": "Now, some weights are going turn out to be super large, some of them will turn out to be relatively small, so to make our model consistent, we can normalise the weights to make sure that they sum to 1." }, { "code": null, "e": 6061, "s": 5939, "text": "And now, after the normalisation, exactly these weights w_{i2} are going to be used to compute representation vector y_2." }, { "code": null, "e": 6105, "s": 6061, "text": "And thus the final diagram would look like:" }, { "code": null, "e": 6359, "s": 6105, "text": "Now we have found y_2, by querying x_2 and we can apply similar procedure to find representation vectors for other tokens: y_1, y_3, y_4. And to align out graph with Transformers terminology in this case: Query, Key Values are marked as in figure below." }, { "code": null, "e": 6629, "s": 6359, "text": "As you could have noticed, this is a very robust and easy to perform method, which did not even include any Neural Network and learning parameters at all (Even though I used word weights to make analogy with time-series example, they are not connected with NN weights)." }, { "code": null, "e": 6986, "s": 6629, "text": "But... aren’t we a little bit naive by just using this simple architecture to reflect self-attention? Probably yes, as in this case it is still might be complicated for us to say wether word “him” refers to Bob or to John. Therefore, in this architecture, we only rely on the quality of our Embedding, and if it is bad, then so are our results going to be." }, { "code": null, "e": 7209, "s": 6986, "text": "So, what could be done in this case? How about we would introduce some simple Feedforward Neural Network at the points of our Key, Query and Value parts. Thus our original architecture could be slightly updated as follows:" }, { "code": null, "e": 7346, "s": 7209, "text": "And this is what actually happens behind the Transformer’s so called “Scaled Dot-Product Attention”. Which in paper is shown like below." }, { "code": null, "e": 7518, "s": 7346, "text": "Where above, Q is matrix that contains queries, K — keys, and V — values. Which we get by passing words embeddings from our sentence through the respective Feedforward NN." }, { "code": null, "e": 7882, "s": 7518, "text": "The only things that were not discussed so far are: the scaling part and the mask. The scaling part is needed just to stabilise the gradients. Mask is used in the decoding part during the training process, to prevent us from attending the words that the is not supposed to see yet (If you still do not understand it don’t worry, for now it is not that important)." }, { "code": null, "e": 8101, "s": 7882, "text": "And what is the beauty of it, is that the whole computation could be completely done in a parallel manner, as we can supply the entire sentence to the model which is going to perform all the computation simultaneously!" }, { "code": null, "e": 8185, "s": 8101, "text": "And in fact this complicated diagram can be easily simplified and shown as formula:" }, { "code": null, "e": 8340, "s": 8185, "text": "There is another question that one could ask: is having one attention enough for us? Unfortunately, no, that is why we need multiple attention mechanisms." }, { "code": null, "e": 8373, "s": 8340, "text": "Consider the following sentence:" }, { "code": null, "e": 8408, "s": 8373, "text": "Today my friend John bought a car." }, { "code": null, "e": 8503, "s": 8408, "text": "From this sentence, let’s consider what words could be related/connected to the word “bought”:" }, { "code": null, "e": 8567, "s": 8503, "text": "Bought what? --> carWho bought? --> JohnWhen? --> today" }, { "code": null, "e": 8861, "s": 8567, "text": "As you can see we in the language we usually have different words related to the query word depending on the “question” that we might be asking. Having only one self-attention is going to oversaturate our mechanism and it might become too complicated for us to find what word matters the most." }, { "code": null, "e": 9013, "s": 8861, "text": "To make analogy with Convolutional Neural Networks, we have multiple kernels in each layer, where each of the kernels learns their own unique features." }, { "code": null, "e": 9148, "s": 9013, "text": "So, instead of using one self-attention, let’s use multiple of those, and this combined block is called called Multi-Headed Attention." }, { "code": null, "e": 9264, "s": 9148, "text": "Let’s now take a moment and see how that works, as it also has some important details that one needs to understand." }, { "code": null, "e": 9687, "s": 9264, "text": "As you can see from the image above, we have sentence X (which is a matrix that contains stacked word embeddings x_1, x_2, ...). Which we pass through the Linear layer and get our Key, Query and Value matrices, which we then supply to the Scaled Dot-Product Attention as described. The only difference now, is that we need to perform all those operations h times, where h corresponds to the number of heads that we define." }, { "code": null, "e": 9765, "s": 9687, "text": "Now, there is one important part that I would like to focus our attention on." }, { "code": null, "e": 9860, "s": 9765, "text": "Each Head does not process the whole embedding vector, it processes just a part of the vector." }, { "code": null, "e": 9879, "s": 9860, "text": "Let me illustrate:" }, { "code": null, "e": 10133, "s": 9879, "text": "Assume that our embedding is of size d, and that we have h heads, that means that the first head is going to process the first d/h dimensions of the vector, the second head is going to process the next d/h dimensions, and we continue in the same pattern" }, { "code": null, "e": 10371, "s": 10133, "text": "Why is this done? As we know from the embeddings article each dimension of the embedding space could represent some special information (if a word represented has wings or is a type of bird) or some abstract information information like:" }, { "code": null, "e": 10411, "s": 10371, "text": "what part of speech the word belongs to" }, { "code": null, "e": 10461, "s": 10411, "text": "what hyperplane between two axis represents, etc." }, { "code": null, "e": 10869, "s": 10461, "text": "So it is possible also that the embedding could also learn to reflect different type of information that is going to help us to distinguish the connection between different words in a sentence. And using this approach, for example one of the Heads will be able to answer the question “who?”, the other Head will answer question “did what?”, some other Head will learn connection to the question “when?” etc." }, { "code": null, "e": 11161, "s": 10869, "text": "After the split of embeddings is done and all the words are passed through the Scaled Dot-Product Attention layer, we will concatenate the output vectors from all our heads, to make sure that for each word in our sentence we can answer a particular question (that head has managed to learn)." }, { "code": null, "e": 11281, "s": 11161, "text": "In the end we make another pass through the Linear FF layer to make sure that our output has some particular dimension." }, { "code": null, "e": 11457, "s": 11281, "text": "This is what the Multi-Head attention is about, which is actually the main, the hardest and the most confusing part of transformer, which turned out to be not too complicated!" }, { "code": null, "e": 11704, "s": 11457, "text": "Now, let’s look at the global picture, focus on the encoder architecture of the transformer (In this article I am not going to touch on decoder, as it has a similar structure, with some little differences which could be omitted for this article)." }, { "code": null, "e": 12069, "s": 11704, "text": "As the first step, our original text is passed through the Input Embedding which is straight forward word-vector representation part. Then we need to sum it up with the Positional Encoding, which is crucial for transformer as we process all tokens all together at the same time, so this allows the transformer to know the order of the tokens inside of the sentence" }, { "code": null, "e": 12167, "s": 12069, "text": "We can either train it from scratch or use a deterministic approach by using some special formula" }, { "code": null, "e": 12406, "s": 12167, "text": "After that, we just our vectors to the Transformer block which on the figure shown as the grey box. This Transformer block is repeated N times to allow us to have deeper architecture, so output of block 1 is used as input for the block 2." }, { "code": null, "e": 12702, "s": 12406, "text": "As you can see when the input enters the transformer block, it passes through the Multi-Headed Attention mechanism (which we now understand very well), but you notice that there is a residual connection, that also passes our input vector around the Multi-Headed Attention block. Why is it there?" }, { "code": null, "e": 12851, "s": 12702, "text": "Think about the training process for a second. Imagine that we are now in a process of updating the weights of the NN and a gradient signal comes in" }, { "code": null, "e": 13094, "s": 12851, "text": "The main problem here is that since we have N transformer blocks, h Multi-Headed Attention blocks in each transformer blocks, then we risk having a vanishing gradient problem, and which might result in a problem of not training our NN at all." }, { "code": null, "e": 13256, "s": 13094, "text": "So we can consider those residual connections to be very important optimisation approach as well as the trick that helps us to avoid vanishing gradients problem." }, { "code": null, "e": 13729, "s": 13256, "text": "So as we have seen in this article is that Transformer architecture is a very neat and beautiful solution that allowed to make some incredible progress in NLP. I really like to think about Transformers as of the undirectional architecture as we can directly supply to it the whole sentence, and the NN will be able to use its Self-Attention mechanism to find the dependencies between the words in a sentence no matter how far apart those words are located in the sentence." }, { "code": null, "e": 13874, "s": 13729, "text": "LSTMs and Bi-LSTMs might have hard time to catch on those word relationships in the sentence, because of the sequential nature of training them." }, { "code": null, "e": 14157, "s": 13874, "text": "Transformers are much easier and much faster to train as the batch-wise operations are very natural using this architecture. While with RNNs to do some similar operations would require one to implement some special tricks which might be quite complex and sometimes counterintuitive." }, { "code": null, "e": 14358, "s": 14157, "text": "I hope after reading this article you have managed to understand that Transformer is a quite simple architecture once you understand the Self-Attention part, and that there is nothing to be afraid of!" } ]
Draw a Quantile-Quantile Plot in R Programming - qqline() Function - GeeksforGeeks
16 Dec, 2021 The Quantile-Quantile Plot in Programming Language, or (Q-Q Plot) is defined as a value of two variables that are plotted corresponding to each other and check whether the distributions of two variables are similar or not with respect to the locations. qqline() function in R Language is used to draw a Q-Q Line Plot. Syntax: qqline(x, y, col) Parameters: x, y: X and Y coordinates of plot col: It defines color Returns: A QQ Line plot of the coordinates provided R # Set seed for reproducibilityset.seed(500) # Create random normally distributed valuesx <- rnorm(1200) # QQplot of normally distributed valuesqqnorm(x) # Add qqline to plotqqline(x, col = "darkgreen") Output: Above is a representation of QQplot of Normally Distributed Random Numbers. R # Set seed for reproducibility # Random values according to logistic distribution# QQplot of logistic distributiony <- rlogis(800) # QQplot of normally distributed valuesqqnorm(y) # Add qqline to plotqqline(y, col = "darkgreen") Output: Above is the Q-Q Plot of theoretical quantiles. kumar_satyam R Plot-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) Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame 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? K-Means Clustering in R Programming
[ { "code": null, "e": 26069, "s": 26041, "text": "\n16 Dec, 2021" }, { "code": null, "e": 26387, "s": 26069, "text": "The Quantile-Quantile Plot in Programming Language, or (Q-Q Plot) is defined as a value of two variables that are plotted corresponding to each other and check whether the distributions of two variables are similar or not with respect to the locations. qqline() function in R Language is used to draw a Q-Q Line Plot." }, { "code": null, "e": 26413, "s": 26387, "text": "Syntax: qqline(x, y, col)" }, { "code": null, "e": 26426, "s": 26413, "text": "Parameters: " }, { "code": null, "e": 26460, "s": 26426, "text": "x, y: X and Y coordinates of plot" }, { "code": null, "e": 26482, "s": 26460, "text": "col: It defines color" }, { "code": null, "e": 26535, "s": 26482, "text": "Returns: A QQ Line plot of the coordinates provided " }, { "code": null, "e": 26537, "s": 26535, "text": "R" }, { "code": "# Set seed for reproducibilityset.seed(500) # Create random normally distributed valuesx <- rnorm(1200) # QQplot of normally distributed valuesqqnorm(x) # Add qqline to plotqqline(x, col = \"darkgreen\")", "e": 26739, "s": 26537, "text": null }, { "code": null, "e": 26747, "s": 26739, "text": "Output:" }, { "code": null, "e": 26823, "s": 26747, "text": "Above is a representation of QQplot of Normally Distributed Random Numbers." }, { "code": null, "e": 26825, "s": 26823, "text": "R" }, { "code": "# Set seed for reproducibility # Random values according to logistic distribution# QQplot of logistic distributiony <- rlogis(800) # QQplot of normally distributed valuesqqnorm(y) # Add qqline to plotqqline(y, col = \"darkgreen\")", "e": 27054, "s": 26825, "text": null }, { "code": null, "e": 27063, "s": 27054, "text": "Output: " }, { "code": null, "e": 27112, "s": 27063, "text": "Above is the Q-Q Plot of theoretical quantiles. " }, { "code": null, "e": 27125, "s": 27112, "text": "kumar_satyam" }, { "code": null, "e": 27141, "s": 27125, "text": "R Plot-Function" }, { "code": null, "e": 27152, "s": 27141, "text": "R Language" }, { "code": null, "e": 27250, "s": 27152, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27308, "s": 27250, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 27360, "s": 27308, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 27392, "s": 27360, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 27444, "s": 27392, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27488, "s": 27444, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 27523, "s": 27488, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27561, "s": 27523, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27593, "s": 27561, "text": "Printing Output of an R Program" }, { "code": null, "e": 27651, "s": 27593, "text": "How to Split Column Into Multiple Columns in R DataFrame?" } ]
How to implement Dark (Night) mode in Android app - GeeksforGeeks
16 Apr, 2020 Light-on-dark colour scheme, also called dark mode, is a supplemental mode that uses a color scheme in which content of a webpage is displayed on a dark background. Such a color scheme reduces the light emitted by screens and enhances readability. Switching to dark mode allows website users to move to an eye-friendly and resource-saving design whenever they want. Dark mode or night mode has been getting a lot of buzz lately as Google has included it into their Latest Android version i.e Android Q(API Level 29) and following that more and more apps started supporting dark mode natively because it has many benefits: Reduces battery/power usage. Improves visibility for users with low vision and those who are sensitive to bright light. Makes it easier to use device in a low-light.How to add dark mode to your android app?Create a new Android ProjectCreate a layout and add a button or switch to toggle On/Off Dark ModeNow Right click on values and Select Show in Explorer OptionNow copy the values folder and paste it into the same directory and rename it to “values-night”Now you’ll see 2 colors.xml files, the normal one and one with (night) written to itNow add these colors to colors.xml for Normal/Light ModeAnd add these colors to colors.xml(night)Add backgroundColor to your main LayoutAdd textColor to your TextView’sNow just use AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)as shown belowpublic class MainActivity extends AppCompatActivity { private Button btnToggleDark; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnToggleDark = findViewById(R.id.btnToggleDark); btnToggleDark.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_YES); } }); }}Save the state of the app so that, when the user reopens the app after applying Dark/Light Mode that mode retains. We will use SharedPreferences to save the state of the apppublic class MainActivity extends AppCompatActivity { private Button btnToggleDark; @SuppressLint("SetTextI18n") @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnToggleDark = findViewById(R.id.btnToggleDark); // Saving state of our app // using SharedPreferences SharedPreferences sharedPreferences = getSharedPreferences( "sharedPrefs", MODE_PRIVATE); final SharedPreferences.Editor editor = sharedPreferences.edit(); final boolean isDarkModeOn = sharedPreferences .getBoolean( "isDarkModeOn", false); // When user reopens the app // after applying dark/light mode if (isDarkModeOn) { AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_YES); btnToggleDark.setText( "Disable Dark Mode"); } else { AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_NO); btnToggleDark .setText( "Enable Dark Mode"); } btnToggleDark.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { // When user taps the enable/disable // dark mode button if (isDarkModeOn) { // if dark mode is on it // will turn it off AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_NO); // it will set isDarkModeOn // boolean to false editor.putBoolean( "isDarkModeOn", false); editor.apply(); // change text of Button btnToggleDark.setText( "Enable Dark Mode"); } else { // if dark mode is off // it will turn it on AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_YES); // it will set isDarkModeOn // boolean to true editor.putBoolean( "isDarkModeOn", true); editor.apply(); // change text of Button btnToggleDark.setText( "Disable Dark Mode"); } } }); }}Output:Want a more fast-paced & competitive environment to learn the fundamentals of Android? Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!My Personal Notes arrow_drop_upSave Create a new Android ProjectCreate a layout and add a button or switch to toggle On/Off Dark ModeNow Right click on values and Select Show in Explorer OptionNow copy the values folder and paste it into the same directory and rename it to “values-night”Now you’ll see 2 colors.xml files, the normal one and one with (night) written to itNow add these colors to colors.xml for Normal/Light ModeAnd add these colors to colors.xml(night)Add backgroundColor to your main LayoutAdd textColor to your TextView’sNow just use AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)as shown belowpublic class MainActivity extends AppCompatActivity { private Button btnToggleDark; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnToggleDark = findViewById(R.id.btnToggleDark); btnToggleDark.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_YES); } }); }}Save the state of the app so that, when the user reopens the app after applying Dark/Light Mode that mode retains. We will use SharedPreferences to save the state of the apppublic class MainActivity extends AppCompatActivity { private Button btnToggleDark; @SuppressLint("SetTextI18n") @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnToggleDark = findViewById(R.id.btnToggleDark); // Saving state of our app // using SharedPreferences SharedPreferences sharedPreferences = getSharedPreferences( "sharedPrefs", MODE_PRIVATE); final SharedPreferences.Editor editor = sharedPreferences.edit(); final boolean isDarkModeOn = sharedPreferences .getBoolean( "isDarkModeOn", false); // When user reopens the app // after applying dark/light mode if (isDarkModeOn) { AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_YES); btnToggleDark.setText( "Disable Dark Mode"); } else { AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_NO); btnToggleDark .setText( "Enable Dark Mode"); } btnToggleDark.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { // When user taps the enable/disable // dark mode button if (isDarkModeOn) { // if dark mode is on it // will turn it off AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_NO); // it will set isDarkModeOn // boolean to false editor.putBoolean( "isDarkModeOn", false); editor.apply(); // change text of Button btnToggleDark.setText( "Enable Dark Mode"); } else { // if dark mode is off // it will turn it on AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_YES); // it will set isDarkModeOn // boolean to true editor.putBoolean( "isDarkModeOn", true); editor.apply(); // change text of Button btnToggleDark.setText( "Disable Dark Mode"); } } }); }} Create a new Android Project Create a layout and add a button or switch to toggle On/Off Dark Mode Now Right click on values and Select Show in Explorer Option Now copy the values folder and paste it into the same directory and rename it to “values-night” Now you’ll see 2 colors.xml files, the normal one and one with (night) written to it Now add these colors to colors.xml for Normal/Light Mode And add these colors to colors.xml(night) Add backgroundColor to your main Layout Add textColor to your TextView’s Now just use AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)as shown belowpublic class MainActivity extends AppCompatActivity { private Button btnToggleDark; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnToggleDark = findViewById(R.id.btnToggleDark); btnToggleDark.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_YES); } }); }} public class MainActivity extends AppCompatActivity { private Button btnToggleDark; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnToggleDark = findViewById(R.id.btnToggleDark); btnToggleDark.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_YES); } }); }} Save the state of the app so that, when the user reopens the app after applying Dark/Light Mode that mode retains. We will use SharedPreferences to save the state of the apppublic class MainActivity extends AppCompatActivity { private Button btnToggleDark; @SuppressLint("SetTextI18n") @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnToggleDark = findViewById(R.id.btnToggleDark); // Saving state of our app // using SharedPreferences SharedPreferences sharedPreferences = getSharedPreferences( "sharedPrefs", MODE_PRIVATE); final SharedPreferences.Editor editor = sharedPreferences.edit(); final boolean isDarkModeOn = sharedPreferences .getBoolean( "isDarkModeOn", false); // When user reopens the app // after applying dark/light mode if (isDarkModeOn) { AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_YES); btnToggleDark.setText( "Disable Dark Mode"); } else { AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_NO); btnToggleDark .setText( "Enable Dark Mode"); } btnToggleDark.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { // When user taps the enable/disable // dark mode button if (isDarkModeOn) { // if dark mode is on it // will turn it off AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_NO); // it will set isDarkModeOn // boolean to false editor.putBoolean( "isDarkModeOn", false); editor.apply(); // change text of Button btnToggleDark.setText( "Enable Dark Mode"); } else { // if dark mode is off // it will turn it on AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_YES); // it will set isDarkModeOn // boolean to true editor.putBoolean( "isDarkModeOn", true); editor.apply(); // change text of Button btnToggleDark.setText( "Disable Dark Mode"); } } }); }} public class MainActivity extends AppCompatActivity { private Button btnToggleDark; @SuppressLint("SetTextI18n") @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnToggleDark = findViewById(R.id.btnToggleDark); // Saving state of our app // using SharedPreferences SharedPreferences sharedPreferences = getSharedPreferences( "sharedPrefs", MODE_PRIVATE); final SharedPreferences.Editor editor = sharedPreferences.edit(); final boolean isDarkModeOn = sharedPreferences .getBoolean( "isDarkModeOn", false); // When user reopens the app // after applying dark/light mode if (isDarkModeOn) { AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_YES); btnToggleDark.setText( "Disable Dark Mode"); } else { AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_NO); btnToggleDark .setText( "Enable Dark Mode"); } btnToggleDark.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { // When user taps the enable/disable // dark mode button if (isDarkModeOn) { // if dark mode is on it // will turn it off AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_NO); // it will set isDarkModeOn // boolean to false editor.putBoolean( "isDarkModeOn", false); editor.apply(); // change text of Button btnToggleDark.setText( "Enable Dark Mode"); } else { // if dark mode is off // it will turn it on AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_YES); // it will set isDarkModeOn // boolean to true editor.putBoolean( "isDarkModeOn", true); editor.apply(); // change text of Button btnToggleDark.setText( "Disable Dark Mode"); } } }); }} Output: android Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25249, "s": 25221, "text": "\n16 Apr, 2020" }, { "code": null, "e": 25615, "s": 25249, "text": "Light-on-dark colour scheme, also called dark mode, is a supplemental mode that uses a color scheme in which content of a webpage is displayed on a dark background. Such a color scheme reduces the light emitted by screens and enhances readability. Switching to dark mode allows website users to move to an eye-friendly and resource-saving design whenever they want." }, { "code": null, "e": 25871, "s": 25615, "text": "Dark mode or night mode has been getting a lot of buzz lately as Google has included it into their Latest Android version i.e Android Q(API Level 29) and following that more and more apps started supporting dark mode natively because it has many benefits:" }, { "code": null, "e": 25900, "s": 25871, "text": "Reduces battery/power usage." }, { "code": null, "e": 25991, "s": 25900, "text": "Improves visibility for users with low vision and those who are sensitive to bright light." }, { "code": null, "e": 30902, "s": 25991, "text": "Makes it easier to use device in a low-light.How to add dark mode to your android app?Create a new Android ProjectCreate a layout and add a button or switch to toggle On/Off Dark ModeNow Right click on values and Select Show in Explorer OptionNow copy the values folder and paste it into the same directory and rename it to “values-night”Now you’ll see 2 colors.xml files, the normal one and one with (night) written to itNow add these colors to colors.xml for Normal/Light ModeAnd add these colors to colors.xml(night)Add backgroundColor to your main LayoutAdd textColor to your TextView’sNow just use AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)as shown belowpublic class MainActivity extends AppCompatActivity { private Button btnToggleDark; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnToggleDark = findViewById(R.id.btnToggleDark); btnToggleDark.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_YES); } }); }}Save the state of the app so that, when the user reopens the app after applying Dark/Light Mode that mode retains. We will use SharedPreferences to save the state of the apppublic class MainActivity extends AppCompatActivity { private Button btnToggleDark; @SuppressLint(\"SetTextI18n\") @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnToggleDark = findViewById(R.id.btnToggleDark); // Saving state of our app // using SharedPreferences SharedPreferences sharedPreferences = getSharedPreferences( \"sharedPrefs\", MODE_PRIVATE); final SharedPreferences.Editor editor = sharedPreferences.edit(); final boolean isDarkModeOn = sharedPreferences .getBoolean( \"isDarkModeOn\", false); // When user reopens the app // after applying dark/light mode if (isDarkModeOn) { AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_YES); btnToggleDark.setText( \"Disable Dark Mode\"); } else { AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_NO); btnToggleDark .setText( \"Enable Dark Mode\"); } btnToggleDark.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { // When user taps the enable/disable // dark mode button if (isDarkModeOn) { // if dark mode is on it // will turn it off AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_NO); // it will set isDarkModeOn // boolean to false editor.putBoolean( \"isDarkModeOn\", false); editor.apply(); // change text of Button btnToggleDark.setText( \"Enable Dark Mode\"); } else { // if dark mode is off // it will turn it on AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_YES); // it will set isDarkModeOn // boolean to true editor.putBoolean( \"isDarkModeOn\", true); editor.apply(); // change text of Button btnToggleDark.setText( \"Disable Dark Mode\"); } } }); }}Output:Want a more fast-paced & competitive environment to learn the fundamentals of Android?\nClick here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 35485, "s": 30902, "text": "Create a new Android ProjectCreate a layout and add a button or switch to toggle On/Off Dark ModeNow Right click on values and Select Show in Explorer OptionNow copy the values folder and paste it into the same directory and rename it to “values-night”Now you’ll see 2 colors.xml files, the normal one and one with (night) written to itNow add these colors to colors.xml for Normal/Light ModeAnd add these colors to colors.xml(night)Add backgroundColor to your main LayoutAdd textColor to your TextView’sNow just use AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)as shown belowpublic class MainActivity extends AppCompatActivity { private Button btnToggleDark; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnToggleDark = findViewById(R.id.btnToggleDark); btnToggleDark.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_YES); } }); }}Save the state of the app so that, when the user reopens the app after applying Dark/Light Mode that mode retains. We will use SharedPreferences to save the state of the apppublic class MainActivity extends AppCompatActivity { private Button btnToggleDark; @SuppressLint(\"SetTextI18n\") @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnToggleDark = findViewById(R.id.btnToggleDark); // Saving state of our app // using SharedPreferences SharedPreferences sharedPreferences = getSharedPreferences( \"sharedPrefs\", MODE_PRIVATE); final SharedPreferences.Editor editor = sharedPreferences.edit(); final boolean isDarkModeOn = sharedPreferences .getBoolean( \"isDarkModeOn\", false); // When user reopens the app // after applying dark/light mode if (isDarkModeOn) { AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_YES); btnToggleDark.setText( \"Disable Dark Mode\"); } else { AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_NO); btnToggleDark .setText( \"Enable Dark Mode\"); } btnToggleDark.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { // When user taps the enable/disable // dark mode button if (isDarkModeOn) { // if dark mode is on it // will turn it off AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_NO); // it will set isDarkModeOn // boolean to false editor.putBoolean( \"isDarkModeOn\", false); editor.apply(); // change text of Button btnToggleDark.setText( \"Enable Dark Mode\"); } else { // if dark mode is off // it will turn it on AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_YES); // it will set isDarkModeOn // boolean to true editor.putBoolean( \"isDarkModeOn\", true); editor.apply(); // change text of Button btnToggleDark.setText( \"Disable Dark Mode\"); } } }); }}" }, { "code": null, "e": 35514, "s": 35485, "text": "Create a new Android Project" }, { "code": null, "e": 35584, "s": 35514, "text": "Create a layout and add a button or switch to toggle On/Off Dark Mode" }, { "code": null, "e": 35645, "s": 35584, "text": "Now Right click on values and Select Show in Explorer Option" }, { "code": null, "e": 35741, "s": 35645, "text": "Now copy the values folder and paste it into the same directory and rename it to “values-night”" }, { "code": null, "e": 35826, "s": 35741, "text": "Now you’ll see 2 colors.xml files, the normal one and one with (night) written to it" }, { "code": null, "e": 35883, "s": 35826, "text": "Now add these colors to colors.xml for Normal/Light Mode" }, { "code": null, "e": 35925, "s": 35883, "text": "And add these colors to colors.xml(night)" }, { "code": null, "e": 35965, "s": 35925, "text": "Add backgroundColor to your main Layout" }, { "code": null, "e": 35998, "s": 35965, "text": "Add textColor to your TextView’s" }, { "code": null, "e": 36815, "s": 35998, "text": "Now just use AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)as shown belowpublic class MainActivity extends AppCompatActivity { private Button btnToggleDark; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnToggleDark = findViewById(R.id.btnToggleDark); btnToggleDark.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_YES); } }); }}" }, { "code": "public class MainActivity extends AppCompatActivity { private Button btnToggleDark; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnToggleDark = findViewById(R.id.btnToggleDark); btnToggleDark.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_YES); } }); }}", "e": 37534, "s": 36815, "text": null }, { "code": null, "e": 40797, "s": 37534, "text": "Save the state of the app so that, when the user reopens the app after applying Dark/Light Mode that mode retains. We will use SharedPreferences to save the state of the apppublic class MainActivity extends AppCompatActivity { private Button btnToggleDark; @SuppressLint(\"SetTextI18n\") @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnToggleDark = findViewById(R.id.btnToggleDark); // Saving state of our app // using SharedPreferences SharedPreferences sharedPreferences = getSharedPreferences( \"sharedPrefs\", MODE_PRIVATE); final SharedPreferences.Editor editor = sharedPreferences.edit(); final boolean isDarkModeOn = sharedPreferences .getBoolean( \"isDarkModeOn\", false); // When user reopens the app // after applying dark/light mode if (isDarkModeOn) { AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_YES); btnToggleDark.setText( \"Disable Dark Mode\"); } else { AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_NO); btnToggleDark .setText( \"Enable Dark Mode\"); } btnToggleDark.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { // When user taps the enable/disable // dark mode button if (isDarkModeOn) { // if dark mode is on it // will turn it off AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_NO); // it will set isDarkModeOn // boolean to false editor.putBoolean( \"isDarkModeOn\", false); editor.apply(); // change text of Button btnToggleDark.setText( \"Enable Dark Mode\"); } else { // if dark mode is off // it will turn it on AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_YES); // it will set isDarkModeOn // boolean to true editor.putBoolean( \"isDarkModeOn\", true); editor.apply(); // change text of Button btnToggleDark.setText( \"Disable Dark Mode\"); } } }); }}" }, { "code": "public class MainActivity extends AppCompatActivity { private Button btnToggleDark; @SuppressLint(\"SetTextI18n\") @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnToggleDark = findViewById(R.id.btnToggleDark); // Saving state of our app // using SharedPreferences SharedPreferences sharedPreferences = getSharedPreferences( \"sharedPrefs\", MODE_PRIVATE); final SharedPreferences.Editor editor = sharedPreferences.edit(); final boolean isDarkModeOn = sharedPreferences .getBoolean( \"isDarkModeOn\", false); // When user reopens the app // after applying dark/light mode if (isDarkModeOn) { AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_YES); btnToggleDark.setText( \"Disable Dark Mode\"); } else { AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_NO); btnToggleDark .setText( \"Enable Dark Mode\"); } btnToggleDark.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { // When user taps the enable/disable // dark mode button if (isDarkModeOn) { // if dark mode is on it // will turn it off AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_NO); // it will set isDarkModeOn // boolean to false editor.putBoolean( \"isDarkModeOn\", false); editor.apply(); // change text of Button btnToggleDark.setText( \"Enable Dark Mode\"); } else { // if dark mode is off // it will turn it on AppCompatDelegate .setDefaultNightMode( AppCompatDelegate .MODE_NIGHT_YES); // it will set isDarkModeOn // boolean to true editor.putBoolean( \"isDarkModeOn\", true); editor.apply(); // change text of Button btnToggleDark.setText( \"Disable Dark Mode\"); } } }); }}", "e": 43887, "s": 40797, "text": null }, { "code": null, "e": 43895, "s": 43887, "text": "Output:" }, { "code": null, "e": 43903, "s": 43895, "text": "android" }, { "code": null, "e": 43908, "s": 43903, "text": "Java" }, { "code": null, "e": 43913, "s": 43908, "text": "Java" }, { "code": null, "e": 44011, "s": 43913, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44026, "s": 44011, "text": "Stream In Java" }, { "code": null, "e": 44047, "s": 44026, "text": "Constructors in Java" }, { "code": null, "e": 44066, "s": 44047, "text": "Exceptions in Java" }, { "code": null, "e": 44096, "s": 44066, "text": "Functional Interfaces in Java" }, { "code": null, "e": 44142, "s": 44096, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 44159, "s": 44142, "text": "Generics in Java" }, { "code": null, "e": 44180, "s": 44159, "text": "Introduction to Java" }, { "code": null, "e": 44223, "s": 44180, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 44259, "s": 44223, "text": "Internal Working of HashMap in Java" } ]
How to Change Image Source URL using AngularJS ? - GeeksforGeeks
14 Oct, 2020 Here the task is to change the source URL of the image with the help of AngularJS. Approach: The approach is to change the URL of the image when the user click on button. When a user clicks on a button then a method is called along with the new URL, that method replaces the new URL with the old one in controller. Example 1: <!DOCTYPE HTML><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.imgUrl ="https://media.geeksforgeeks.org/wp-content/uploads/20190515121004/gfgbg1-300x136.png"; $scope.changeURL = function (url) { $scope.imgUrl = url; }; }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> How to Change Image Src URL in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> <button ng-click="changeURL('https://media.geeksforgeeks.org/wp-content/uploads/20190515120525/gfglogo1.png')"> Change Image</button> <br> <br> <img src="{{imgUrl}}"> </div> </div></body> </html> Output: Example 2: In this example, the URL changing can be seen in output. <!DOCTYPE HTML><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.imgUrl ="https://media.geeksforgeeks.org/wp-content/uploads/20190529122828/bs21.png"; $scope.changeURL = function (url) { $scope.imgUrl = url; }; }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> How to Change Image Src URL in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> <button ng-click="changeURL('https://media.geeksforgeeks.org/wp-content/uploads/20190529122826/bs11.png')"> Change Image</button> <br> <br> URL - {{imgUrl}} <img src="{{imgUrl}}"> </div> </div></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. AngularJS-Misc HTML-Misc AngularJS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular PrimeNG Messages Component Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property
[ { "code": null, "e": 26354, "s": 26326, "text": "\n14 Oct, 2020" }, { "code": null, "e": 26437, "s": 26354, "text": "Here the task is to change the source URL of the image with the help of AngularJS." }, { "code": null, "e": 26669, "s": 26437, "text": "Approach: The approach is to change the URL of the image when the user click on button. When a user clicks on a button then a method is called along with the new URL, that method replaces the new URL with the old one in controller." }, { "code": null, "e": 26680, "s": 26669, "text": "Example 1:" }, { "code": "<!DOCTYPE HTML><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.imgUrl =\"https://media.geeksforgeeks.org/wp-content/uploads/20190515121004/gfgbg1-300x136.png\"; $scope.changeURL = function (url) { $scope.imgUrl = url; }; }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> How to Change Image Src URL in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> <button ng-click=\"changeURL('https://media.geeksforgeeks.org/wp-content/uploads/20190515120525/gfglogo1.png')\"> Change Image</button> <br> <br> <img src=\"{{imgUrl}}\"> </div> </div></body> </html> ", "e": 27649, "s": 26680, "text": null }, { "code": null, "e": 27657, "s": 27649, "text": "Output:" }, { "code": null, "e": 27725, "s": 27657, "text": "Example 2: In this example, the URL changing can be seen in output." }, { "code": "<!DOCTYPE HTML><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.imgUrl =\"https://media.geeksforgeeks.org/wp-content/uploads/20190529122828/bs21.png\"; $scope.changeURL = function (url) { $scope.imgUrl = url; }; }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> How to Change Image Src URL in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> <button ng-click=\"changeURL('https://media.geeksforgeeks.org/wp-content/uploads/20190529122826/bs11.png')\"> Change Image</button> <br> <br> URL - {{imgUrl}} <img src=\"{{imgUrl}}\"> </div> </div></body> </html> ", "e": 28714, "s": 27725, "text": null }, { "code": null, "e": 28722, "s": 28714, "text": "Output:" }, { "code": null, "e": 28859, "s": 28722, "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": 28874, "s": 28859, "text": "AngularJS-Misc" }, { "code": null, "e": 28884, "s": 28874, "text": "HTML-Misc" }, { "code": null, "e": 28894, "s": 28884, "text": "AngularJS" }, { "code": null, "e": 28899, "s": 28894, "text": "HTML" }, { "code": null, "e": 28916, "s": 28899, "text": "Web Technologies" }, { "code": null, "e": 28921, "s": 28916, "text": "HTML" }, { "code": null, "e": 29019, "s": 28921, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29054, "s": 29019, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 29089, "s": 29054, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 29113, "s": 29089, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 29166, "s": 29113, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 29201, "s": 29166, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 29263, "s": 29201, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29313, "s": 29263, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 29361, "s": 29313, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 29421, "s": 29361, "text": "How to set the default value for an HTML <select> element ?" } ]
Minimize cost of painting N houses such that adjacent houses have different colors - GeeksforGeeks
04 Oct, 2021 Given an integer N and a 2D array cost[][3], where cost[i][0], cost[i][1], and cost[i][2] is the cost of painting ith house with colors red, blue, and green respectively, the task is to find the minimum cost to paint all the houses such that no two adjacent houses have the same color. Examples: Input: N = 3, cost[][3] = {{14, 2, 11}, {11, 14, 5}, {14, 3, 10}}Output: 10Explanation: Paint house 0 as blue. Cost = 2. Paint house 1 as green. Cost = 5. Paint house 2 as blue. Cost = 3.Therefore, the total cost = 2 + 5 + 3 = 10. Input: N = 2, cost[][3] = {{1, 2, 3}, {1, 4, 6}}Output: 3 Naive Approach: The simplest approach to solve the given problem is to generate all possible ways of coloring all the houses with the colors red, blue, and green and find the minimum cost among all the possible combinations such that no two adjacent houses have the same colors. Time Complexity: (3N)Auxiliary Space: O(1) Efficient Approach: The above approach can be optimized by using Dynamic Programming as there are overlapping subproblems that can be stored to minimize the number of recursive calls. The idea is to find the minimum cost of painting the current house by any color on the basis of the minimum cost of the other two colors of previously colored houses. Follow the steps below to solve the given problem: Follow the steps below to solve the problem: Create an auxiliary 2D dp[][3] array to store the minimum cost of previously colored houses. Initialize dp[0][0], dp[0][1], and dp[0][2] as the cost of cost[i][0], cost[i][1], and cost[i][2] respectively. Traverse the given array cost[][3] over the range [1, N] and update the cost of painting the current house with colors red, blue, and green with the minimum of the cost other two colors in dp[i][0], dp[i][1], and dp[i][2] respectively. After completing the above steps, print the minimum of dp[N – 1][0], dp[N – 1][1], and dp[N – 1][2] as the minimum cost of painting all the houses with different adjacent colors. 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 find the minimum cost of// coloring the houses such that no two// adjacent houses has the same colorint minCost(vector<vector<int> >& costs, int N){ // Corner Case if (N == 0) return 0; // Auxiliary 2D dp array vector<vector<int> > dp( N, vector<int>(3, 0)); // Base Case dp[0][0] = costs[0][0]; dp[0][1] = costs[0][1]; dp[0][2] = costs[0][2]; for (int i = 1; i < N; i++) { // If current house is colored // with red the take min cost of // previous houses colored with // (blue and green) dp[i][0] = min(dp[i - 1][1], dp[i - 1][2]) + costs[i][0]; // If current house is colored // with blue the take min cost of // previous houses colored with // (red and green) dp[i][1] = min(dp[i - 1][0], dp[i - 1][2]) + costs[i][1]; // If current house is colored // with green the take min cost of // previous houses colored with // (red and blue) dp[i][2] = min(dp[i - 1][0], dp[i - 1][1]) + costs[i][2]; } // Print the min cost of the // last painted house cout << min(dp[N - 1][0], min(dp[N - 1][1], dp[N - 1][2]));} // Driver Codeint main(){ vector<vector<int> > costs{ { 14, 2, 11 }, { 11, 14, 5 }, { 14, 3, 10 } }; int N = costs.size(); // Function Call minCost(costs, N); return 0;} // Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG { // Function to find the minimum cost of // coloring the houses such that no two // adjacent houses has the same color static void minCost(int costs[][], int N) { // Corner Case if (N == 0) return; // Auxiliary 2D dp array int dp[][] = new int[N][3]; // Base Case dp[0][0] = costs[0][0]; dp[0][1] = costs[0][1]; dp[0][2] = costs[0][2]; for (int i = 1; i < N; i++) { // If current house is colored // with red the take min cost of // previous houses colored with // (blue and green) dp[i][0] = Math.min(dp[i - 1][1], dp[i - 1][2]) + costs[i][0]; // If current house is colored // with blue the take min cost of // previous houses colored with // (red and green) dp[i][1] = Math.min(dp[i - 1][0], dp[i - 1][2]) + costs[i][1]; // If current house is colored // with green the take min cost of // previous houses colored with // (red and blue) dp[i][2] = Math.min(dp[i - 1][0], dp[i - 1][1]) + costs[i][2]; } // Print the min cost of the // last painted house System.out.println( Math.min(dp[N - 1][0], Math.min(dp[N - 1][1], dp[N - 1][2]))); } // Driver code public static void main(String[] args) { int costs[][] = { { 14, 2, 11 }, { 11, 14, 5 }, { 14, 3, 10 } }; int N = costs.length; // Function Call minCost(costs, N); }} // This code is contributed by Kingash. # Python 3 program for the above approach # Function to find the minimum cost of# coloring the houses such that no two# adjacent houses has the same colordef minCost(costs, N): # Corner Case if (N == 0): return 0 # Auxiliary 2D dp array dp = [[0 for i in range(3)] for j in range(3)] # Base Case dp[0][0] = costs[0][0] dp[0][1] = costs[0][1] dp[0][2] = costs[0][2] for i in range(1, N, 1): # If current house is colored # with red the take min cost of # previous houses colored with # (blue and green) dp[i][0] = min(dp[i - 1][1], dp[i - 1][2]) + costs[i][0] # If current house is colored # with blue the take min cost of # previous houses colored with # (red and green) dp[i][1] = min(dp[i - 1][0], dp[i - 1][2]) + costs[i][1] # If current house is colored # with green the take min cost of # previous houses colored with # (red and blue) dp[i][2] = min(dp[i - 1][0], dp[i - 1][1]) + costs[i][2] # Print the min cost of the # last painted house print(min(dp[N - 1][0], min(dp[N - 1][1],dp[N - 1][2]))) # Driver Codeif __name__ == '__main__': costs = [[14, 2, 11], [11, 14, 5], [14, 3, 10]] N = len(costs) # Function Call minCost(costs, N) # This code is contributed by ipg2016107. // C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find the minimum cost of // coloring the houses such that no two // adjacent houses has the same color static int minCost(List<List<int>>costs, int N) { // Corner Case if (N == 0) return 0; // Auxiliary 2D dp array List<int> temp = new List<int>(); for(int i=0;i<3;i++) temp.Add(0); List<List<int>> dp = new List<List<int>>(); for(int i=0;i<N;i++) dp.Add(temp); // Base Case dp[0][0] = costs[0][0]; dp[0][1] = costs[0][1]; dp[0][2] = costs[0][2]; for (int i = 1; i < N; i++) { // If current house is colored // with red the take min cost of // previous houses colored with // (blue and green) dp[i][0] = Math.Min(dp[i - 1][1], dp[i - 1][2]) + costs[i][0]; // If current house is colored // with blue the take min cost of // previous houses colored with // (red and green) dp[i][1] = Math.Min(dp[i - 1][0], dp[i - 1][2]) + costs[i][1]; // If current house is colored // with green the take min cost of // previous houses colored with // (red and blue) dp[i][2] = Math.Min(dp[i - 1][0], dp[i - 1][1]) + costs[i][2]; } // Print the min cost of the // last painted house return (Math.Min(dp[N - 1][0], Math.Min(dp[N - 1][1],dp[N - 1][2])))-11; } // Driver Code public static void Main() { List<List<int>>costs = new List<List<int>>(); costs.Add(new List<int>(){14, 2, 11}); costs.Add(new List<int>(){11, 14, 5 }); costs.Add(new List<int>(){14, 3, 10 }); int N = 3; // Function Call Console.WriteLine((int)(minCost(costs, N))); }} // This code is contributed by bgangwar59. <script> // Javascript program for the above approach // Function to find the minimum cost of // coloring the houses such that no two // adjacent houses has the same color function minCost(costs, N) { // Corner Case if (N == 0) return 0; // Auxiliary 2D dp array let dp = new Array(N); for(let i = 0; i < N; i++) { dp[i] = new Array(3); for(let j = 0; j < 3; j++) { dp[i][j] = 0; } } // Base Case dp[0][0] = costs[0][0]; dp[0][1] = costs[0][1]; dp[0][2] = costs[0][2]; for(let i = 1; i < N; i++) { // If current house is colored // with red the take min cost of // previous houses colored with // (blue and green) dp[i][0] = Math.min(dp[i - 1][1], dp[i - 1][2]) + costs[i][0]; // If current house is colored // with blue the take min cost of // previous houses colored with // (red and green) dp[i][1] = Math.min(dp[i - 1][0], dp[i - 1][2]) + costs[i][1]; // If current house is colored // with green the take min cost of // previous houses colored with // (red and blue) dp[i][2] = Math.min(dp[i - 1][0], dp[i - 1][1]) + costs[i][2]; } // Print the min cost of the // last painted house document.write(Math.min(dp[N - 1][0], Math.min(dp[N - 1][1],dp[N - 1][2]))); } let costs = [[14, 2, 11], [11, 14, 5], [14, 3, 10]]; let N = costs.length; // Function Call minCost(costs, N); // This code is contributed by decode2207.</script> 10 Time Complexity: O(N)Auxiliary Space: O(N) ipg2016107 bgangwar59 Kingash simmytarika5 decode2207 Algorithms-Dynamic Programming interview-preparation Linkedin Arrays Dynamic Programming Recursion Linkedin Arrays Dynamic Programming Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 26067, "s": 26039, "text": "\n04 Oct, 2021" }, { "code": null, "e": 26353, "s": 26067, "text": "Given an integer N and a 2D array cost[][3], where cost[i][0], cost[i][1], and cost[i][2] is the cost of painting ith house with colors red, blue, and green respectively, the task is to find the minimum cost to paint all the houses such that no two adjacent houses have the same color." }, { "code": null, "e": 26363, "s": 26353, "text": "Examples:" }, { "code": null, "e": 26594, "s": 26363, "text": "Input: N = 3, cost[][3] = {{14, 2, 11}, {11, 14, 5}, {14, 3, 10}}Output: 10Explanation: Paint house 0 as blue. Cost = 2. Paint house 1 as green. Cost = 5. Paint house 2 as blue. Cost = 3.Therefore, the total cost = 2 + 5 + 3 = 10." }, { "code": null, "e": 26652, "s": 26594, "text": "Input: N = 2, cost[][3] = {{1, 2, 3}, {1, 4, 6}}Output: 3" }, { "code": null, "e": 26974, "s": 26652, "text": "Naive Approach: The simplest approach to solve the given problem is to generate all possible ways of coloring all the houses with the colors red, blue, and green and find the minimum cost among all the possible combinations such that no two adjacent houses have the same colors. Time Complexity: (3N)Auxiliary Space: O(1)" }, { "code": null, "e": 27376, "s": 26974, "text": "Efficient Approach: The above approach can be optimized by using Dynamic Programming as there are overlapping subproblems that can be stored to minimize the number of recursive calls. The idea is to find the minimum cost of painting the current house by any color on the basis of the minimum cost of the other two colors of previously colored houses. Follow the steps below to solve the given problem:" }, { "code": null, "e": 27421, "s": 27376, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 27514, "s": 27421, "text": "Create an auxiliary 2D dp[][3] array to store the minimum cost of previously colored houses." }, { "code": null, "e": 27626, "s": 27514, "text": "Initialize dp[0][0], dp[0][1], and dp[0][2] as the cost of cost[i][0], cost[i][1], and cost[i][2] respectively." }, { "code": null, "e": 27862, "s": 27626, "text": "Traverse the given array cost[][3] over the range [1, N] and update the cost of painting the current house with colors red, blue, and green with the minimum of the cost other two colors in dp[i][0], dp[i][1], and dp[i][2] respectively." }, { "code": null, "e": 28041, "s": 27862, "text": "After completing the above steps, print the minimum of dp[N – 1][0], dp[N – 1][1], and dp[N – 1][2] as the minimum cost of painting all the houses with different adjacent colors." }, { "code": null, "e": 28092, "s": 28041, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28096, "s": 28092, "text": "C++" }, { "code": null, "e": 28101, "s": 28096, "text": "Java" }, { "code": null, "e": 28109, "s": 28101, "text": "Python3" }, { "code": null, "e": 28112, "s": 28109, "text": "C#" }, { "code": null, "e": 28123, "s": 28112, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the minimum cost of// coloring the houses such that no two// adjacent houses has the same colorint minCost(vector<vector<int> >& costs, int N){ // Corner Case if (N == 0) return 0; // Auxiliary 2D dp array vector<vector<int> > dp( N, vector<int>(3, 0)); // Base Case dp[0][0] = costs[0][0]; dp[0][1] = costs[0][1]; dp[0][2] = costs[0][2]; for (int i = 1; i < N; i++) { // If current house is colored // with red the take min cost of // previous houses colored with // (blue and green) dp[i][0] = min(dp[i - 1][1], dp[i - 1][2]) + costs[i][0]; // If current house is colored // with blue the take min cost of // previous houses colored with // (red and green) dp[i][1] = min(dp[i - 1][0], dp[i - 1][2]) + costs[i][1]; // If current house is colored // with green the take min cost of // previous houses colored with // (red and blue) dp[i][2] = min(dp[i - 1][0], dp[i - 1][1]) + costs[i][2]; } // Print the min cost of the // last painted house cout << min(dp[N - 1][0], min(dp[N - 1][1], dp[N - 1][2]));} // Driver Codeint main(){ vector<vector<int> > costs{ { 14, 2, 11 }, { 11, 14, 5 }, { 14, 3, 10 } }; int N = costs.size(); // Function Call minCost(costs, N); return 0;}", "e": 29810, "s": 28123, "text": null }, { "code": "// Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG { // Function to find the minimum cost of // coloring the houses such that no two // adjacent houses has the same color static void minCost(int costs[][], int N) { // Corner Case if (N == 0) return; // Auxiliary 2D dp array int dp[][] = new int[N][3]; // Base Case dp[0][0] = costs[0][0]; dp[0][1] = costs[0][1]; dp[0][2] = costs[0][2]; for (int i = 1; i < N; i++) { // If current house is colored // with red the take min cost of // previous houses colored with // (blue and green) dp[i][0] = Math.min(dp[i - 1][1], dp[i - 1][2]) + costs[i][0]; // If current house is colored // with blue the take min cost of // previous houses colored with // (red and green) dp[i][1] = Math.min(dp[i - 1][0], dp[i - 1][2]) + costs[i][1]; // If current house is colored // with green the take min cost of // previous houses colored with // (red and blue) dp[i][2] = Math.min(dp[i - 1][0], dp[i - 1][1]) + costs[i][2]; } // Print the min cost of the // last painted house System.out.println( Math.min(dp[N - 1][0], Math.min(dp[N - 1][1], dp[N - 1][2]))); } // Driver code public static void main(String[] args) { int costs[][] = { { 14, 2, 11 }, { 11, 14, 5 }, { 14, 3, 10 } }; int N = costs.length; // Function Call minCost(costs, N); }} // This code is contributed by Kingash.", "e": 31412, "s": 29810, "text": null }, { "code": "# Python 3 program for the above approach # Function to find the minimum cost of# coloring the houses such that no two# adjacent houses has the same colordef minCost(costs, N): # Corner Case if (N == 0): return 0 # Auxiliary 2D dp array dp = [[0 for i in range(3)] for j in range(3)] # Base Case dp[0][0] = costs[0][0] dp[0][1] = costs[0][1] dp[0][2] = costs[0][2] for i in range(1, N, 1): # If current house is colored # with red the take min cost of # previous houses colored with # (blue and green) dp[i][0] = min(dp[i - 1][1], dp[i - 1][2]) + costs[i][0] # If current house is colored # with blue the take min cost of # previous houses colored with # (red and green) dp[i][1] = min(dp[i - 1][0], dp[i - 1][2]) + costs[i][1] # If current house is colored # with green the take min cost of # previous houses colored with # (red and blue) dp[i][2] = min(dp[i - 1][0], dp[i - 1][1]) + costs[i][2] # Print the min cost of the # last painted house print(min(dp[N - 1][0], min(dp[N - 1][1],dp[N - 1][2]))) # Driver Codeif __name__ == '__main__': costs = [[14, 2, 11], [11, 14, 5], [14, 3, 10]] N = len(costs) # Function Call minCost(costs, N) # This code is contributed by ipg2016107.", "e": 32807, "s": 31412, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find the minimum cost of // coloring the houses such that no two // adjacent houses has the same color static int minCost(List<List<int>>costs, int N) { // Corner Case if (N == 0) return 0; // Auxiliary 2D dp array List<int> temp = new List<int>(); for(int i=0;i<3;i++) temp.Add(0); List<List<int>> dp = new List<List<int>>(); for(int i=0;i<N;i++) dp.Add(temp); // Base Case dp[0][0] = costs[0][0]; dp[0][1] = costs[0][1]; dp[0][2] = costs[0][2]; for (int i = 1; i < N; i++) { // If current house is colored // with red the take min cost of // previous houses colored with // (blue and green) dp[i][0] = Math.Min(dp[i - 1][1], dp[i - 1][2]) + costs[i][0]; // If current house is colored // with blue the take min cost of // previous houses colored with // (red and green) dp[i][1] = Math.Min(dp[i - 1][0], dp[i - 1][2]) + costs[i][1]; // If current house is colored // with green the take min cost of // previous houses colored with // (red and blue) dp[i][2] = Math.Min(dp[i - 1][0], dp[i - 1][1]) + costs[i][2]; } // Print the min cost of the // last painted house return (Math.Min(dp[N - 1][0], Math.Min(dp[N - 1][1],dp[N - 1][2])))-11; } // Driver Code public static void Main() { List<List<int>>costs = new List<List<int>>(); costs.Add(new List<int>(){14, 2, 11}); costs.Add(new List<int>(){11, 14, 5 }); costs.Add(new List<int>(){14, 3, 10 }); int N = 3; // Function Call Console.WriteLine((int)(minCost(costs, N))); }} // This code is contributed by bgangwar59.", "e": 34679, "s": 32807, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to find the minimum cost of // coloring the houses such that no two // adjacent houses has the same color function minCost(costs, N) { // Corner Case if (N == 0) return 0; // Auxiliary 2D dp array let dp = new Array(N); for(let i = 0; i < N; i++) { dp[i] = new Array(3); for(let j = 0; j < 3; j++) { dp[i][j] = 0; } } // Base Case dp[0][0] = costs[0][0]; dp[0][1] = costs[0][1]; dp[0][2] = costs[0][2]; for(let i = 1; i < N; i++) { // If current house is colored // with red the take min cost of // previous houses colored with // (blue and green) dp[i][0] = Math.min(dp[i - 1][1], dp[i - 1][2]) + costs[i][0]; // If current house is colored // with blue the take min cost of // previous houses colored with // (red and green) dp[i][1] = Math.min(dp[i - 1][0], dp[i - 1][2]) + costs[i][1]; // If current house is colored // with green the take min cost of // previous houses colored with // (red and blue) dp[i][2] = Math.min(dp[i - 1][0], dp[i - 1][1]) + costs[i][2]; } // Print the min cost of the // last painted house document.write(Math.min(dp[N - 1][0], Math.min(dp[N - 1][1],dp[N - 1][2]))); } let costs = [[14, 2, 11], [11, 14, 5], [14, 3, 10]]; let N = costs.length; // Function Call minCost(costs, N); // This code is contributed by decode2207.</script>", "e": 36450, "s": 34679, "text": null }, { "code": null, "e": 36453, "s": 36450, "text": "10" }, { "code": null, "e": 36498, "s": 36455, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 36509, "s": 36498, "text": "ipg2016107" }, { "code": null, "e": 36520, "s": 36509, "text": "bgangwar59" }, { "code": null, "e": 36528, "s": 36520, "text": "Kingash" }, { "code": null, "e": 36541, "s": 36528, "text": "simmytarika5" }, { "code": null, "e": 36552, "s": 36541, "text": "decode2207" }, { "code": null, "e": 36583, "s": 36552, "text": "Algorithms-Dynamic Programming" }, { "code": null, "e": 36605, "s": 36583, "text": "interview-preparation" }, { "code": null, "e": 36614, "s": 36605, "text": "Linkedin" }, { "code": null, "e": 36621, "s": 36614, "text": "Arrays" }, { "code": null, "e": 36641, "s": 36621, "text": "Dynamic Programming" }, { "code": null, "e": 36651, "s": 36641, "text": "Recursion" }, { "code": null, "e": 36660, "s": 36651, "text": "Linkedin" }, { "code": null, "e": 36667, "s": 36660, "text": "Arrays" }, { "code": null, "e": 36687, "s": 36667, "text": "Dynamic Programming" }, { "code": null, "e": 36697, "s": 36687, "text": "Recursion" }, { "code": null, "e": 36795, "s": 36697, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36822, "s": 36795, "text": "Count pairs with given sum" }, { "code": null, "e": 36853, "s": 36822, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 36878, "s": 36853, "text": "Window Sliding Technique" }, { "code": null, "e": 36916, "s": 36878, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 36937, "s": 36916, "text": "Next Greater Element" }, { "code": null, "e": 36966, "s": 36937, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 36996, "s": 36966, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 37030, "s": 36996, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 37061, "s": 37030, "text": "Bellman–Ford Algorithm | DP-23" } ]
HTML | <input> name Attribute - GeeksforGeeks
19 Oct, 2020 The HTML <input> name Attribute is used to specify a name for an <input> element. It is used to reference the form-data after submitting the form or to reference the element in a JavaScript. Syntax: <input name="name"> Attribute Values: It contains a single value name which describes the name of the <input> element. Example: <!DOCTYPE html><html> <head> <title> HTML Input name Attribute </title></head> <body style="text-align:center;"> <h1>GeeksForGeeks</h1> <h2>HTML Input name Attribute</h2> <form id="myGeeks"> <input type="text" id="text_id" name="geeks" pattern="[A-Za-z]{3}" value="Manas Chhabra"> </form> <br></body> </html> Output: Supported Browsers: Google Chrome 1.0 Firefox 1.0 Edge 2.0 Opera 1.0 Apple Safari 1.0 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. arorakashish0911 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) How to Insert Form Data into Database using PHP ? How to position a div at the bottom of its container using CSS? HTML Cheat Sheet - A Basic Guide to HTML Form validation using HTML and 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 ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25791, "s": 25763, "text": "\n19 Oct, 2020" }, { "code": null, "e": 25982, "s": 25791, "text": "The HTML <input> name Attribute is used to specify a name for an <input> element. It is used to reference the form-data after submitting the form or to reference the element in a JavaScript." }, { "code": null, "e": 25990, "s": 25982, "text": "Syntax:" }, { "code": null, "e": 26011, "s": 25990, "text": "<input name=\"name\"> " }, { "code": null, "e": 26110, "s": 26011, "text": "Attribute Values: It contains a single value name which describes the name of the <input> element." }, { "code": null, "e": 26119, "s": 26110, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML Input name Attribute </title></head> <body style=\"text-align:center;\"> <h1>GeeksForGeeks</h1> <h2>HTML Input name Attribute</h2> <form id=\"myGeeks\"> <input type=\"text\" id=\"text_id\" name=\"geeks\" pattern=\"[A-Za-z]{3}\" value=\"Manas Chhabra\"> </form> <br></body> </html>", "e": 26528, "s": 26119, "text": null }, { "code": null, "e": 26536, "s": 26528, "text": "Output:" }, { "code": null, "e": 26556, "s": 26536, "text": "Supported Browsers:" }, { "code": null, "e": 26574, "s": 26556, "text": "Google Chrome 1.0" }, { "code": null, "e": 26586, "s": 26574, "text": "Firefox 1.0" }, { "code": null, "e": 26595, "s": 26586, "text": "Edge 2.0" }, { "code": null, "e": 26605, "s": 26595, "text": "Opera 1.0" }, { "code": null, "e": 26622, "s": 26605, "text": "Apple Safari 1.0" }, { "code": null, "e": 26759, "s": 26622, "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": 26776, "s": 26759, "text": "arorakashish0911" }, { "code": null, "e": 26792, "s": 26776, "text": "HTML-Attributes" }, { "code": null, "e": 26797, "s": 26792, "text": "HTML" }, { "code": null, "e": 26814, "s": 26797, "text": "Web Technologies" }, { "code": null, "e": 26819, "s": 26814, "text": "HTML" }, { "code": null, "e": 26917, "s": 26819, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26941, "s": 26917, "text": "REST API (Introduction)" }, { "code": null, "e": 26991, "s": 26941, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27055, "s": 26991, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 27096, "s": 27055, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 27138, "s": 27096, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 27178, "s": 27138, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27211, "s": 27178, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27256, "s": 27211, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27299, "s": 27256, "text": "How to fetch data from an API in ReactJS ?" } ]
Dummy Variables in R Programming - GeeksforGeeks
05 Aug, 2020 R programming is one of the most used languages for data mining and visualization of the data. Using this language, any type of machine learning algorithm can be processed like regression, classification, etc. Dummy coding is used in regression analysis for categorizing the variable. Dummy variable in R programming is a type of variable that represents a characteristic of an experiment. A dummy variable is either 1 or 0 and 1 can be represented as either True or False and 0 can be represented as False or True depending upon the user. This variable is used to categorize the characteristic of an observation. For example, a person is either male or female, discipline is either good or bad, etc. Further, new columns will be made accordingly which will specify if the person is male or not as the binary value of gender_m and if the person is female or not as the binary value of gender_f.Original dataframe:After creating dummy variable: In this article, let us discuss to create dummy variables in R using 2 methods i.e., ifelse() method and another is by using dummy_cols() function. ifelse() function performs a test and based on the result of the test return true value or false value as provided in the parameters of the function. Using this function, dummy variable can be created accordingly. Syntax:ifelse(test, yes, no) Parameters:test: represents test conditionyes: represents the value which will be executed if test condition satisfiesno: represents the value which will be executed if test condition does not satisfies Example 1: # Using PlantGrowth datasetpg <- PlantGrowth # Printcat("Original dataset:\n")head(pg, 20) # Create dummy variablepg$group_ctr1 <- ifelse(pg$group == "ctrl", 1, 0) # Printcat("After creating dummy variable:\n")head(pg, 20) Output: Original dataset: weight group 1 4.17 ctrl 2 5.58 ctrl 3 5.18 ctrl 4 6.11 ctrl 5 4.50 ctrl 6 4.61 ctrl 7 5.17 ctrl 8 4.53 ctrl 9 5.33 ctrl 10 5.14 ctrl 11 4.81 trt1 12 4.17 trt1 13 4.41 trt1 14 3.59 trt1 15 5.87 trt1 16 3.83 trt1 17 6.03 trt1 18 4.89 trt1 19 4.32 trt1 20 4.69 trt1 After creating dummy variable: weight group group_ctr1 1 4.17 ctrl 1 2 5.58 ctrl 1 3 5.18 ctrl 1 4 6.11 ctrl 1 5 4.50 ctrl 1 6 4.61 ctrl 1 7 5.17 ctrl 1 8 4.53 ctrl 1 9 5.33 ctrl 1 10 5.14 ctrl 1 11 4.81 trt1 0 12 4.17 trt1 0 13 4.41 trt1 0 14 3.59 trt1 0 15 5.87 trt1 0 16 3.83 trt1 0 17 6.03 trt1 0 18 4.89 trt1 0 19 4.32 trt1 0 20 4.69 trt1 0 Example 2: # Create a dataframedf <- data.frame(gender = c("m", "f", "m"), age = c(19, 20, 20), city = c("Delhi", "Mumbai", "Delhi")) # Print original datasetprint(df) # Create dummy variabledf$gender_m <- ifelse(df$gender == "m", 1, 0)df$gender_f <- ifelse(df$gender == "f", 1, 0) # Print resultantprint(df) Output: gender age city 1 m 19 Delhi 2 f 20 Mumbai 3 m 20 Delhi gender age city gender_m gender_f 1 m 19 Delhi 1 0 2 f 20 Mumbai 0 1 3 m 20 Delhi 1 0 dummy_cols() function is present in fastDummies package. It creates dummy variables on the basis of parameters provided in the function. If columns are not selected in the function call for which dummy variable has to be created, then dummy variables are created for all characters and factors column in the dataframe. Syntax:dummy_cols(.data, select_columns = NULL) Parameters:.data: represents object for which dummy columns has to be createdselect_columns: represents columns for which dummy variables has to be created Example 1: # Install the required packageinstall.packages("fastDummies") # Load the librarylibrary(fastDummies) # Using PlantGrowth datasetdata <- PlantGrowth # Create dummy variabledata <- dummy_cols(data, select_columns = "group") # Printprint(data) Output: weight group group_ctrl group_trt1 group_trt2 1 4.17 ctrl 1 0 0 2 5.58 ctrl 1 0 0 3 5.18 ctrl 1 0 0 4 6.11 ctrl 1 0 0 5 4.50 ctrl 1 0 0 6 4.61 ctrl 1 0 0 7 5.17 ctrl 1 0 0 8 4.53 ctrl 1 0 0 9 5.33 ctrl 1 0 0 10 5.14 ctrl 1 0 0 11 4.81 trt1 0 1 0 12 4.17 trt1 0 1 0 13 4.41 trt1 0 1 0 14 3.59 trt1 0 1 0 15 5.87 trt1 0 1 0 16 3.83 trt1 0 1 0 17 6.03 trt1 0 1 0 18 4.89 trt1 0 1 0 19 4.32 trt1 0 1 0 20 4.69 trt1 0 1 0 21 6.31 trt2 0 0 1 22 5.12 trt2 0 0 1 23 5.54 trt2 0 0 1 24 5.50 trt2 0 0 1 25 5.37 trt2 0 0 1 26 5.29 trt2 0 0 1 27 4.92 trt2 0 0 1 28 6.15 trt2 0 0 1 29 5.80 trt2 0 0 1 30 5.26 trt2 0 0 1 Example 2: # Create a dataframedf <- data.frame(gender = c("m", "f", "m"), age = c(19, 20, 20), city = c("Delhi", "Mumbai", "Delhi")) # Create dummy variables# select_columns = NULL uses all # character and factor columns# to create dummy variabledf <- dummy_cols(df) # Printprint(df) Output: gender age city gender_f gender_m city_Delhi city_Mumbai 1 m 19 Delhi 0 1 1 0 2 f 20 Mumbai 1 0 0 1 3 m 20 Delhi 0 1 1 0 Picked R Data-science R-Variables 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? R - if statement How to import an Excel File into R ? Plot mean and standard deviation using ggplot2 in R How to filter R dataframe by multiple conditions?
[ { "code": null, "e": 26487, "s": 26459, "text": "\n05 Aug, 2020" }, { "code": null, "e": 27431, "s": 26487, "text": "R programming is one of the most used languages for data mining and visualization of the data. Using this language, any type of machine learning algorithm can be processed like regression, classification, etc. Dummy coding is used in regression analysis for categorizing the variable. Dummy variable in R programming is a type of variable that represents a characteristic of an experiment. A dummy variable is either 1 or 0 and 1 can be represented as either True or False and 0 can be represented as False or True depending upon the user. This variable is used to categorize the characteristic of an observation. For example, a person is either male or female, discipline is either good or bad, etc. Further, new columns will be made accordingly which will specify if the person is male or not as the binary value of gender_m and if the person is female or not as the binary value of gender_f.Original dataframe:After creating dummy variable:" }, { "code": null, "e": 27579, "s": 27431, "text": "In this article, let us discuss to create dummy variables in R using 2 methods i.e., ifelse() method and another is by using dummy_cols() function." }, { "code": null, "e": 27793, "s": 27579, "text": "ifelse() function performs a test and based on the result of the test return true value or false value as provided in the parameters of the function. Using this function, dummy variable can be created accordingly." }, { "code": null, "e": 27822, "s": 27793, "text": "Syntax:ifelse(test, yes, no)" }, { "code": null, "e": 28025, "s": 27822, "text": "Parameters:test: represents test conditionyes: represents the value which will be executed if test condition satisfiesno: represents the value which will be executed if test condition does not satisfies" }, { "code": null, "e": 28036, "s": 28025, "text": "Example 1:" }, { "code": "# Using PlantGrowth datasetpg <- PlantGrowth # Printcat(\"Original dataset:\\n\")head(pg, 20) # Create dummy variablepg$group_ctr1 <- ifelse(pg$group == \"ctrl\", 1, 0) # Printcat(\"After creating dummy variable:\\n\")head(pg, 20)", "e": 28262, "s": 28036, "text": null }, { "code": null, "e": 28270, "s": 28262, "text": "Output:" }, { "code": null, "e": 29224, "s": 28270, "text": "Original dataset:\n weight group\n1 4.17 ctrl\n2 5.58 ctrl\n3 5.18 ctrl\n4 6.11 ctrl\n5 4.50 ctrl\n6 4.61 ctrl\n7 5.17 ctrl\n8 4.53 ctrl\n9 5.33 ctrl\n10 5.14 ctrl\n11 4.81 trt1\n12 4.17 trt1\n13 4.41 trt1\n14 3.59 trt1\n15 5.87 trt1\n16 3.83 trt1\n17 6.03 trt1\n18 4.89 trt1\n19 4.32 trt1\n20 4.69 trt1\n\nAfter creating dummy variable:\n weight group group_ctr1\n1 4.17 ctrl 1\n2 5.58 ctrl 1\n3 5.18 ctrl 1\n4 6.11 ctrl 1\n5 4.50 ctrl 1\n6 4.61 ctrl 1\n7 5.17 ctrl 1\n8 4.53 ctrl 1\n9 5.33 ctrl 1\n10 5.14 ctrl 1\n11 4.81 trt1 0\n12 4.17 trt1 0\n13 4.41 trt1 0\n14 3.59 trt1 0\n15 5.87 trt1 0\n16 3.83 trt1 0\n17 6.03 trt1 0\n18 4.89 trt1 0\n19 4.32 trt1 0\n20 4.69 trt1 0\n" }, { "code": null, "e": 29235, "s": 29224, "text": "Example 2:" }, { "code": "# Create a dataframedf <- data.frame(gender = c(\"m\", \"f\", \"m\"), age = c(19, 20, 20), city = c(\"Delhi\", \"Mumbai\", \"Delhi\")) # Print original datasetprint(df) # Create dummy variabledf$gender_m <- ifelse(df$gender == \"m\", 1, 0)df$gender_f <- ifelse(df$gender == \"f\", 1, 0) # Print resultantprint(df)", "e": 29603, "s": 29235, "text": null }, { "code": null, "e": 29611, "s": 29603, "text": "Output:" }, { "code": null, "e": 29845, "s": 29611, "text": " gender age city\n1 m 19 Delhi\n2 f 20 Mumbai\n3 m 20 Delhi\n\n gender age city gender_m gender_f\n1 m 19 Delhi 1 0\n2 f 20 Mumbai 0 1\n3 m 20 Delhi 1 0\n" }, { "code": null, "e": 30164, "s": 29845, "text": "dummy_cols() function is present in fastDummies package. It creates dummy variables on the basis of parameters provided in the function. If columns are not selected in the function call for which dummy variable has to be created, then dummy variables are created for all characters and factors column in the dataframe." }, { "code": null, "e": 30212, "s": 30164, "text": "Syntax:dummy_cols(.data, select_columns = NULL)" }, { "code": null, "e": 30368, "s": 30212, "text": "Parameters:.data: represents object for which dummy columns has to be createdselect_columns: represents columns for which dummy variables has to be created" }, { "code": null, "e": 30379, "s": 30368, "text": "Example 1:" }, { "code": "# Install the required packageinstall.packages(\"fastDummies\") # Load the librarylibrary(fastDummies) # Using PlantGrowth datasetdata <- PlantGrowth # Create dummy variabledata <- dummy_cols(data, select_columns = \"group\") # Printprint(data)", "e": 30643, "s": 30379, "text": null }, { "code": null, "e": 30651, "s": 30643, "text": "Output:" }, { "code": null, "e": 32171, "s": 30651, "text": " weight group group_ctrl group_trt1 group_trt2\n1 4.17 ctrl 1 0 0\n2 5.58 ctrl 1 0 0\n3 5.18 ctrl 1 0 0\n4 6.11 ctrl 1 0 0\n5 4.50 ctrl 1 0 0\n6 4.61 ctrl 1 0 0\n7 5.17 ctrl 1 0 0\n8 4.53 ctrl 1 0 0\n9 5.33 ctrl 1 0 0\n10 5.14 ctrl 1 0 0\n11 4.81 trt1 0 1 0\n12 4.17 trt1 0 1 0\n13 4.41 trt1 0 1 0\n14 3.59 trt1 0 1 0\n15 5.87 trt1 0 1 0\n16 3.83 trt1 0 1 0\n17 6.03 trt1 0 1 0\n18 4.89 trt1 0 1 0\n19 4.32 trt1 0 1 0\n20 4.69 trt1 0 1 0\n21 6.31 trt2 0 0 1\n22 5.12 trt2 0 0 1\n23 5.54 trt2 0 0 1\n24 5.50 trt2 0 0 1\n25 5.37 trt2 0 0 1\n26 5.29 trt2 0 0 1\n27 4.92 trt2 0 0 1\n28 6.15 trt2 0 0 1\n29 5.80 trt2 0 0 1\n30 5.26 trt2 0 0 1\n" }, { "code": null, "e": 32182, "s": 32171, "text": "Example 2:" }, { "code": "# Create a dataframedf <- data.frame(gender = c(\"m\", \"f\", \"m\"), age = c(19, 20, 20), city = c(\"Delhi\", \"Mumbai\", \"Delhi\")) # Create dummy variables# select_columns = NULL uses all # character and factor columns# to create dummy variabledf <- dummy_cols(df) # Printprint(df)", "e": 32524, "s": 32182, "text": null }, { "code": null, "e": 32532, "s": 32524, "text": "Output:" }, { "code": null, "e": 32777, "s": 32532, "text": " gender age city gender_f gender_m city_Delhi city_Mumbai\n1 m 19 Delhi 0 1 1 0\n2 f 20 Mumbai 1 0 0 1\n3 m 20 Delhi 0 1 1 0\n" }, { "code": null, "e": 32784, "s": 32777, "text": "Picked" }, { "code": null, "e": 32799, "s": 32784, "text": "R Data-science" }, { "code": null, "e": 32811, "s": 32799, "text": "R-Variables" }, { "code": null, "e": 32822, "s": 32811, "text": "R Language" }, { "code": null, "e": 32920, "s": 32822, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32972, "s": 32920, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 33007, "s": 32972, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 33045, "s": 33007, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 33103, "s": 33045, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 33146, "s": 33103, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 33195, "s": 33146, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 33212, "s": 33195, "text": "R - if statement" }, { "code": null, "e": 33249, "s": 33212, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 33301, "s": 33249, "text": "Plot mean and standard deviation using ggplot2 in R" } ]
JavaScript Regular Expressions - GeeksforGeeks
13 Jan, 2022 Below is the example of the JavaScript Regular Expressions. Example: JAVASCRIPT <script>function GFGFun() { var str = "Visit geeksforGeeks"; var n = str.search(/GeeksforGeeks/i); document.write(n);}GFGFun();</script> Output: 6 A regular expression is a sequence of characters that forms a search pattern. The search pattern can be used for text search and text to replace operations. A regular expression can be a single character or a more complicated pattern. Regular expressions can be used to perform all types of text search and text replace operations.Syntax: /pattern/modifiers; Example: var patt = /GeeksforGeeks/i; Explanation: /GeeksforGeeks/i is a regular expression.GeeksforGeeks is a pattern (to be used in a search).i is a modifier (modifies the search to be Case-Insensitive).Regular Expression Modifiers :Modifiers can be used to perform multiline searches: Examples: Regular Expression Patterns :Metacharacters are characters with a special meaning: Examples: Quantifiers define quantities: Examples: Using String Methods:In JavaScript, regular expressions are often used with the two string methods: search() and replace().The search() method uses an expression to search for a match, and returns the position of the match.The replace() method returns a modified string where the pattern is replaced.Using String search() With a Regular Expression :Use a regular expression to do a case-insensitive search for “GeeksforGeeks” in a string:Example: JAVASCRIPT <script>function myFunction() { // input string var str = "Visit geeksforGeeks!"; // searching string with modifier i var n = str.search(/GeeksforGeeks/i); document.write(n + '<br>'); // searching string without modifier i var n = str.search(/GeeksforGeeks/); document.write(n);}myFunction();</script> Output: 6 -1 Use String replace() With a Regular Expression : Use a case insensitive regular expression to replace gfG with GeeksforGeeks in a string:Example: JAVASCRIPT <script>function myFunction() { // input string var str = "Please visit gfG!"; // replacing with modifier i var txt = str.replace(/gfg/i, "geeksforgeeks"); document.write(txt);}myFunction();</script> Output: Please visit geeksforgeeks! adnanirshad158 JavaScript-Misc javascript-string JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to 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 ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 31329, "s": 31301, "text": "\n13 Jan, 2022" }, { "code": null, "e": 31391, "s": 31329, "text": "Below is the example of the JavaScript Regular Expressions. " }, { "code": null, "e": 31402, "s": 31391, "text": "Example: " }, { "code": null, "e": 31413, "s": 31402, "text": "JAVASCRIPT" }, { "code": "<script>function GFGFun() { var str = \"Visit geeksforGeeks\"; var n = str.search(/GeeksforGeeks/i); document.write(n);}GFGFun();</script>", "e": 31559, "s": 31413, "text": null }, { "code": null, "e": 31569, "s": 31559, "text": "Output: " }, { "code": null, "e": 31571, "s": 31569, "text": "6" }, { "code": null, "e": 31912, "s": 31571, "text": "A regular expression is a sequence of characters that forms a search pattern. The search pattern can be used for text search and text to replace operations. A regular expression can be a single character or a more complicated pattern. Regular expressions can be used to perform all types of text search and text replace operations.Syntax: " }, { "code": null, "e": 31932, "s": 31912, "text": "/pattern/modifiers;" }, { "code": null, "e": 31943, "s": 31932, "text": "Example: " }, { "code": null, "e": 31972, "s": 31943, "text": "var patt = /GeeksforGeeks/i;" }, { "code": null, "e": 32233, "s": 31972, "text": "Explanation: /GeeksforGeeks/i is a regular expression.GeeksforGeeks is a pattern (to be used in a search).i is a modifier (modifies the search to be Case-Insensitive).Regular Expression Modifiers :Modifiers can be used to perform multiline searches: Examples: " }, { "code": null, "e": 32329, "s": 32235, "text": "Regular Expression Patterns :Metacharacters are characters with a special meaning: Examples: " }, { "code": null, "e": 32373, "s": 32331, "text": "Quantifiers define quantities: Examples: " }, { "code": null, "e": 32823, "s": 32375, "text": "Using String Methods:In JavaScript, regular expressions are often used with the two string methods: search() and replace().The search() method uses an expression to search for a match, and returns the position of the match.The replace() method returns a modified string where the pattern is replaced.Using String search() With a Regular Expression :Use a regular expression to do a case-insensitive search for “GeeksforGeeks” in a string:Example: " }, { "code": null, "e": 32834, "s": 32823, "text": "JAVASCRIPT" }, { "code": "<script>function myFunction() { // input string var str = \"Visit geeksforGeeks!\"; // searching string with modifier i var n = str.search(/GeeksforGeeks/i); document.write(n + '<br>'); // searching string without modifier i var n = str.search(/GeeksforGeeks/); document.write(n);}myFunction();</script>", "e": 33165, "s": 32834, "text": null }, { "code": null, "e": 33175, "s": 33165, "text": "Output: " }, { "code": null, "e": 33180, "s": 33175, "text": "6\n-1" }, { "code": null, "e": 33327, "s": 33180, "text": "Use String replace() With a Regular Expression : Use a case insensitive regular expression to replace gfG with GeeksforGeeks in a string:Example: " }, { "code": null, "e": 33338, "s": 33327, "text": "JAVASCRIPT" }, { "code": "<script>function myFunction() { // input string var str = \"Please visit gfG!\"; // replacing with modifier i var txt = str.replace(/gfg/i, \"geeksforgeeks\"); document.write(txt);}myFunction();</script>", "e": 33560, "s": 33338, "text": null }, { "code": null, "e": 33570, "s": 33560, "text": "Output: " }, { "code": null, "e": 33599, "s": 33570, "text": "Please visit geeksforgeeks! " }, { "code": null, "e": 33616, "s": 33601, "text": "adnanirshad158" }, { "code": null, "e": 33632, "s": 33616, "text": "JavaScript-Misc" }, { "code": null, "e": 33650, "s": 33632, "text": "javascript-string" }, { "code": null, "e": 33661, "s": 33650, "text": "JavaScript" }, { "code": null, "e": 33678, "s": 33661, "text": "Web Technologies" }, { "code": null, "e": 33776, "s": 33678, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33816, "s": 33776, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 33861, "s": 33816, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 33922, "s": 33861, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 33994, "s": 33922, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 34063, "s": 33994, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 34103, "s": 34063, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 34136, "s": 34103, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34181, "s": 34136, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 34224, "s": 34181, "text": "How to fetch data from an API in ReactJS ?" } ]
Implementation of a Falling Matrix - GeeksforGeeks
29 May, 2017 Since the dawn of computers, Hollywood has greatly demonstrated a Hacker or a Programmer as someone sitting on a computer typing random keys on computer which ultimately compiles to a Falling matrix like simulation. Here, we will try to implement a similar falling matrix simulation on the console using C++. The idea here is to print random characters over a defined width, where the two successive characters may or may not have certain amount of gap defined randomly. A certain amount of delay between printing successive lines has to be implemented in order to have a ‘falling effect’. // C++ program for implementation of falling matrix.#include<iostream>#include<string>#include<thread>#include<cstdlib>#include<ctime>#include<chrono> // Width of the matrix lineconst int width = 70; // Defines the number of flips in Boolean Array 'switches'const int flipsPerLine =5; // Delay between two successive line printconst int sleepTime = 100; using namespace std; int main(){ int i=0, x=0; // srand initialized with time function // to get distinct rand values at runtime srand(time(NULL)); // Used to decide whether to print // the character in that particular iteration bool switches[width] = {0}; // Set of characters to print from const string ch = "1234567890qwertyuiopasdfghjkl" "zxcvbnm,./';[]!@#$%^&*()-=_+"; const int l = ch.size(); // Green font over black console, duh! system("Color 0A"); // Indefinite Loop while (true) { // Loop over the width // Increment by 2 gives better effect for (i=0;i<width;i+=2) { // Print character if switches[i] is 1 // Else print a blank character if (switches[i]) cout << ch[rand() % l] << " "; else cout<<" "; } // Flip the defined amount of Boolean values // after each line for (i=0; i!=flipsPerLine; ++i) { x = rand() % width; switches[x] = !switches[x]; } // New Line cout << endl; // Using sleep_for function to delay, // chrono milliseconds function to convert to milliseconds this_thread::sleep_for(chrono::milliseconds(sleepTime)); } return 0;} This prints the amazing Falling-Matrix simulation on the console. Note : This program would not run using Run on IDE button because system is disabled. If you get compiler error while compiling this program. Compile it using below command on GCC.$ g++ -std=c++11 abc.cpp -o falling.o $ falling.o $ g++ -std=c++11 abc.cpp -o falling.o $ falling.o This article is contributed by Raghav Jajodia. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. computer-graphics C Language C++ Technical Scripter CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Converting Strings to Numbers in C/C++ Function Pointer in C Vector in C++ STL Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 26209, "s": 26181, "text": "\n29 May, 2017" }, { "code": null, "e": 26518, "s": 26209, "text": "Since the dawn of computers, Hollywood has greatly demonstrated a Hacker or a Programmer as someone sitting on a computer typing random keys on computer which ultimately compiles to a Falling matrix like simulation. Here, we will try to implement a similar falling matrix simulation on the console using C++." }, { "code": null, "e": 26799, "s": 26518, "text": "The idea here is to print random characters over a defined width, where the two successive characters may or may not have certain amount of gap defined randomly. A certain amount of delay between printing successive lines has to be implemented in order to have a ‘falling effect’." }, { "code": "// C++ program for implementation of falling matrix.#include<iostream>#include<string>#include<thread>#include<cstdlib>#include<ctime>#include<chrono> // Width of the matrix lineconst int width = 70; // Defines the number of flips in Boolean Array 'switches'const int flipsPerLine =5; // Delay between two successive line printconst int sleepTime = 100; using namespace std; int main(){ int i=0, x=0; // srand initialized with time function // to get distinct rand values at runtime srand(time(NULL)); // Used to decide whether to print // the character in that particular iteration bool switches[width] = {0}; // Set of characters to print from const string ch = \"1234567890qwertyuiopasdfghjkl\" \"zxcvbnm,./';[]!@#$%^&*()-=_+\"; const int l = ch.size(); // Green font over black console, duh! system(\"Color 0A\"); // Indefinite Loop while (true) { // Loop over the width // Increment by 2 gives better effect for (i=0;i<width;i+=2) { // Print character if switches[i] is 1 // Else print a blank character if (switches[i]) cout << ch[rand() % l] << \" \"; else cout<<\" \"; } // Flip the defined amount of Boolean values // after each line for (i=0; i!=flipsPerLine; ++i) { x = rand() % width; switches[x] = !switches[x]; } // New Line cout << endl; // Using sleep_for function to delay, // chrono milliseconds function to convert to milliseconds this_thread::sleep_for(chrono::milliseconds(sleepTime)); } return 0;}", "e": 28505, "s": 26799, "text": null }, { "code": null, "e": 28571, "s": 28505, "text": "This prints the amazing Falling-Matrix simulation on the console." }, { "code": null, "e": 28578, "s": 28571, "text": "Note :" }, { "code": null, "e": 28657, "s": 28578, "text": "This program would not run using Run on IDE button because system is disabled." }, { "code": null, "e": 28802, "s": 28657, "text": "If you get compiler error while compiling this program. Compile it using below command on GCC.$ g++ -std=c++11 abc.cpp -o falling.o\n$ falling.o " }, { "code": null, "e": 28853, "s": 28802, "text": "$ g++ -std=c++11 abc.cpp -o falling.o\n$ falling.o " }, { "code": null, "e": 29155, "s": 28853, "text": "This article is contributed by Raghav Jajodia. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 29280, "s": 29155, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 29298, "s": 29280, "text": "computer-graphics" }, { "code": null, "e": 29309, "s": 29298, "text": "C Language" }, { "code": null, "e": 29313, "s": 29309, "text": "C++" }, { "code": null, "e": 29332, "s": 29313, "text": "Technical Scripter" }, { "code": null, "e": 29336, "s": 29332, "text": "CPP" }, { "code": null, "e": 29434, "s": 29336, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29451, "s": 29434, "text": "Substring in C++" }, { "code": null, "e": 29486, "s": 29451, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 29532, "s": 29486, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 29571, "s": 29532, "text": "Converting Strings to Numbers in C/C++" }, { "code": null, "e": 29593, "s": 29571, "text": "Function Pointer in C" }, { "code": null, "e": 29611, "s": 29593, "text": "Vector in C++ STL" }, { "code": null, "e": 29657, "s": 29611, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 29676, "s": 29657, "text": "Inheritance in C++" }, { "code": null, "e": 29719, "s": 29676, "text": "Map in C++ Standard Template Library (STL)" } ]
Pandas remove rows with special characters - GeeksforGeeks
19 Oct, 2020 In this article we will learn how to remove the rows with special characters i.e; if a row contains any value which contains special characters like @, %, &, $, #, +, -, *, /, etc. then drop such row and modify the data. To drop such types of rows, first, we have to search rows having special characters per column and then drop. To search we use regular expression either [@#&$%+-/*] or [^0-9a-zA-Z]. Let’s discuss the whole procedure with some examples : Example 1: This example consists of some parts with code and the dataframe used can be download by clicking data1.csv or shown below. Python3 # importing packageimport pandas as pd # load datasetdf = pd.read_csv("data1.csv") # view datasetprint(df) Output: Select rows with columns having special characters value Python3 # select the rows# if Name column# has special charactersprint(df[df.Name.str.contains(r'[@#&$%+-/*]')]) Output: Python3 # select the rows# if Grade column# has special charactersprint(df[df.Grade.str.contains(r'[^0-9a-zA-Z]')]) Output: Merging of selected rows Python3 # merge the selected rows# by using orprint(df[df.Name.str.contains(r'[^0-9a-zA-Z]') | df.Grade.str.contains(r'[@#&$%+-/*]')]) Output: Remove the merged selected rows Python3 # drop the merged selected rowsprint(df.drop(df[df.Name.str.contains(r'[^0-9a-zA-Z]') | df.Grade.str.contains(r'[^0-9a-zA-Z]')].index)) Output: Example 2: This example uses a dataframe which can be download by clicking data2.csv or shown below : Python3 # importing packageimport pandas as pd # load datasetdf = pd.read_csv("data2.csv") # view datasetprint(df) # select and then merge rows# with special charactersprint(df[df.ID.str.contains(r'[^0-9a-zA-Z]') | df.Name.str.contains(r'[^0-9a-zA-Z]') | df.Age.str.contains(r'[^0-9a-zA-Z]') | df.Country.str.contains(r'[^0-9a-zA-Z]')]) # drop the rowsprint(df.drop(df[df.ID.str.contains(r'[^0-9a-zA-Z]') | df.Name.str.contains(r'[^0-9a-zA-Z]') | df.Age.str.contains(r'[^0-9a-zA-Z]') | df.Country.str.contains(r'[^0-9a-zA-Z]')].index)) Output : anshitaagarwal Python pandas-dataFrame Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n19 Oct, 2020" }, { "code": null, "e": 25995, "s": 25537, "text": "In this article we will learn how to remove the rows with special characters i.e; if a row contains any value which contains special characters like @, %, &, $, #, +, -, *, /, etc. then drop such row and modify the data. To drop such types of rows, first, we have to search rows having special characters per column and then drop. To search we use regular expression either [@#&$%+-/*] or [^0-9a-zA-Z]. Let’s discuss the whole procedure with some examples :" }, { "code": null, "e": 26006, "s": 25995, "text": "Example 1:" }, { "code": null, "e": 26129, "s": 26006, "text": "This example consists of some parts with code and the dataframe used can be download by clicking data1.csv or shown below." }, { "code": null, "e": 26137, "s": 26129, "text": "Python3" }, { "code": "# importing packageimport pandas as pd # load datasetdf = pd.read_csv(\"data1.csv\") # view datasetprint(df)", "e": 26244, "s": 26137, "text": null }, { "code": null, "e": 26252, "s": 26244, "text": "Output:" }, { "code": null, "e": 26310, "s": 26252, "text": " Select rows with columns having special characters value" }, { "code": null, "e": 26318, "s": 26310, "text": "Python3" }, { "code": "# select the rows# if Name column# has special charactersprint(df[df.Name.str.contains(r'[@#&$%+-/*]')])", "e": 26423, "s": 26318, "text": null }, { "code": null, "e": 26434, "s": 26423, "text": " Output: " }, { "code": null, "e": 26442, "s": 26434, "text": "Python3" }, { "code": "# select the rows# if Grade column# has special charactersprint(df[df.Grade.str.contains(r'[^0-9a-zA-Z]')])", "e": 26550, "s": 26442, "text": null }, { "code": null, "e": 26559, "s": 26550, "text": " Output:" }, { "code": null, "e": 26585, "s": 26559, "text": " Merging of selected rows" }, { "code": null, "e": 26593, "s": 26585, "text": "Python3" }, { "code": "# merge the selected rows# by using orprint(df[df.Name.str.contains(r'[^0-9a-zA-Z]') | df.Grade.str.contains(r'[@#&$%+-/*]')])", "e": 26728, "s": 26593, "text": null }, { "code": null, "e": 26736, "s": 26728, "text": "Output:" }, { "code": null, "e": 26769, "s": 26736, "text": "Remove the merged selected rows " }, { "code": null, "e": 26777, "s": 26769, "text": "Python3" }, { "code": "# drop the merged selected rowsprint(df.drop(df[df.Name.str.contains(r'[^0-9a-zA-Z]') | df.Grade.str.contains(r'[^0-9a-zA-Z]')].index))", "e": 26929, "s": 26777, "text": null }, { "code": null, "e": 26937, "s": 26929, "text": "Output:" }, { "code": null, "e": 27040, "s": 26937, "text": "Example 2: This example uses a dataframe which can be download by clicking data2.csv or shown below :" }, { "code": null, "e": 27048, "s": 27040, "text": "Python3" }, { "code": "# importing packageimport pandas as pd # load datasetdf = pd.read_csv(\"data2.csv\") # view datasetprint(df) # select and then merge rows# with special charactersprint(df[df.ID.str.contains(r'[^0-9a-zA-Z]') | df.Name.str.contains(r'[^0-9a-zA-Z]') | df.Age.str.contains(r'[^0-9a-zA-Z]') | df.Country.str.contains(r'[^0-9a-zA-Z]')]) # drop the rowsprint(df.drop(df[df.ID.str.contains(r'[^0-9a-zA-Z]') | df.Name.str.contains(r'[^0-9a-zA-Z]') | df.Age.str.contains(r'[^0-9a-zA-Z]') | df.Country.str.contains(r'[^0-9a-zA-Z]')].index))", "e": 27648, "s": 27048, "text": null }, { "code": null, "e": 27657, "s": 27648, "text": "Output :" }, { "code": null, "e": 27672, "s": 27657, "text": "anshitaagarwal" }, { "code": null, "e": 27696, "s": 27672, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27719, "s": 27696, "text": "Python Pandas-exercise" }, { "code": null, "e": 27733, "s": 27719, "text": "Python-pandas" }, { "code": null, "e": 27740, "s": 27733, "text": "Python" }, { "code": null, "e": 27838, "s": 27740, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27870, "s": 27838, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27912, "s": 27870, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27954, "s": 27912, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28010, "s": 27954, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28037, "s": 28010, "text": "Python Classes and Objects" }, { "code": null, "e": 28076, "s": 28037, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28107, "s": 28076, "text": "Python | os.path.join() method" }, { "code": null, "e": 28129, "s": 28107, "text": "Defaultdict in Python" }, { "code": null, "e": 28158, "s": 28129, "text": "Create a directory in Python" } ]
Create a two-dimensional array of sequence of even integers in R - GeeksforGeeks
30 May, 2021 In this article, we will discuss how to create a 2D array of sequences of even integers in R Programming Language. The array() method can be used to create an array with >=1 dimensions. This method returns an array with the extents specified in the dim attribute. For a two-dimensional array, the dim attribute contains a vector of two elements, first indicating the number of rows and then the number of columns respectively. Syntax: array(data , dim) Parameter : data – The data to fill into the array dim – The dimensions of the matrix in the form of vector The data in this method can be created using the seq() method, which is used to generate regular sequences, within the defined range of numbers. Syntax: seq(from = 1, to = 1, length.out , by = ((to – from)/(length.out – 1)) Parameter: from, to – (Default : 1) The starting and (maximal) end values of the sequence. by – Indicator of the number to increment the sequence by. length.out – A non-negative integer indicator of the length of the sequence. In this approach, the from attribute must be even in order to generate a sequence of even integers. The length.out argument will be equal to the product of dimensions of the 2-D matrix. And by attribute holds a value of 2, to increment the number by 2 each time. Example: R # creating integersmat <- seq(from = 2, length.out = 12, by = 2) # creating dimensionsdim <- c(4, 3)arr <- array( mat , dim ) print("Array of even integers sequence:")print(arr) Output [1] "Array of even integers sequence:" [,1] [,2] [,3] [1,] 2 10 18 [2,] 4 12 20 [3,] 6 14 22 [4,] 8 16 24 The starting position to begin the sequence of data is specified along with the desired dimensions of the 2-D array. Since the total number of required elements is equal to the product of dimensions, but here we need even numbers that occur at alternate positions. So, the total number of elements will be equivalent to double the product of dimensions. Now, the ending position is given by : ending_position = starting_position + number of elements A for loop is started to iterate from the starting position to ending position-1 to generate a sequence of elements within this range, and whenever an even number is encountered, the number is appended to an empty list. This vector forms the sequence of even integers and can be fed to the matrix() method of base R, which creates a 2D matrix. Syntax: matrix (data , nrow = ) Time complexity can be assumed to be nearly constant until very large dimensional sizes. Example: R # specifying where to start the # even integers from start_pos <- 20 # specifying dimensions of matrixnrow <- 3ncol <- 2 # calculating starting positionend_pos = (nrow * ncol * 2) + start_pos # creating empty vectorvec <- c()for (i in start_pos : end_pos-1){ # check if element is divisible by 2 if(!(i%%2)){ # append element to vector vec <- c(vec, i ) }} # creating matrix mat <- matrix(vec , nrow = 3)print ("Sequence of even integers in 2-D array")print (mat) Output [1] "Sequence of even integers in 2-D array" [,1] [,2] [1,] 20 26 [2,] 22 28 [3,] 24 30 Picked R-Arrays 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 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 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": 26511, "s": 26483, "text": "\n30 May, 2021" }, { "code": null, "e": 26626, "s": 26511, "text": "In this article, we will discuss how to create a 2D array of sequences of even integers in R Programming Language." }, { "code": null, "e": 26939, "s": 26626, "text": "The array() method can be used to create an array with >=1 dimensions. This method returns an array with the extents specified in the dim attribute. For a two-dimensional array, the dim attribute contains a vector of two elements, first indicating the number of rows and then the number of columns respectively. " }, { "code": null, "e": 26965, "s": 26939, "text": "Syntax: array(data , dim)" }, { "code": null, "e": 26978, "s": 26965, "text": "Parameter : " }, { "code": null, "e": 27018, "s": 26978, "text": "data – The data to fill into the array " }, { "code": null, "e": 27075, "s": 27018, "text": "dim – The dimensions of the matrix in the form of vector" }, { "code": null, "e": 27221, "s": 27075, "text": "The data in this method can be created using the seq() method, which is used to generate regular sequences, within the defined range of numbers. " }, { "code": null, "e": 27300, "s": 27221, "text": "Syntax: seq(from = 1, to = 1, length.out , by = ((to – from)/(length.out – 1))" }, { "code": null, "e": 27312, "s": 27300, "text": "Parameter: " }, { "code": null, "e": 27394, "s": 27312, "text": "from, to – (Default : 1) The starting and (maximal) end values of the sequence. " }, { "code": null, "e": 27453, "s": 27394, "text": "by – Indicator of the number to increment the sequence by." }, { "code": null, "e": 27531, "s": 27453, "text": "length.out – A non-negative integer indicator of the length of the sequence. " }, { "code": null, "e": 27795, "s": 27531, "text": "In this approach, the from attribute must be even in order to generate a sequence of even integers. The length.out argument will be equal to the product of dimensions of the 2-D matrix. And by attribute holds a value of 2, to increment the number by 2 each time. " }, { "code": null, "e": 27804, "s": 27795, "text": "Example:" }, { "code": null, "e": 27806, "s": 27804, "text": "R" }, { "code": "# creating integersmat <- seq(from = 2, length.out = 12, by = 2) # creating dimensionsdim <- c(4, 3)arr <- array( mat , dim ) print(\"Array of even integers sequence:\")print(arr)", "e": 27986, "s": 27806, "text": null }, { "code": null, "e": 27993, "s": 27986, "text": "Output" }, { "code": null, "e": 28132, "s": 27993, "text": "[1] \"Array of even integers sequence:\"\n [,1] [,2] [,3]\n[1,] 2 10 18\n[2,] 4 12 20\n[3,] 6 14 22\n[4,] 8 16 24" }, { "code": null, "e": 28527, "s": 28132, "text": "The starting position to begin the sequence of data is specified along with the desired dimensions of the 2-D array. Since the total number of required elements is equal to the product of dimensions, but here we need even numbers that occur at alternate positions. So, the total number of elements will be equivalent to double the product of dimensions. Now, the ending position is given by : " }, { "code": null, "e": 28584, "s": 28527, "text": "ending_position = starting_position + number of elements" }, { "code": null, "e": 28929, "s": 28584, "text": "A for loop is started to iterate from the starting position to ending position-1 to generate a sequence of elements within this range, and whenever an even number is encountered, the number is appended to an empty list. This vector forms the sequence of even integers and can be fed to the matrix() method of base R, which creates a 2D matrix. " }, { "code": null, "e": 28937, "s": 28929, "text": "Syntax:" }, { "code": null, "e": 28961, "s": 28937, "text": "matrix (data , nrow = )" }, { "code": null, "e": 29050, "s": 28961, "text": "Time complexity can be assumed to be nearly constant until very large dimensional sizes." }, { "code": null, "e": 29060, "s": 29050, "text": "Example: " }, { "code": null, "e": 29062, "s": 29060, "text": "R" }, { "code": "# specifying where to start the # even integers from start_pos <- 20 # specifying dimensions of matrixnrow <- 3ncol <- 2 # calculating starting positionend_pos = (nrow * ncol * 2) + start_pos # creating empty vectorvec <- c()for (i in start_pos : end_pos-1){ # check if element is divisible by 2 if(!(i%%2)){ # append element to vector vec <- c(vec, i ) }} # creating matrix mat <- matrix(vec , nrow = 3)print (\"Sequence of even integers in 2-D array\")print (mat)", "e": 29563, "s": 29062, "text": null }, { "code": null, "e": 29570, "s": 29563, "text": "Output" }, { "code": null, "e": 29676, "s": 29570, "text": "[1] \"Sequence of even integers in 2-D array\"\n [,1] [,2]\n[1,] 20 26\n[2,] 22 28\n[3,] 24 30" }, { "code": null, "e": 29683, "s": 29676, "text": "Picked" }, { "code": null, "e": 29692, "s": 29683, "text": "R-Arrays" }, { "code": null, "e": 29703, "s": 29692, "text": "R Language" }, { "code": null, "e": 29714, "s": 29703, "text": "R Programs" }, { "code": null, "e": 29812, "s": 29714, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29864, "s": 29812, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29899, "s": 29864, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29937, "s": 29899, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29995, "s": 29937, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30038, "s": 29995, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 30096, "s": 30038, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30139, "s": 30096, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 30188, "s": 30139, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30238, "s": 30188, "text": "How to filter R dataframe by multiple conditions?" } ]
Python | Pandas dataframe.round() - GeeksforGeeks
30 Aug, 2021 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.round() function is used to round a DataFrame to a variable number of decimal places. This function provides the flexibility to round different columns by different places. Syntax:DataFrame.round(decimals=0, *args, **kwargs)Parameters :decimals : Number of decimal places to round each column to. If an int is given, round each column to the same number of places. Otherwise dict and Series round to variable numbers of places. Column names should be in the keys if decimals is a dict-like, or in the index if decimals is a Series. Any columns not included in decimals will be left as is. Elements of decimals which are not columns of the input will be ignored. Returns : DataFrame object Example #1: Use round() function to round off all columns in the dataframe to 3 decimal places Note : We need to populate our dataframe with decimal values. Let’s use numpy random function to achieve the task. # importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # setting the seed to re-create the dataframenp.random.seed(25) # Creating a 5 * 4 dataframe df = pd.DataFrame(np.random.random([5, 4]), columns =["A", "B", "C", "D"]) # Print the dataframedf Lets use the dataframe.round() function to round off all the decimal values in the dataframe to 3 decimal places. df.round(3) Output : Example #2: Use round() function to round off all the columns in dataframe to different places. # importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # setting the seed to re-create the dataframenp.random.seed(25) # Creating a 5 * 4 dataframe df = pd.DataFrame(np.random.random([5, 4]), columns =["A", "B", "C", "D"]) # Print the dataframedf Lets perform round off each column to different places # round off the columns in this manner# "A" to 1 decimal place# "B" to 2 decimal place# "C" to 3 decimal place# "D" to 4 decimal place df.round({"A":1, "B":2, "C":3, "D":4}) Output : YouTubeGeeksforGeeks507K subscribersPython | Pandas dataframe.round() | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:18•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=rOnKa_tzV04" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 26115, "s": 26087, "text": "\n30 Aug, 2021" }, { "code": null, "e": 26329, "s": 26115, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 26519, "s": 26329, "text": "Pandas dataframe.round() function is used to round a DataFrame to a variable number of decimal places. This function provides the flexibility to round different columns by different places." }, { "code": null, "e": 27008, "s": 26519, "text": "Syntax:DataFrame.round(decimals=0, *args, **kwargs)Parameters :decimals : Number of decimal places to round each column to. If an int is given, round each column to the same number of places. Otherwise dict and Series round to variable numbers of places. Column names should be in the keys if decimals is a dict-like, or in the index if decimals is a Series. Any columns not included in decimals will be left as is. Elements of decimals which are not columns of the input will be ignored." }, { "code": null, "e": 27035, "s": 27008, "text": "Returns : DataFrame object" }, { "code": null, "e": 27130, "s": 27035, "text": "Example #1: Use round() function to round off all columns in the dataframe to 3 decimal places" }, { "code": null, "e": 27245, "s": 27130, "text": "Note : We need to populate our dataframe with decimal values. Let’s use numpy random function to achieve the task." }, { "code": "# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # setting the seed to re-create the dataframenp.random.seed(25) # Creating a 5 * 4 dataframe df = pd.DataFrame(np.random.random([5, 4]), columns =[\"A\", \"B\", \"C\", \"D\"]) # Print the dataframedf", "e": 27527, "s": 27245, "text": null }, { "code": null, "e": 27641, "s": 27527, "text": "Lets use the dataframe.round() function to round off all the decimal values in the dataframe to 3 decimal places." }, { "code": "df.round(3)", "e": 27653, "s": 27641, "text": null }, { "code": null, "e": 27758, "s": 27653, "text": "Output : Example #2: Use round() function to round off all the columns in dataframe to different places." }, { "code": "# importing pandas as pdimport pandas as pd # importing numpy as npimport numpy as np # setting the seed to re-create the dataframenp.random.seed(25) # Creating a 5 * 4 dataframe df = pd.DataFrame(np.random.random([5, 4]), columns =[\"A\", \"B\", \"C\", \"D\"]) # Print the dataframedf", "e": 28040, "s": 27758, "text": null }, { "code": null, "e": 28095, "s": 28040, "text": "Lets perform round off each column to different places" }, { "code": "# round off the columns in this manner# \"A\" to 1 decimal place# \"B\" to 2 decimal place# \"C\" to 3 decimal place# \"D\" to 4 decimal place df.round({\"A\":1, \"B\":2, \"C\":3, \"D\":4})", "e": 28270, "s": 28095, "text": null }, { "code": null, "e": 28279, "s": 28270, "text": "Output :" }, { "code": null, "e": 29111, "s": 28279, "text": "YouTubeGeeksforGeeks507K subscribersPython | Pandas dataframe.round() | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:18•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=rOnKa_tzV04\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 29135, "s": 29111, "text": "Python pandas-dataFrame" }, { "code": null, "e": 29167, "s": 29135, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 29181, "s": 29167, "text": "Python-pandas" }, { "code": null, "e": 29188, "s": 29181, "text": "Python" }, { "code": null, "e": 29286, "s": 29188, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29304, "s": 29286, "text": "Python Dictionary" }, { "code": null, "e": 29336, "s": 29304, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29358, "s": 29336, "text": "Enumerate() in Python" }, { "code": null, "e": 29400, "s": 29358, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29429, "s": 29400, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29473, "s": 29429, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29510, "s": 29473, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29546, "s": 29510, "text": "Convert integer to string in Python" }, { "code": null, "e": 29588, "s": 29546, "text": "Check if element exists in list in Python" } ]
Django Request and Response cycle - HttpRequest and HttpResponse Objects - GeeksforGeeks
27 May, 2021 Prerequisite – Views In Django | PythonBefore we jump into using convenience methods that views come with, Let’s talk about the Request and Response cycle. So, when a Request happens to a Django server, a couple of things go on. One of them is Middleware. Middleware Middleware is like a middle ground between a request and response. It is like a window through which data passes. As in a window, light passes in and out of the house. Similarly, when a request is made it moves through middlewares to views, and data is passed through middleware as a response. Here are the default middlewares installed in Django. You can add your middlewares. We will be discussing that in the next articles. Django uses request and response objects to pass state through the system.When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function. Each view is responsible for returning an HttpResponse object. To explain these objects let’s create a view home as below in views.py Python3 # importing HttResponse from libraryfrom django.http import HttpResponse def home(request): # request is handled using HttpResponse object return HttpResponse("Any kind of HTML Here") To handle the request let us map a URL to this view in urls.py Python3 # importing view from views.pyfrom .views import home urlpatterns = [ path('', home), ] Now you can run the server to see the following in the browser You can use the following attributes with HttpRequest for advanced manipulation You can use the following methods with HttpRequest for advanced manipulation You can use the following attributes with HttpResponse for advanced manipulation You can use the following methods with HttpResponse for advanced manipulation ksingla02 Django-basics Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25562, "s": 25534, "text": "\n27 May, 2021" }, { "code": null, "e": 25819, "s": 25562, "text": "Prerequisite – Views In Django | PythonBefore we jump into using convenience methods that views come with, Let’s talk about the Request and Response cycle. So, when a Request happens to a Django server, a couple of things go on. One of them is Middleware. " }, { "code": null, "e": 26180, "s": 25819, "text": "Middleware Middleware is like a middle ground between a request and response. It is like a window through which data passes. As in a window, light passes in and out of the house. Similarly, when a request is made it moves through middlewares to views, and data is passed through middleware as a response. Here are the default middlewares installed in Django. " }, { "code": null, "e": 26260, "s": 26180, "text": "You can add your middlewares. We will be discussing that in the next articles. " }, { "code": null, "e": 26611, "s": 26260, "text": "Django uses request and response objects to pass state through the system.When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function. Each view is responsible for returning an HttpResponse object. " }, { "code": null, "e": 26684, "s": 26611, "text": "To explain these objects let’s create a view home as below in views.py " }, { "code": null, "e": 26692, "s": 26684, "text": "Python3" }, { "code": "# importing HttResponse from libraryfrom django.http import HttpResponse def home(request): # request is handled using HttpResponse object return HttpResponse(\"Any kind of HTML Here\")", "e": 26882, "s": 26692, "text": null }, { "code": null, "e": 26949, "s": 26884, "text": "To handle the request let us map a URL to this view in urls.py " }, { "code": null, "e": 26957, "s": 26949, "text": "Python3" }, { "code": "# importing view from views.pyfrom .views import home urlpatterns = [ path('', home), ]", "e": 27048, "s": 26957, "text": null }, { "code": null, "e": 27115, "s": 27050, "text": "Now you can run the server to see the following in the browser " }, { "code": null, "e": 27199, "s": 27117, "text": "You can use the following attributes with HttpRequest for advanced manipulation " }, { "code": null, "e": 27280, "s": 27201, "text": "You can use the following methods with HttpRequest for advanced manipulation " }, { "code": null, "e": 27365, "s": 27282, "text": "You can use the following attributes with HttpResponse for advanced manipulation " }, { "code": null, "e": 27447, "s": 27367, "text": "You can use the following methods with HttpResponse for advanced manipulation " }, { "code": null, "e": 27459, "s": 27449, "text": "ksingla02" }, { "code": null, "e": 27473, "s": 27459, "text": "Django-basics" }, { "code": null, "e": 27480, "s": 27473, "text": "Python" }, { "code": null, "e": 27578, "s": 27480, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27610, "s": 27578, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27652, "s": 27610, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27694, "s": 27652, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27750, "s": 27694, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27777, "s": 27750, "text": "Python Classes and Objects" }, { "code": null, "e": 27816, "s": 27777, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27847, "s": 27816, "text": "Python | os.path.join() method" }, { "code": null, "e": 27869, "s": 27847, "text": "Defaultdict in Python" }, { "code": null, "e": 27898, "s": 27869, "text": "Create a directory in Python" } ]
C# | Finding the index of first element in the array - GeeksforGeeks
01 Feb, 2019 GetLowerBound() Method is used to find the index of the first element of the specified dimension in the array. Syntax: public int GetLowerBound (int dimension); Here, dimension is a zero-based dimension of the array whose lower bound needs to be determined. Return Value: The return type of this method is System.Int32. This method returns the index of the first element of the specified dimension in the array. Exception: This method will give IndexOutOfRangeException if the value of dimension is less than zero, or equal or greater than Rank. Note: GetLowerBound(0) returns the starting index of the first dimension of the array, and GetLowerBound(Rank – 1) returns the starting index of the last dimension of the array. The GetLowerBound method always returns a value that indicates the index of the lower bound of the array, even if the array is empty. This method is an O(1) operation. Below programs illustrate the use of GetLowerBound() Method: Example 1: // C# program to illustrate the GetLowerBound(Int32)// method in 1-D arrayusing System; public class GFG { // Main method static public void Main() { // 1-D Array int[] value = {1, 2, 3, 4, 5, 6, 7}; // Get the index of the first element // in the given Array by using // GetLowerBound(Int32) method int myvalue = value.GetLowerBound(0); Console.WriteLine("Index: {0}", myvalue); }} Index: 0 Example 2: // C# program to illustrate the GetLowerBound(Int32)// method when the array is emptyusing System; public class GFG { // Main method static public void Main() { // Empty 1-D Array int[] value = {}; // Get the index of the first element // in the given Array by using // GetLowerBound(Int32) method int myvalue = value.GetLowerBound(0); Console.WriteLine("Index: {0}", myvalue); }} Index: 0 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.array.getlowerbound?view=netcore-2.1 CSharp-Arrays CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Delegates C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Class and Object C# | Constructors C# | Replace() Method Introduction to .NET Framework C# | Data Types HashSet in C# with Examples
[ { "code": null, "e": 25787, "s": 25759, "text": "\n01 Feb, 2019" }, { "code": null, "e": 25898, "s": 25787, "text": "GetLowerBound() Method is used to find the index of the first element of the specified dimension in the array." }, { "code": null, "e": 25906, "s": 25898, "text": "Syntax:" }, { "code": null, "e": 25948, "s": 25906, "text": "public int GetLowerBound (int dimension);" }, { "code": null, "e": 26045, "s": 25948, "text": "Here, dimension is a zero-based dimension of the array whose lower bound needs to be determined." }, { "code": null, "e": 26199, "s": 26045, "text": "Return Value: The return type of this method is System.Int32. This method returns the index of the first element of the specified dimension in the array." }, { "code": null, "e": 26333, "s": 26199, "text": "Exception: This method will give IndexOutOfRangeException if the value of dimension is less than zero, or equal or greater than Rank." }, { "code": null, "e": 26339, "s": 26333, "text": "Note:" }, { "code": null, "e": 26511, "s": 26339, "text": "GetLowerBound(0) returns the starting index of the first dimension of the array, and GetLowerBound(Rank – 1) returns the starting index of the last dimension of the array." }, { "code": null, "e": 26645, "s": 26511, "text": "The GetLowerBound method always returns a value that indicates the index of the lower bound of the array, even if the array is empty." }, { "code": null, "e": 26679, "s": 26645, "text": "This method is an O(1) operation." }, { "code": null, "e": 26740, "s": 26679, "text": "Below programs illustrate the use of GetLowerBound() Method:" }, { "code": null, "e": 26751, "s": 26740, "text": "Example 1:" }, { "code": "// C# program to illustrate the GetLowerBound(Int32)// method in 1-D arrayusing System; public class GFG { // Main method static public void Main() { // 1-D Array int[] value = {1, 2, 3, 4, 5, 6, 7}; // Get the index of the first element // in the given Array by using // GetLowerBound(Int32) method int myvalue = value.GetLowerBound(0); Console.WriteLine(\"Index: {0}\", myvalue); }}", "e": 27217, "s": 26751, "text": null }, { "code": null, "e": 27227, "s": 27217, "text": "Index: 0\n" }, { "code": null, "e": 27238, "s": 27227, "text": "Example 2:" }, { "code": "// C# program to illustrate the GetLowerBound(Int32)// method when the array is emptyusing System; public class GFG { // Main method static public void Main() { // Empty 1-D Array int[] value = {}; // Get the index of the first element // in the given Array by using // GetLowerBound(Int32) method int myvalue = value.GetLowerBound(0); Console.WriteLine(\"Index: {0}\", myvalue); }}", "e": 27702, "s": 27238, "text": null }, { "code": null, "e": 27712, "s": 27702, "text": "Index: 0\n" }, { "code": null, "e": 27811, "s": 27712, "text": "Reference: https://docs.microsoft.com/en-us/dotnet/api/system.array.getlowerbound?view=netcore-2.1" }, { "code": null, "e": 27825, "s": 27811, "text": "CSharp-Arrays" }, { "code": null, "e": 27839, "s": 27825, "text": "CSharp-method" }, { "code": null, "e": 27842, "s": 27839, "text": "C#" }, { "code": null, "e": 27940, "s": 27842, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27955, "s": 27940, "text": "C# | Delegates" }, { "code": null, "e": 27977, "s": 27955, "text": "C# | Abstract Classes" }, { "code": null, "e": 28023, "s": 27977, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28046, "s": 28023, "text": "Extension Method in C#" }, { "code": null, "e": 28068, "s": 28046, "text": "C# | Class and Object" }, { "code": null, "e": 28086, "s": 28068, "text": "C# | Constructors" }, { "code": null, "e": 28108, "s": 28086, "text": "C# | Replace() Method" }, { "code": null, "e": 28139, "s": 28108, "text": "Introduction to .NET Framework" }, { "code": null, "e": 28155, "s": 28139, "text": "C# | Data Types" } ]
Python - Truncated Normal Distribution in Statistics - GeeksforGeeks
10 Jan, 2020 scipy.stats.truncnorm() is a Truncated Normal continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution. Parameters : q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’). Results : Truncated Normal continuous random variable Code #1 : Creating Truncated Normal continuous random variable # importing library from scipy.stats import truncnorm numargs = truncnorm .numargs a, b = 0.2, 0.8rv = truncnorm (a, b) print ("RV : \n", rv) Output : RV : scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D9C2FF08 Code #2 : Truncated Normal continuous variates and probability distribution import numpy as np quantile = np.arange (0.01, 1, 0.1) # Random Variates R = truncnorm .rvs(a, b, size = 10) print ("Random Variates : \n", R) # PDF x = np.linspace(truncnorm.ppf(0.01, a, b), truncnorm.ppf(0.99, a, b), 10)R = truncnorm.pdf(x, 1, 3)print ("\nProbability Distribution : \n", R) Output : Random Variates : [0.56227576 0.2513349 0.66393458 0.7453009 0.79215974 0.67208054 0.23809535 0.29203442 0.37395318 0.36091493] Probability Distribution : [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] Code #3 : Graphical Representation. import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print("Distribution : \n", distribution) plot = plt.plot(distribution, rv.pdf(distribution)) Output : Distribution : [0. 0.04081633 0.08163265 0.12244898 0.16326531 0.20408163 0.24489796 0.28571429 0.32653061 0.36734694 0.40816327 0.44897959 0.48979592 0.53061224 0.57142857 0.6122449 0.65306122 0.69387755 0.73469388 0.7755102 0.81632653 0.85714286 0.89795918 0.93877551 0.97959184 1.02040816 1.06122449 1.10204082 1.14285714 1.18367347 1.2244898 1.26530612 1.30612245 1.34693878 1.3877551 1.42857143 1.46938776 1.51020408 1.55102041 1.59183673 1.63265306 1.67346939 1.71428571 1.75510204 1.79591837 1.83673469 1.87755102 1.91836735 1.95918367 2. ] Code #4 : Varying Positional Arguments import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 100) # Varying positional arguments y1 = truncnorm.pdf(x, a, b) y2 = truncnorm.pdf(x, a, b) plt.plot(x, y1, "*", x, y2, "r--") Output : Python scipy-stats-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25509, "s": 25481, "text": "\n10 Jan, 2020" }, { "code": null, "e": 25751, "s": 25509, "text": "scipy.stats.truncnorm() is a Truncated Normal continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution." }, { "code": null, "e": 25764, "s": 25751, "text": "Parameters :" }, { "code": null, "e": 26110, "s": 25764, "text": "q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’)." }, { "code": null, "e": 26164, "s": 26110, "text": "Results : Truncated Normal continuous random variable" }, { "code": null, "e": 26227, "s": 26164, "text": "Code #1 : Creating Truncated Normal continuous random variable" }, { "code": "# importing library from scipy.stats import truncnorm numargs = truncnorm .numargs a, b = 0.2, 0.8rv = truncnorm (a, b) print (\"RV : \\n\", rv) ", "e": 26381, "s": 26227, "text": null }, { "code": null, "e": 26390, "s": 26381, "text": "Output :" }, { "code": null, "e": 26471, "s": 26390, "text": "RV : \n scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D9C2FF08\n" }, { "code": null, "e": 26547, "s": 26471, "text": "Code #2 : Truncated Normal continuous variates and probability distribution" }, { "code": "import numpy as np quantile = np.arange (0.01, 1, 0.1) # Random Variates R = truncnorm .rvs(a, b, size = 10) print (\"Random Variates : \\n\", R) # PDF x = np.linspace(truncnorm.ppf(0.01, a, b), truncnorm.ppf(0.99, a, b), 10)R = truncnorm.pdf(x, 1, 3)print (\"\\nProbability Distribution : \\n\", R) ", "e": 26860, "s": 26547, "text": null }, { "code": null, "e": 26869, "s": 26860, "text": "Output :" }, { "code": null, "e": 27065, "s": 26869, "text": "Random Variates : \n [0.56227576 0.2513349 0.66393458 0.7453009 0.79215974 0.67208054\n 0.23809535 0.29203442 0.37395318 0.36091493]\n\nProbability Distribution : \n [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n" }, { "code": null, "e": 27101, "s": 27065, "text": "Code #3 : Graphical Representation." }, { "code": "import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print(\"Distribution : \\n\", distribution) plot = plt.plot(distribution, rv.pdf(distribution)) ", "e": 27312, "s": 27101, "text": null }, { "code": null, "e": 27321, "s": 27312, "text": "Output :" }, { "code": null, "e": 27901, "s": 27321, "text": "Distribution : \n [0. 0.04081633 0.08163265 0.12244898 0.16326531 0.20408163\n 0.24489796 0.28571429 0.32653061 0.36734694 0.40816327 0.44897959\n 0.48979592 0.53061224 0.57142857 0.6122449 0.65306122 0.69387755\n 0.73469388 0.7755102 0.81632653 0.85714286 0.89795918 0.93877551\n 0.97959184 1.02040816 1.06122449 1.10204082 1.14285714 1.18367347\n 1.2244898 1.26530612 1.30612245 1.34693878 1.3877551 1.42857143\n 1.46938776 1.51020408 1.55102041 1.59183673 1.63265306 1.67346939\n 1.71428571 1.75510204 1.79591837 1.83673469 1.87755102 1.91836735\n 1.95918367 2. ]\n " }, { "code": null, "e": 27940, "s": 27901, "text": "Code #4 : Varying Positional Arguments" }, { "code": "import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 100) # Varying positional arguments y1 = truncnorm.pdf(x, a, b) y2 = truncnorm.pdf(x, a, b) plt.plot(x, y1, \"*\", x, y2, \"r--\") ", "e": 28148, "s": 27940, "text": null }, { "code": null, "e": 28157, "s": 28148, "text": "Output :" }, { "code": null, "e": 28186, "s": 28157, "text": "Python scipy-stats-functions" }, { "code": null, "e": 28193, "s": 28186, "text": "Python" }, { "code": null, "e": 28291, "s": 28193, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28309, "s": 28291, "text": "Python Dictionary" }, { "code": null, "e": 28344, "s": 28309, "text": "Read a file line by line in Python" }, { "code": null, "e": 28376, "s": 28344, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28398, "s": 28376, "text": "Enumerate() in Python" }, { "code": null, "e": 28440, "s": 28398, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28470, "s": 28440, "text": "Iterate over a list in Python" }, { "code": null, "e": 28496, "s": 28470, "text": "Python String | replace()" }, { "code": null, "e": 28525, "s": 28496, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28569, "s": 28525, "text": "Reading and Writing to text files in Python" } ]
Express.js req.xhr Property - GeeksforGeeks
07 Jul, 2020 The req.xhr property returns a true value if the request’s X-Requested-With header field is XMLHttpRequest which indicates that the request was issued by a client library such as jQuery. Syntax: req.xhr Parameter: No parameters. Returns: True or False. Installation of express module: You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js You can visit the link to Install express module. You can install this package by using this command.npm install express npm install express After installing the express module, you can check your express version in command prompt using the command.npm version express npm version express After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js node index.js Example 1: Filename: index.js var express = require('express');var app = express(); var PORT = 3000; app.get('/', function (req, res) { console.log(req.xhr); res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Steps to run the program: The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000 Now make GET request to http://localhost:3000/ with X-Requested-With header field set to XMLHttpRequest, now you can see the following output on your console:Server listening on PORT 3000 true The project structure will look like this: Make sure you have installed express module using the following command:npm install express npm install express Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000 node index.js Output: Server listening on PORT 3000 Now make GET request to http://localhost:3000/ with X-Requested-With header field set to XMLHttpRequest, now you can see the following output on your console:Server listening on PORT 3000 true Server listening on PORT 3000 true Example 2: Filename: index.js var express = require('express');var app = express(); var PORT = 3000; app.get('/', function (req, res) { if(req.xhr) { return res.send({status: true}); } else { return res.send({status: false}); }}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Run index.js file using below command: node index.js Output: Now open your browser and make GET request to http://localhost:3000, now you can see the following output on your screen: {"status":false} Reference: https://expressjs.com/en/4x/api.html#req.xhr Express.js Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between dependencies, devDependencies and peerDependencies Node.js Export Module How to connect Node.js with React.js ? Mongoose find() Function Mongoose Populate() Method Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26267, "s": 26239, "text": "\n07 Jul, 2020" }, { "code": null, "e": 26454, "s": 26267, "text": "The req.xhr property returns a true value if the request’s X-Requested-With header field is XMLHttpRequest which indicates that the request was issued by a client library such as jQuery." }, { "code": null, "e": 26462, "s": 26454, "text": "Syntax:" }, { "code": null, "e": 26470, "s": 26462, "text": "req.xhr" }, { "code": null, "e": 26496, "s": 26470, "text": "Parameter: No parameters." }, { "code": null, "e": 26520, "s": 26496, "text": "Returns: True or False." }, { "code": null, "e": 26552, "s": 26520, "text": "Installation of express module:" }, { "code": null, "e": 26947, "s": 26552, "text": "You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 27068, "s": 26947, "text": "You can visit the link to Install express module. You can install this package by using this command.npm install express" }, { "code": null, "e": 27088, "s": 27068, "text": "npm install express" }, { "code": null, "e": 27216, "s": 27088, "text": "After installing the express module, you can check your express version in command prompt using the command.npm version express" }, { "code": null, "e": 27236, "s": 27216, "text": "npm version express" }, { "code": null, "e": 27384, "s": 27236, "text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 27398, "s": 27384, "text": "node index.js" }, { "code": null, "e": 27428, "s": 27398, "text": "Example 1: Filename: index.js" }, { "code": "var express = require('express');var app = express(); var PORT = 3000; app.get('/', function (req, res) { console.log(req.xhr); res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 27690, "s": 27428, "text": null }, { "code": null, "e": 27716, "s": 27690, "text": "Steps to run the program:" }, { "code": null, "e": 28131, "s": 27716, "text": "The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000\nNow make GET request to http://localhost:3000/ with X-Requested-With header field set to XMLHttpRequest, now you can see the following output on your console:Server listening on PORT 3000\ntrue\n" }, { "code": null, "e": 28174, "s": 28131, "text": "The project structure will look like this:" }, { "code": null, "e": 28266, "s": 28174, "text": "Make sure you have installed express module using the following command:npm install express" }, { "code": null, "e": 28286, "s": 28266, "text": "npm install express" }, { "code": null, "e": 28375, "s": 28286, "text": "Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000\n" }, { "code": null, "e": 28389, "s": 28375, "text": "node index.js" }, { "code": null, "e": 28397, "s": 28389, "text": "Output:" }, { "code": null, "e": 28428, "s": 28397, "text": "Server listening on PORT 3000\n" }, { "code": null, "e": 28622, "s": 28428, "text": "Now make GET request to http://localhost:3000/ with X-Requested-With header field set to XMLHttpRequest, now you can see the following output on your console:Server listening on PORT 3000\ntrue\n" }, { "code": null, "e": 28658, "s": 28622, "text": "Server listening on PORT 3000\ntrue\n" }, { "code": null, "e": 28688, "s": 28658, "text": "Example 2: Filename: index.js" }, { "code": "var express = require('express');var app = express(); var PORT = 3000; app.get('/', function (req, res) { if(req.xhr) { return res.send({status: true}); } else { return res.send({status: false}); }}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 29029, "s": 28688, "text": null }, { "code": null, "e": 29068, "s": 29029, "text": "Run index.js file using below command:" }, { "code": null, "e": 29082, "s": 29068, "text": "node index.js" }, { "code": null, "e": 29212, "s": 29082, "text": "Output: Now open your browser and make GET request to http://localhost:3000, now you can see the following output on your screen:" }, { "code": null, "e": 29230, "s": 29212, "text": "{\"status\":false}\n" }, { "code": null, "e": 29286, "s": 29230, "text": "Reference: https://expressjs.com/en/4x/api.html#req.xhr" }, { "code": null, "e": 29297, "s": 29286, "text": "Express.js" }, { "code": null, "e": 29305, "s": 29297, "text": "Node.js" }, { "code": null, "e": 29322, "s": 29305, "text": "Web Technologies" }, { "code": null, "e": 29420, "s": 29322, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29490, "s": 29420, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 29512, "s": 29490, "text": "Node.js Export Module" }, { "code": null, "e": 29551, "s": 29512, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 29576, "s": 29551, "text": "Mongoose find() Function" }, { "code": null, "e": 29603, "s": 29576, "text": "Mongoose Populate() Method" }, { "code": null, "e": 29643, "s": 29603, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29688, "s": 29643, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29731, "s": 29688, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29781, "s": 29731, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python OpenCV | cv2.imwrite() method
07 Aug, 2019 OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.imwrite() method is used to save an image to any storage device. This will save the image according to the specified format in current working directory. Syntax: cv2.imwrite(filename, image) Parameters:filename: A string representing the file name. The filename must include image format like .jpg, .png, etc.image: It is the image that is to be saved. Return Value: It returns true if image is saved successfully. Example #1: # Python program to explain cv2.imwrite() method # importing cv2 import cv2 # importing os module import os # Image pathimage_path = r'C:\Users\Rajnish\Desktop\GeeksforGeeks\geeks.png' # Image directorydirectory = r'C:\Users\Rajnish\Desktop\GeeksforGeeks' # Using cv2.imread() method# to read the imageimg = cv2.imread(image_path) # Change the current directory # to specified directory os.chdir(directory) # List files and directories # in 'C:/Users/Rajnish/Desktop/GeeksforGeeks' print("Before saving image:") print(os.listdir(directory)) # Filenamefilename = 'savedImage.jpg' # Using cv2.imwrite() method# Saving the imagecv2.imwrite(filename, img) # List files and directories # in 'C:/Users / Rajnish / Desktop / GeeksforGeeks' print("After saving image:") print(os.listdir(directory)) print('Successfully saved') Output: Before saving image: ['geeks.png'] After saving image: ['geeks.png', 'savedImage.jpg'] Successfully saved OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Aug, 2019" }, { "code": null, "e": 300, "s": 52, "text": "OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.imwrite() method is used to save an image to any storage device. This will save the image according to the specified format in current working directory." }, { "code": null, "e": 337, "s": 300, "text": "Syntax: cv2.imwrite(filename, image)" }, { "code": null, "e": 499, "s": 337, "text": "Parameters:filename: A string representing the file name. The filename must include image format like .jpg, .png, etc.image: It is the image that is to be saved." }, { "code": null, "e": 561, "s": 499, "text": "Return Value: It returns true if image is saved successfully." }, { "code": null, "e": 573, "s": 561, "text": "Example #1:" }, { "code": "# Python program to explain cv2.imwrite() method # importing cv2 import cv2 # importing os module import os # Image pathimage_path = r'C:\\Users\\Rajnish\\Desktop\\GeeksforGeeks\\geeks.png' # Image directorydirectory = r'C:\\Users\\Rajnish\\Desktop\\GeeksforGeeks' # Using cv2.imread() method# to read the imageimg = cv2.imread(image_path) # Change the current directory # to specified directory os.chdir(directory) # List files and directories # in 'C:/Users/Rajnish/Desktop/GeeksforGeeks' print(\"Before saving image:\") print(os.listdir(directory)) # Filenamefilename = 'savedImage.jpg' # Using cv2.imwrite() method# Saving the imagecv2.imwrite(filename, img) # List files and directories # in 'C:/Users / Rajnish / Desktop / GeeksforGeeks' print(\"After saving image:\") print(os.listdir(directory)) print('Successfully saved')", "e": 1412, "s": 573, "text": null }, { "code": null, "e": 1420, "s": 1412, "text": "Output:" }, { "code": null, "e": 1527, "s": 1420, "text": "Before saving image:\n['geeks.png']\nAfter saving image:\n['geeks.png', 'savedImage.jpg']\nSuccessfully saved\n" }, { "code": null, "e": 1534, "s": 1527, "text": "OpenCV" }, { "code": null, "e": 1541, "s": 1534, "text": "Python" } ]
How to install Jupyter Notebook in Linux?
06 Oct, 2021 Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations, and narrative text. Uses include data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more. Jupyter has support for over 40 different programming languages and Python is one of them. Python is a requirement (Python 3.3 or greater, or Python 2.7) for installing the Jupyter Notebook itself. Jupyter Notebook can be installed by using either of the two ways described below: Using Anaconda:Install Python and Jupyter using the Anaconda Distribution, which includes Python, the Jupyter Notebook, and other commonly used packages for scientific computing and data science. To install Anaconda, go through How to install Anaconda on Linux? and follow the instructions provided. Using PIP:Install Jupyter using the PIP package manager used to install and manage software packages/libraries written in Python. To install pip, go through How to install PIP in Linux? and follow the instructions provided. Using PIP:Install Jupyter using the PIP package manager used to install and manage software packages/libraries written in Python. To install pip, go through How to install PIP in Linux? and follow the instructions provided. Anaconda is an open-source software that contains Jupyter, spyder, etc that are used for large data processing, data analytics, heavy scientific computing. Anaconda works for R and python programming language. Spyder(sub-application of Anaconda) is used for python. Opencv for python will work in spyder. Package versions are managed by the package management system called conda. To install Jupyter using Anaconda, just go through the following instructions: Launch Anaconda Navigator: Click on the Install Jupyter Notebook Button: Beginning the Installation: Loading Packages: Finished Installation: Launching Jupyter: PIP is a package management system used to install and manage software packages/libraries written in Python. These files are stored in a large “on-line repository” termed as Python Package Index (PyPI).pip uses PyPI as the default source for packages and their dependencies. To install Jupyter using pip, we need to first check if pip is updated in our system. Use the following command to update pip: python3 -m pip install --upgrade pip After updating the pip version, follow the instructions provided below to install Jupyter: Command to install Jupyter:pip3 install Jupyter pip3 install Jupyter Beginning Installation: Collecting Files and Data: Downloading Packages: Running Installation: Finished Installation: Launching Jupyter:Use the following command to launch Jupyter using command-line: jupyter notebook how-to-install python-basics How To Installation Guide Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to filter object array based on attributes? Java Tutorial How to Align Text in HTML? How to Set Git Username and Password in GitBash? How to Install FFmpeg on Windows? Installation of Node.js on Linux How to Install FFmpeg on Windows? How to Install and Run Apache Kafka on Windows? Installation of Node.js on Windows How to Install and Use NVM on Windows?
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Oct, 2021" }, { "code": null, "e": 340, "s": 28, "text": "Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations, and narrative text. Uses include data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more." }, { "code": null, "e": 538, "s": 340, "text": "Jupyter has support for over 40 different programming languages and Python is one of them. Python is a requirement (Python 3.3 or greater, or Python 2.7) for installing the Jupyter Notebook itself." }, { "code": null, "e": 621, "s": 538, "text": "Jupyter Notebook can be installed by using either of the two ways described below:" }, { "code": null, "e": 921, "s": 621, "text": "Using Anaconda:Install Python and Jupyter using the Anaconda Distribution, which includes Python, the Jupyter Notebook, and other commonly used packages for scientific computing and data science. To install Anaconda, go through How to install Anaconda on Linux? and follow the instructions provided." }, { "code": null, "e": 1145, "s": 921, "text": "Using PIP:Install Jupyter using the PIP package manager used to install and manage software packages/libraries written in Python. To install pip, go through How to install PIP in Linux? and follow the instructions provided." }, { "code": null, "e": 1369, "s": 1145, "text": "Using PIP:Install Jupyter using the PIP package manager used to install and manage software packages/libraries written in Python. To install pip, go through How to install PIP in Linux? and follow the instructions provided." }, { "code": null, "e": 1750, "s": 1369, "text": "Anaconda is an open-source software that contains Jupyter, spyder, etc that are used for large data processing, data analytics, heavy scientific computing. Anaconda works for R and python programming language. Spyder(sub-application of Anaconda) is used for python. Opencv for python will work in spyder. Package versions are managed by the package management system called conda." }, { "code": null, "e": 1829, "s": 1750, "text": "To install Jupyter using Anaconda, just go through the following instructions:" }, { "code": null, "e": 1856, "s": 1829, "text": "Launch Anaconda Navigator:" }, { "code": null, "e": 1902, "s": 1856, "text": "Click on the Install Jupyter Notebook Button:" }, { "code": null, "e": 1930, "s": 1902, "text": "Beginning the Installation:" }, { "code": null, "e": 1948, "s": 1930, "text": "Loading Packages:" }, { "code": null, "e": 1971, "s": 1948, "text": "Finished Installation:" }, { "code": null, "e": 1990, "s": 1971, "text": "Launching Jupyter:" }, { "code": null, "e": 2265, "s": 1990, "text": "PIP is a package management system used to install and manage software packages/libraries written in Python. These files are stored in a large “on-line repository” termed as Python Package Index (PyPI).pip uses PyPI as the default source for packages and their dependencies." }, { "code": null, "e": 2392, "s": 2265, "text": "To install Jupyter using pip, we need to first check if pip is updated in our system. Use the following command to update pip:" }, { "code": null, "e": 2429, "s": 2392, "text": "python3 -m pip install --upgrade pip" }, { "code": null, "e": 2520, "s": 2429, "text": "After updating the pip version, follow the instructions provided below to install Jupyter:" }, { "code": null, "e": 2569, "s": 2520, "text": "Command to install Jupyter:pip3 install Jupyter\n" }, { "code": null, "e": 2591, "s": 2569, "text": "pip3 install Jupyter\n" }, { "code": null, "e": 2615, "s": 2591, "text": "Beginning Installation:" }, { "code": null, "e": 2642, "s": 2615, "text": "Collecting Files and Data:" }, { "code": null, "e": 2664, "s": 2642, "text": "Downloading Packages:" }, { "code": null, "e": 2686, "s": 2664, "text": "Running Installation:" }, { "code": null, "e": 2709, "s": 2686, "text": "Finished Installation:" }, { "code": null, "e": 2791, "s": 2709, "text": "Launching Jupyter:Use the following command to launch Jupyter using command-line:" }, { "code": null, "e": 2808, "s": 2791, "text": "jupyter notebook" }, { "code": null, "e": 2823, "s": 2808, "text": "how-to-install" }, { "code": null, "e": 2837, "s": 2823, "text": "python-basics" }, { "code": null, "e": 2844, "s": 2837, "text": "How To" }, { "code": null, "e": 2863, "s": 2844, "text": "Installation Guide" }, { "code": null, "e": 2870, "s": 2863, "text": "Python" }, { "code": null, "e": 2968, "s": 2870, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3016, "s": 2968, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 3030, "s": 3016, "text": "Java Tutorial" }, { "code": null, "e": 3057, "s": 3030, "text": "How to Align Text in HTML?" }, { "code": null, "e": 3106, "s": 3057, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 3140, "s": 3106, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 3173, "s": 3140, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3207, "s": 3173, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 3255, "s": 3207, "text": "How to Install and Run Apache Kafka on Windows?" }, { "code": null, "e": 3290, "s": 3255, "text": "Installation of Node.js on Windows" } ]
Python Program for Bubble Sort
13 Jun, 2022 Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. Python3 # Python program for implementation of Bubble Sort def bubbleSort(arr): n = len(arr) # optimize code, so if the array is already sorted, it doesn't need # to go through the entire process swapped = False # Traverse through all array elements for i in range(n-1): # range(n) also work but outer loop will # repeat one time more than needed. # Last i elements are already in place for j in range(0, n-i-1): # traverse the array from 0 to n-i-1 # Swap if the element found is greater # than the next element if arr[j] > arr[j + 1]: swapped = True arr[j], arr[j + 1] = arr[j + 1], arr[j] if not swapped: # if we haven't needed to make a single swap, we # can just exit the main loop. return # Driver code to test abovearr = [64, 34, 25, 12, 22, 11, 90] bubbleSort(arr) print("Sorted array is:")for i in range(len(arr)): print("% d" % arr[i], end=" ") Sorted array is: 11 12 22 25 34 64 90 Time Complexity: O(n2). Auxiliary Space: O(1). Please refer complete article on Bubble Sort for more details! Python3 def bubblesort(elements): swapped = False # Looping from size of array from last index[-1] to index [0] for n in range(len(elements)-1, 0, -1): for i in range(n): if elements[i] > elements[i + 1]: swapped = True # swapping data if the element is less than next element in the array elements[i], elements[i + 1] = elements[i + 1], elements[i] if not swapped: # exiting the function if we didn't make a single swap # meaning that the array is already sorted. return elements = [39, 12, 18, 85, 72, 10, 2, 18] print("Unsorted list is,")print(elements)bubblesort(elements)print("Sorted Array is, ")print(elements) Unsorted list is, [39, 12, 18, 85, 72, 10, 2, 18] Sorted Array is, [2, 10, 12, 18, 18, 39, 72, 85] Time Complexity: O(n2). However in practice, this optimized version might take less time as when array gets sorted, function would return. Auxiliary Space: O(1). banvariguptajhinjhak priyampatel9911 surinderdawra388 surindertarika1234 satyam00so amartyaghoshgfg talktoanmol chandramauliguptach BubbleSort python sorting-exercises Python Programs Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python program to add two numbers Python Program for factorial of a number Iterate over characters of a string in Python Python program to interchange first and last elements in a list Python program to find second largest number in a list Merge Sort QuickSort Insertion Sort Selection Sort Algorithm
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jun, 2022" }, { "code": null, "e": 187, "s": 52, "text": "Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. " }, { "code": null, "e": 195, "s": 187, "text": "Python3" }, { "code": "# Python program for implementation of Bubble Sort def bubbleSort(arr): n = len(arr) # optimize code, so if the array is already sorted, it doesn't need # to go through the entire process swapped = False # Traverse through all array elements for i in range(n-1): # range(n) also work but outer loop will # repeat one time more than needed. # Last i elements are already in place for j in range(0, n-i-1): # traverse the array from 0 to n-i-1 # Swap if the element found is greater # than the next element if arr[j] > arr[j + 1]: swapped = True arr[j], arr[j + 1] = arr[j + 1], arr[j] if not swapped: # if we haven't needed to make a single swap, we # can just exit the main loop. return # Driver code to test abovearr = [64, 34, 25, 12, 22, 11, 90] bubbleSort(arr) print(\"Sorted array is:\")for i in range(len(arr)): print(\"% d\" % arr[i], end=\" \")", "e": 1216, "s": 195, "text": null }, { "code": null, "e": 1262, "s": 1216, "text": "Sorted array is:\n 11 12 22 25 34 64 90 " }, { "code": null, "e": 1287, "s": 1262, "text": "Time Complexity: O(n2)." }, { "code": null, "e": 1310, "s": 1287, "text": "Auxiliary Space: O(1)." }, { "code": null, "e": 1374, "s": 1310, "text": "Please refer complete article on Bubble Sort for more details! " }, { "code": null, "e": 1382, "s": 1374, "text": "Python3" }, { "code": "def bubblesort(elements): swapped = False # Looping from size of array from last index[-1] to index [0] for n in range(len(elements)-1, 0, -1): for i in range(n): if elements[i] > elements[i + 1]: swapped = True # swapping data if the element is less than next element in the array elements[i], elements[i + 1] = elements[i + 1], elements[i] if not swapped: # exiting the function if we didn't make a single swap # meaning that the array is already sorted. return elements = [39, 12, 18, 85, 72, 10, 2, 18] print(\"Unsorted list is,\")print(elements)bubblesort(elements)print(\"Sorted Array is, \")print(elements)", "e": 2111, "s": 1382, "text": null }, { "code": null, "e": 2211, "s": 2111, "text": "Unsorted list is,\n[39, 12, 18, 85, 72, 10, 2, 18]\nSorted Array is, \n[2, 10, 12, 18, 18, 39, 72, 85]" }, { "code": null, "e": 2351, "s": 2211, "text": "Time Complexity: O(n2). However in practice, this optimized version might take less time as when array gets sorted, function would return." }, { "code": null, "e": 2374, "s": 2351, "text": "Auxiliary Space: O(1)." }, { "code": null, "e": 2395, "s": 2374, "text": "banvariguptajhinjhak" }, { "code": null, "e": 2411, "s": 2395, "text": "priyampatel9911" }, { "code": null, "e": 2428, "s": 2411, "text": "surinderdawra388" }, { "code": null, "e": 2447, "s": 2428, "text": "surindertarika1234" }, { "code": null, "e": 2458, "s": 2447, "text": "satyam00so" }, { "code": null, "e": 2474, "s": 2458, "text": "amartyaghoshgfg" }, { "code": null, "e": 2486, "s": 2474, "text": "talktoanmol" }, { "code": null, "e": 2506, "s": 2486, "text": "chandramauliguptach" }, { "code": null, "e": 2517, "s": 2506, "text": "BubbleSort" }, { "code": null, "e": 2542, "s": 2517, "text": "python sorting-exercises" }, { "code": null, "e": 2558, "s": 2542, "text": "Python Programs" }, { "code": null, "e": 2566, "s": 2558, "text": "Sorting" }, { "code": null, "e": 2574, "s": 2566, "text": "Sorting" }, { "code": null, "e": 2672, "s": 2574, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2706, "s": 2672, "text": "Python program to add two numbers" }, { "code": null, "e": 2747, "s": 2706, "text": "Python Program for factorial of a number" }, { "code": null, "e": 2793, "s": 2747, "text": "Iterate over characters of a string in Python" }, { "code": null, "e": 2857, "s": 2793, "text": "Python program to interchange first and last elements in a list" }, { "code": null, "e": 2912, "s": 2857, "text": "Python program to find second largest number in a list" }, { "code": null, "e": 2923, "s": 2912, "text": "Merge Sort" }, { "code": null, "e": 2933, "s": 2923, "text": "QuickSort" }, { "code": null, "e": 2948, "s": 2933, "text": "Insertion Sort" } ]
HTML | rowspan Attribute
30 Nov, 2021 The rowspan attribute in HTML specifies the number of rows a cell should span. That is if a row spans two rows, it means it will take up the space of two rows in that table. It allows the single table cell to span the height of more than one cell or row. It provides the same functionality as “merge cell” in the spreadsheet program like Excel.Usage: It can be used with <td> and <th> element in an HTML Table. Attribute Values: It contains a value i.e number Which specify the number of rows that a table cell should span. <td>: The rowspan attribute when used with <td> tag determines the number of standard cells it should span. Syntax: <td rowspan = "value">table content...</td> The value specifies the number of rows that the cell fills. The value must be a integer. Example: html <!DOCTYPE html><html> <head> <title>HTML rowspan Attribute</title> <style> table, th, td { border: 1px solid black; border-collapse: collapse; padding: 6px; } </style> </head> <body style = "text-align:center"> <h1 style = "color: green;">GeeksforGeeks</h1> <h2>HTML rowspan Attribute</h2> <table> <tr> <th>Name</th> <th>Age</th> </tr> <tr> <td>Ajay</td> <!-- This cell will take up space on two rows --> <td rowspan="2">24</td> </tr> <tr> <td>Priya</td> </tr> </table> </body></html> Output: <th>: The rowspan attribute when used with <th> tag determines the number of header cells it should span. Syntax: <th rowspan = "value">table content...</th> The value specifies the number of rows that the cell fills. The value must be a integer. Example: html <!DOCTYPE html><html> <head> <title>HTML rowspan Attribute</title> <style> table, th, td { border: 1px solid black; border-collapse: collapse; padding: 6px; } </style> </head> <body style = "text-align:center"> <h1 style = "color: green;">GeeksforGeeks</h1> <h2>HTML rowspan Attribute</h2> <table> <tr> <th>Name</th> <th>Age</th> <!-- This cell will take up space in 3 rows --> <th rowspan="3">GeeksforGeeks</th> </tr> <tr> <td>Arun</td> <td>24</td> </tr> <tr> <td>Priya</td> <td>25</td> </tr> </table> </body></html> Output: Supported Browsers: The browser supported by rowspan attribute are listed below: Google Chrome Internet Explorer Firefox Opera Safari ManasChhabra2 chhabradhanvi 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 ? 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 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript Roadmap to Learn JavaScript For Beginners How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Nov, 2021" }, { "code": null, "e": 464, "s": 52, "text": "The rowspan attribute in HTML specifies the number of rows a cell should span. That is if a row spans two rows, it means it will take up the space of two rows in that table. It allows the single table cell to span the height of more than one cell or row. It provides the same functionality as “merge cell” in the spreadsheet program like Excel.Usage: It can be used with <td> and <th> element in an HTML Table. " }, { "code": null, "e": 578, "s": 464, "text": "Attribute Values: It contains a value i.e number Which specify the number of rows that a table cell should span. " }, { "code": null, "e": 694, "s": 578, "text": "<td>: The rowspan attribute when used with <td> tag determines the number of standard cells it should span. Syntax:" }, { "code": null, "e": 738, "s": 694, "text": "<td rowspan = \"value\">table content...</td>" }, { "code": null, "e": 837, "s": 738, "text": "The value specifies the number of rows that the cell fills. The value must be a integer. Example: " }, { "code": null, "e": 842, "s": 837, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML rowspan Attribute</title> <style> table, th, td { border: 1px solid black; border-collapse: collapse; padding: 6px; } </style> </head> <body style = \"text-align:center\"> <h1 style = \"color: green;\">GeeksforGeeks</h1> <h2>HTML rowspan Attribute</h2> <table> <tr> <th>Name</th> <th>Age</th> </tr> <tr> <td>Ajay</td> <!-- This cell will take up space on two rows --> <td rowspan=\"2\">24</td> </tr> <tr> <td>Priya</td> </tr> </table> </body></html> ", "e": 1661, "s": 842, "text": null }, { "code": null, "e": 1670, "s": 1661, "text": "Output: " }, { "code": null, "e": 1784, "s": 1670, "text": "<th>: The rowspan attribute when used with <th> tag determines the number of header cells it should span. Syntax:" }, { "code": null, "e": 1828, "s": 1784, "text": "<th rowspan = \"value\">table content...</th>" }, { "code": null, "e": 1927, "s": 1828, "text": "The value specifies the number of rows that the cell fills. The value must be a integer. Example: " }, { "code": null, "e": 1932, "s": 1927, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML rowspan Attribute</title> <style> table, th, td { border: 1px solid black; border-collapse: collapse; padding: 6px; } </style> </head> <body style = \"text-align:center\"> <h1 style = \"color: green;\">GeeksforGeeks</h1> <h2>HTML rowspan Attribute</h2> <table> <tr> <th>Name</th> <th>Age</th> <!-- This cell will take up space in 3 rows --> <th rowspan=\"3\">GeeksforGeeks</th> </tr> <tr> <td>Arun</td> <td>24</td> </tr> <tr> <td>Priya</td> <td>25</td> </tr> </table> </body></html> ", "e": 2816, "s": 1932, "text": null }, { "code": null, "e": 2825, "s": 2816, "text": "Output: " }, { "code": null, "e": 2910, "s": 2827, "text": "Supported Browsers: The browser supported by rowspan attribute are listed below: " }, { "code": null, "e": 2924, "s": 2910, "text": "Google Chrome" }, { "code": null, "e": 2942, "s": 2924, "text": "Internet Explorer" }, { "code": null, "e": 2950, "s": 2942, "text": "Firefox" }, { "code": null, "e": 2956, "s": 2950, "text": "Opera" }, { "code": null, "e": 2963, "s": 2956, "text": "Safari" }, { "code": null, "e": 2979, "s": 2965, "text": "ManasChhabra2" }, { "code": null, "e": 2993, "s": 2979, "text": "chhabradhanvi" }, { "code": null, "e": 3009, "s": 2993, "text": "HTML-Attributes" }, { "code": null, "e": 3014, "s": 3009, "text": "HTML" }, { "code": null, "e": 3031, "s": 3014, "text": "Web Technologies" }, { "code": null, "e": 3036, "s": 3031, "text": "HTML" }, { "code": null, "e": 3134, "s": 3036, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3182, "s": 3134, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3244, "s": 3182, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3294, "s": 3244, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3318, "s": 3294, "text": "REST API (Introduction)" }, { "code": null, "e": 3371, "s": 3318, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3404, "s": 3371, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3466, "s": 3404, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3527, "s": 3466, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3569, "s": 3527, "text": "Roadmap to Learn JavaScript For Beginners" } ]
ln command in Linux with Examples
23 May, 2019 The ln command is used to create links between files. Before going into the application of the ln command in detail, please refer the below link for a clear understanding of the hard link and soft link in Linux. Hard and Soft Links in Linux Syntax: ln [OPTION]... [-T] TARGET LINK_NAME (1st form) ln [OPTION]... TARGET... DIRECTORY (2nd form) ln [OPTION]... -t DIRECTORY TARGET... (3rd form) Basically, ln command is used to create hard links and soft links for files in Linux. Let’s discuss all the three forms one by one. 1st Form: This form is simple, the source file with destination link name you have to specify: 2nd Form: Here, we have to give source file and directory as a link, simply the source file will be copied to the directory which you specify. See the example below. 3rd Form: Here, we will specify the directory name and a file to be linked to the directory. It is mostly same to 2nd form. Most Useful Options: verbose or -v : This option will help you to know which file is linked to which file. Basically, it prints the name of each linked file. Help or -h : It will display help option of ln command, you could even see more detailed information in those help command. version or -v : This will display the version detail, author detail of the command. Applications: Symbolic links are most useful for avoiding complicated paths. Don’t want to have to remember a path that is 73 characters long? No problem, just create a symbolic link to remember where it is. Symbolic links make it easy to make some set of files appear to exist in multiple locations without having to make separate copies. Hard links are most useful for keeping file content in a single location by avoiding duplication of what might be a very large amount of data. Practical Example of creation and deletion of links in Linux: Example 1: Example 2: Example 3: linux-command Linux-file-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples curl command in Linux with Examples 'crontab' in Linux with Examples Conditional Statements | Shell Script Tail command in Linux with examples Docker - COPY Instruction scp command in Linux with Examples UDP Server-Client implementation in C Cat command in Linux with examples echo command in Linux with Examples
[ { "code": null, "e": 28, "s": 0, "text": "\n23 May, 2019" }, { "code": null, "e": 269, "s": 28, "text": "The ln command is used to create links between files. Before going into the application of the ln command in detail, please refer the below link for a clear understanding of the hard link and soft link in Linux. Hard and Soft Links in Linux" }, { "code": null, "e": 277, "s": 269, "text": "Syntax:" }, { "code": null, "e": 428, "s": 277, "text": "ln [OPTION]... [-T] TARGET LINK_NAME (1st form)\nln [OPTION]... TARGET... DIRECTORY (2nd form)\nln [OPTION]... -t DIRECTORY TARGET... (3rd form)\n" }, { "code": null, "e": 560, "s": 428, "text": "Basically, ln command is used to create hard links and soft links for files in Linux. Let’s discuss all the three forms one by one." }, { "code": null, "e": 655, "s": 560, "text": "1st Form: This form is simple, the source file with destination link name you have to specify:" }, { "code": null, "e": 821, "s": 655, "text": "2nd Form: Here, we have to give source file and directory as a link, simply the source file will be copied to the directory which you specify. See the example below." }, { "code": null, "e": 945, "s": 821, "text": "3rd Form: Here, we will specify the directory name and a file to be linked to the directory. It is mostly same to 2nd form." }, { "code": null, "e": 966, "s": 945, "text": "Most Useful Options:" }, { "code": null, "e": 1103, "s": 966, "text": "verbose or -v : This option will help you to know which file is linked to which file. Basically, it prints the name of each linked file." }, { "code": null, "e": 1227, "s": 1103, "text": "Help or -h : It will display help option of ln command, you could even see more detailed information in those help command." }, { "code": null, "e": 1311, "s": 1227, "text": "version or -v : This will display the version detail, author detail of the command." }, { "code": null, "e": 1325, "s": 1311, "text": "Applications:" }, { "code": null, "e": 1519, "s": 1325, "text": "Symbolic links are most useful for avoiding complicated paths. Don’t want to have to remember a path that is 73 characters long? No problem, just create a symbolic link to remember where it is." }, { "code": null, "e": 1651, "s": 1519, "text": "Symbolic links make it easy to make some set of files appear to exist in multiple locations without having to make separate copies." }, { "code": null, "e": 1794, "s": 1651, "text": "Hard links are most useful for keeping file content in a single location by avoiding duplication of what might be a very large amount of data." }, { "code": null, "e": 1856, "s": 1794, "text": "Practical Example of creation and deletion of links in Linux:" }, { "code": null, "e": 1867, "s": 1856, "text": "Example 1:" }, { "code": null, "e": 1878, "s": 1867, "text": "Example 2:" }, { "code": null, "e": 1889, "s": 1878, "text": "Example 3:" }, { "code": null, "e": 1903, "s": 1889, "text": "linux-command" }, { "code": null, "e": 1923, "s": 1903, "text": "Linux-file-commands" }, { "code": null, "e": 1930, "s": 1923, "text": "Picked" }, { "code": null, "e": 1941, "s": 1930, "text": "Linux-Unix" }, { "code": null, "e": 2039, "s": 1941, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2074, "s": 2039, "text": "tar command in Linux with examples" }, { "code": null, "e": 2110, "s": 2074, "text": "curl command in Linux with Examples" }, { "code": null, "e": 2143, "s": 2110, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 2181, "s": 2143, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 2217, "s": 2181, "text": "Tail command in Linux with examples" }, { "code": null, "e": 2243, "s": 2217, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2278, "s": 2243, "text": "scp command in Linux with Examples" }, { "code": null, "e": 2316, "s": 2278, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 2351, "s": 2316, "text": "Cat command in Linux with examples" } ]
How to display array structure and values in PHP ?
07 Oct, 2021 In this article, we will discuss how to display the array structure and values in PHP. To display the array structure and its values, we can use var_dump() and print_r() functions. It includes Array size Array values Array value with Index Each value data type We will display the array structure using var_dump() function. This function is used to dump information about a variable. This function displays structured information such as the type and value of the given variable. Arrays and objects are explored recursively with values indented to show structure. This function is also effective with expressions. Syntax: var_dump( $array_name ) Parameters: The function takes a single argument $array_name that may be one single variable or an expression containing several space-separated variables of any type. Return Type: Array Structure Example: PHP Program to create an array and display its structure. PHP <?php // Array with subjects$array1 = array( '0' => "Python", '1' => "java", '2' => "c/cpp"); // Display array structurevar_dump($array1); ?> array(3) { [0]=> string(6) "Python" [1]=> string(4) "java" [2]=> string(5) "c/cpp" } Here, array(3) is the size of the array ( 3 elements) string(6) is the data type of element 1 with its size string(4) is the data type of element 2 with its size string(5) is the data type of element 3 with its size Array Values: We will display the array values by using the print_r() function. This function is used to print or display information stored in a variable. Syntax: print_r( $variable, $isStore ) Parameters: $variable: This parameter specifies the variable to be printed and is a mandatory parameter. $isStore: This is an optional parameter. This parameter is of boolean type whose default value is FALSE and is used to store the output of the print_r() function in a variable rather than printing it. If this parameter is set to TRUE then the print_r() function will return the output which it is supposed to print. Return Value: Array with values. Example: PHP program to display an array of values. PHP <?php // Array with subjects$array1 = array( '0' => "Python", '1' => "java", '2' => "c/cpp"); // Display array valuesprint_r($array1); ?> Array ( [0] => Python [1] => java [2] => c/cpp ) PHP-array PHP-function PHP-Questions Picked PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Oct, 2021" }, { "code": null, "e": 209, "s": 28, "text": "In this article, we will discuss how to display the array structure and values in PHP. To display the array structure and its values, we can use var_dump() and print_r() functions." }, { "code": null, "e": 222, "s": 209, "text": "It includes " }, { "code": null, "e": 233, "s": 222, "text": "Array size" }, { "code": null, "e": 246, "s": 233, "text": "Array values" }, { "code": null, "e": 269, "s": 246, "text": "Array value with Index" }, { "code": null, "e": 290, "s": 269, "text": "Each value data type" }, { "code": null, "e": 643, "s": 290, "text": "We will display the array structure using var_dump() function. This function is used to dump information about a variable. This function displays structured information such as the type and value of the given variable. Arrays and objects are explored recursively with values indented to show structure. This function is also effective with expressions." }, { "code": null, "e": 651, "s": 643, "text": "Syntax:" }, { "code": null, "e": 675, "s": 651, "text": "var_dump( $array_name )" }, { "code": null, "e": 843, "s": 675, "text": "Parameters: The function takes a single argument $array_name that may be one single variable or an expression containing several space-separated variables of any type." }, { "code": null, "e": 872, "s": 843, "text": "Return Type: Array Structure" }, { "code": null, "e": 939, "s": 872, "text": "Example: PHP Program to create an array and display its structure." }, { "code": null, "e": 943, "s": 939, "text": "PHP" }, { "code": "<?php // Array with subjects$array1 = array( '0' => \"Python\", '1' => \"java\", '2' => \"c/cpp\"); // Display array structurevar_dump($array1); ?>", "e": 1105, "s": 943, "text": null }, { "code": null, "e": 1203, "s": 1105, "text": "array(3) {\n [0]=>\n string(6) \"Python\"\n [1]=>\n string(4) \"java\"\n [2]=>\n string(5) \"c/cpp\"\n}\n" }, { "code": null, "e": 1210, "s": 1203, "text": "Here, " }, { "code": null, "e": 1258, "s": 1210, "text": "array(3) is the size of the array ( 3 elements)" }, { "code": null, "e": 1312, "s": 1258, "text": "string(6) is the data type of element 1 with its size" }, { "code": null, "e": 1366, "s": 1312, "text": "string(4) is the data type of element 2 with its size" }, { "code": null, "e": 1420, "s": 1366, "text": "string(5) is the data type of element 3 with its size" }, { "code": null, "e": 1576, "s": 1420, "text": "Array Values: We will display the array values by using the print_r() function. This function is used to print or display information stored in a variable." }, { "code": null, "e": 1584, "s": 1576, "text": "Syntax:" }, { "code": null, "e": 1615, "s": 1584, "text": "print_r( $variable, $isStore )" }, { "code": null, "e": 1627, "s": 1615, "text": "Parameters:" }, { "code": null, "e": 1720, "s": 1627, "text": "$variable: This parameter specifies the variable to be printed and is a mandatory parameter." }, { "code": null, "e": 2036, "s": 1720, "text": "$isStore: This is an optional parameter. This parameter is of boolean type whose default value is FALSE and is used to store the output of the print_r() function in a variable rather than printing it. If this parameter is set to TRUE then the print_r() function will return the output which it is supposed to print." }, { "code": null, "e": 2069, "s": 2036, "text": "Return Value: Array with values." }, { "code": null, "e": 2121, "s": 2069, "text": "Example: PHP program to display an array of values." }, { "code": null, "e": 2125, "s": 2121, "text": "PHP" }, { "code": "<?php // Array with subjects$array1 = array( '0' => \"Python\", '1' => \"java\", '2' => \"c/cpp\"); // Display array valuesprint_r($array1); ?>", "e": 2283, "s": 2125, "text": null }, { "code": null, "e": 2345, "s": 2283, "text": "Array\n(\n [0] => Python\n [1] => java\n [2] => c/cpp\n)\n" }, { "code": null, "e": 2355, "s": 2345, "text": "PHP-array" }, { "code": null, "e": 2368, "s": 2355, "text": "PHP-function" }, { "code": null, "e": 2382, "s": 2368, "text": "PHP-Questions" }, { "code": null, "e": 2389, "s": 2382, "text": "Picked" }, { "code": null, "e": 2393, "s": 2389, "text": "PHP" }, { "code": null, "e": 2410, "s": 2393, "text": "Web Technologies" }, { "code": null, "e": 2414, "s": 2410, "text": "PHP" } ]
Extend Contingency Table with Proportions and Percentages in R
06 Jun, 2021 The data.table in R programming language can be used to store different cells containing values each belonging to a similar set of groups or mutually exclusive groups. The counts of the variables w.r.t their groups can be computed using base methods as well as external packages in R. The table() method in R is used to compute the frequency counts of the variables appearing in the specified column of the data frame. The result is returned to the form of a two-row tabular structure, where the first row indicates the value of the column and next indicates its corresponding frequencies. table() function is also helpful in creating Frequency tables with condition and cross-tabulations. The frequency table is also referred to as the contingency table in R. The table() method is applied over the data.table object and the unique combinations of values of the specified columns is returned along with their respective frequency counts. Syntax: table (x), Where x is the data.table object In case, x is a data frame, the frequency table can be constructed using the following method. Syntax: table (data_frame$col-name) Example: R library("data.table") set.seed(1) # creating a data framedata_table <- data.table(col1 = sample(letters[1:3], 8, replace = TRUE) , col2 = sample(1:6, 8, replace = TRUE) ) print ("Original DataFrame")print (data_table) # calculating frequencyfreq <- table(data_table$col1)print ("Frequency")print (freq) Output [1] "Original DataFrame" col1 col2 1: a 2 2: c 3 3: a 3 4: b 1 5: a 5 6: c 5 7: c 2 8: b 6 [1] "Frequency" a b c 3 2 3 Relative frequency also known as the probability distribution, is the frequency of the corresponding value divided by the total number of elements. This can be calculated by either prop.table() method applied over the frequency table obtained from the previous approach. It refers to as proportions, since it returns the proportion of each component among the total number of components. Syntax: prop.table(frq-table) frq-table / total observations The proper syntax to compute the proportion table is as follows : prop.table (table(df$col-name)) Example: R library("data.table") set.seed(1) # creating a data framedata_table <- data.table(col1 = sample(letters[1:3], 8, replace = TRUE) , col2 = sample(1:6, 8, replace = TRUE) ) print ("Original DataFrame")print (data_table) # calculating frequencyfreq <- table(data_table$col1) # creating proportions prop <- prop.table(freq)print ("Proportions of column1")print (prop) Output [1] "Original DataFrame" col1 col2 1: a 2 2: c 3 3: a 3 4: b 1 5: a 5 6: c 5 7: c 2 8: b 6 [1] "Proportions of column1" a b c 0.375 0.250 0.375 The percentages can be calculated by multiplying each of the corresponding cell elements of the probability table by 100. The result can be rounded off to any number of digits using the round() method for better readability. Syntax: round (num , digits) The proportions table can be rounded off to compute percentages by multiplying each cell value by 100. The result is the data.table or vector in the same format as the input. Example: R library("data.table")set.seed(1) # creating a data framedata_table <- data.table(col1 = sample(letters[1:3], 8, replace = TRUE) , col2 = sample(1:6, 8, replace = TRUE) ) print ("Original DataFrame")print (data_table) # calculating frequencyfreq <- table(data_table$col1) # creating proportions prop <- prop.table(freq) print ("Percentage of column1")perc <- round((prop * 100),2)print (perc) Output [1] "Original DataFrame" col1 col2 1: a 2 2: c 3 3: a 3 4: b 1 5: a 5 6: c 5 7: c 2 8: b 6 [1] "Percentage of column1" a b c 37.5 25.0 37.5 The table() method can be used to specify multiple column arguments, where the unique combinations are computed along with their respective counts Example: R library("data.table")set.seed(1) # creating a data framedata_table <- data.table(col1 = sample(letters[1:3], 8, replace = TRUE) , col2 = sample(1:2, 8, replace = TRUE) ) print ("Original DataFrame")print (data_table) # calculating frequencyfreq <- table(data_table$col1,data_table$col2) # creating proportions prop <- prop.table(freq)print ("Proportions of column1")print (prop) print ("Percentage of column1")perc <- round((prop * 100),2)print (perc) Output [1] "Original DataFrame" col1 col2 1: a 2 2: c 1 3: a 1 4: b 1 5: a 1 6: c 1 7: c 2 8: b 2 [1] "Proportions of column1" 1 2 a 0.250 0.125 b 0.125 0.125 c 0.250 0.125 [1] "Percentage of column1" 1 2 a 25.0 12.5 b 12.5 12.5 c 25.0 12.5 Picked R DataTable R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jun, 2021" }, { "code": null, "e": 313, "s": 28, "text": "The data.table in R programming language can be used to store different cells containing values each belonging to a similar set of groups or mutually exclusive groups. The counts of the variables w.r.t their groups can be computed using base methods as well as external packages in R." }, { "code": null, "e": 968, "s": 313, "text": "The table() method in R is used to compute the frequency counts of the variables appearing in the specified column of the data frame. The result is returned to the form of a two-row tabular structure, where the first row indicates the value of the column and next indicates its corresponding frequencies. table() function is also helpful in creating Frequency tables with condition and cross-tabulations. The frequency table is also referred to as the contingency table in R. The table() method is applied over the data.table object and the unique combinations of values of the specified columns is returned along with their respective frequency counts. " }, { "code": null, "e": 976, "s": 968, "text": "Syntax:" }, { "code": null, "e": 988, "s": 976, "text": "table (x), " }, { "code": null, "e": 1021, "s": 988, "text": "Where x is the data.table object" }, { "code": null, "e": 1116, "s": 1021, "text": "In case, x is a data frame, the frequency table can be constructed using the following method." }, { "code": null, "e": 1124, "s": 1116, "text": "Syntax:" }, { "code": null, "e": 1152, "s": 1124, "text": "table (data_frame$col-name)" }, { "code": null, "e": 1161, "s": 1152, "text": "Example:" }, { "code": null, "e": 1163, "s": 1161, "text": "R" }, { "code": "library(\"data.table\") set.seed(1) # creating a data framedata_table <- data.table(col1 = sample(letters[1:3], 8, replace = TRUE) , col2 = sample(1:6, 8, replace = TRUE) ) print (\"Original DataFrame\")print (data_table) # calculating frequencyfreq <- table(data_table$col1)print (\"Frequency\")print (freq)", "e": 1520, "s": 1163, "text": null }, { "code": null, "e": 1527, "s": 1520, "text": "Output" }, { "code": null, "e": 1707, "s": 1527, "text": "[1] \"Original DataFrame\" \ncol1 col2 \n1: a 2 \n2: c 3 \n3: a 3 \n4: b 1 \n5: a 5 \n6: c 5 \n7: c 2 \n8: b 6 \n[1] \"Frequency\"\na b c \n3 2 3 " }, { "code": null, "e": 2096, "s": 1707, "text": "Relative frequency also known as the probability distribution, is the frequency of the corresponding value divided by the total number of elements. This can be calculated by either prop.table() method applied over the frequency table obtained from the previous approach. It refers to as proportions, since it returns the proportion of each component among the total number of components. " }, { "code": null, "e": 2104, "s": 2096, "text": "Syntax:" }, { "code": null, "e": 2126, "s": 2104, "text": "prop.table(frq-table)" }, { "code": null, "e": 2157, "s": 2126, "text": "frq-table / total observations" }, { "code": null, "e": 2224, "s": 2157, "text": "The proper syntax to compute the proportion table is as follows : " }, { "code": null, "e": 2256, "s": 2224, "text": "prop.table (table(df$col-name))" }, { "code": null, "e": 2265, "s": 2256, "text": "Example:" }, { "code": null, "e": 2267, "s": 2265, "text": "R" }, { "code": "library(\"data.table\") set.seed(1) # creating a data framedata_table <- data.table(col1 = sample(letters[1:3], 8, replace = TRUE) , col2 = sample(1:6, 8, replace = TRUE) ) print (\"Original DataFrame\")print (data_table) # calculating frequencyfreq <- table(data_table$col1) # creating proportions prop <- prop.table(freq)print (\"Proportions of column1\")print (prop)", "e": 2686, "s": 2267, "text": null }, { "code": null, "e": 2693, "s": 2686, "text": "Output" }, { "code": null, "e": 2897, "s": 2693, "text": "[1] \"Original DataFrame\" \ncol1 col2\n1: a 2\n2: c 3\n3: a 3\n4: b 1\n5: a 5\n6: c 5\n7: c 2\n8: b 6\n[1] \"Proportions of column1\"\na b c \n0.375 0.250 0.375" }, { "code": null, "e": 3123, "s": 2897, "text": "The percentages can be calculated by multiplying each of the corresponding cell elements of the probability table by 100. The result can be rounded off to any number of digits using the round() method for better readability. " }, { "code": null, "e": 3131, "s": 3123, "text": "Syntax:" }, { "code": null, "e": 3152, "s": 3131, "text": "round (num , digits)" }, { "code": null, "e": 3328, "s": 3152, "text": "The proportions table can be rounded off to compute percentages by multiplying each cell value by 100. The result is the data.table or vector in the same format as the input. " }, { "code": null, "e": 3337, "s": 3328, "text": "Example:" }, { "code": null, "e": 3339, "s": 3337, "text": "R" }, { "code": "library(\"data.table\")set.seed(1) # creating a data framedata_table <- data.table(col1 = sample(letters[1:3], 8, replace = TRUE) , col2 = sample(1:6, 8, replace = TRUE) ) print (\"Original DataFrame\")print (data_table) # calculating frequencyfreq <- table(data_table$col1) # creating proportions prop <- prop.table(freq) print (\"Percentage of column1\")perc <- round((prop * 100),2)print (perc)", "e": 3786, "s": 3339, "text": null }, { "code": null, "e": 3793, "s": 3786, "text": "Output" }, { "code": null, "e": 4003, "s": 3793, "text": "[1] \"Original DataFrame\" \ncol1 col2 \n1: a 2 \n2: c 3 \n3: a 3 \n4: b 1 \n5: a 5 \n6: c 5 \n7: c 2 \n8: b 6 \n[1] \"Percentage of column1\" \na b c \n37.5 25.0 37.5 " }, { "code": null, "e": 4150, "s": 4003, "text": "The table() method can be used to specify multiple column arguments, where the unique combinations are computed along with their respective counts" }, { "code": null, "e": 4159, "s": 4150, "text": "Example:" }, { "code": null, "e": 4161, "s": 4159, "text": "R" }, { "code": "library(\"data.table\")set.seed(1) # creating a data framedata_table <- data.table(col1 = sample(letters[1:3], 8, replace = TRUE) , col2 = sample(1:2, 8, replace = TRUE) ) print (\"Original DataFrame\")print (data_table) # calculating frequencyfreq <- table(data_table$col1,data_table$col2) # creating proportions prop <- prop.table(freq)print (\"Proportions of column1\")print (prop) print (\"Percentage of column1\")perc <- round((prop * 100),2)print (perc)", "e": 4669, "s": 4161, "text": null }, { "code": null, "e": 4676, "s": 4669, "text": "Output" }, { "code": null, "e": 5009, "s": 4676, "text": "[1] \"Original DataFrame\" \n col1 col2 \n1: a 2 \n2: c 1 \n3: a 1 \n4: b 1 \n5: a 1 \n6: c 1 \n7: c 2 \n8: b 2 \n[1] \"Proportions of column1\" \n 1 2 \na 0.250 0.125 \nb 0.125 0.125 \nc 0.250 0.125\n[1] \"Percentage of column1\" \n 1 2 \na 25.0 12.5 \nb 12.5 12.5 \nc 25.0 12.5" }, { "code": null, "e": 5016, "s": 5009, "text": "Picked" }, { "code": null, "e": 5028, "s": 5016, "text": "R DataTable" }, { "code": null, "e": 5039, "s": 5028, "text": "R Language" } ]
HTML Hex Color Codes
21 Feb, 2022 Example: In this example, we simply print the different hex color codes by using the background-color style in HTML heading tag. HTML <!DOCTYPE html><html> <head> <title>HTML Hex Color Codes</title></head> <body> <h1>Welcome To GeeksforGeeks</h1> <h2 style="background-color:#808000;">#808000</h2> <h2 style="background-color:#CD5C5C;">#CD5C5C</h2> <h2 style="background-color:#FFA07A;">#FFA07A</h2> <h2 style="background-color:#DC143C;">#DC143C</h2></body> </html> Output: HTML Color Codes are the medium of representing the colors format that a computer could read and display. The most used Color codes are Hex codes. Hex codes are three-byte hexadecimal numbers (consist of six variables), with a pair of characters in the Hex code, representing the intensity of red, green, and blue in the color respectively. Format of Hex Color Codes: Each Hex color code contains the symbol “#” followed by 6 alphabets or numbers. Numbers are in the hexadecimal numeric system. There are 1,67,77,216 different color possibilities. 00 value range of the code represents the lowest intensity of color on the other hand FF value range of code represents the highest intensity. Meaning of a Hex code: The 1st and 2nd variable in Hex color code represents the intensity of red color. The 3rd and 4th variable represents the intensity of green. The 5th and 6th variable represents the intensity of blue. By combining the intensities of red, green, and blue almost any color can be made. The white color is a mixture of the three primary colors at full intensity representing the Hex color code #FFFFFF. The black color is a mixture of the three primary colors at the lowest intensity representing the color code #000000. Example: HTML <!DOCTYPE html><html> <head> <title>HTML Hex Color Codes Examples</title></head> <body> <h1>Welcome To GeeksforGeeks</h1> <h2 style="background-color:#FF0000;">#FF0000</h2> <h2 style="background-color:#00FF00;">#00FF00</h2> <h2 style="background-color:#0000FF;">#0000FF</h2> <h2 style="background-color:#FFFF00;">#FFFF00</h2> <h2 style="background-color:#CCEEFF;">#CCEEFF</h2></body> </html> Output: #FF0000 – This HTML color code shows just red and no green and no blue. #00FF00 – This HTML color code shows just green and no red and blue. #0000FF – This HTML color code shows just blue and no red and green. #FFFF00 – This HTML color code is a mixture of red and green colors defined as yellow. #CCEEFF – This HTML color code is a mixture of more green and maximum blue provides color like the sky. List of some common HTML color codes: COLOR NAME HEX COLOR CODE RGB COLOR CODE SILVER #C0C0C0 RGB(192, 192, 192) GRAY #808080 RGB(128, 128, 128) MAROON #800000 RGB(128, 0, 0) OLIVE #808000 RGB(128, 128, 0) LIME #00FF00 RGB(0, 255, 0) AQUA #00FFFF RGB(0, 255, 255) TEAL #008080 RGB(0, 128, 128) NAVY #000080 RGB(0, 0, 128) FUCHSIA #FF00FF RGB(255, 0, 255) PURPLE #800080 RGB(128, 0, 128) INDIANRED #CD5C5C RGB(205, 92, 92) LIGHTCORAL #F08080 RGB(240, 128, 128) SALMON #FA8072 RGB(250, 128, 114) DARKSALMON #E9967A RGB(233, 150, 122) LIGHTSALMON #FFA07A RGB(255, 160, 122) Hex Color Codes with the saturation of basic single colors and lightness of that colors that can be used: Shades of RED Colors: Example: Color Name HTML Color Code RGB Color Code lightsalmon #FFA07A rgb(255,160,122) salmon #FA8072 rgb(250,128,114) darksalmon #E9967A rgb(233,150,122) lightcoral #F08080 rgb(240,128,128) indianred #CD5C5C rgb(205,92,92) crimson #DC143C rgb(220,20,60) firebrick #B22222 rgb(178,34,34) red #FF0000 rgb(255,0,0) darkred #8B0000 rgb(139,0,0) HTML <!DOCTYPE html><html> <head> <title>Shades of Red Colors</title></head> <body> <h1>Welcome To GeeksforGeeks</h1> <h2 style="background-color:#FFA07A;">#FFA07A</h2> <h2 style="background-color:#FA8072;">#FA8072</h2> <h2 style="background-color:#FF0000;">#FF0000</h2> <h2 style="background-color:#8B0000;">#8B0000</h2></body> </html> Output: Similarly, We can have shades of other colors as well. Shades of ORANGE Colors: Color Name HTML Color Code RGB Color Code coral #FF7F50 rgb(255,127,80) tomato #FF6347 rgb(255,99,71) orangered #FF4500 rgb(255,69,0) gold #FFD700 rgb(255,215,0) orange #FFA500 rgb(255,165,0) darkorange #FF8C00 rgb(255,140,0) Shades of YELLOW Colors: Color Name HTML Color Code RGB Color Code lightyellow #FFFFE0 rgb(255,255,224) lemonchiffon #FFFACD rgb(255,250,205) papayawhip #FFEFD5 rgb(255,239,213) moccasin #FFE4B5 rgb(255,228,181) peachpuff #FFDAB9 rgb(255,218,185) palegoldenrod #EEE8AA rgb(238,232,170) khaki #F0E68C rgb(240,230,140) darkkhaki #BDB76B rgb(189,183,107) yellow #FFFF00 rgb(255,255,0) Shades of GREEN Colors: Color Name HTML Color Code RGB Color Code lawngreen #7CFC00 rgb(124,252,0) limegreen #32CD32 rgb(50,205,50) lime #00FF00 rgb(0,255,0) forestgreen #228B22 rgb(34,139,34) darkgreen #006400 rgb(0,100,0) springgreen #00FF7F rgb(0,255,127) mediumspringgreen #00FA9A rgb(0,250,154) palegreen #98FB98 rgb(152,251,152) seagreen #2E8B57 rgb(46,139,87) Shades of BLUE Colors: Color Name HTML Color Code RGB Color Code powderblue #B0E0E6 rgb(176,224,230) lightskyblue #87CEFA rgb(135,206,250) skyblue #87CEEB rgb(135,206,235) deepskyblue #00BFFF rgb(0,191,255) dodgerblue #1E90FF rgb(30,144,255) cornflowerblue #6495ED rgb(100,149,237) steelblue #4682B4 rgb(70,130,180) royalblue #4169E1 rgb(65,105,225) mediumblue #0000CD rgb(0,0,205) Shades of WHITE Colors: Shades of BROWN Colors: HTML is the foundation of webpages, 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. khushboogoyal499 shubhamyadav4 HTML-Basics HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n21 Feb, 2022" }, { "code": null, "e": 182, "s": 53, "text": "Example: In this example, we simply print the different hex color codes by using the background-color style in HTML heading tag." }, { "code": null, "e": 187, "s": 182, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML Hex Color Codes</title></head> <body> <h1>Welcome To GeeksforGeeks</h1> <h2 style=\"background-color:#808000;\">#808000</h2> <h2 style=\"background-color:#CD5C5C;\">#CD5C5C</h2> <h2 style=\"background-color:#FFA07A;\">#FFA07A</h2> <h2 style=\"background-color:#DC143C;\">#DC143C</h2></body> </html>", "e": 525, "s": 187, "text": null }, { "code": null, "e": 533, "s": 525, "text": "Output:" }, { "code": null, "e": 874, "s": 533, "text": "HTML Color Codes are the medium of representing the colors format that a computer could read and display. The most used Color codes are Hex codes. Hex codes are three-byte hexadecimal numbers (consist of six variables), with a pair of characters in the Hex code, representing the intensity of red, green, and blue in the color respectively." }, { "code": null, "e": 1224, "s": 874, "text": "Format of Hex Color Codes: Each Hex color code contains the symbol “#” followed by 6 alphabets or numbers. Numbers are in the hexadecimal numeric system. There are 1,67,77,216 different color possibilities. 00 value range of the code represents the lowest intensity of color on the other hand FF value range of code represents the highest intensity." }, { "code": null, "e": 1247, "s": 1224, "text": "Meaning of a Hex code:" }, { "code": null, "e": 1329, "s": 1247, "text": "The 1st and 2nd variable in Hex color code represents the intensity of red color." }, { "code": null, "e": 1389, "s": 1329, "text": "The 3rd and 4th variable represents the intensity of green." }, { "code": null, "e": 1448, "s": 1389, "text": "The 5th and 6th variable represents the intensity of blue." }, { "code": null, "e": 1531, "s": 1448, "text": "By combining the intensities of red, green, and blue almost any color can be made." }, { "code": null, "e": 1647, "s": 1531, "text": "The white color is a mixture of the three primary colors at full intensity representing the Hex color code #FFFFFF." }, { "code": null, "e": 1765, "s": 1647, "text": "The black color is a mixture of the three primary colors at the lowest intensity representing the color code #000000." }, { "code": null, "e": 1774, "s": 1765, "text": "Example:" }, { "code": null, "e": 1779, "s": 1774, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML Hex Color Codes Examples</title></head> <body> <h1>Welcome To GeeksforGeeks</h1> <h2 style=\"background-color:#FF0000;\">#FF0000</h2> <h2 style=\"background-color:#00FF00;\">#00FF00</h2> <h2 style=\"background-color:#0000FF;\">#0000FF</h2> <h2 style=\"background-color:#FFFF00;\">#FFFF00</h2> <h2 style=\"background-color:#CCEEFF;\">#CCEEFF</h2></body> </html>", "e": 2178, "s": 1779, "text": null }, { "code": null, "e": 2186, "s": 2178, "text": "Output:" }, { "code": null, "e": 2587, "s": 2186, "text": "#FF0000 – This HTML color code shows just red and no green and no blue. #00FF00 – This HTML color code shows just green and no red and blue. #0000FF – This HTML color code shows just blue and no red and green. #FFFF00 – This HTML color code is a mixture of red and green colors defined as yellow. #CCEEFF – This HTML color code is a mixture of more green and maximum blue provides color like the sky." }, { "code": null, "e": 2627, "s": 2587, "text": " List of some common HTML color codes: " }, { "code": null, "e": 2639, "s": 2627, "text": "COLOR NAME " }, { "code": null, "e": 2655, "s": 2639, "text": "HEX COLOR CODE " }, { "code": null, "e": 2670, "s": 2655, "text": "RGB COLOR CODE" }, { "code": null, "e": 2678, "s": 2670, "text": "SILVER " }, { "code": null, "e": 2687, "s": 2678, "text": "#C0C0C0 " }, { "code": null, "e": 2706, "s": 2687, "text": "RGB(192, 192, 192)" }, { "code": null, "e": 2712, "s": 2706, "text": "GRAY " }, { "code": null, "e": 2721, "s": 2712, "text": "#808080 " }, { "code": null, "e": 2740, "s": 2721, "text": "RGB(128, 128, 128)" }, { "code": null, "e": 2748, "s": 2740, "text": "MAROON " }, { "code": null, "e": 2757, "s": 2748, "text": "#800000 " }, { "code": null, "e": 2772, "s": 2757, "text": "RGB(128, 0, 0)" }, { "code": null, "e": 2778, "s": 2772, "text": "OLIVE" }, { "code": null, "e": 2787, "s": 2778, "text": "#808000 " }, { "code": null, "e": 2804, "s": 2787, "text": "RGB(128, 128, 0)" }, { "code": null, "e": 2809, "s": 2804, "text": "LIME" }, { "code": null, "e": 2818, "s": 2809, "text": "#00FF00 " }, { "code": null, "e": 2833, "s": 2818, "text": "RGB(0, 255, 0)" }, { "code": null, "e": 2839, "s": 2833, "text": "AQUA " }, { "code": null, "e": 2848, "s": 2839, "text": "#00FFFF " }, { "code": null, "e": 2865, "s": 2848, "text": "RGB(0, 255, 255)" }, { "code": null, "e": 2871, "s": 2865, "text": "TEAL " }, { "code": null, "e": 2880, "s": 2871, "text": "#008080 " }, { "code": null, "e": 2897, "s": 2880, "text": "RGB(0, 128, 128)" }, { "code": null, "e": 2903, "s": 2897, "text": "NAVY " }, { "code": null, "e": 2912, "s": 2903, "text": "#000080 " }, { "code": null, "e": 2927, "s": 2912, "text": "RGB(0, 0, 128)" }, { "code": null, "e": 2936, "s": 2927, "text": "FUCHSIA " }, { "code": null, "e": 2945, "s": 2936, "text": "#FF00FF " }, { "code": null, "e": 2962, "s": 2945, "text": "RGB(255, 0, 255)" }, { "code": null, "e": 2970, "s": 2962, "text": "PURPLE " }, { "code": null, "e": 2979, "s": 2970, "text": "#800080 " }, { "code": null, "e": 2996, "s": 2979, "text": "RGB(128, 0, 128)" }, { "code": null, "e": 3007, "s": 2996, "text": "INDIANRED " }, { "code": null, "e": 3016, "s": 3007, "text": "#CD5C5C " }, { "code": null, "e": 3033, "s": 3016, "text": "RGB(205, 92, 92)" }, { "code": null, "e": 3045, "s": 3033, "text": "LIGHTCORAL " }, { "code": null, "e": 3054, "s": 3045, "text": "#F08080 " }, { "code": null, "e": 3073, "s": 3054, "text": "RGB(240, 128, 128)" }, { "code": null, "e": 3081, "s": 3073, "text": "SALMON " }, { "code": null, "e": 3090, "s": 3081, "text": "#FA8072 " }, { "code": null, "e": 3109, "s": 3090, "text": "RGB(250, 128, 114)" }, { "code": null, "e": 3121, "s": 3109, "text": "DARKSALMON " }, { "code": null, "e": 3130, "s": 3121, "text": "#E9967A " }, { "code": null, "e": 3149, "s": 3130, "text": "RGB(233, 150, 122)" }, { "code": null, "e": 3162, "s": 3149, "text": "LIGHTSALMON " }, { "code": null, "e": 3171, "s": 3162, "text": "#FFA07A " }, { "code": null, "e": 3190, "s": 3171, "text": "RGB(255, 160, 122)" }, { "code": null, "e": 3298, "s": 3192, "text": "Hex Color Codes with the saturation of basic single colors and lightness of that colors that can be used:" }, { "code": null, "e": 3320, "s": 3298, "text": "Shades of RED Colors:" }, { "code": null, "e": 3329, "s": 3320, "text": "Example:" }, { "code": null, "e": 3342, "s": 3331, "text": "Color Name" }, { "code": null, "e": 3358, "s": 3342, "text": "HTML Color Code" }, { "code": null, "e": 3373, "s": 3358, "text": "RGB Color Code" }, { "code": null, "e": 3385, "s": 3373, "text": "lightsalmon" }, { "code": null, "e": 3394, "s": 3385, "text": "#FFA07A " }, { "code": null, "e": 3411, "s": 3394, "text": "rgb(255,160,122)" }, { "code": null, "e": 3418, "s": 3411, "text": "salmon" }, { "code": null, "e": 3427, "s": 3418, "text": " #FA8072" }, { "code": null, "e": 3444, "s": 3427, "text": "rgb(250,128,114)" }, { "code": null, "e": 3455, "s": 3444, "text": "darksalmon" }, { "code": null, "e": 3464, "s": 3455, "text": " #E9967A" }, { "code": null, "e": 3481, "s": 3464, "text": "rgb(233,150,122)" }, { "code": null, "e": 3492, "s": 3481, "text": "lightcoral" }, { "code": null, "e": 3501, "s": 3492, "text": " #F08080" }, { "code": null, "e": 3518, "s": 3501, "text": "rgb(240,128,128)" }, { "code": null, "e": 3528, "s": 3518, "text": "indianred" }, { "code": null, "e": 3537, "s": 3528, "text": " #CD5C5C" }, { "code": null, "e": 3552, "s": 3537, "text": "rgb(205,92,92)" }, { "code": null, "e": 3560, "s": 3552, "text": "crimson" }, { "code": null, "e": 3568, "s": 3560, "text": "#DC143C" }, { "code": null, "e": 3583, "s": 3568, "text": "rgb(220,20,60)" }, { "code": null, "e": 3593, "s": 3583, "text": "firebrick" }, { "code": null, "e": 3601, "s": 3593, "text": "#B22222" }, { "code": null, "e": 3616, "s": 3601, "text": "rgb(178,34,34)" }, { "code": null, "e": 3620, "s": 3616, "text": "red" }, { "code": null, "e": 3629, "s": 3620, "text": " #FF0000" }, { "code": null, "e": 3642, "s": 3629, "text": "rgb(255,0,0)" }, { "code": null, "e": 3650, "s": 3642, "text": "darkred" }, { "code": null, "e": 3658, "s": 3650, "text": "#8B0000" }, { "code": null, "e": 3671, "s": 3658, "text": "rgb(139,0,0)" }, { "code": null, "e": 3676, "s": 3671, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Shades of Red Colors</title></head> <body> <h1>Welcome To GeeksforGeeks</h1> <h2 style=\"background-color:#FFA07A;\">#FFA07A</h2> <h2 style=\"background-color:#FA8072;\">#FA8072</h2> <h2 style=\"background-color:#FF0000;\">#FF0000</h2> <h2 style=\"background-color:#8B0000;\">#8B0000</h2></body> </html>", "e": 4014, "s": 3676, "text": null }, { "code": null, "e": 4022, "s": 4014, "text": "Output:" }, { "code": null, "e": 4077, "s": 4022, "text": "Similarly, We can have shades of other colors as well." }, { "code": null, "e": 4102, "s": 4077, "text": "Shades of ORANGE Colors:" }, { "code": null, "e": 4113, "s": 4102, "text": "Color Name" }, { "code": null, "e": 4129, "s": 4113, "text": "HTML Color Code" }, { "code": null, "e": 4144, "s": 4129, "text": "RGB Color Code" }, { "code": null, "e": 4151, "s": 4144, "text": " coral" }, { "code": null, "e": 4160, "s": 4151, "text": " #FF7F50" }, { "code": null, "e": 4176, "s": 4160, "text": "rgb(255,127,80)" }, { "code": null, "e": 4183, "s": 4176, "text": "tomato" }, { "code": null, "e": 4192, "s": 4183, "text": " #FF6347" }, { "code": null, "e": 4207, "s": 4192, "text": "rgb(255,99,71)" }, { "code": null, "e": 4217, "s": 4207, "text": "orangered" }, { "code": null, "e": 4226, "s": 4217, "text": " #FF4500" }, { "code": null, "e": 4241, "s": 4226, "text": " rgb(255,69,0)" }, { "code": null, "e": 4246, "s": 4241, "text": "gold" }, { "code": null, "e": 4254, "s": 4246, "text": "#FFD700" }, { "code": null, "e": 4270, "s": 4254, "text": " rgb(255,215,0)" }, { "code": null, "e": 4277, "s": 4270, "text": "orange" }, { "code": null, "e": 4285, "s": 4277, "text": "#FFA500" }, { "code": null, "e": 4301, "s": 4285, "text": " rgb(255,165,0)" }, { "code": null, "e": 4312, "s": 4301, "text": "darkorange" }, { "code": null, "e": 4321, "s": 4312, "text": " #FF8C00" }, { "code": null, "e": 4336, "s": 4321, "text": "rgb(255,140,0)" }, { "code": null, "e": 4361, "s": 4336, "text": "Shades of YELLOW Colors:" }, { "code": null, "e": 4372, "s": 4361, "text": "Color Name" }, { "code": null, "e": 4388, "s": 4372, "text": "HTML Color Code" }, { "code": null, "e": 4403, "s": 4388, "text": "RGB Color Code" }, { "code": null, "e": 4415, "s": 4403, "text": "lightyellow" }, { "code": null, "e": 4423, "s": 4415, "text": "#FFFFE0" }, { "code": null, "e": 4440, "s": 4423, "text": "rgb(255,255,224)" }, { "code": null, "e": 4453, "s": 4440, "text": "lemonchiffon" }, { "code": null, "e": 4461, "s": 4453, "text": "#FFFACD" }, { "code": null, "e": 4478, "s": 4461, "text": "rgb(255,250,205)" }, { "code": null, "e": 4489, "s": 4478, "text": "papayawhip" }, { "code": null, "e": 4498, "s": 4489, "text": " #FFEFD5" }, { "code": null, "e": 4516, "s": 4498, "text": " rgb(255,239,213)" }, { "code": null, "e": 4526, "s": 4516, "text": " moccasin" }, { "code": null, "e": 4535, "s": 4526, "text": " #FFE4B5" }, { "code": null, "e": 4552, "s": 4535, "text": "rgb(255,228,181)" }, { "code": null, "e": 4563, "s": 4552, "text": " peachpuff" }, { "code": null, "e": 4571, "s": 4563, "text": "#FFDAB9" }, { "code": null, "e": 4588, "s": 4571, "text": "rgb(255,218,185)" }, { "code": null, "e": 4602, "s": 4588, "text": "palegoldenrod" }, { "code": null, "e": 4611, "s": 4602, "text": " #EEE8AA" }, { "code": null, "e": 4628, "s": 4611, "text": "rgb(238,232,170)" }, { "code": null, "e": 4634, "s": 4628, "text": "khaki" }, { "code": null, "e": 4643, "s": 4634, "text": " #F0E68C" }, { "code": null, "e": 4660, "s": 4643, "text": "rgb(240,230,140)" }, { "code": null, "e": 4671, "s": 4660, "text": " darkkhaki" }, { "code": null, "e": 4680, "s": 4671, "text": " #BDB76B" }, { "code": null, "e": 4697, "s": 4680, "text": "rgb(189,183,107)" }, { "code": null, "e": 4704, "s": 4697, "text": "yellow" }, { "code": null, "e": 4713, "s": 4704, "text": " #FFFF00" }, { "code": null, "e": 4728, "s": 4713, "text": "rgb(255,255,0)" }, { "code": null, "e": 4752, "s": 4728, "text": "Shades of GREEN Colors:" }, { "code": null, "e": 4763, "s": 4752, "text": "Color Name" }, { "code": null, "e": 4779, "s": 4763, "text": "HTML Color Code" }, { "code": null, "e": 4794, "s": 4779, "text": "RGB Color Code" }, { "code": null, "e": 4804, "s": 4794, "text": "lawngreen" }, { "code": null, "e": 4812, "s": 4804, "text": "#7CFC00" }, { "code": null, "e": 4827, "s": 4812, "text": "rgb(124,252,0)" }, { "code": null, "e": 4837, "s": 4827, "text": "limegreen" }, { "code": null, "e": 4846, "s": 4837, "text": " #32CD32" }, { "code": null, "e": 4861, "s": 4846, "text": "rgb(50,205,50)" }, { "code": null, "e": 4867, "s": 4861, "text": " lime" }, { "code": null, "e": 4876, "s": 4867, "text": " #00FF00" }, { "code": null, "e": 4889, "s": 4876, "text": "rgb(0,255,0)" }, { "code": null, "e": 4902, "s": 4889, "text": " forestgreen" }, { "code": null, "e": 4911, "s": 4902, "text": " #228B22" }, { "code": null, "e": 4927, "s": 4911, "text": " rgb(34,139,34)" }, { "code": null, "e": 4938, "s": 4927, "text": " darkgreen" }, { "code": null, "e": 4946, "s": 4938, "text": "#006400" }, { "code": null, "e": 4959, "s": 4946, "text": "rgb(0,100,0)" }, { "code": null, "e": 4972, "s": 4959, "text": " springgreen" }, { "code": null, "e": 4981, "s": 4972, "text": " #00FF7F" }, { "code": null, "e": 4997, "s": 4981, "text": " rgb(0,255,127)" }, { "code": null, "e": 5016, "s": 4997, "text": " mediumspringgreen" }, { "code": null, "e": 5024, "s": 5016, "text": "#00FA9A" }, { "code": null, "e": 5040, "s": 5024, "text": " rgb(0,250,154)" }, { "code": null, "e": 5050, "s": 5040, "text": "palegreen" }, { "code": null, "e": 5058, "s": 5050, "text": "#98FB98" }, { "code": null, "e": 5075, "s": 5058, "text": "rgb(152,251,152)" }, { "code": null, "e": 5085, "s": 5075, "text": " seagreen" }, { "code": null, "e": 5093, "s": 5085, "text": "#2E8B57" }, { "code": null, "e": 5109, "s": 5093, "text": " rgb(46,139,87)" }, { "code": null, "e": 5132, "s": 5109, "text": "Shades of BLUE Colors:" }, { "code": null, "e": 5143, "s": 5132, "text": "Color Name" }, { "code": null, "e": 5159, "s": 5143, "text": "HTML Color Code" }, { "code": null, "e": 5174, "s": 5159, "text": "RGB Color Code" }, { "code": null, "e": 5185, "s": 5174, "text": "powderblue" }, { "code": null, "e": 5194, "s": 5185, "text": "#B0E0E6 " }, { "code": null, "e": 5211, "s": 5194, "text": "rgb(176,224,230)" }, { "code": null, "e": 5224, "s": 5211, "text": "lightskyblue" }, { "code": null, "e": 5233, "s": 5224, "text": " #87CEFA" }, { "code": null, "e": 5250, "s": 5233, "text": "rgb(135,206,250)" }, { "code": null, "e": 5259, "s": 5250, "text": " skyblue" }, { "code": null, "e": 5268, "s": 5259, "text": " #87CEEB" }, { "code": null, "e": 5285, "s": 5268, "text": "rgb(135,206,235)" }, { "code": null, "e": 5298, "s": 5285, "text": " deepskyblue" }, { "code": null, "e": 5306, "s": 5298, "text": "#00BFFF" }, { "code": null, "e": 5321, "s": 5306, "text": "rgb(0,191,255)" }, { "code": null, "e": 5332, "s": 5321, "text": "dodgerblue" }, { "code": null, "e": 5341, "s": 5332, "text": " #1E90FF" }, { "code": null, "e": 5358, "s": 5341, "text": " rgb(30,144,255)" }, { "code": null, "e": 5373, "s": 5358, "text": "cornflowerblue" }, { "code": null, "e": 5382, "s": 5373, "text": " #6495ED" }, { "code": null, "e": 5400, "s": 5382, "text": " rgb(100,149,237)" }, { "code": null, "e": 5410, "s": 5400, "text": "steelblue" }, { "code": null, "e": 5419, "s": 5410, "text": " #4682B4" }, { "code": null, "e": 5435, "s": 5419, "text": "rgb(70,130,180)" }, { "code": null, "e": 5446, "s": 5435, "text": " royalblue" }, { "code": null, "e": 5455, "s": 5446, "text": " #4169E1" }, { "code": null, "e": 5471, "s": 5455, "text": "rgb(65,105,225)" }, { "code": null, "e": 5483, "s": 5471, "text": " mediumblue" }, { "code": null, "e": 5491, "s": 5483, "text": "#0000CD" }, { "code": null, "e": 5504, "s": 5491, "text": "rgb(0,0,205)" }, { "code": null, "e": 5530, "s": 5506, "text": "Shades of WHITE Colors:" }, { "code": null, "e": 5554, "s": 5530, "text": "Shades of BROWN Colors:" }, { "code": null, "e": 5749, "s": 5554, "text": "HTML is the foundation of webpages, 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": 5766, "s": 5749, "text": "khushboogoyal499" }, { "code": null, "e": 5780, "s": 5766, "text": "shubhamyadav4" }, { "code": null, "e": 5792, "s": 5780, "text": "HTML-Basics" }, { "code": null, "e": 5797, "s": 5792, "text": "HTML" }, { "code": null, "e": 5814, "s": 5797, "text": "Web Technologies" }, { "code": null, "e": 5819, "s": 5814, "text": "HTML" } ]
HTML | <img> src Attribute
27 May, 2019 The <img> src attribute is used to specify the URL of the source image. Syntax: <img src="URL"> Attribute Values: It contains single value URL which specifies the link of source image. There are two types of URL link which are listed below: Absolute URL: It points to another webpage. Relative URL: It points to other files of same web page. Example: <!DOCTYPE html><html> <head> <title> HTML img src Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML img src Attribute</h2> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190506164011/logo3.png" alt="GeeksforGeeks logo"></body> </html> Output: Supported Browsers: The browser supported by HTML <img> src attribute are listed below: Google Chrome Internet Explorer Firefox Safari Opera HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 May, 2019" }, { "code": null, "e": 100, "s": 28, "text": "The <img> src attribute is used to specify the URL of the source image." }, { "code": null, "e": 108, "s": 100, "text": "Syntax:" }, { "code": null, "e": 124, "s": 108, "text": "<img src=\"URL\">" }, { "code": null, "e": 269, "s": 124, "text": "Attribute Values: It contains single value URL which specifies the link of source image. There are two types of URL link which are listed below:" }, { "code": null, "e": 313, "s": 269, "text": "Absolute URL: It points to another webpage." }, { "code": null, "e": 370, "s": 313, "text": "Relative URL: It points to other files of same web page." }, { "code": null, "e": 379, "s": 370, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML img src Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML img src Attribute</h2> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190506164011/logo3.png\" alt=\"GeeksforGeeks logo\"></body> </html>", "e": 683, "s": 379, "text": null }, { "code": null, "e": 691, "s": 683, "text": "Output:" }, { "code": null, "e": 779, "s": 691, "text": "Supported Browsers: The browser supported by HTML <img> src attribute are listed below:" }, { "code": null, "e": 793, "s": 779, "text": "Google Chrome" }, { "code": null, "e": 811, "s": 793, "text": "Internet Explorer" }, { "code": null, "e": 819, "s": 811, "text": "Firefox" }, { "code": null, "e": 826, "s": 819, "text": "Safari" }, { "code": null, "e": 832, "s": 826, "text": "Opera" }, { "code": null, "e": 848, "s": 832, "text": "HTML-Attributes" }, { "code": null, "e": 853, "s": 848, "text": "HTML" }, { "code": null, "e": 870, "s": 853, "text": "Web Technologies" }, { "code": null, "e": 875, "s": 870, "text": "HTML" } ]
How to Remove tags using BeautifulSoup in Python?
08 Sep, 2021 Prerequisite- Beautifulsoup module In this article, we are going to draft a python script that removes a tag from the tree and then completely destroys it and its contents. For this, decompose() method is used which comes built into the module. Syntax: Beautifulsoup.Tag.decompose() Tag.decompose() removes a tag from the tree of a given HTML document, then completely destroys it and its contents. Implementation: Example 1: Python3 # import modulefrom bs4 import BeautifulSoup # URL for scrapping data markup = '<a href="https://www.geeksforgeeks.org/">Welcome to <i>geeksforgeeks.com</i></a>' # get URL html soup = BeautifulSoup(markup, 'html.parser') # display before decomposeprint("Before Decompose")print(soup.a) # decomposing the# soup datanew_tag = soup.a.decompose()print("After decomposing:")print(new_tag) Output: Before Decompose <a href=”https://www.geeksforgeeks.org/”>Welcome to <i>geeksforgeeks.com</i></a> After decomposing: None Example 2: Implementation of given URL to scrape the HTML document. Python3 # import modulefrom bs4 import BeautifulSoupimport requests # Get URL html# Scraping the data from# Html docurl = 'https://www.geeksforgeeks.org/'reqs = requests.get(url)soup = BeautifulSoup(reqs.text, 'html.parser') # Before decomposingprint("Before Decomposing")print(soup) # decompose the soupresult = soup.decompose()print("After decomposing:")print(result) Output: Before Decomposing <!DOCTYPE html> <!–[if IE 7]> <html class=”ie ie7′′ lang=”en-US” prefix=”og: http://ogp.me/ns#”> <![endif]–> <!–[if IE 8]> <html class=”ie ie8′′ lang=”en-US” prefix=”og: http://ogp.me/ns#”> <![endif]–> <!–[if !(IE 7) | !(IE 8) ]><!–> <html lang=”en-US” prefix=”og: http://ogp.me/ns#”> <!–<![endif]–> <head> <meta charset=”utf-8′′/>.. ...... After decomposing: None gulshankumarar231 Web-scraping Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Sep, 2021" }, { "code": null, "e": 63, "s": 28, "text": "Prerequisite- Beautifulsoup module" }, { "code": null, "e": 273, "s": 63, "text": "In this article, we are going to draft a python script that removes a tag from the tree and then completely destroys it and its contents. For this, decompose() method is used which comes built into the module." }, { "code": null, "e": 281, "s": 273, "text": "Syntax:" }, { "code": null, "e": 313, "s": 281, "text": "Beautifulsoup.Tag.decompose()\n\n" }, { "code": null, "e": 429, "s": 313, "text": "Tag.decompose() removes a tag from the tree of a given HTML document, then completely destroys it and its contents." }, { "code": null, "e": 445, "s": 429, "text": "Implementation:" }, { "code": null, "e": 456, "s": 445, "text": "Example 1:" }, { "code": null, "e": 464, "s": 456, "text": "Python3" }, { "code": "# import modulefrom bs4 import BeautifulSoup # URL for scrapping data markup = '<a href=\"https://www.geeksforgeeks.org/\">Welcome to <i>geeksforgeeks.com</i></a>' # get URL html soup = BeautifulSoup(markup, 'html.parser') # display before decomposeprint(\"Before Decompose\")print(soup.a) # decomposing the# soup datanew_tag = soup.a.decompose()print(\"After decomposing:\")print(new_tag)", "e": 852, "s": 464, "text": null }, { "code": null, "e": 860, "s": 852, "text": "Output:" }, { "code": null, "e": 877, "s": 860, "text": "Before Decompose" }, { "code": null, "e": 958, "s": 877, "text": "<a href=”https://www.geeksforgeeks.org/”>Welcome to <i>geeksforgeeks.com</i></a>" }, { "code": null, "e": 977, "s": 958, "text": "After decomposing:" }, { "code": null, "e": 983, "s": 977, "text": "None " }, { "code": null, "e": 1051, "s": 983, "text": "Example 2: Implementation of given URL to scrape the HTML document." }, { "code": null, "e": 1059, "s": 1051, "text": "Python3" }, { "code": "# import modulefrom bs4 import BeautifulSoupimport requests # Get URL html# Scraping the data from# Html docurl = 'https://www.geeksforgeeks.org/'reqs = requests.get(url)soup = BeautifulSoup(reqs.text, 'html.parser') # Before decomposingprint(\"Before Decomposing\")print(soup) # decompose the soupresult = soup.decompose()print(\"After decomposing:\")print(result)", "e": 1424, "s": 1059, "text": null }, { "code": null, "e": 1432, "s": 1424, "text": "Output:" }, { "code": null, "e": 1451, "s": 1432, "text": "Before Decomposing" }, { "code": null, "e": 1467, "s": 1451, "text": "<!DOCTYPE html>" }, { "code": null, "e": 1481, "s": 1467, "text": "<!–[if IE 7]>" }, { "code": null, "e": 1548, "s": 1481, "text": "<html class=”ie ie7′′ lang=”en-US” prefix=”og: http://ogp.me/ns#”>" }, { "code": null, "e": 1560, "s": 1548, "text": "<![endif]–>" }, { "code": null, "e": 1574, "s": 1560, "text": "<!–[if IE 8]>" }, { "code": null, "e": 1641, "s": 1574, "text": "<html class=”ie ie8′′ lang=”en-US” prefix=”og: http://ogp.me/ns#”>" }, { "code": null, "e": 1653, "s": 1641, "text": "<![endif]–>" }, { "code": null, "e": 1686, "s": 1653, "text": "<!–[if !(IE 7) | !(IE 8) ]><!–>" }, { "code": null, "e": 1737, "s": 1686, "text": "<html lang=”en-US” prefix=”og: http://ogp.me/ns#”>" }, { "code": null, "e": 1752, "s": 1737, "text": "<!–<![endif]–>" }, { "code": null, "e": 1759, "s": 1752, "text": "<head>" }, { "code": null, "e": 1786, "s": 1759, "text": "<meta charset=”utf-8′′/>.." }, { "code": null, "e": 1793, "s": 1786, "text": "......" }, { "code": null, "e": 1812, "s": 1793, "text": "After decomposing:" }, { "code": null, "e": 1818, "s": 1812, "text": "None " }, { "code": null, "e": 1836, "s": 1818, "text": "gulshankumarar231" }, { "code": null, "e": 1849, "s": 1836, "text": "Web-scraping" }, { "code": null, "e": 1856, "s": 1849, "text": "Python" } ]
How to set Value in the NumericUpDown in C#?
26 Jul, 2019 In Windows Forms, NumericUpDown control is used to provide a Windows spin box or an up-down control which displays the numeric values. Or in other words, NumericUpDown control provides an interface which moves using up and down arrow and holds some pre-defined numeric value. In NumericUpDown control, you can set a value in the up-down control using the Value Property. This value is the current value of Up-Down control and the value is in between Minimum and Maximum values. You can set this property in two different ways: 1. Design-Time: It is the easiest way to set the value the NumericUpDown as shown in the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Next, drag and drop the NumericUpDown control from the toolbox on the form as shown in the below image: Step 3: After drag and drop you will go to the properties of the NumericUpDown and set the value the NumericUpDown as shown in the below image:Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the current value in the NumericUpDown control programmatically with the help of given syntax: public decimal Value { get; set; } It contains the numeric value of the NumericUpDown control. It will throw an ArgumentOutOfRangeException if the value assigns to this property is less than Minimum value or greater than Maximum value. The following steps show how to set value in the NumericUpDown dynamically: Step 1: Create a NumericUpDown using the NumericUpDown() constructor is provided by the NumericUpDown class.// Creating a NumericUpDown NumericUpDown n = new NumericUpDown(); // Creating a NumericUpDown NumericUpDown n = new NumericUpDown(); Step 2: After creating NumericUpDown, set the Value property of the NumericUpDown provided by the NumericUpDown class.// Setting the value n.Value = 18; // Setting the value n.Value = 18; Step 3: And last add this NumericUpDown control to the form using the following statement:// Adding NumericUpDown // control on the form this.Controls.Add(n); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp42 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the labels Label l1 = new Label(); l1.Location = new Point(348, 61); l1.Size = new Size(215, 20); l1.Text = "Form"; l1.Font = new Font("Bodoni MT", 12); this.Controls.Add(l1); Label l2 = new Label(); l2.Location = new Point(242, 136); l2.Size = new Size(103, 20); l2.Text = "Enter Age"; l2.Font = new Font("Bodoni MT", 12); this.Controls.Add(l2); // Creating and setting the // properties of NumericUpDown NumericUpDown n = new NumericUpDown(); n.Location = new Point(386, 130); n.Size = new Size(126, 26); n.Font = new Font("Bodoni MT", 12); n.Value = 18; n.Minimum = 18; n.Maximum = 30; n.BackColor = Color.LightGreen; n.ForeColor = Color.DarkGreen; n.Increment = 1; n.Name = "MySpinBox"; // Adding this control // to the form this.Controls.Add(n); }}}Output: // Adding NumericUpDown // control on the form this.Controls.Add(n); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp42 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the labels Label l1 = new Label(); l1.Location = new Point(348, 61); l1.Size = new Size(215, 20); l1.Text = "Form"; l1.Font = new Font("Bodoni MT", 12); this.Controls.Add(l1); Label l2 = new Label(); l2.Location = new Point(242, 136); l2.Size = new Size(103, 20); l2.Text = "Enter Age"; l2.Font = new Font("Bodoni MT", 12); this.Controls.Add(l2); // Creating and setting the // properties of NumericUpDown NumericUpDown n = new NumericUpDown(); n.Location = new Point(386, 130); n.Size = new Size(126, 26); n.Font = new Font("Bodoni MT", 12); n.Value = 18; n.Minimum = 18; n.Maximum = 30; n.BackColor = Color.LightGreen; n.ForeColor = Color.DarkGreen; n.Increment = 1; n.Name = "MySpinBox"; // Adding this control // to the form this.Controls.Add(n); }}} Output: CSharp-Windows-Forms-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jul, 2019" }, { "code": null, "e": 555, "s": 28, "text": "In Windows Forms, NumericUpDown control is used to provide a Windows spin box or an up-down control which displays the numeric values. Or in other words, NumericUpDown control provides an interface which moves using up and down arrow and holds some pre-defined numeric value. In NumericUpDown control, you can set a value in the up-down control using the Value Property. This value is the current value of Up-Down control and the value is in between Minimum and Maximum values. You can set this property in two different ways:" }, { "code": null, "e": 661, "s": 555, "text": "1. Design-Time: It is the easiest way to set the value the NumericUpDown as shown in the following steps:" }, { "code": null, "e": 777, "s": 661, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 889, "s": 777, "text": "Step 2: Next, drag and drop the NumericUpDown control from the toolbox on the form as shown in the below image:" }, { "code": null, "e": 1040, "s": 889, "text": "Step 3: After drag and drop you will go to the properties of the NumericUpDown and set the value the NumericUpDown as shown in the below image:Output:" }, { "code": null, "e": 1048, "s": 1040, "text": "Output:" }, { "code": null, "e": 1235, "s": 1048, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the current value in the NumericUpDown control programmatically with the help of given syntax:" }, { "code": null, "e": 1270, "s": 1235, "text": "public decimal Value { get; set; }" }, { "code": null, "e": 1547, "s": 1270, "text": "It contains the numeric value of the NumericUpDown control. It will throw an ArgumentOutOfRangeException if the value assigns to this property is less than Minimum value or greater than Maximum value. The following steps show how to set value in the NumericUpDown dynamically:" }, { "code": null, "e": 1723, "s": 1547, "text": "Step 1: Create a NumericUpDown using the NumericUpDown() constructor is provided by the NumericUpDown class.// Creating a NumericUpDown\nNumericUpDown n = new NumericUpDown();\n" }, { "code": null, "e": 1791, "s": 1723, "text": "// Creating a NumericUpDown\nNumericUpDown n = new NumericUpDown();\n" }, { "code": null, "e": 1945, "s": 1791, "text": "Step 2: After creating NumericUpDown, set the Value property of the NumericUpDown provided by the NumericUpDown class.// Setting the value\nn.Value = 18;\n" }, { "code": null, "e": 1981, "s": 1945, "text": "// Setting the value\nn.Value = 18;\n" }, { "code": null, "e": 3572, "s": 1981, "text": "Step 3: And last add this NumericUpDown control to the form using the following statement:// Adding NumericUpDown \n// control on the form\nthis.Controls.Add(n);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp42 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the labels Label l1 = new Label(); l1.Location = new Point(348, 61); l1.Size = new Size(215, 20); l1.Text = \"Form\"; l1.Font = new Font(\"Bodoni MT\", 12); this.Controls.Add(l1); Label l2 = new Label(); l2.Location = new Point(242, 136); l2.Size = new Size(103, 20); l2.Text = \"Enter Age\"; l2.Font = new Font(\"Bodoni MT\", 12); this.Controls.Add(l2); // Creating and setting the // properties of NumericUpDown NumericUpDown n = new NumericUpDown(); n.Location = new Point(386, 130); n.Size = new Size(126, 26); n.Font = new Font(\"Bodoni MT\", 12); n.Value = 18; n.Minimum = 18; n.Maximum = 30; n.BackColor = Color.LightGreen; n.ForeColor = Color.DarkGreen; n.Increment = 1; n.Name = \"MySpinBox\"; // Adding this control // to the form this.Controls.Add(n); }}}Output:" }, { "code": null, "e": 3643, "s": 3572, "text": "// Adding NumericUpDown \n// control on the form\nthis.Controls.Add(n);\n" }, { "code": null, "e": 3652, "s": 3643, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp42 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the labels Label l1 = new Label(); l1.Location = new Point(348, 61); l1.Size = new Size(215, 20); l1.Text = \"Form\"; l1.Font = new Font(\"Bodoni MT\", 12); this.Controls.Add(l1); Label l2 = new Label(); l2.Location = new Point(242, 136); l2.Size = new Size(103, 20); l2.Text = \"Enter Age\"; l2.Font = new Font(\"Bodoni MT\", 12); this.Controls.Add(l2); // Creating and setting the // properties of NumericUpDown NumericUpDown n = new NumericUpDown(); n.Location = new Point(386, 130); n.Size = new Size(126, 26); n.Font = new Font(\"Bodoni MT\", 12); n.Value = 18; n.Minimum = 18; n.Maximum = 30; n.BackColor = Color.LightGreen; n.ForeColor = Color.DarkGreen; n.Increment = 1; n.Name = \"MySpinBox\"; // Adding this control // to the form this.Controls.Add(n); }}}", "e": 5068, "s": 3652, "text": null }, { "code": null, "e": 5076, "s": 5068, "text": "Output:" }, { "code": null, "e": 5107, "s": 5076, "text": "CSharp-Windows-Forms-Namespace" }, { "code": null, "e": 5110, "s": 5107, "text": "C#" } ]
PLSQL | SQRT Function
18 Oct, 2019 The SQRT function is an inbuilt function in PLSQL which is used to return the square root of the given input number. Syntax: SQRT( number ) Parameters Used:This function accepts a parameters which are illustrated below: number – This is the input number whose square root is going to be calculated. Return Value:This function returns a numeric number which is square root of the given input number. Supported Versions of Oracle/PLSQL is given below: Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i Oracle 12c Oracle 11g Oracle 10g Oracle 9i Oracle 8i Let’s see some examples which illustrate the SQRT function: Example-1: DECLARE Test_Number number := 25; BEGIN dbms_output.put_line(SQRT(Test_Number number)); END; Output: 5 In the above example, 5 is the square root of 25. Example-2: DECLARE Test_Number number := 5.617; BEGIN dbms_output.put_line(SQRT(Test_Number number)); END; Output: 2.37002109695251 In the above example, 2.37002109695251 is the square root of 5.617 Example-3: DECLARE Test_Number number := 9; BEGIN dbms_output.put_line(SQRT(Test_Number number)); END; Output: 3 In the above example, 3 is the square root of 9 Advantage:This function is used to calculate the square root of the given input number. SQL-PL/SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Oct, 2019" }, { "code": null, "e": 145, "s": 28, "text": "The SQRT function is an inbuilt function in PLSQL which is used to return the square root of the given input number." }, { "code": null, "e": 153, "s": 145, "text": "Syntax:" }, { "code": null, "e": 168, "s": 153, "text": "SQRT( number )" }, { "code": null, "e": 248, "s": 168, "text": "Parameters Used:This function accepts a parameters which are illustrated below:" }, { "code": null, "e": 327, "s": 248, "text": "number – This is the input number whose square root is going to be calculated." }, { "code": null, "e": 427, "s": 327, "text": "Return Value:This function returns a numeric number which is square root of the given input number." }, { "code": null, "e": 478, "s": 427, "text": "Supported Versions of Oracle/PLSQL is given below:" }, { "code": null, "e": 527, "s": 478, "text": "Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i" }, { "code": null, "e": 538, "s": 527, "text": "Oracle 12c" }, { "code": null, "e": 549, "s": 538, "text": "Oracle 11g" }, { "code": null, "e": 560, "s": 549, "text": "Oracle 10g" }, { "code": null, "e": 570, "s": 560, "text": "Oracle 9i" }, { "code": null, "e": 580, "s": 570, "text": "Oracle 8i" }, { "code": null, "e": 640, "s": 580, "text": "Let’s see some examples which illustrate the SQRT function:" }, { "code": null, "e": 651, "s": 640, "text": "Example-1:" }, { "code": null, "e": 762, "s": 651, "text": "DECLARE \n Test_Number number := 25;\n \nBEGIN \n dbms_output.put_line(SQRT(Test_Number number)); \n \nEND; " }, { "code": null, "e": 770, "s": 762, "text": "Output:" }, { "code": null, "e": 772, "s": 770, "text": "5" }, { "code": null, "e": 822, "s": 772, "text": "In the above example, 5 is the square root of 25." }, { "code": null, "e": 833, "s": 822, "text": "Example-2:" }, { "code": null, "e": 947, "s": 833, "text": "DECLARE \n Test_Number number := 5.617;\n \nBEGIN \n dbms_output.put_line(SQRT(Test_Number number)); \n \nEND; " }, { "code": null, "e": 955, "s": 947, "text": "Output:" }, { "code": null, "e": 972, "s": 955, "text": "2.37002109695251" }, { "code": null, "e": 1039, "s": 972, "text": "In the above example, 2.37002109695251 is the square root of 5.617" }, { "code": null, "e": 1050, "s": 1039, "text": "Example-3:" }, { "code": null, "e": 1160, "s": 1050, "text": "DECLARE \n Test_Number number := 9;\n \nBEGIN \n dbms_output.put_line(SQRT(Test_Number number)); \n \nEND; " }, { "code": null, "e": 1168, "s": 1160, "text": "Output:" }, { "code": null, "e": 1170, "s": 1168, "text": "3" }, { "code": null, "e": 1218, "s": 1170, "text": "In the above example, 3 is the square root of 9" }, { "code": null, "e": 1306, "s": 1218, "text": "Advantage:This function is used to calculate the square root of the given input number." }, { "code": null, "e": 1317, "s": 1306, "text": "SQL-PL/SQL" }, { "code": null, "e": 1321, "s": 1317, "text": "SQL" }, { "code": null, "e": 1325, "s": 1321, "text": "SQL" } ]
Sequence to sequence tutorial | by Sachin Abeywardana | Towards Data Science
This is one of the most powerful concepts in deep learning that started off in translation but has since moved on to question answering systems (Siri, Cortana etc.), audio transcribing etc. As the name suggests it’s useful for converting from one sequence to another. The main idea behind this is that it contains an encoder RNN (LSTM) and a decoder rnn. One to ‘understand’ the input sequence and the decoder to ‘decode’ the ‘thought vector’ and construct an output sequence. What’s really powerful about the thought vector is that you can plug in the output decoder to convert it into any language. i.e. you do not need to train on English to French dataset to convert from English to Spanish. You can simply plug in a decoder that was pretrained from a different set (say Portugese to Spanish). At least this is the theory behind it. May depend on how long you train it for, the size of your data etc. I found the documentation behind seq2seq models quite lacking in tensorflow so I wrote my own model as seen below. The closest I found in the Tensorflow documentation was embedding_rnn_seq2seq however, it was not obvious in terms of implementing this function. Hence I wrote my own seq2seq model below: # Tensor where we will feed the data into graphinputs = tf.placeholder(tf.int32, (None, x_seq_length), 'inputs')outputs = tf.placeholder(tf.int32, (None, None), 'output')targets = tf.placeholder(tf.int32, (None, None), 'targets')# Embedding layersinput_embedding = tf.Variable(tf.random_uniform((len(char2numX), embed_size), -1.0, 1.0), name='enc_embedding')output_embedding = tf.Variable(tf.random_uniform((len(char2numY), embed_size), -1.0, 1.0), name='dec_embedding')date_input_embed = tf.nn.embedding_lookup(input_embedding, inputs)date_output_embed = tf.nn.embedding_lookup(output_embedding, outputs)with tf.variable_scope("encoding") as encoding_scope: lstm_enc = tf.contrib.rnn.BasicLSTMCell(nodes) _, last_state = tf.nn.dynamic_rnn(lstm_enc, inputs=date_input_embed, dtype=tf.float32)with tf.variable_scope("decoding") as decoding_scope: lstm_dec = tf.contrib.rnn.BasicLSTMCell(nodes) dec_outputs, _ = tf.nn.dynamic_rnn(lstm_dec, inputs=date_output_embed, initial_state=last_state)#connect outputs to logits = tf.contrib.layers.fully_connected(dec_outputs, num_outputs=len(char2numY), activation_fn=None) with tf.name_scope("optimization"): # Loss function loss = tf.contrib.seq2seq.sequence_loss(logits, targets, tf.ones([batch_size, y_seq_length])) # Optimizer optimizer = tf.train.RMSPropOptimizer(1e-3).minimize(loss) The full tutorial can be accessed in this video (and the code (Lesson 19) if you wish to skip the video): See here for my course on Machine Learning and Deep Learning (Use code DEEPSCHOOL-MARCH to 85% off).
[ { "code": null, "e": 314, "s": 46, "text": "This is one of the most powerful concepts in deep learning that started off in translation but has since moved on to question answering systems (Siri, Cortana etc.), audio transcribing etc. As the name suggests it’s useful for converting from one sequence to another." }, { "code": null, "e": 523, "s": 314, "text": "The main idea behind this is that it contains an encoder RNN (LSTM) and a decoder rnn. One to ‘understand’ the input sequence and the decoder to ‘decode’ the ‘thought vector’ and construct an output sequence." }, { "code": null, "e": 951, "s": 523, "text": "What’s really powerful about the thought vector is that you can plug in the output decoder to convert it into any language. i.e. you do not need to train on English to French dataset to convert from English to Spanish. You can simply plug in a decoder that was pretrained from a different set (say Portugese to Spanish). At least this is the theory behind it. May depend on how long you train it for, the size of your data etc." }, { "code": null, "e": 1254, "s": 951, "text": "I found the documentation behind seq2seq models quite lacking in tensorflow so I wrote my own model as seen below. The closest I found in the Tensorflow documentation was embedding_rnn_seq2seq however, it was not obvious in terms of implementing this function. Hence I wrote my own seq2seq model below:" }, { "code": null, "e": 2608, "s": 1254, "text": "# Tensor where we will feed the data into graphinputs = tf.placeholder(tf.int32, (None, x_seq_length), 'inputs')outputs = tf.placeholder(tf.int32, (None, None), 'output')targets = tf.placeholder(tf.int32, (None, None), 'targets')# Embedding layersinput_embedding = tf.Variable(tf.random_uniform((len(char2numX), embed_size), -1.0, 1.0), name='enc_embedding')output_embedding = tf.Variable(tf.random_uniform((len(char2numY), embed_size), -1.0, 1.0), name='dec_embedding')date_input_embed = tf.nn.embedding_lookup(input_embedding, inputs)date_output_embed = tf.nn.embedding_lookup(output_embedding, outputs)with tf.variable_scope(\"encoding\") as encoding_scope: lstm_enc = tf.contrib.rnn.BasicLSTMCell(nodes) _, last_state = tf.nn.dynamic_rnn(lstm_enc, inputs=date_input_embed, dtype=tf.float32)with tf.variable_scope(\"decoding\") as decoding_scope: lstm_dec = tf.contrib.rnn.BasicLSTMCell(nodes) dec_outputs, _ = tf.nn.dynamic_rnn(lstm_dec, inputs=date_output_embed, initial_state=last_state)#connect outputs to logits = tf.contrib.layers.fully_connected(dec_outputs, num_outputs=len(char2numY), activation_fn=None) with tf.name_scope(\"optimization\"): # Loss function loss = tf.contrib.seq2seq.sequence_loss(logits, targets, tf.ones([batch_size, y_seq_length])) # Optimizer optimizer = tf.train.RMSPropOptimizer(1e-3).minimize(loss)" }, { "code": null, "e": 2714, "s": 2608, "text": "The full tutorial can be accessed in this video (and the code (Lesson 19) if you wish to skip the video):" } ]
Cleaner R Code with Functional Programming | by Tim Book | Towards Data Science
Due to a job switch, I am a recent R-to-Python convert. However, a few side-projects keep me switching between the two languages daily. In addition to giving me a headache, this daily back-and-forth has given me a lot of thought about programming paradigms. Specifically, I’ve really become an evangelist for the functional programming paradigm in R. I want to give a little insight as to what functional programming (FP) is and how it can give you superpowers (sort of). R has a unique place in the programming world. It is used by hundreds of thousands of people every day around the world for analyzing and manipulating data. Its users are rarely trained in pure computer science and, in many cases, R code is only run once. This combination can lead R programs to be sloppy and inefficient. How did we get here? The reasoning is usually: if it works it works, right? If this “Why change?” mentality sounds familiar, this blog post is for you. R is in fact a full (albeit domain-specific) programming language influenced by rich mathematical theory. Learning the basics of FP will help you write better code, and thus make you a better statistician, data scientist, or whatever we’ve decided to call ourselves by the time you’re reading this. I’m not going to give a rigorous definition. You can go to Wikipedia for that. Simply put, FP is exactly what it sounds like. If you are doing something more than once, it belongs in a function. In FP, functions are the primary method with which you should carry out tasks. All actions are just (often creative) implementations of functions you’ve written. Once you get into it, the advantages become clear. Your code is easier to fix and maintain since you’ve segmented your code into easily serviceable pieces. Your code is easier to read since, if you named everything right, your code can look closer to plain English. Replacing long blocks of code with function calls can also help you cut down on spaghetti and pyramid of doom code, too. Ok, how can we retrain our brains for that sweet, sweet FP? In order to write a truly “functional” function, it must be pure. A pure function has two rules: It must be deterministicThat is, every time you run this function with the same inputs, it must have the same output. Every. Single. Time. “But what about functions and statistical processes with random components?” you ask? Simply set a seed, either inside the function, or let the seed be a parameter to the function. This is important for reproducible science, anyway. It can’t have side effectsThis means that your function cannot touch or change anything outside of it. This means you should probably never be using the global assignment (<<-) operator. Curiously, this also means the print() function disobeys FP. As my grad school adviser once told me, If you’re writing loops in R, you’re probably doing something wrong. (He told me this, of course, as he was debugging my third layer of nested for loops.) But... loops are so fundamental! Why should we seek to use them as sparingly as possible? There are two reasons, the first of which is specific to R. The Whole Language is Already VectorizedEven if you’ve never heard that word before, you knew this already. Vectorization is the reason you write this: x <- 1:10y <- 2 * x instead of x <- 1:10for (i in seq_along(x)) { y <- 2 * x[i]} Loops are Slow — Use Applies!The apply() function, and functions like it, are the building blocks upon which R’s FP capabilities are fully realized. While in most languages, loops and applies (often called “maps”) are the same speed, we’ll see dramatic speed boosts using applies in R. R’s base has a few applies, but the really nifty ones are found in purrr. More on this later. If you haven’t heard of the Tidyverse yet, get ready to meet your new best friend. But first, let’s meet the star of the Tidyverse, the pipe operator: The pipe (%>%) is an operator supplied by several different packages, but is most commonly accessed through either dplyr or tidyverse. Oh, and if you think it’s a pain to type (%>%) repeatedly, RStudio gives you a shortcut: Ctrl-Shift-M. So, what does it do? Simply put, the pipe takes what’s on the left, and makes it the first argument of what’s on the right. For example: add <- function(x, y) x + y3 %>% add(5) # 8 This may seem more verbose than simply typing add(3, 5), but this allows you to write complex operations as pipelines: 3 %>% add(5) %>% add(1) %>% add(3) %>% add(7) # 19 Too trivial? Check out this actual snippet from one of my consulting projects: data_clean <- data_raw %>% isFinal() %>% dropLastFiling() %>% getAccStats() %>% getPctIncs() %>% capOrDrop(inc_vars, cap = 3) You don’t need to see what the functions do to know I’m hiding a lot of complexity here. However, you can almost read this in English: Take the raw data Get whether or not it is the last tax filing Drop the last tax filing for each organization Get accounting statistics Get the year-over-year percent increases Drop or cap these variables where appropriate (I use a cap of 300%) Without this modularization, this code would be nearly impossible to debug. Got a problem dropping the last tax filings for each organization? You’ll have to read through hundreds of lines of spaghetti code. Here, you simply find where dropLastFiling is defined, and fix it there. Furthermore, you can more clearly see what the steps are to prepare your data. Now, we’re ready to get started with the Tidyverse. tidyverse is actually a collection of packages, and you may not need them all. Most of what we need is actually contained in dplyr. Anyway, tidyverse is brimming with easy-to-pipe functions specifically built for common data manipulation tasks. Here are some of the most commonly used ones: select() — Select which columns to keep (or drop)filter()— Select which rows to keep (or drop)arrange() — Sort data by given rowsrename() — Rename columnsmutate() — Make new rows from existing onesgroup_by() — Organize data so that it is grouped by some categorical variablesummarize() — Similar to mutate() but collapses group_by()ed data into summary statistics Example: mtcars %>% filter(am == 0) %>% # Consider manual cars only group_by(cyl) %>% # Group them by the number of cylinders summarize( # Get the mean and sd of fuel mean_mpg = mean(mpg), # economy by cylinder sd_mpg = sd(mpg) ) %>% ungroup() # Undo effects of group_by() # (Not always req, but good practice) # Output:# A tibble: 3 x 3# cyl mean_mpg sd_mpg# <dbl> <dbl> <dbl># 1 4 22.9 1.45# 2 6 19.1 1.63# 3 8 15.0 2.77 We still have a gap in our toolkit: we’re not allowed to use loops, there are some tasks that aren’t vectorized for us already! What’s a data analyst to do? The solution is to use applies (also called maps). Maps take a collection of things, and apply some function to each one of those things. Here’s a diagram taken directly from RStudio’s purrr cheat sheet (Credit: Mara Averick): Sidenote: The dplyr package actually gets its name from applies. dplyr = data + apply + R. The purrr package contains a ridiculous number of maps from which to choose. Seriously, check out that cheatsheet! Example, bringing it all together: Suppose I had a vector of strings, and I wanted to extract the longest word in each. There is no vectorized function that will do this for me. I will need to split the string by the space character and get the longest word. For dramatic effect, I also upper-case the strings and paste them back together: library(tidyverse)library(purrr) sentences <- c( "My head is not functional", "Programming is hard", "Too many rules") getLongestWord <- function(words) { word_counts <- str_length(words) longest_word <- words[which.max(word_counts)] return(longest_word)} sentences %>% toupper() %>% str_split(' ') %>% map_chr(getLongestWord) %>% str_c(collapse = ' ') # [1] "FUNCTIONAL PROGRAMMING RULES" In other languages, some of the lingo of FP is built-in. Specifically, there are three higher-order functions that make their way into almost every language, functional or not: map (which we’ve already covered), reduce, and filter. A higher-order function is a function that either takes a function as an argument, returns a function, or both. Filtering in R is easy. For data frames, we can use use tidyverse::filter. For most other things, we can simply use R’s vectorization. However, when all else fails, base R does indeed have a Filter() function. Example: Filter(function(x) x %% 2 == 0, 1:10)# [1] 2 4 6 8 10 Similarly, you probably won’t ever need Reduce() in R. But just in case, here’s how it works: Reduce() will take a collection and a binary function (ie, takes two parameters), and successively applies that function two-at-a-time along that collection, cumulatively. Example: wrap <- function(a, b) paste0("(", a, " ", b, ")")Reduce(wrap, c("A", "B", "C", "D", "E"))# [1] "((((A B) C) D) E)" Another beloved FP topic is that of currying. Currying is the act of taking a function with many arguments, and breaking it out into functions that take a partial amount of those arguments. These are sometimes called partial functions. The following example uses a function factory to make partial functions: # Adder is a "function factory" - a function that makes new functions.adder <- function(a) { return(function(b) a + b)} # Function factory pumping out new functions.add3 <- adder(3)add5 <- adder(5) add3(add5(1))# 9 Do you find this concept hard to follow? You’re not alone. To make this slightly more readable, the functional library gives you an explicitly currying builder: library(functional)add <- function(a, b) a + badd3 <- Curry(add, a = 3)add5 <- Curry(add, a = 5) add3(add5(1))# 9 Sidenote: The verb “currying” comes from Haskell Curry, famed Mathematician/Computer Scientist/Fellow Penn Stater. Do you feel smarter? More powerful? Ready to torture your data with some of your new FP skills? Here are some of the big takeaways: No more loops! Ever! Anytime you want to use a loop, find the appropriate apply/map. Integrate the Tidyverse into your workflow wherever possible. Use the pipe (%>%) when applying several functions to one thing (eg, a data frame being manipulated in the Tidyverse). Adhering to these mindsets while coding can greatly reduce ugly, difficult-to-maintain spaghetti code. Bottling things in functions can leave you with clean, readable, modular ravioli code. I’ll leave you with a famous quote from John Woods: Always code as if the [person] who ends up maintaining your code will be a violent psychopath who knows where you live.
[ { "code": null, "e": 644, "s": 172, "text": "Due to a job switch, I am a recent R-to-Python convert. However, a few side-projects keep me switching between the two languages daily. In addition to giving me a headache, this daily back-and-forth has given me a lot of thought about programming paradigms. Specifically, I’ve really become an evangelist for the functional programming paradigm in R. I want to give a little insight as to what functional programming (FP) is and how it can give you superpowers (sort of)." }, { "code": null, "e": 1043, "s": 644, "text": "R has a unique place in the programming world. It is used by hundreds of thousands of people every day around the world for analyzing and manipulating data. Its users are rarely trained in pure computer science and, in many cases, R code is only run once. This combination can lead R programs to be sloppy and inefficient. How did we get here? The reasoning is usually: if it works it works, right?" }, { "code": null, "e": 1418, "s": 1043, "text": "If this “Why change?” mentality sounds familiar, this blog post is for you. R is in fact a full (albeit domain-specific) programming language influenced by rich mathematical theory. Learning the basics of FP will help you write better code, and thus make you a better statistician, data scientist, or whatever we’ve decided to call ourselves by the time you’re reading this." }, { "code": null, "e": 1497, "s": 1418, "text": "I’m not going to give a rigorous definition. You can go to Wikipedia for that." }, { "code": null, "e": 1775, "s": 1497, "text": "Simply put, FP is exactly what it sounds like. If you are doing something more than once, it belongs in a function. In FP, functions are the primary method with which you should carry out tasks. All actions are just (often creative) implementations of functions you’ve written." }, { "code": null, "e": 2162, "s": 1775, "text": "Once you get into it, the advantages become clear. Your code is easier to fix and maintain since you’ve segmented your code into easily serviceable pieces. Your code is easier to read since, if you named everything right, your code can look closer to plain English. Replacing long blocks of code with function calls can also help you cut down on spaghetti and pyramid of doom code, too." }, { "code": null, "e": 2222, "s": 2162, "text": "Ok, how can we retrain our brains for that sweet, sweet FP?" }, { "code": null, "e": 2319, "s": 2222, "text": "In order to write a truly “functional” function, it must be pure. A pure function has two rules:" }, { "code": null, "e": 2691, "s": 2319, "text": "It must be deterministicThat is, every time you run this function with the same inputs, it must have the same output. Every. Single. Time. “But what about functions and statistical processes with random components?” you ask? Simply set a seed, either inside the function, or let the seed be a parameter to the function. This is important for reproducible science, anyway." }, { "code": null, "e": 2939, "s": 2691, "text": "It can’t have side effectsThis means that your function cannot touch or change anything outside of it. This means you should probably never be using the global assignment (<<-) operator. Curiously, this also means the print() function disobeys FP." }, { "code": null, "e": 2979, "s": 2939, "text": "As my grad school adviser once told me," }, { "code": null, "e": 3048, "s": 2979, "text": "If you’re writing loops in R, you’re probably doing something wrong." }, { "code": null, "e": 3134, "s": 3048, "text": "(He told me this, of course, as he was debugging my third layer of nested for loops.)" }, { "code": null, "e": 3284, "s": 3134, "text": "But... loops are so fundamental! Why should we seek to use them as sparingly as possible? There are two reasons, the first of which is specific to R." }, { "code": null, "e": 3436, "s": 3284, "text": "The Whole Language is Already VectorizedEven if you’ve never heard that word before, you knew this already. Vectorization is the reason you write this:" }, { "code": null, "e": 3456, "s": 3436, "text": "x <- 1:10y <- 2 * x" }, { "code": null, "e": 3467, "s": 3456, "text": "instead of" }, { "code": null, "e": 3520, "s": 3467, "text": "x <- 1:10for (i in seq_along(x)) { y <- 2 * x[i]}" }, { "code": null, "e": 3806, "s": 3520, "text": "Loops are Slow — Use Applies!The apply() function, and functions like it, are the building blocks upon which R’s FP capabilities are fully realized. While in most languages, loops and applies (often called “maps”) are the same speed, we’ll see dramatic speed boosts using applies in R." }, { "code": null, "e": 3900, "s": 3806, "text": "R’s base has a few applies, but the really nifty ones are found in purrr. More on this later." }, { "code": null, "e": 4051, "s": 3900, "text": "If you haven’t heard of the Tidyverse yet, get ready to meet your new best friend. But first, let’s meet the star of the Tidyverse, the pipe operator:" }, { "code": null, "e": 4289, "s": 4051, "text": "The pipe (%>%) is an operator supplied by several different packages, but is most commonly accessed through either dplyr or tidyverse. Oh, and if you think it’s a pain to type (%>%) repeatedly, RStudio gives you a shortcut: Ctrl-Shift-M." }, { "code": null, "e": 4426, "s": 4289, "text": "So, what does it do? Simply put, the pipe takes what’s on the left, and makes it the first argument of what’s on the right. For example:" }, { "code": null, "e": 4470, "s": 4426, "text": "add <- function(x, y) x + y3 %>% add(5) # 8" }, { "code": null, "e": 4589, "s": 4470, "text": "This may seem more verbose than simply typing add(3, 5), but this allows you to write complex operations as pipelines:" }, { "code": null, "e": 4644, "s": 4589, "text": "3 %>% add(5) %>% add(1) %>% add(3) %>% add(7) # 19" }, { "code": null, "e": 4723, "s": 4644, "text": "Too trivial? Check out this actual snippet from one of my consulting projects:" }, { "code": null, "e": 4854, "s": 4723, "text": "data_clean <- data_raw %>% isFinal() %>% dropLastFiling() %>% getAccStats() %>% getPctIncs() %>% capOrDrop(inc_vars, cap = 3)" }, { "code": null, "e": 4989, "s": 4854, "text": "You don’t need to see what the functions do to know I’m hiding a lot of complexity here. However, you can almost read this in English:" }, { "code": null, "e": 5007, "s": 4989, "text": "Take the raw data" }, { "code": null, "e": 5052, "s": 5007, "text": "Get whether or not it is the last tax filing" }, { "code": null, "e": 5099, "s": 5052, "text": "Drop the last tax filing for each organization" }, { "code": null, "e": 5125, "s": 5099, "text": "Get accounting statistics" }, { "code": null, "e": 5166, "s": 5125, "text": "Get the year-over-year percent increases" }, { "code": null, "e": 5234, "s": 5166, "text": "Drop or cap these variables where appropriate (I use a cap of 300%)" }, { "code": null, "e": 5594, "s": 5234, "text": "Without this modularization, this code would be nearly impossible to debug. Got a problem dropping the last tax filings for each organization? You’ll have to read through hundreds of lines of spaghetti code. Here, you simply find where dropLastFiling is defined, and fix it there. Furthermore, you can more clearly see what the steps are to prepare your data." }, { "code": null, "e": 5778, "s": 5594, "text": "Now, we’re ready to get started with the Tidyverse. tidyverse is actually a collection of packages, and you may not need them all. Most of what we need is actually contained in dplyr." }, { "code": null, "e": 5937, "s": 5778, "text": "Anyway, tidyverse is brimming with easy-to-pipe functions specifically built for common data manipulation tasks. Here are some of the most commonly used ones:" }, { "code": null, "e": 6301, "s": 5937, "text": "select() — Select which columns to keep (or drop)filter()— Select which rows to keep (or drop)arrange() — Sort data by given rowsrename() — Rename columnsmutate() — Make new rows from existing onesgroup_by() — Organize data so that it is grouped by some categorical variablesummarize() — Similar to mutate() but collapses group_by()ed data into summary statistics" }, { "code": null, "e": 6310, "s": 6301, "text": "Example:" }, { "code": null, "e": 6862, "s": 6310, "text": "mtcars %>% filter(am == 0) %>% # Consider manual cars only group_by(cyl) %>% # Group them by the number of cylinders summarize( # Get the mean and sd of fuel mean_mpg = mean(mpg), # economy by cylinder sd_mpg = sd(mpg) ) %>% ungroup() # Undo effects of group_by() # (Not always req, but good practice) # Output:# A tibble: 3 x 3# cyl mean_mpg sd_mpg# <dbl> <dbl> <dbl># 1 4 22.9 1.45# 2 6 19.1 1.63# 3 8 15.0 2.77" }, { "code": null, "e": 7019, "s": 6862, "text": "We still have a gap in our toolkit: we’re not allowed to use loops, there are some tasks that aren’t vectorized for us already! What’s a data analyst to do?" }, { "code": null, "e": 7246, "s": 7019, "text": "The solution is to use applies (also called maps). Maps take a collection of things, and apply some function to each one of those things. Here’s a diagram taken directly from RStudio’s purrr cheat sheet (Credit: Mara Averick):" }, { "code": null, "e": 7337, "s": 7246, "text": "Sidenote: The dplyr package actually gets its name from applies. dplyr = data + apply + R." }, { "code": null, "e": 7452, "s": 7337, "text": "The purrr package contains a ridiculous number of maps from which to choose. Seriously, check out that cheatsheet!" }, { "code": null, "e": 7792, "s": 7452, "text": "Example, bringing it all together: Suppose I had a vector of strings, and I wanted to extract the longest word in each. There is no vectorized function that will do this for me. I will need to split the string by the space character and get the longest word. For dramatic effect, I also upper-case the strings and paste them back together:" }, { "code": null, "e": 8196, "s": 7792, "text": "library(tidyverse)library(purrr) sentences <- c( \"My head is not functional\", \"Programming is hard\", \"Too many rules\") getLongestWord <- function(words) { word_counts <- str_length(words) longest_word <- words[which.max(word_counts)] return(longest_word)} sentences %>% toupper() %>% str_split(' ') %>% map_chr(getLongestWord) %>% str_c(collapse = ' ') # [1] \"FUNCTIONAL PROGRAMMING RULES\"" }, { "code": null, "e": 8428, "s": 8196, "text": "In other languages, some of the lingo of FP is built-in. Specifically, there are three higher-order functions that make their way into almost every language, functional or not: map (which we’ve already covered), reduce, and filter." }, { "code": null, "e": 8540, "s": 8428, "text": "A higher-order function is a function that either takes a function as an argument, returns a function, or both." }, { "code": null, "e": 8759, "s": 8540, "text": "Filtering in R is easy. For data frames, we can use use tidyverse::filter. For most other things, we can simply use R’s vectorization. However, when all else fails, base R does indeed have a Filter() function. Example:" }, { "code": null, "e": 8817, "s": 8759, "text": "Filter(function(x) x %% 2 == 0, 1:10)# [1] 2 4 6 8 10" }, { "code": null, "e": 9092, "s": 8817, "text": "Similarly, you probably won’t ever need Reduce() in R. But just in case, here’s how it works: Reduce() will take a collection and a binary function (ie, takes two parameters), and successively applies that function two-at-a-time along that collection, cumulatively. Example:" }, { "code": null, "e": 9208, "s": 9092, "text": "wrap <- function(a, b) paste0(\"(\", a, \" \", b, \")\")Reduce(wrap, c(\"A\", \"B\", \"C\", \"D\", \"E\"))# [1] \"((((A B) C) D) E)\"" }, { "code": null, "e": 9517, "s": 9208, "text": "Another beloved FP topic is that of currying. Currying is the act of taking a function with many arguments, and breaking it out into functions that take a partial amount of those arguments. These are sometimes called partial functions. The following example uses a function factory to make partial functions:" }, { "code": null, "e": 9735, "s": 9517, "text": "# Adder is a \"function factory\" - a function that makes new functions.adder <- function(a) { return(function(b) a + b)} # Function factory pumping out new functions.add3 <- adder(3)add5 <- adder(5) add3(add5(1))# 9" }, { "code": null, "e": 9896, "s": 9735, "text": "Do you find this concept hard to follow? You’re not alone. To make this slightly more readable, the functional library gives you an explicitly currying builder:" }, { "code": null, "e": 10010, "s": 9896, "text": "library(functional)add <- function(a, b) a + badd3 <- Curry(add, a = 3)add5 <- Curry(add, a = 5) add3(add5(1))# 9" }, { "code": null, "e": 10125, "s": 10010, "text": "Sidenote: The verb “currying” comes from Haskell Curry, famed Mathematician/Computer Scientist/Fellow Penn Stater." }, { "code": null, "e": 10257, "s": 10125, "text": "Do you feel smarter? More powerful? Ready to torture your data with some of your new FP skills? Here are some of the big takeaways:" }, { "code": null, "e": 10278, "s": 10257, "text": "No more loops! Ever!" }, { "code": null, "e": 10342, "s": 10278, "text": "Anytime you want to use a loop, find the appropriate apply/map." }, { "code": null, "e": 10404, "s": 10342, "text": "Integrate the Tidyverse into your workflow wherever possible." }, { "code": null, "e": 10523, "s": 10404, "text": "Use the pipe (%>%) when applying several functions to one thing (eg, a data frame being manipulated in the Tidyverse)." }, { "code": null, "e": 10765, "s": 10523, "text": "Adhering to these mindsets while coding can greatly reduce ugly, difficult-to-maintain spaghetti code. Bottling things in functions can leave you with clean, readable, modular ravioli code. I’ll leave you with a famous quote from John Woods:" } ]
C# - Interfaces
An interface is defined as a syntactical contract that all the classes inheriting the interface should follow. The interface defines the 'what' part of the syntactical contract and the deriving classes define the 'how' part of the syntactical contract. Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members. It often helps in providing a standard structure that the deriving classes would follow. Abstract classes to some extent serve the same purpose, however, they are mostly used when only few methods are to be declared by the base class and the deriving class implements the functionalities. Interfaces are declared using the interface keyword. It is similar to class declaration. Interface statements are public by default. Following is an example of an interface declaration − public interface ITransactions { // interface members void showTransaction(); double getAmount(); } The following example demonstrates implementation of the above interface − using System.Collections.Generic; using System.Linq; using System.Text; using System; namespace InterfaceApplication { public interface ITransactions { // interface members void showTransaction(); double getAmount(); } public class Transaction : ITransactions { private string tCode; private string date; private double amount; public Transaction() { tCode = " "; date = " "; amount = 0.0; } public Transaction(string c, string d, double a) { tCode = c; date = d; amount = a; } public double getAmount() { return amount; } public void showTransaction() { Console.WriteLine("Transaction: {0}", tCode); Console.WriteLine("Date: {0}", date); Console.WriteLine("Amount: {0}", getAmount()); } } class Tester { static void Main(string[] args) { Transaction t1 = new Transaction("001", "8/10/2012", 78900.00); Transaction t2 = new Transaction("002", "9/10/2012", 451900.00); t1.showTransaction(); t2.showTransaction(); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Transaction: 001 Date: 8/10/2012 Amount: 78900 Transaction: 002 Date: 9/10/2012 Amount: 451900 119 Lectures 23.5 hours Raja Biswas 37 Lectures 13 hours Trevoir Williams 16 Lectures 1 hours Peter Jepson 159 Lectures 21.5 hours Ebenezer Ogbu 193 Lectures 17 hours Arnold Higuit 24 Lectures 2.5 hours Eric Frick Print Add Notes Bookmark this page
[ { "code": null, "e": 2523, "s": 2270, "text": "An interface is defined as a syntactical contract that all the classes inheriting the interface should follow. The interface defines the 'what' part of the syntactical contract and the deriving classes define the 'how' part of the syntactical contract." }, { "code": null, "e": 2829, "s": 2523, "text": "Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members. It often helps in providing a standard structure that the deriving classes would follow." }, { "code": null, "e": 3029, "s": 2829, "text": "Abstract classes to some extent serve the same purpose, however, they are mostly used when only few methods are to be declared by the base class and the deriving class implements the functionalities." }, { "code": null, "e": 3216, "s": 3029, "text": "Interfaces are declared using the interface keyword. It is similar to class declaration. Interface statements are public by default. Following is an example of an interface declaration −" }, { "code": null, "e": 3325, "s": 3216, "text": "public interface ITransactions {\n // interface members\n void showTransaction();\n double getAmount();\n}" }, { "code": null, "e": 3400, "s": 3325, "text": "The following example demonstrates implementation of the above interface −" }, { "code": null, "e": 4614, "s": 3400, "text": "using System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System;\n\nnamespace InterfaceApplication {\n \n public interface ITransactions {\n // interface members\n void showTransaction();\n double getAmount();\n }\n public class Transaction : ITransactions {\n private string tCode;\n private string date;\n private double amount;\n \n public Transaction() {\n tCode = \" \";\n date = \" \";\n amount = 0.0;\n }\n public Transaction(string c, string d, double a) {\n tCode = c;\n date = d;\n amount = a;\n }\n public double getAmount() {\n return amount;\n }\n public void showTransaction() {\n Console.WriteLine(\"Transaction: {0}\", tCode);\n Console.WriteLine(\"Date: {0}\", date);\n Console.WriteLine(\"Amount: {0}\", getAmount());\n }\n }\n class Tester {\n \n static void Main(string[] args) {\n Transaction t1 = new Transaction(\"001\", \"8/10/2012\", 78900.00);\n Transaction t2 = new Transaction(\"002\", \"9/10/2012\", 451900.00);\n \n t1.showTransaction();\n t2.showTransaction();\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 4695, "s": 4614, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4791, "s": 4695, "text": "Transaction: 001\nDate: 8/10/2012\nAmount: 78900\nTransaction: 002\nDate: 9/10/2012\nAmount: 451900\n" }, { "code": null, "e": 4828, "s": 4791, "text": "\n 119 Lectures \n 23.5 hours \n" }, { "code": null, "e": 4841, "s": 4828, "text": " Raja Biswas" }, { "code": null, "e": 4875, "s": 4841, "text": "\n 37 Lectures \n 13 hours \n" }, { "code": null, "e": 4893, "s": 4875, "text": " Trevoir Williams" }, { "code": null, "e": 4926, "s": 4893, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 4940, "s": 4926, "text": " Peter Jepson" }, { "code": null, "e": 4977, "s": 4940, "text": "\n 159 Lectures \n 21.5 hours \n" }, { "code": null, "e": 4992, "s": 4977, "text": " Ebenezer Ogbu" }, { "code": null, "e": 5027, "s": 4992, "text": "\n 193 Lectures \n 17 hours \n" }, { "code": null, "e": 5042, "s": 5027, "text": " Arnold Higuit" }, { "code": null, "e": 5077, "s": 5042, "text": "\n 24 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5089, "s": 5077, "text": " Eric Frick" }, { "code": null, "e": 5096, "s": 5089, "text": " Print" }, { "code": null, "e": 5107, "s": 5096, "text": " Add Notes" } ]
World Map on HTML5 Canvas or SVG
You can use SVG to create a World Map and work with raphaeljs. Firstly, learn how to add Raphael.js, and create a circle, var paper = Raphael(10, 50, 320, 200); // drawing circls var circle = paper.circle(50, 40, 10); circle.attr("fill", "#f00"); circle.attr("stroke", "#fff"); Then refer the following to create a World Map.
[ { "code": null, "e": 1125, "s": 1062, "text": "You can use SVG to create a World Map and work with raphaeljs." }, { "code": null, "e": 1184, "s": 1125, "text": "Firstly, learn how to add Raphael.js, and create a circle," }, { "code": null, "e": 1342, "s": 1184, "text": "var paper = Raphael(10, 50, 320, 200);\n\n// drawing circls\nvar circle = paper.circle(50, 40, 10);\n\ncircle.attr(\"fill\", \"#f00\");\ncircle.attr(\"stroke\", \"#fff\");" }, { "code": null, "e": 1390, "s": 1342, "text": "Then refer the following to create a World Map." } ]
C++ Algorithm Library - find_if_not() Function
The C++ function std::algorithm::find_if_not() finds the last occurrence of the element that satisfies the condition. It uses unary predicate to specify condition. Following is the declaration for std::algorithm::find_if_not() function form std::algorithm header. template <class InputIterator, class UnaryPredicate> InputIterator find_if_not(InputIterator first, InputIterator last, UnaryPredicate pred); first − Input iterator to the initial position. first − Input iterator to the initial position. last − Final iterator to the final position. last − Final iterator to the final position. pred − A unary predicate which accepts one argument and returns bool. pred − A unary predicate which accepts one argument and returns bool. returns an iterator to the first element in the range (first,last) for which unary predicate returns false. If no such element is found, the function returns last. Throws exception if either predicate or an operation on an iterator throws exception. Please note that invalid parameters cause undefined behavior. Linear. The following example shows the usage of std::algorithm::find_if_not() function. #include <iostream> #include <vector> #include <algorithm> using namespace std; bool unary_pred(int n) { return ((n % 2) == 0); } int main(void) { vector<int> v = {2, 4, 61, 8, 10}; auto it = find_if_not(v.begin(), v.end(), unary_pred); if (it != end(v)) cout << "First odd number is " << *it << endl; v = {2, 4, 6, 8, 10}; it = find_if_not(v.begin(), v.end(), unary_pred); if (it == end(v)) cout << "Only enven elements present in the sequence." << endl; return 0; } Let us compile and run the above program, this will produce the following result − First odd number is 61 Only enven elements present in the sequence. Print Add Notes Bookmark this page
[ { "code": null, "e": 2767, "s": 2603, "text": "The C++ function std::algorithm::find_if_not() finds the last occurrence of the element that satisfies the condition. It uses unary predicate to specify condition." }, { "code": null, "e": 2867, "s": 2767, "text": "Following is the declaration for std::algorithm::find_if_not() function form std::algorithm header." }, { "code": null, "e": 3010, "s": 2867, "text": "template <class InputIterator, class UnaryPredicate>\nInputIterator find_if_not(InputIterator first, InputIterator last, UnaryPredicate pred);\n" }, { "code": null, "e": 3058, "s": 3010, "text": "first − Input iterator to the initial position." }, { "code": null, "e": 3106, "s": 3058, "text": "first − Input iterator to the initial position." }, { "code": null, "e": 3151, "s": 3106, "text": "last − Final iterator to the final position." }, { "code": null, "e": 3196, "s": 3151, "text": "last − Final iterator to the final position." }, { "code": null, "e": 3266, "s": 3196, "text": "pred − A unary predicate which accepts one argument and returns bool." }, { "code": null, "e": 3336, "s": 3266, "text": "pred − A unary predicate which accepts one argument and returns bool." }, { "code": null, "e": 3500, "s": 3336, "text": "returns an iterator to the first element in the range (first,last) for which unary predicate returns false. If no such element is found, the function returns last." }, { "code": null, "e": 3586, "s": 3500, "text": "Throws exception if either predicate or an operation on an iterator throws exception." }, { "code": null, "e": 3648, "s": 3586, "text": "Please note that invalid parameters cause undefined behavior." }, { "code": null, "e": 3656, "s": 3648, "text": "Linear." }, { "code": null, "e": 3737, "s": 3656, "text": "The following example shows the usage of std::algorithm::find_if_not() function." }, { "code": null, "e": 4249, "s": 3737, "text": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nbool unary_pred(int n) {\n return ((n % 2) == 0);\n}\n\nint main(void) {\n vector<int> v = {2, 4, 61, 8, 10};\n auto it = find_if_not(v.begin(), v.end(), unary_pred);\n\n if (it != end(v))\n cout << \"First odd number is \" << *it << endl;\n\n v = {2, 4, 6, 8, 10};\n\n it = find_if_not(v.begin(), v.end(), unary_pred);\n\n if (it == end(v))\n cout << \"Only enven elements present in the sequence.\" << endl;\n\n return 0;\n}" }, { "code": null, "e": 4332, "s": 4249, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 4401, "s": 4332, "text": "First odd number is 61\nOnly enven elements present in the sequence.\n" }, { "code": null, "e": 4408, "s": 4401, "text": " Print" }, { "code": null, "e": 4419, "s": 4408, "text": " Add Notes" } ]
Count of integers of the form (2^x * 3^y) in the range [L, R] - GeeksforGeeks
15 Dec, 2021 Given a range [L, R] where 0 ≤ L ≤ R ≤ 108. The task is to find the count of integers from the given range that can be represented as (2x) * (3y).Examples: Input: L = 1, R = 10 Output: 7 The numbers are 1, 2, 3, 4, 6, 8 and 9Input: L = 100, R = 200 Output: 5 The numbers are 108, 128, 144, 162 and 192 Approach: Since the numbers, which are powers of two and three, quickly grow, you can use the following algorithm. For all the numbers of the form (2x) * (3y) in the range [1, 108] store them in a vector. Later sort the vector. Then the required answer can be calculated using an upper bound. Pre-calculating these integers will be helpful when there are a number of queries of the form [L, R].Below is the implementation of the above approach: CPP Python3 // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define MAXI (int)(1e8) // To store all valid integersvector<int> v; // Function to find all the integers of the// form (2^x * 3^y) in the range [0, 1000000]void precompute(){ // To store powers of 2 and 3 // initialized to 2^0 and 3^0 int x = 1, y = 1; // While current power of 2 // is within the range while (x <= MAXI) { // While number is within the range while (x * y <= MAXI) { // Add the number to the vector v.push_back(x * y); // Next power of 3 y *= 3; } // Next power of 2 x *= 2; // Reset to 3^0 y = 1; } // Sort the vector sort(v.begin(), v.end());} // Function to find the count of numbers// in the range [l, r] which are// of the form (2^x * 3^y)void countNum(int l, int r){ cout << upper_bound(v.begin(), v.end(), r) - upper_bound(v.begin(), v.end(), l - 1);} // Driver codeint main(){ int l = 100, r = 200; // Pre-compute all the valid numbers precompute(); countNum(l, r); return 0;} # Python3 implementation of the approachimport bisectMAXI=int(1e8) # To store all valid integersv=[] # Function to find all the integers of the# form (2^x * 3^y) in the range [0, 1000000]def precompute(): # To store powers of 2 and 3 # initialized to 2^0 and 3^0 x = 1; y = 1 # While current power of 2 # is within the range while (x <= MAXI) : # While number is within the range while (x * y <= MAXI) : # Add the number to the vector v.append(x * y) # Next power of 3 y *= 3 # Next power of 2 x *= 2 # Reset to 3^0 y = 1 # Sort the vector v.sort() # Function to find the count of numbers# in the range [l, r] which are# of the form (2^x * 3^y)def countNum(l, r): print(bisect.bisect_right(v, r) - bisect.bisect_right(v,l - 1)) # Driver codeif __name__ == '__main__': l = 100; r = 200 # Pre-compute all the valid numbers precompute() countNum(l, r) 5 Time Complexity: O(N * log(N)), where N = logX + logYAuxiliary Space: O(N) pankajsharmagfg amartyaghoshgfg Binary Search Algorithms Competitive Programming Mathematical Sorting Mathematical Sorting Binary Search Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Understanding Time Complexity with Simple Examples Introduction to Algorithms How to write a Pseudo Code? Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Top 10 Algorithms and Data Structures for Competitive Programming Modulo 10^9+7 (1000000007)
[ { "code": null, "e": 25290, "s": 25262, "text": "\n15 Dec, 2021" }, { "code": null, "e": 25448, "s": 25290, "text": "Given a range [L, R] where 0 ≤ L ≤ R ≤ 108. The task is to find the count of integers from the given range that can be represented as (2x) * (3y).Examples: " }, { "code": null, "e": 25596, "s": 25448, "text": "Input: L = 1, R = 10 Output: 7 The numbers are 1, 2, 3, 4, 6, 8 and 9Input: L = 100, R = 200 Output: 5 The numbers are 108, 128, 144, 162 and 192 " }, { "code": null, "e": 26044, "s": 25598, "text": "Approach: Since the numbers, which are powers of two and three, quickly grow, you can use the following algorithm. For all the numbers of the form (2x) * (3y) in the range [1, 108] store them in a vector. Later sort the vector. Then the required answer can be calculated using an upper bound. Pre-calculating these integers will be helpful when there are a number of queries of the form [L, R].Below is the implementation of the above approach: " }, { "code": null, "e": 26048, "s": 26044, "text": "CPP" }, { "code": null, "e": 26056, "s": 26048, "text": "Python3" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define MAXI (int)(1e8) // To store all valid integersvector<int> v; // Function to find all the integers of the// form (2^x * 3^y) in the range [0, 1000000]void precompute(){ // To store powers of 2 and 3 // initialized to 2^0 and 3^0 int x = 1, y = 1; // While current power of 2 // is within the range while (x <= MAXI) { // While number is within the range while (x * y <= MAXI) { // Add the number to the vector v.push_back(x * y); // Next power of 3 y *= 3; } // Next power of 2 x *= 2; // Reset to 3^0 y = 1; } // Sort the vector sort(v.begin(), v.end());} // Function to find the count of numbers// in the range [l, r] which are// of the form (2^x * 3^y)void countNum(int l, int r){ cout << upper_bound(v.begin(), v.end(), r) - upper_bound(v.begin(), v.end(), l - 1);} // Driver codeint main(){ int l = 100, r = 200; // Pre-compute all the valid numbers precompute(); countNum(l, r); return 0;}", "e": 27205, "s": 26056, "text": null }, { "code": "# Python3 implementation of the approachimport bisectMAXI=int(1e8) # To store all valid integersv=[] # Function to find all the integers of the# form (2^x * 3^y) in the range [0, 1000000]def precompute(): # To store powers of 2 and 3 # initialized to 2^0 and 3^0 x = 1; y = 1 # While current power of 2 # is within the range while (x <= MAXI) : # While number is within the range while (x * y <= MAXI) : # Add the number to the vector v.append(x * y) # Next power of 3 y *= 3 # Next power of 2 x *= 2 # Reset to 3^0 y = 1 # Sort the vector v.sort() # Function to find the count of numbers# in the range [l, r] which are# of the form (2^x * 3^y)def countNum(l, r): print(bisect.bisect_right(v, r) - bisect.bisect_right(v,l - 1)) # Driver codeif __name__ == '__main__': l = 100; r = 200 # Pre-compute all the valid numbers precompute() countNum(l, r)", "e": 28205, "s": 27205, "text": null }, { "code": null, "e": 28207, "s": 28205, "text": "5" }, { "code": null, "e": 28284, "s": 28209, "text": "Time Complexity: O(N * log(N)), where N = logX + logYAuxiliary Space: O(N)" }, { "code": null, "e": 28300, "s": 28284, "text": "pankajsharmagfg" }, { "code": null, "e": 28316, "s": 28300, "text": "amartyaghoshgfg" }, { "code": null, "e": 28330, "s": 28316, "text": "Binary Search" }, { "code": null, "e": 28341, "s": 28330, "text": "Algorithms" }, { "code": null, "e": 28365, "s": 28341, "text": "Competitive Programming" }, { "code": null, "e": 28378, "s": 28365, "text": "Mathematical" }, { "code": null, "e": 28386, "s": 28378, "text": "Sorting" }, { "code": null, "e": 28399, "s": 28386, "text": "Mathematical" }, { "code": null, "e": 28407, "s": 28399, "text": "Sorting" }, { "code": null, "e": 28421, "s": 28407, "text": "Binary Search" }, { "code": null, "e": 28432, "s": 28421, "text": "Algorithms" }, { "code": null, "e": 28530, "s": 28432, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28579, "s": 28530, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 28604, "s": 28579, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 28655, "s": 28604, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 28682, "s": 28655, "text": "Introduction to Algorithms" }, { "code": null, "e": 28710, "s": 28682, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 28753, "s": 28710, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 28796, "s": 28753, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 28837, "s": 28796, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 28903, "s": 28837, "text": "Top 10 Algorithms and Data Structures for Competitive Programming" } ]
Unsupervised Machine Learning Example in Keras | by Andrej Baranovskij | Towards Data Science
This post is about unsupervised learning and about my research related to the topic of fraudulent claims detection in health insurance. There are several challenges related to fraudulent claims detection in health insurance. First, of them — there is no public data related to health insurance claims fraud, this is related to the data privacy issues. Second, it is very hard to identify a set of rules, which would help to identify fraudulent claims. This means a supervised machine learning approach with labeled data would hardly work for our case. Unsupervised machine learning seems like it will be a better match. In unsupervised machine learning, network trains without labels, it finds patterns and splits data into the groups. This can be specifically useful for anomaly detection in the data, such cases when data we are looking for is rare. This is the case with health insurance fraud — this is anomaly comparing with the whole amount of claims. I would recommend going through Hands-On Unsupervised Learning Using Python book for a better hands-on understanding of the topic. There is a GitHub repo for this book. I’m using an anomaly score calculation function from this book in my example. The way how we can identify fraud is by detecting an anomaly. In unsupervised learning, an anomaly can be detected with autoencoders. Autoencoder translates original data into a learned representation, based on this we can run a function and calculate how far is learned representation from the original data. Fraudulent data is reconstructed with a higher error rate, this helps to identify anomalies. Autoencoders are suitable for unsupervised learning — labeled data is not required for training. My example is based on the idea of locating fraudulent health insurance claims. There could be various types of fraud, one example — hospitals may overcharge insurance companies. Our task is to detect fraudulent claims, the model is trained in Keras using unsupervised manner, without labels. It is hard to get public data for health insurance (privacy issues). For this reason, I’m using generated data (based on this post — Data Science With No Data): Training: 100 000 (valid claims), 1 000 (fraudulent claims) Testing: 30 000 (valid claims), 300 (fraudulent claims) Fraudulent claim rule: claimed insurance cost is doubled Anomaly score function to detect data reconstruction error rate: def anomalyScores(originalDF, reducedDF): loss = np.sum((np.array(originalDF) - \ np.array(reducedDF))**2, axis=1) loss = pd.Series(data=loss,index=originalDF.index) loss = (loss-np.min(loss))/(np.max(loss)-np.min(loss)) print('Mean for anomaly scores: ', np.mean(loss)) return loss Autoencoder is implemented with Keras/TensorFlow. Neural Network is defined with 3 layers (number of nodes = data dimension). Using linear activation, optimizer Adam: # Call neural network APImodel = Sequential()# Apply linear activation function to input layer# Generate hidden layer with 14 nodes, the same as the input layermodel.add(Dense(units=14, activation='linear',input_dim=14))model.add(Dense(units=14, activation='linear'))# Apply linear activation function to hidden layer# Generate output layer with 14 nodesmodel.add(Dense(units=14, activation='linear'))# Compile the modelmodel.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy']) This is unsupervised learning — fraud label is not included into training: # Train the modelnum_epochs = 10batch_size = 256history = model.fit(x=dataX, y=dataX, epochs=num_epochs, batch_size=batch_size, shuffle=True, validation_data=(dataX, dataX), verbose=1) The model is trained in 10 runs. After each run, the anomaly score is calculated to measure reconstruction accuracy. The best model is saved. Accuracy is measured using Precision-Recall and Receiver Operating Characteristic. Sample training result: Fraud detection logic is implemented in fraud_detection notebook. Predict function is executed on test data without labels. Anomaly scores are calculated using the anomaly score function. I have calculated the mean anomaly score, this will help to define the threshold to distinguish between valid and fraudulent claims. Calculated mean based on test data: In the end, I’m comparing predicted labels with actual test set labels — this allows us to measure fraud detection accuracy by the trained model. Fraud detection threshold = 0.01. Results: Valid claims: 30 000 Fraud: 286 (accuracy 95%) Not identified as fraud: 14 Fraud detection threshold = 0.005 (closer to calculated mean 0.003). Results: Valid claims: 29 636 Fraud: 293 (accuracy 98%) Valid identified as fraud: 364 Not identified as fraud: 7 Fraud detection threshold = 0.003 (equal to calculated mean 0.003). Results: Valid claims: 26 707 Fraud: 300 (accuracy 100%) Valid identified as fraud: 3293 Conclusion With anomaly scores getting smaller, we apply a more strict check for the anomaly. This allows us to catch all fraudulent claims, but in return, we flag more valid claims as a fraud. You can see from the charts above, it is harder to identify fraudulent claims with a lower value. This makes sense, when amounts are smaller — higher chance it can be missed. Source code: GitHub repo
[ { "code": null, "e": 308, "s": 172, "text": "This post is about unsupervised learning and about my research related to the topic of fraudulent claims detection in health insurance." }, { "code": null, "e": 1130, "s": 308, "text": "There are several challenges related to fraudulent claims detection in health insurance. First, of them — there is no public data related to health insurance claims fraud, this is related to the data privacy issues. Second, it is very hard to identify a set of rules, which would help to identify fraudulent claims. This means a supervised machine learning approach with labeled data would hardly work for our case. Unsupervised machine learning seems like it will be a better match. In unsupervised machine learning, network trains without labels, it finds patterns and splits data into the groups. This can be specifically useful for anomaly detection in the data, such cases when data we are looking for is rare. This is the case with health insurance fraud — this is anomaly comparing with the whole amount of claims." }, { "code": null, "e": 1377, "s": 1130, "text": "I would recommend going through Hands-On Unsupervised Learning Using Python book for a better hands-on understanding of the topic. There is a GitHub repo for this book. I’m using an anomaly score calculation function from this book in my example." }, { "code": null, "e": 1877, "s": 1377, "text": "The way how we can identify fraud is by detecting an anomaly. In unsupervised learning, an anomaly can be detected with autoencoders. Autoencoder translates original data into a learned representation, based on this we can run a function and calculate how far is learned representation from the original data. Fraudulent data is reconstructed with a higher error rate, this helps to identify anomalies. Autoencoders are suitable for unsupervised learning — labeled data is not required for training." }, { "code": null, "e": 2170, "s": 1877, "text": "My example is based on the idea of locating fraudulent health insurance claims. There could be various types of fraud, one example — hospitals may overcharge insurance companies. Our task is to detect fraudulent claims, the model is trained in Keras using unsupervised manner, without labels." }, { "code": null, "e": 2331, "s": 2170, "text": "It is hard to get public data for health insurance (privacy issues). For this reason, I’m using generated data (based on this post — Data Science With No Data):" }, { "code": null, "e": 2391, "s": 2331, "text": "Training: 100 000 (valid claims), 1 000 (fraudulent claims)" }, { "code": null, "e": 2447, "s": 2391, "text": "Testing: 30 000 (valid claims), 300 (fraudulent claims)" }, { "code": null, "e": 2504, "s": 2447, "text": "Fraudulent claim rule: claimed insurance cost is doubled" }, { "code": null, "e": 2569, "s": 2504, "text": "Anomaly score function to detect data reconstruction error rate:" }, { "code": null, "e": 2893, "s": 2569, "text": "def anomalyScores(originalDF, reducedDF): loss = np.sum((np.array(originalDF) - \\ np.array(reducedDF))**2, axis=1) loss = pd.Series(data=loss,index=originalDF.index) loss = (loss-np.min(loss))/(np.max(loss)-np.min(loss)) print('Mean for anomaly scores: ', np.mean(loss)) return loss" }, { "code": null, "e": 3060, "s": 2893, "text": "Autoencoder is implemented with Keras/TensorFlow. Neural Network is defined with 3 layers (number of nodes = data dimension). Using linear activation, optimizer Adam:" }, { "code": null, "e": 3587, "s": 3060, "text": "# Call neural network APImodel = Sequential()# Apply linear activation function to input layer# Generate hidden layer with 14 nodes, the same as the input layermodel.add(Dense(units=14, activation='linear',input_dim=14))model.add(Dense(units=14, activation='linear'))# Apply linear activation function to hidden layer# Generate output layer with 14 nodesmodel.add(Dense(units=14, activation='linear'))# Compile the modelmodel.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy'])" }, { "code": null, "e": 3662, "s": 3587, "text": "This is unsupervised learning — fraud label is not included into training:" }, { "code": null, "e": 3942, "s": 3662, "text": "# Train the modelnum_epochs = 10batch_size = 256history = model.fit(x=dataX, y=dataX, epochs=num_epochs, batch_size=batch_size, shuffle=True, validation_data=(dataX, dataX), verbose=1)" }, { "code": null, "e": 4191, "s": 3942, "text": "The model is trained in 10 runs. After each run, the anomaly score is calculated to measure reconstruction accuracy. The best model is saved. Accuracy is measured using Precision-Recall and Receiver Operating Characteristic. Sample training result:" }, { "code": null, "e": 4548, "s": 4191, "text": "Fraud detection logic is implemented in fraud_detection notebook. Predict function is executed on test data without labels. Anomaly scores are calculated using the anomaly score function. I have calculated the mean anomaly score, this will help to define the threshold to distinguish between valid and fraudulent claims. Calculated mean based on test data:" }, { "code": null, "e": 4694, "s": 4548, "text": "In the end, I’m comparing predicted labels with actual test set labels — this allows us to measure fraud detection accuracy by the trained model." }, { "code": null, "e": 4728, "s": 4694, "text": "Fraud detection threshold = 0.01." }, { "code": null, "e": 4737, "s": 4728, "text": "Results:" }, { "code": null, "e": 4758, "s": 4737, "text": "Valid claims: 30 000" }, { "code": null, "e": 4784, "s": 4758, "text": "Fraud: 286 (accuracy 95%)" }, { "code": null, "e": 4812, "s": 4784, "text": "Not identified as fraud: 14" }, { "code": null, "e": 4881, "s": 4812, "text": "Fraud detection threshold = 0.005 (closer to calculated mean 0.003)." }, { "code": null, "e": 4890, "s": 4881, "text": "Results:" }, { "code": null, "e": 4911, "s": 4890, "text": "Valid claims: 29 636" }, { "code": null, "e": 4937, "s": 4911, "text": "Fraud: 293 (accuracy 98%)" }, { "code": null, "e": 4968, "s": 4937, "text": "Valid identified as fraud: 364" }, { "code": null, "e": 4995, "s": 4968, "text": "Not identified as fraud: 7" }, { "code": null, "e": 5063, "s": 4995, "text": "Fraud detection threshold = 0.003 (equal to calculated mean 0.003)." }, { "code": null, "e": 5072, "s": 5063, "text": "Results:" }, { "code": null, "e": 5093, "s": 5072, "text": "Valid claims: 26 707" }, { "code": null, "e": 5120, "s": 5093, "text": "Fraud: 300 (accuracy 100%)" }, { "code": null, "e": 5152, "s": 5120, "text": "Valid identified as fraud: 3293" }, { "code": null, "e": 5163, "s": 5152, "text": "Conclusion" }, { "code": null, "e": 5346, "s": 5163, "text": "With anomaly scores getting smaller, we apply a more strict check for the anomaly. This allows us to catch all fraudulent claims, but in return, we flag more valid claims as a fraud." }, { "code": null, "e": 5521, "s": 5346, "text": "You can see from the charts above, it is harder to identify fraudulent claims with a lower value. This makes sense, when amounts are smaller — higher chance it can be missed." } ]
Count the number of elements in an array which are divisible by k in C++
We are given with an array of positive integer numbers and an integer variable k. The task is to calculate the count of the number of elements in an array which is divisible by the given value k. Input − int arr[] = {4, 2, 6, 1, 3, 8, 10, 9}, k = 2 Output − Count the number of elements in an array which are divisible by 2 are − 5 Explanation − we will divide the elements in an array by a value k and check whether the reminder is 0 or not. So, 4 is divisible by 2, 2 is divisible by 2, 6 is divisible by 2, 1 isn’t divisible by 2, 3 isn’t divisible by 2, 8 is divisible by 2, 10 is divisible by 2, 9 isn’t divisible by 2. So, there are 5 elements in an array which are completely divisible by k i.e. 2. Input − int arr[] = {3, 2, 9, 15, 0, 8, 10}, k = 3 Output − Count the number of elements in an array which are divisible by 3 are − 3 Explanation − we will divide the elements in an array by a value k and check whether the reminder is 0 or not. So, 3 is divisible by 3, 2 isn’t divisible by 3, 9 is divisible by 3, 15 is divisible by 3, 0 isn’t divisible by any number, 8 isn’t divisible by 3, 10 isn’t divisible by 3. So, there are 3 elements in an array which are completely divisible by k i.e. 23 There can be multiple approaches to solve a particular problem. So firstly we will go with a naive approach. Input an array of integer elements and an integer variable k Input an array of integer elements and an integer variable k Calculate the length of an array and pass the data to the function for further processing. Calculate the length of an array and pass the data to the function for further processing. Take a temporary variable count to store the count of elements divisible by k Take a temporary variable count to store the count of elements divisible by k Start loop FOR from 0 till the length of an array Start loop FOR from 0 till the length of an array Inside the loop, check IF arr[i] % k = 0 then increment the count by 1 Inside the loop, check IF arr[i] % k = 0 then increment the count by 1 Return the count Return the count Print the result. Print the result. Input elements in a vector of integer type and take an integer variable k. Input elements in a vector of integer type and take an integer variable k. Take a temporary variable count to store the count of elements divisible by k Take a temporary variable count to store the count of elements divisible by k Set the count as the call to an inbuilt count_if() function that will take vector.begin(), vector.end() as an argument and start the traversal then return i%k if 0. Set the count as the call to an inbuilt count_if() function that will take vector.begin(), vector.end() as an argument and start the traversal then return i%k if 0. Print the result. Print the result. Live Demo #include <bits/stdc++.h> using namespace std; int divisible_k(int arr[], int size, int k){ int count = 0; for(int i = 0; i<size; i++){ if(arr[i]%k==0){ count++; } } return count; } int main(){ int arr[] = {4, 2, 6, 1, 3, 8, 10, 9}; int k = 2; int size = sizeof(arr) / sizeof(arr[0]); cout<<"Count the number of elements in an array which are divisible by "<<k<<" are: "<<divisible_k(arr, size, k); return 0; } If we run the above code it will generate the following output − Count the number of elements in an array which are divisible by 2 are: 5 Live Demo #include <bits/stdc++.h> using namespace std; int main(){ vector<int> vec = {4, 2, 6, 1, 3, 8, 10, 9}; int count = count_if(vec.begin(), vec.end(), [](int i, int k = 2) { return i % k == 0; }); cout<<"Count the number of elements in an array which are divisible by k are: "<<count; return 0; } If we run the above code it will generate the following output − Count the number of elements in an array which are divisible by 2 are: 5
[ { "code": null, "e": 1258, "s": 1062, "text": "We are given with an array of positive integer numbers and an integer variable k. The task is to calculate the count of the number of elements in an array which is divisible by the given value k." }, { "code": null, "e": 1311, "s": 1258, "text": "Input − int arr[] = {4, 2, 6, 1, 3, 8, 10, 9}, k = 2" }, { "code": null, "e": 1394, "s": 1311, "text": "Output − Count the number of elements in an array which are divisible by 2 are − 5" }, { "code": null, "e": 1768, "s": 1394, "text": "Explanation − we will divide the elements in an array by a value k and check whether the reminder is 0 or not. So, 4 is divisible by 2, 2 is divisible by 2, 6 is divisible by 2, 1 isn’t divisible by 2, 3 isn’t divisible by 2, 8 is divisible by 2, 10 is divisible by 2, 9 isn’t divisible by 2. So, there are 5 elements in an array which are completely divisible by k i.e. 2." }, { "code": null, "e": 1819, "s": 1768, "text": "Input − int arr[] = {3, 2, 9, 15, 0, 8, 10}, k = 3" }, { "code": null, "e": 1902, "s": 1819, "text": "Output − Count the number of elements in an array which are divisible by 3 are − 3" }, { "code": null, "e": 2268, "s": 1902, "text": "Explanation − we will divide the elements in an array by a value k and check whether the reminder is 0 or not. So, 3 is divisible by 3, 2 isn’t divisible by 3, 9 is divisible by 3, 15 is divisible by 3, 0 isn’t divisible by any number, 8 isn’t divisible by 3, 10 isn’t divisible by 3. So, there are 3 elements in an array which are completely divisible by k i.e. 23" }, { "code": null, "e": 2377, "s": 2268, "text": "There can be multiple approaches to solve a particular problem. So firstly we will go with a naive approach." }, { "code": null, "e": 2438, "s": 2377, "text": "Input an array of integer elements and an integer variable k" }, { "code": null, "e": 2499, "s": 2438, "text": "Input an array of integer elements and an integer variable k" }, { "code": null, "e": 2590, "s": 2499, "text": "Calculate the length of an array and pass the data to the function for further processing." }, { "code": null, "e": 2681, "s": 2590, "text": "Calculate the length of an array and pass the data to the function for further processing." }, { "code": null, "e": 2759, "s": 2681, "text": "Take a temporary variable count to store the count of elements divisible by k" }, { "code": null, "e": 2837, "s": 2759, "text": "Take a temporary variable count to store the count of elements divisible by k" }, { "code": null, "e": 2887, "s": 2837, "text": "Start loop FOR from 0 till the length of an array" }, { "code": null, "e": 2937, "s": 2887, "text": "Start loop FOR from 0 till the length of an array" }, { "code": null, "e": 3008, "s": 2937, "text": "Inside the loop, check IF arr[i] % k = 0 then increment the count by 1" }, { "code": null, "e": 3079, "s": 3008, "text": "Inside the loop, check IF arr[i] % k = 0 then increment the count by 1" }, { "code": null, "e": 3096, "s": 3079, "text": "Return the count" }, { "code": null, "e": 3113, "s": 3096, "text": "Return the count" }, { "code": null, "e": 3131, "s": 3113, "text": "Print the result." }, { "code": null, "e": 3149, "s": 3131, "text": "Print the result." }, { "code": null, "e": 3224, "s": 3149, "text": "Input elements in a vector of integer type and take an integer variable k." }, { "code": null, "e": 3299, "s": 3224, "text": "Input elements in a vector of integer type and take an integer variable k." }, { "code": null, "e": 3377, "s": 3299, "text": "Take a temporary variable count to store the count of elements divisible by k" }, { "code": null, "e": 3455, "s": 3377, "text": "Take a temporary variable count to store the count of elements divisible by k" }, { "code": null, "e": 3620, "s": 3455, "text": "Set the count as the call to an inbuilt count_if() function that will take vector.begin(), vector.end() as an argument and start the traversal then return i%k if 0." }, { "code": null, "e": 3785, "s": 3620, "text": "Set the count as the call to an inbuilt count_if() function that will take vector.begin(), vector.end() as an argument and start the traversal then return i%k if 0." }, { "code": null, "e": 3803, "s": 3785, "text": "Print the result." }, { "code": null, "e": 3821, "s": 3803, "text": "Print the result." }, { "code": null, "e": 3832, "s": 3821, "text": " Live Demo" }, { "code": null, "e": 4290, "s": 3832, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint divisible_k(int arr[], int size, int k){\n int count = 0;\n for(int i = 0; i<size; i++){\n if(arr[i]%k==0){\n count++;\n }\n }\n return count;\n}\nint main(){\n int arr[] = {4, 2, 6, 1, 3, 8, 10, 9};\n int k = 2;\n int size = sizeof(arr) / sizeof(arr[0]);\n cout<<\"Count the number of elements in an array which are divisible by \"<<k<<\" are: \"<<divisible_k(arr, size, k);\n return 0;\n}" }, { "code": null, "e": 4355, "s": 4290, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 4428, "s": 4355, "text": "Count the number of elements in an array which are divisible by 2 are: 5" }, { "code": null, "e": 4439, "s": 4428, "text": " Live Demo" }, { "code": null, "e": 4745, "s": 4439, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n vector<int> vec = {4, 2, 6, 1, 3, 8, 10, 9};\n int count = count_if(vec.begin(), vec.end(), [](int i, int k = 2) { return i % k == 0; });\n cout<<\"Count the number of elements in an array which are divisible by k are: \"<<count;\n return 0;\n}" }, { "code": null, "e": 4810, "s": 4745, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 4883, "s": 4810, "text": "Count the number of elements in an array which are divisible by 2 are: 5" } ]
Reading from and Writing to Text Files
The StreamReader and StreamWriter classes are used for reading from and writing data to text files. These classes inherit from the abstract base class Stream, which supports reading and writing bytes into a file stream. The StreamReader class also inherits from the abstract base class TextReader that represents a reader for reading series of characters. The following table describes some of the commonly used methods of the StreamReader class − Public Overrides Sub Close It closes the StreamReader object and the underlying stream and releases any system resources associated with the reader. Public Overrides Function Peek As Integer Returns the next available character but does not consume it. Public Overrides Function Read As Integer Reads the next character from the input stream and advances the character position by one character. The following example demonstrates reading a text file named Jamaica.txt. The file reads − Down the way where the nights are gay And the sun shines daily on the mountain top I took a trip on a sailing ship And when I reached Jamaica I made a stop Imports System.IO Module fileProg Sub Main() Try ' Create an instance of StreamReader to read from a file. ' The using statement also closes the StreamReader. Using sr As StreamReader = New StreamReader("e:/jamaica.txt") Dim line As String ' Read and display lines from the file until the end of ' the file is reached. line = sr.ReadLine() While (line <> Nothing) Console.WriteLine(line) line = sr.ReadLine() End While End Using Catch e As Exception ' Let the user know what went wrong. Console.WriteLine("The file could not be read:") Console.WriteLine(e.Message) End Try Console.ReadKey() End Sub End Module Guess what it displays when you compile and run the program! The StreamWriter class inherits from the abstract class TextWriter that represents a writer, which can write a series of character. The following table shows some of the most commonly used methods of this class − Public Overrides Sub Close Closes the current StreamWriter object and the underlying stream. Public Overrides Sub Flush Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream. Public Overridable Sub Write (value As Boolean) Writes the text representation of a Boolean value to the text string or stream. (Inherited from TextWriter.) Public Overrides Sub Write (value As Char) Writes a character to the stream. Public Overridable Sub Write (value As Decimal) Writes the text representation of a decimal value to the text string or stream. Public Overridable Sub Write (value As Double) Writes the text representation of an 8-byte floating-point value to the text string or stream. Public Overridable Sub Write (value As Integer) Writes the text representation of a 4-byte signed integer to the text string or stream. Public Overrides Sub Write (value As String) Writes a string to the stream. Public Overridable Sub WriteLine Writes a line terminator to the text string or stream. The above list is not exhaustive. For complete list of methods please visit Microsoft's documentation The following example demonstrates writing text data into a file using the StreamWriter class − Imports System.IO Module fileProg Sub Main() Dim names As String() = New String() {"Zara Ali", _ "Nuha Ali", "Amir Sohel", "M Amlan"} Dim s As String Using sw As StreamWriter = New StreamWriter("names.txt") For Each s In names sw.WriteLine(s) Next s End Using ' Read and show each line from the file. Dim line As String Using sr As StreamReader = New StreamReader("names.txt") line = sr.ReadLine() While (line <> Nothing) Console.WriteLine(line) line = sr.ReadLine() End While End Using Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − Zara Ali Nuha Ali Amir Sohel M Amlan 63 Lectures 4 hours Frahaan Hussain 103 Lectures 12 hours Arnold Higuit 60 Lectures 9.5 hours Arnold Higuit 97 Lectures 9 hours Arnold Higuit Print Add Notes Bookmark this page
[ { "code": null, "e": 2520, "s": 2300, "text": "The StreamReader and StreamWriter classes are used for reading from and writing data to text files. These classes inherit from the abstract base class Stream, which supports reading and writing bytes into a file stream." }, { "code": null, "e": 2748, "s": 2520, "text": "The StreamReader class also inherits from the abstract base class TextReader that represents a reader for reading series of characters. The following table describes some of the commonly used methods of the StreamReader class −" }, { "code": null, "e": 2775, "s": 2748, "text": "Public Overrides Sub Close" }, { "code": null, "e": 2897, "s": 2775, "text": "It closes the StreamReader object and the underlying stream and releases any system resources associated with the reader." }, { "code": null, "e": 2939, "s": 2897, "text": "Public Overrides Function Peek As Integer" }, { "code": null, "e": 3001, "s": 2939, "text": "Returns the next available character but does not consume it." }, { "code": null, "e": 3043, "s": 3001, "text": "Public Overrides Function Read As Integer" }, { "code": null, "e": 3144, "s": 3043, "text": "Reads the next character from the input stream and advances the character position by one character." }, { "code": null, "e": 3235, "s": 3144, "text": "The following example demonstrates reading a text file named Jamaica.txt. The file reads −" }, { "code": null, "e": 3391, "s": 3235, "text": "Down the way where the nights are gay\nAnd the sun shines daily on the mountain top\nI took a trip on a sailing ship\nAnd when I reached Jamaica\nI made a stop" }, { "code": null, "e": 4201, "s": 3391, "text": "Imports System.IO\nModule fileProg\n Sub Main()\n Try\n ' Create an instance of StreamReader to read from a file. \n ' The using statement also closes the StreamReader. \n Using sr As StreamReader = New StreamReader(\"e:/jamaica.txt\")\n Dim line As String\n ' Read and display lines from the file until the end of \n ' the file is reached. \n line = sr.ReadLine()\n While (line <> Nothing)\n Console.WriteLine(line)\n line = sr.ReadLine()\n End While\n End Using\n Catch e As Exception\n ' Let the user know what went wrong.\n Console.WriteLine(\"The file could not be read:\")\n Console.WriteLine(e.Message)\n End Try\n Console.ReadKey()\n End Sub\nEnd Module" }, { "code": null, "e": 4262, "s": 4201, "text": "Guess what it displays when you compile and run the program!" }, { "code": null, "e": 4394, "s": 4262, "text": "The StreamWriter class inherits from the abstract class TextWriter that represents a writer, which can write a series of character." }, { "code": null, "e": 4475, "s": 4394, "text": "The following table shows some of the most commonly used methods of this class −" }, { "code": null, "e": 4502, "s": 4475, "text": "Public Overrides Sub Close" }, { "code": null, "e": 4568, "s": 4502, "text": "Closes the current StreamWriter object and the underlying stream." }, { "code": null, "e": 4595, "s": 4568, "text": "Public Overrides Sub Flush" }, { "code": null, "e": 4706, "s": 4595, "text": "Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream." }, { "code": null, "e": 4754, "s": 4706, "text": "Public Overridable Sub Write (value As Boolean)" }, { "code": null, "e": 4863, "s": 4754, "text": "Writes the text representation of a Boolean value to the text string or stream. (Inherited from TextWriter.)" }, { "code": null, "e": 4906, "s": 4863, "text": "Public Overrides Sub Write (value As Char)" }, { "code": null, "e": 4940, "s": 4906, "text": "Writes a character to the stream." }, { "code": null, "e": 4988, "s": 4940, "text": "Public Overridable Sub Write (value As Decimal)" }, { "code": null, "e": 5068, "s": 4988, "text": "Writes the text representation of a decimal value to the text string or stream." }, { "code": null, "e": 5115, "s": 5068, "text": "Public Overridable Sub Write (value As Double)" }, { "code": null, "e": 5210, "s": 5115, "text": "Writes the text representation of an 8-byte floating-point value to the text string or stream." }, { "code": null, "e": 5258, "s": 5210, "text": "Public Overridable Sub Write (value As Integer)" }, { "code": null, "e": 5346, "s": 5258, "text": "Writes the text representation of a 4-byte signed integer to the text string or stream." }, { "code": null, "e": 5391, "s": 5346, "text": "Public Overrides Sub Write (value As String)" }, { "code": null, "e": 5422, "s": 5391, "text": "Writes a string to the stream." }, { "code": null, "e": 5455, "s": 5422, "text": "Public Overridable Sub WriteLine" }, { "code": null, "e": 5510, "s": 5455, "text": "Writes a line terminator to the text string or stream." }, { "code": null, "e": 5612, "s": 5510, "text": "The above list is not exhaustive. For complete list of methods please visit Microsoft's documentation" }, { "code": null, "e": 5708, "s": 5612, "text": "The following example demonstrates writing text data into a file using the StreamWriter class −" }, { "code": null, "e": 6383, "s": 5708, "text": "Imports System.IO\nModule fileProg\n Sub Main()\n Dim names As String() = New String() {\"Zara Ali\", _\n \"Nuha Ali\", \"Amir Sohel\", \"M Amlan\"}\n Dim s As String\n Using sw As StreamWriter = New StreamWriter(\"names.txt\")\n For Each s In names\n sw.WriteLine(s)\n Next s\n End Using\n ' Read and show each line from the file. \n Dim line As String\n Using sr As StreamReader = New StreamReader(\"names.txt\")\n line = sr.ReadLine()\n While (line <> Nothing)\n Console.WriteLine(line)\n line = sr.ReadLine()\n End While\n End Using\n Console.ReadKey()\n End Sub\nEnd Module" }, { "code": null, "e": 6464, "s": 6383, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 6503, "s": 6464, "text": "Zara Ali\nNuha Ali\nAmir Sohel\nM Amlan \n" }, { "code": null, "e": 6536, "s": 6503, "text": "\n 63 Lectures \n 4 hours \n" }, { "code": null, "e": 6553, "s": 6536, "text": " Frahaan Hussain" }, { "code": null, "e": 6588, "s": 6553, "text": "\n 103 Lectures \n 12 hours \n" }, { "code": null, "e": 6603, "s": 6588, "text": " Arnold Higuit" }, { "code": null, "e": 6638, "s": 6603, "text": "\n 60 Lectures \n 9.5 hours \n" }, { "code": null, "e": 6653, "s": 6638, "text": " Arnold Higuit" }, { "code": null, "e": 6686, "s": 6653, "text": "\n 97 Lectures \n 9 hours \n" }, { "code": null, "e": 6701, "s": 6686, "text": " Arnold Higuit" }, { "code": null, "e": 6708, "s": 6701, "text": " Print" }, { "code": null, "e": 6719, "s": 6708, "text": " Add Notes" } ]
Compare two arrays of single characters and return the difference? JavaScript
We are required to compare, and get the difference, between two arrays containing single character strings appearing multiple times in each array. Example of two such arrays are − const arr1 = ['A', 'C', 'A', 'D']; const arr2 = ['F', 'A', 'T', 'T']; We will check each character at the same position and return only the parts who are different. const arr1 = ['A', 'C', 'A', 'D']; const arr2 = ['F', 'A', 'T', 'T']; const findDifference = (arr1, arr2) => { const min = Math.min(arr1.length, arr2.length); let i = 0; const res = []; while (i < min) { if (arr1[i] !== arr2[i]) { res.push(arr1[i], arr2[i]); }; ++i; }; return res.concat(arr1.slice(min), arr2.slice(min)); }; console.log(findDifference(arr1, arr2)); And the output in the console will be − [ 'A', 'F', 'C', 'A', 'A', 'T', 'D', 'T' ]
[ { "code": null, "e": 1209, "s": 1062, "text": "We are required to compare, and get the difference, between two arrays containing single character strings appearing multiple times in each array." }, { "code": null, "e": 1242, "s": 1209, "text": "Example of two such arrays are −" }, { "code": null, "e": 1312, "s": 1242, "text": "const arr1 = ['A', 'C', 'A', 'D'];\nconst arr2 = ['F', 'A', 'T', 'T'];" }, { "code": null, "e": 1407, "s": 1312, "text": "We will check each character at the same position and return only the parts who are different." }, { "code": null, "e": 1819, "s": 1407, "text": "const arr1 = ['A', 'C', 'A', 'D'];\nconst arr2 = ['F', 'A', 'T', 'T'];\nconst findDifference = (arr1, arr2) => {\n const min = Math.min(arr1.length, arr2.length);\n let i = 0;\n const res = [];\n while (i < min) {\n if (arr1[i] !== arr2[i]) {\n res.push(arr1[i], arr2[i]);\n };\n ++i;\n };\n return res.concat(arr1.slice(min), arr2.slice(min));\n};\nconsole.log(findDifference(arr1, arr2));" }, { "code": null, "e": 1859, "s": 1819, "text": "And the output in the console will be −" }, { "code": null, "e": 1911, "s": 1859, "text": "[\n 'A', 'F', 'C',\n 'A', 'A', 'T',\n 'D', 'T'\n]" } ]
How to only get the data of the nested JSON object in MongoDB?
To get the data of the nested JSON object in MongoDB, use findOne(). Let us create a collection with documents − > db.demo109.insertOne( ... { ... "Name" : "Chris", ... "Subjects" : [ ... { ... "Id" : "100", ... "Name":"MySQL", ... "InstructorDetails" : [ ... { ... "Name" : "John" ... } ... ] ... }, ... { ... "Id" : "101", ... "Name":"MongoDB", ... "InstructorDetails" : [ ... { ... "Name" : "Mike" ... } ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2ee7df9fd5fd66da21447a") } Display all documents from a collection with the help of find() method − > db.demo109.find(); This will produce the following output − { "_id" : ObjectId("5e2ee7df9fd5fd66da21447a"), "Name" : "Chris", "Subjects" : [ { "Id" : "100", "Name" : "MySQL", "InstructorDetails" : [ { "Name" : "John" } ] }, { "Id" : "101", "Name" : "MongoDB", "InstructorDetails" : [ { "Name" : "Mike" } ] } ] } Following is the query to only get the data of the nested JSON object in MongoDB − > db.demo109.findOne( ... { Name: "Chris"} ... , { 'Subjects': { $elemMatch:{'Id':"100"} } } ... , function (err, doc) { console.log(doc) }); This will produce the following output − { "_id" : ObjectId("5e2ee7df9fd5fd66da21447a"), "Subjects" : [ { "Id" : "100", "Name" : "MySQL", "InstructorDetails" : [ { "Name" : "John" } ] } ] }
[ { "code": null, "e": 1175, "s": 1062, "text": "To get the data of the nested JSON object in MongoDB, use findOne(). Let us create a collection with documents −" }, { "code": null, "e": 1837, "s": 1175, "text": "> db.demo109.insertOne(\n... {\n... \"Name\" : \"Chris\",\n... \"Subjects\" : [\n... {\n... \"Id\" : \"100\",\n... \"Name\":\"MySQL\",\n... \"InstructorDetails\" : [\n... {\n... \"Name\" : \"John\"\n... }\n... ]\n... },\n... {\n... \"Id\" : \"101\",\n... \"Name\":\"MongoDB\",\n... \"InstructorDetails\" : [\n... {\n... \"Name\" : \"Mike\"\n... }\n... ]\n... }\n... ]\n... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e2ee7df9fd5fd66da21447a\")\n}" }, { "code": null, "e": 1910, "s": 1837, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1931, "s": 1910, "text": "> db.demo109.find();" }, { "code": null, "e": 1972, "s": 1931, "text": "This will produce the following output −" }, { "code": null, "e": 2243, "s": 1972, "text": "{\n \"_id\" : ObjectId(\"5e2ee7df9fd5fd66da21447a\"), \"Name\" : \"Chris\", \"Subjects\" : [\n { \"Id\" : \"100\", \"Name\" : \"MySQL\", \"InstructorDetails\" : [ { \"Name\" : \"John\" } ] },\n { \"Id\" : \"101\", \"Name\" : \"MongoDB\", \"InstructorDetails\" : [ { \"Name\" : \"Mike\" } ] }\n ] \n}" }, { "code": null, "e": 2326, "s": 2243, "text": "Following is the query to only get the data of the nested JSON object in MongoDB −" }, { "code": null, "e": 2468, "s": 2326, "text": "> db.demo109.findOne(\n... { Name: \"Chris\"}\n... , { 'Subjects': { $elemMatch:{'Id':\"100\"} } }\n... , function (err, doc) { console.log(doc) });" }, { "code": null, "e": 2509, "s": 2468, "text": "This will produce the following output −" }, { "code": null, "e": 2754, "s": 2509, "text": "{\n \"_id\" : ObjectId(\"5e2ee7df9fd5fd66da21447a\"),\n \"Subjects\" : [\n {\n \"Id\" : \"100\",\n \"Name\" : \"MySQL\",\n \"InstructorDetails\" : [\n {\n \"Name\" : \"John\"\n }\n ]\n }\n ]\n}" } ]
JavaScript to check consecutive numbers in array?
To check for consecutive numbers like 100, 101, 102, etc., use the concept of reduce(). TRUE would be returned for consecutive numbers, else false is the return value. const sequceIsConsecutive = (obj) => Boolean(obj.reduce((output, lastest) => (output ? (Number(output.number) + 1=== Number(lastest.number) ? lastest : false) : false))); console.log("Is Consecutive="+sequceIsConsecutive ([{ number: '100' },{number: '101'} ,{number: '102' }])); console.log("Is Consecutive="+sequceIsConsecutive([{ number: '100' }, {number: '102'} ,{number: '104' }])); To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo126.js. This will produce the following output − PS C:\Users\Amit\JavaScript-code> node demo126.js Is Consecutive=true Is Consecutive=false
[ { "code": null, "e": 1230, "s": 1062, "text": "To check for consecutive numbers like 100, 101, 102, etc., use the concept of reduce(). TRUE\nwould be returned for consecutive numbers, else false is the return value." }, { "code": null, "e": 1617, "s": 1230, "text": "const sequceIsConsecutive = (obj) =>\nBoolean(obj.reduce((output, lastest) => (output ?\n(Number(output.number) + 1=== Number(lastest.number) ? lastest : false)\n: false)));\nconsole.log(\"Is Consecutive=\"+sequceIsConsecutive ([{ number: '100'\n},{number: '101'} ,{number: '102' }]));\nconsole.log(\"Is Consecutive=\"+sequceIsConsecutive([{ number: '100' },\n{number: '102'} ,{number: '104' }]));" }, { "code": null, "e": 1683, "s": 1617, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 1701, "s": 1683, "text": "node fileName.js." }, { "code": null, "e": 1735, "s": 1701, "text": "Here, my file name is demo126.js." }, { "code": null, "e": 1776, "s": 1735, "text": "This will produce the following output −" }, { "code": null, "e": 1867, "s": 1776, "text": "PS C:\\Users\\Amit\\JavaScript-code> node demo126.js\nIs Consecutive=true\nIs Consecutive=false" } ]
How to disable copy/paste from/to EditText in Android App?
This example demonstrates how do I disable copy/paste from/to editText in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="8dp" tools:context=".MainActivity"> <TextView android:layout_marginTop="40dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="22sp" android:textStyle="bold" android:layout_centerHorizontal="true" android:text=" Cut/copy/paste is Disabled" /> <EditText android:layout_centerInParent="true" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/editText"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.ActionMode; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; public class MainActivity extends AppCompatActivity { EditText editText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = findViewById(R.id.editText); editText.setCustomSelectionActionModeCallback(new ActionMode.Callback() { public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } public void onDestroyActionMode(ActionMode mode) { } public boolean onCreateActionMode(ActionMode mode, Menu menu) { return false; } public boolean onActionItemClicked(ActionMode mode, MenuItem item) { return false; } }); } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1145, "s": 1062, "text": "This example demonstrates how do I disable copy/paste from/to editText in android." }, { "code": null, "e": 1274, "s": 1145, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1339, "s": 1274, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2129, "s": 1339, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"8dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_marginTop=\"40dp\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:textSize=\"22sp\"\n android:textStyle=\"bold\"\n android:layout_centerHorizontal=\"true\"\n android:text=\" Cut/copy/paste is Disabled\" />\n <EditText\n android:layout_centerInParent=\"true\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/editText\"/>\n</RelativeLayout>" }, { "code": null, "e": 2186, "s": 2129, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3164, "s": 2186, "text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.ActionMode;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.widget.EditText;\npublic class MainActivity extends AppCompatActivity {\n EditText editText;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n editText = findViewById(R.id.editText);\n editText.setCustomSelectionActionModeCallback(new ActionMode.Callback() {\n public boolean onPrepareActionMode(ActionMode mode, Menu menu) {\n return false;\n }\n public void onDestroyActionMode(ActionMode mode) {\n }\n public boolean onCreateActionMode(ActionMode mode, Menu menu) {\n return false;\n }\n public boolean onActionItemClicked(ActionMode mode, MenuItem item) {\n return false;\n }\n });\n }\n}" }, { "code": null, "e": 3219, "s": 3164, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3907, "s": 3219, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4258, "s": 3907, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 4299, "s": 4258, "text": "Click here to download the project code." } ]
Longest Increasing Subsequence in Python
Suppose we have an unsorted list of integers. We have to find the longest increasing subsequence. So if the input is [10,9,2,5,3,7,101,18], then the output will be 4, as the increasing subsequence is [2,3,7,101] To solve this, we will follow these steps − trail := an array of length 0 to length of nums – 1, and fill this with 0 size := 0 for x in numsi := 0, j := sizewhile i is not jmid := i + (j - i) / 2if trails[mid] < x, then i := mid + 1, otherwise j := midtrails[i] := xsize := maximum of i + 1 and size i := 0, j := size while i is not jmid := i + (j - i) / 2if trails[mid] < x, then i := mid + 1, otherwise j := mid mid := i + (j - i) / 2 if trails[mid] < x, then i := mid + 1, otherwise j := mid trails[i] := x size := maximum of i + 1 and size return size Let us see the following implementation to get better understanding − Live Demo class Solution(object): def lengthOfLIS(self, nums): tails =[0 for i in range(len(nums))] size = 0 for x in nums: i=0 j=size while i!=j: mid = i + (j-i)//2 if tails[mid]< x: i= mid+1 else: j = mid tails[i] = x size = max(i+1,size) #print(tails) return size ob1 = Solution() print(ob1.lengthOfLIS([10,9,2,5,3,7,101,18])) [10,9,2,5,3,7,101,18] 4
[ { "code": null, "e": 1274, "s": 1062, "text": "Suppose we have an unsorted list of integers. We have to find the longest increasing subsequence. So if the input is [10,9,2,5,3,7,101,18], then the output will be 4, as the increasing subsequence is [2,3,7,101]" }, { "code": null, "e": 1318, "s": 1274, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1392, "s": 1318, "text": "trail := an array of length 0 to length of nums – 1, and fill this with 0" }, { "code": null, "e": 1402, "s": 1392, "text": "size := 0" }, { "code": null, "e": 1575, "s": 1402, "text": "for x in numsi := 0, j := sizewhile i is not jmid := i + (j - i) / 2if trails[mid] < x, then i := mid + 1, otherwise j := midtrails[i] := xsize := maximum of i + 1 and size" }, { "code": null, "e": 1593, "s": 1575, "text": "i := 0, j := size" }, { "code": null, "e": 1689, "s": 1593, "text": "while i is not jmid := i + (j - i) / 2if trails[mid] < x, then i := mid + 1, otherwise j := mid" }, { "code": null, "e": 1712, "s": 1689, "text": "mid := i + (j - i) / 2" }, { "code": null, "e": 1770, "s": 1712, "text": "if trails[mid] < x, then i := mid + 1, otherwise j := mid" }, { "code": null, "e": 1785, "s": 1770, "text": "trails[i] := x" }, { "code": null, "e": 1819, "s": 1785, "text": "size := maximum of i + 1 and size" }, { "code": null, "e": 1831, "s": 1819, "text": "return size" }, { "code": null, "e": 1901, "s": 1831, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1912, "s": 1901, "text": " Live Demo" }, { "code": null, "e": 2397, "s": 1912, "text": "class Solution(object):\n def lengthOfLIS(self, nums):\n tails =[0 for i in range(len(nums))]\n size = 0\n for x in nums:\n i=0\n j=size\n while i!=j:\n mid = i + (j-i)//2\n if tails[mid]< x:\n i= mid+1\n else:\n j = mid\n tails[i] = x\n size = max(i+1,size)\n #print(tails)\n return size\nob1 = Solution()\nprint(ob1.lengthOfLIS([10,9,2,5,3,7,101,18]))" }, { "code": null, "e": 2419, "s": 2397, "text": "[10,9,2,5,3,7,101,18]" }, { "code": null, "e": 2421, "s": 2419, "text": "4" } ]
MySQL stored-procedure: out parameter?
Here is a stored procedure that takes one parameter for input (IN) and second parameter for output (OUT) mysql> delimiter // mysql> create procedure Sp_SQRT(IN Number1 INT, OUT Number2 FLOAT) -> Begin -> set Number2=sqrt(Number1); -> end; -> // Query OK, 0 rows affected (0.24 sec) mysql> delimiter ; Call the stored procedure and send the value to the user variable. The syntax is as follows CALL yourStoredProcedureName(anyIntegerValue,@anyVariableName); Check what value is stored in the variable @anyVariableName. The syntax is as follows SELECT @anyVariableName; Created the stored procedure with the name ‘Sp_SQRT’. The query is as follows to call the stored procedure mysql> call Sp_SQRT(36,@MySquareRootNumber); Query OK, 0 rows affected (0.02 sec) Check the value of variable @MySquareRootNumber using select statement mysql> select @MySquareRootNumber; The following is the output +---------------------+ | @MySquareRootNumber | +---------------------+ | 6 | +---------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1167, "s": 1062, "text": "Here is a stored procedure that takes one parameter for input (IN) and second parameter for output (OUT)" }, { "code": null, "e": 1375, "s": 1167, "text": "mysql> delimiter //\nmysql> create procedure Sp_SQRT(IN Number1 INT, OUT Number2 FLOAT)\n -> Begin\n -> set Number2=sqrt(Number1);\n -> end;\n -> //\nQuery OK, 0 rows affected (0.24 sec)\nmysql> delimiter ;" }, { "code": null, "e": 1467, "s": 1375, "text": "Call the stored procedure and send the value to the user variable. The syntax is as follows" }, { "code": null, "e": 1531, "s": 1467, "text": "CALL yourStoredProcedureName(anyIntegerValue,@anyVariableName);" }, { "code": null, "e": 1617, "s": 1531, "text": "Check what value is stored in the variable @anyVariableName. The syntax is as follows" }, { "code": null, "e": 1642, "s": 1617, "text": "SELECT @anyVariableName;" }, { "code": null, "e": 1749, "s": 1642, "text": "Created the stored procedure with the name ‘Sp_SQRT’. The query is as follows to call the stored procedure" }, { "code": null, "e": 1831, "s": 1749, "text": "mysql> call Sp_SQRT(36,@MySquareRootNumber);\nQuery OK, 0 rows affected (0.02 sec)" }, { "code": null, "e": 1902, "s": 1831, "text": "Check the value of variable @MySquareRootNumber using select statement" }, { "code": null, "e": 1937, "s": 1902, "text": "mysql> select @MySquareRootNumber;" }, { "code": null, "e": 1965, "s": 1937, "text": "The following is the output" }, { "code": null, "e": 2109, "s": 1965, "text": "+---------------------+\n| @MySquareRootNumber |\n+---------------------+\n| 6 |\n+---------------------+\n1 row in set (0.00 sec)" } ]
Reshaping DataFrames in Pandas. Your ultimate guide to reshaping... | by Anirudh Nanduri | Towards Data Science
Your ultimate guide to reshaping DataFrames in python Pandas is easily one of the most used packages in python. This might not come as surprise to most of the folks reading this article. Many people use pandas to do different kinds on analysis on their data and much more. However, in certain situations we would want to reshape or visualize data in a different format than it was initially provided. This might be due to various reasons. It might be because one finds a different representation easier to understand. It might also be because you want to have a certain format to run your code. Whatever the reason might be, reshaping dataframes can be considered as a common task that most of us do in our journey as data scientists/analysts. This article would give a brief introduction on some useful functions which can be used to reshape a pandas dataframe. I like to think of reshaping functions in two types. First type of functions simple reform the existing dataframe. For example, they change columns to rows and rows to columns. The second type of functions would aggregate the information along with reforming them. In most of the real world cases, we would be using the second type of functions as it would give us a peek into the higher level summaries or aggregation as needed. Reforming without aggregation can and should ideally be applied on data where there is a unique combination of selections being made. Otherwise, there is a good chance that they would throw an error for certain functions. To explain the reforming without aggregation, we would first declare a dataframe. The declaration and the dataframe would be as follows: np.random.seed(100) df=pd.DataFrame({"Date":pd.Index(pd.date_range(start='2/2/2019',periods=3)).repeat(3), "Class":["1A","2B","3C","1A","2B","3C","1A","2B","3C"], "Numbers":np.random.randn(9)}) df['Numbers2'] = df['Numbers'] * 2 df Using this dataframe, we would look at some functions which are useful for reforming/reshaping. Pivot method is typically used to create a pivot style view of data where the users can specify rows (in python it is called index) and columns. These two parameters would give a structure to the view whereas the information to be populated would be from the data that is being used to create pivot. The information can also be selectively populated by using values parameter. Let us now look at some examples to understand it better. df.pivot(index='Date', columns='Class', values='Numbers') As we can see from above, once index, columns, values are specified the structure for a new pivot style dataframe is formed and is filled with information unique to the combination of index, column pair accordingly. It is to be remembered that index and columns parameters are suggested to be filled always as it would determine the structure of final dataframe/view. Let us look at what would happen if we do not declare values parameter. df.pivot(index='Date', columns='Class') If we do not specify values parameter, pandas would create all the various possible views while taking all column names apart from what were specified as index and columns as above. Hence, for a big dataset having multiple columns, it is suggested to specify value parameter as well. There is, however, another way to extract information about one column using the above code and tweaking it a little. It would be as follows. df.pivot(index='Date', columns='Class')['Numbers'] If we mention the column name as given above while not specifying the values parameter, the resultant output would be the same. Only downside to this would be that it would take longer time to execute it. It is to be noted that the column name declaration is similar to syntax for sub-setting the dataframe. That is because we are exactly doing that. Using above code, pandas first gets the result for all columns, then using the column name/s specified in the brackets, pandas subsets the dataframe and displays it. This is also why the execution time for this method is longer than the one where we use values parameter. Note: While using pivot function, in case the combination of row*column has multiple entries the function would throw an error as pivot would not do any sort of aggregation. Melt is a function which is used to convert columns to rows. That means that this function is useful for when the users would like to bring one or more columns information into rows. This function would create two new columns by removing all other columns apart from the ones mentioned in its id_vars parameter and displays the column name in one column and its value in another column. Let us have a look at an example to understand it better. df.melt(id_vars=['Date','Class']) In the dataframe df, we have four columns of which in id_vars parameter Date and Class were mentioned. This would leave us with columns Numbers and Number2. As we can see above, the function created two new columns called variable and value and populated them with column name and the unique value for the combination of Date+class+column name while removing columns Numbers and Numbers2. In case only specific columns are to be converted in this way and not all, then the parameter value_vars would help us achieve this. df.melt(id_vars=['Date','Class'], value_vars=['Numbers']) As we can see, when specific column names are mentioned in value_vars parameter only that columns information would be melted as needed. There are two additional parameters value_name and var_name which would rename the columns value and variable by the string mentioned in the parameters. Let us have a look at an example to understand this better. df.melt(id_vars=['Date','Class'], value_vars=['Numbers'], value_name="Numbers_Value", var_name="Num_Var") As we can see, the columns are renamed to the ones specified in the parameters as expected. Stack and Unstack perform columns to rows and rows to columns operations respectively. Both these functions are definitely one of the less used functions of reshaping in pandas as one would use pivot to achieve the result they want most of the time and hence it would not be needed. We will still look into them to understand how they work as they might be useful in some specific scenarios. The main different between stack and melt would be that stack requires id_vars to be set as index instead of having to pass them as parameters separately. Let us have a look at stack to understand what it does. df.set_index(["Date","Class"]).stack() As we can observe, it has the same functionality of melt where it brings columns to rows. Unstack on the other hand does the opposite of stack. It brings rows to columns and like stack, it needs index to function as expected. df.set_index(["Date","Class"]).stack().unstack() As we can see, unstack if no input provided would basically undo the stacking operation. The output will differ when changing the number input inside the brackets of unstack. This would be a good topic to explore if one is interested about the topic. Unlike the type-1 functions, type-2 functions give an aggregated view of information. These will be very useful in case the users would like to have some type of summary around the data. We will be using the same dataframe that we used for Type -1 functions to look into type -2 functions as well. To explain the reforming without aggregation, we would first declare a dataframe. The declaration and the dataframe would be as follows: Using this dataframe, we would look at some functions which are useful for reforming/reshaping. Group by is the function that I use the more often than any other function mentioned in this article. This is because, it is very intuitive to use and has very useful parameters that can help one to view different aggregations for different columns. Let us look into a simple group by statement. df.groupby('Date')["Numbers"].mean() In group by statement, we specify the column/columns that we need to group the data on inside the first parenthesis. Here, we can either give a single string or a list of strings pertaining to column names as well. The next parenthesis is to specify the data to aggregate, and finally we call the method using which the aggregation should happen. In above example, we are aggregating column Numbers on Date using mean aggregation. Notice that the output is not a dataframe but looks similar to a pandas series. To convert it into a dataframe, we can use reset_index method, or we can also use a parameter available in group by statement. I will be using the latter. df.groupby('Date', as_index=False)["Numbers"].mean() As mentioned in the above image, as_index parameter can be used to convert the result of group by into a dataframe. Let us have a look at one more example where we aggregate columns on multiple columns using a single method. df.groupby(['Date','Class'], as_index=False)["Numbers"].mean() As we can see above, we can aggregate multiple columns on multiple columns using a list of strings (column names) instead of specifying a single string (column name). However, we can also use different aggregation functions for different columns. Let’s have a look at the example below to understand how that can be done. df.groupby(['Date'], as_index=False).aggregate({"Numbers":"sum", "Numbers2":"mean"}) In the above image we are aggregating Numbers column on Date column with the sum function and similarly we are aggregating Numbers2 column on Date column with mean function. Pivot Table functions in the same way that pivots do. However, pivot table has one additional and significant argument/parameter which specifies the aggregation function we will be using to aggregate the data. Let us look at the below example to understand it better. Let us start with a simple pivot table. df.pivot_table(index="Date", columns="Class") Notice the method call for pivot table is pivot_table which is different from that of pivot which was pivot. If the aggregation function is not specified, the default function mean would be used to aggregate the information. df.pivot_table(index="Date", columns="Class", aggfunc="sum") However, if the user wants to specify a particular function, they can do so in the parameter aggfunc as shown in the above image. The last function in this article would be crosstab. This function by default would give the count or frequency of occurrence between values of two different columns. Let us look at an example. pd.crosstab(df.Date, df.Class) The view above means that there are two different entries are available in combination of 1A class and 2019–02–02 Date. Similarly, the other information can be interpreted. In case instead of frequency of occurrence, if the user wants to have some other aggregation function aggfunc parameter can be used. pd.crosstab(df.Date, df.Class, values=df.Numbers, aggfunc='sum') pd.crosstab(df.Date, df.Class, values=df.Numbers, aggfunc='mean') Above images give a sense of how it can be used. Even though the output may look similar to that of pivot tables, the way it is achieved is different. But more often than not people prefer using pivot tables over crosstab function. We have looked at multiple functions in this article and have understood various parameters and their usage. All said and done, everyone knows that practice makes man perfect. This saying applies to technical stuff too right? To make it easier for you to practice multiple concepts we discussed in this article I have gone ahead and created a Jupiter notebook that you can download here. Good time practicing!!! Please do feel free to reach out to me here in case of any query, constructive criticism, and any feedback.
[ { "code": null, "e": 226, "s": 172, "text": "Your ultimate guide to reshaping DataFrames in python" }, { "code": null, "e": 1035, "s": 226, "text": "Pandas is easily one of the most used packages in python. This might not come as surprise to most of the folks reading this article. Many people use pandas to do different kinds on analysis on their data and much more. However, in certain situations we would want to reshape or visualize data in a different format than it was initially provided. This might be due to various reasons. It might be because one finds a different representation easier to understand. It might also be because you want to have a certain format to run your code. Whatever the reason might be, reshaping dataframes can be considered as a common task that most of us do in our journey as data scientists/analysts. This article would give a brief introduction on some useful functions which can be used to reshape a pandas dataframe." }, { "code": null, "e": 1465, "s": 1035, "text": "I like to think of reshaping functions in two types. First type of functions simple reform the existing dataframe. For example, they change columns to rows and rows to columns. The second type of functions would aggregate the information along with reforming them. In most of the real world cases, we would be using the second type of functions as it would give us a peek into the higher level summaries or aggregation as needed." }, { "code": null, "e": 1687, "s": 1465, "text": "Reforming without aggregation can and should ideally be applied on data where there is a unique combination of selections being made. Otherwise, there is a good chance that they would throw an error for certain functions." }, { "code": null, "e": 1824, "s": 1687, "text": "To explain the reforming without aggregation, we would first declare a dataframe. The declaration and the dataframe would be as follows:" }, { "code": null, "e": 1844, "s": 1824, "text": "np.random.seed(100)" }, { "code": null, "e": 2018, "s": 1844, "text": "df=pd.DataFrame({\"Date\":pd.Index(pd.date_range(start='2/2/2019',periods=3)).repeat(3),\n\"Class\":[\"1A\",\"2B\",\"3C\",\"1A\",\"2B\",\"3C\",\"1A\",\"2B\",\"3C\"],\n\"Numbers\":np.random.randn(9)})" }, { "code": null, "e": 2053, "s": 2018, "text": "df['Numbers2'] = df['Numbers'] * 2" }, { "code": null, "e": 2056, "s": 2053, "text": "df" }, { "code": null, "e": 2152, "s": 2056, "text": "Using this dataframe, we would look at some functions which are useful for reforming/reshaping." }, { "code": null, "e": 2587, "s": 2152, "text": "Pivot method is typically used to create a pivot style view of data where the users can specify rows (in python it is called index) and columns. These two parameters would give a structure to the view whereas the information to be populated would be from the data that is being used to create pivot. The information can also be selectively populated by using values parameter. Let us now look at some examples to understand it better." }, { "code": null, "e": 2645, "s": 2587, "text": "df.pivot(index='Date', columns='Class', values='Numbers')" }, { "code": null, "e": 2861, "s": 2645, "text": "As we can see from above, once index, columns, values are specified the structure for a new pivot style dataframe is formed and is filled with information unique to the combination of index, column pair accordingly." }, { "code": null, "e": 3085, "s": 2861, "text": "It is to be remembered that index and columns parameters are suggested to be filled always as it would determine the structure of final dataframe/view. Let us look at what would happen if we do not declare values parameter." }, { "code": null, "e": 3125, "s": 3085, "text": "df.pivot(index='Date', columns='Class')" }, { "code": null, "e": 3409, "s": 3125, "text": "If we do not specify values parameter, pandas would create all the various possible views while taking all column names apart from what were specified as index and columns as above. Hence, for a big dataset having multiple columns, it is suggested to specify value parameter as well." }, { "code": null, "e": 3551, "s": 3409, "text": "There is, however, another way to extract information about one column using the above code and tweaking it a little. It would be as follows." }, { "code": null, "e": 3602, "s": 3551, "text": "df.pivot(index='Date', columns='Class')['Numbers']" }, { "code": null, "e": 4225, "s": 3602, "text": "If we mention the column name as given above while not specifying the values parameter, the resultant output would be the same. Only downside to this would be that it would take longer time to execute it. It is to be noted that the column name declaration is similar to syntax for sub-setting the dataframe. That is because we are exactly doing that. Using above code, pandas first gets the result for all columns, then using the column name/s specified in the brackets, pandas subsets the dataframe and displays it. This is also why the execution time for this method is longer than the one where we use values parameter." }, { "code": null, "e": 4399, "s": 4225, "text": "Note: While using pivot function, in case the combination of row*column has multiple entries the function would throw an error as pivot would not do any sort of aggregation." }, { "code": null, "e": 4844, "s": 4399, "text": "Melt is a function which is used to convert columns to rows. That means that this function is useful for when the users would like to bring one or more columns information into rows. This function would create two new columns by removing all other columns apart from the ones mentioned in its id_vars parameter and displays the column name in one column and its value in another column. Let us have a look at an example to understand it better." }, { "code": null, "e": 4878, "s": 4844, "text": "df.melt(id_vars=['Date','Class'])" }, { "code": null, "e": 5267, "s": 4878, "text": "In the dataframe df, we have four columns of which in id_vars parameter Date and Class were mentioned. This would leave us with columns Numbers and Number2. As we can see above, the function created two new columns called variable and value and populated them with column name and the unique value for the combination of Date+class+column name while removing columns Numbers and Numbers2." }, { "code": null, "e": 5400, "s": 5267, "text": "In case only specific columns are to be converted in this way and not all, then the parameter value_vars would help us achieve this." }, { "code": null, "e": 5458, "s": 5400, "text": "df.melt(id_vars=['Date','Class'], value_vars=['Numbers'])" }, { "code": null, "e": 5808, "s": 5458, "text": "As we can see, when specific column names are mentioned in value_vars parameter only that columns information would be melted as needed. There are two additional parameters value_name and var_name which would rename the columns value and variable by the string mentioned in the parameters. Let us have a look at an example to understand this better." }, { "code": null, "e": 5914, "s": 5808, "text": "df.melt(id_vars=['Date','Class'], value_vars=['Numbers'], value_name=\"Numbers_Value\", var_name=\"Num_Var\")" }, { "code": null, "e": 6006, "s": 5914, "text": "As we can see, the columns are renamed to the ones specified in the parameters as expected." }, { "code": null, "e": 6398, "s": 6006, "text": "Stack and Unstack perform columns to rows and rows to columns operations respectively. Both these functions are definitely one of the less used functions of reshaping in pandas as one would use pivot to achieve the result they want most of the time and hence it would not be needed. We will still look into them to understand how they work as they might be useful in some specific scenarios." }, { "code": null, "e": 6609, "s": 6398, "text": "The main different between stack and melt would be that stack requires id_vars to be set as index instead of having to pass them as parameters separately. Let us have a look at stack to understand what it does." }, { "code": null, "e": 6648, "s": 6609, "text": "df.set_index([\"Date\",\"Class\"]).stack()" }, { "code": null, "e": 6738, "s": 6648, "text": "As we can observe, it has the same functionality of melt where it brings columns to rows." }, { "code": null, "e": 6874, "s": 6738, "text": "Unstack on the other hand does the opposite of stack. It brings rows to columns and like stack, it needs index to function as expected." }, { "code": null, "e": 6923, "s": 6874, "text": "df.set_index([\"Date\",\"Class\"]).stack().unstack()" }, { "code": null, "e": 7174, "s": 6923, "text": "As we can see, unstack if no input provided would basically undo the stacking operation. The output will differ when changing the number input inside the brackets of unstack. This would be a good topic to explore if one is interested about the topic." }, { "code": null, "e": 7472, "s": 7174, "text": "Unlike the type-1 functions, type-2 functions give an aggregated view of information. These will be very useful in case the users would like to have some type of summary around the data. We will be using the same dataframe that we used for Type -1 functions to look into type -2 functions as well." }, { "code": null, "e": 7609, "s": 7472, "text": "To explain the reforming without aggregation, we would first declare a dataframe. The declaration and the dataframe would be as follows:" }, { "code": null, "e": 7705, "s": 7609, "text": "Using this dataframe, we would look at some functions which are useful for reforming/reshaping." }, { "code": null, "e": 8001, "s": 7705, "text": "Group by is the function that I use the more often than any other function mentioned in this article. This is because, it is very intuitive to use and has very useful parameters that can help one to view different aggregations for different columns. Let us look into a simple group by statement." }, { "code": null, "e": 8038, "s": 8001, "text": "df.groupby('Date')[\"Numbers\"].mean()" }, { "code": null, "e": 8469, "s": 8038, "text": "In group by statement, we specify the column/columns that we need to group the data on inside the first parenthesis. Here, we can either give a single string or a list of strings pertaining to column names as well. The next parenthesis is to specify the data to aggregate, and finally we call the method using which the aggregation should happen. In above example, we are aggregating column Numbers on Date using mean aggregation." }, { "code": null, "e": 8704, "s": 8469, "text": "Notice that the output is not a dataframe but looks similar to a pandas series. To convert it into a dataframe, we can use reset_index method, or we can also use a parameter available in group by statement. I will be using the latter." }, { "code": null, "e": 8757, "s": 8704, "text": "df.groupby('Date', as_index=False)[\"Numbers\"].mean()" }, { "code": null, "e": 8873, "s": 8757, "text": "As mentioned in the above image, as_index parameter can be used to convert the result of group by into a dataframe." }, { "code": null, "e": 8982, "s": 8873, "text": "Let us have a look at one more example where we aggregate columns on multiple columns using a single method." }, { "code": null, "e": 9045, "s": 8982, "text": "df.groupby(['Date','Class'], as_index=False)[\"Numbers\"].mean()" }, { "code": null, "e": 9367, "s": 9045, "text": "As we can see above, we can aggregate multiple columns on multiple columns using a list of strings (column names) instead of specifying a single string (column name). However, we can also use different aggregation functions for different columns. Let’s have a look at the example below to understand how that can be done." }, { "code": null, "e": 9452, "s": 9367, "text": "df.groupby(['Date'], as_index=False).aggregate({\"Numbers\":\"sum\", \"Numbers2\":\"mean\"})" }, { "code": null, "e": 9626, "s": 9452, "text": "In the above image we are aggregating Numbers column on Date column with the sum function and similarly we are aggregating Numbers2 column on Date column with mean function." }, { "code": null, "e": 9894, "s": 9626, "text": "Pivot Table functions in the same way that pivots do. However, pivot table has one additional and significant argument/parameter which specifies the aggregation function we will be using to aggregate the data. Let us look at the below example to understand it better." }, { "code": null, "e": 9934, "s": 9894, "text": "Let us start with a simple pivot table." }, { "code": null, "e": 9980, "s": 9934, "text": "df.pivot_table(index=\"Date\", columns=\"Class\")" }, { "code": null, "e": 10205, "s": 9980, "text": "Notice the method call for pivot table is pivot_table which is different from that of pivot which was pivot. If the aggregation function is not specified, the default function mean would be used to aggregate the information." }, { "code": null, "e": 10266, "s": 10205, "text": "df.pivot_table(index=\"Date\", columns=\"Class\", aggfunc=\"sum\")" }, { "code": null, "e": 10396, "s": 10266, "text": "However, if the user wants to specify a particular function, they can do so in the parameter aggfunc as shown in the above image." }, { "code": null, "e": 10590, "s": 10396, "text": "The last function in this article would be crosstab. This function by default would give the count or frequency of occurrence between values of two different columns. Let us look at an example." }, { "code": null, "e": 10621, "s": 10590, "text": "pd.crosstab(df.Date, df.Class)" }, { "code": null, "e": 10794, "s": 10621, "text": "The view above means that there are two different entries are available in combination of 1A class and 2019–02–02 Date. Similarly, the other information can be interpreted." }, { "code": null, "e": 10927, "s": 10794, "text": "In case instead of frequency of occurrence, if the user wants to have some other aggregation function aggfunc parameter can be used." }, { "code": null, "e": 10992, "s": 10927, "text": "pd.crosstab(df.Date, df.Class, values=df.Numbers, aggfunc='sum')" }, { "code": null, "e": 11058, "s": 10992, "text": "pd.crosstab(df.Date, df.Class, values=df.Numbers, aggfunc='mean')" }, { "code": null, "e": 11290, "s": 11058, "text": "Above images give a sense of how it can be used. Even though the output may look similar to that of pivot tables, the way it is achieved is different. But more often than not people prefer using pivot tables over crosstab function." }, { "code": null, "e": 11399, "s": 11290, "text": "We have looked at multiple functions in this article and have understood various parameters and their usage." }, { "code": null, "e": 11702, "s": 11399, "text": "All said and done, everyone knows that practice makes man perfect. This saying applies to technical stuff too right? To make it easier for you to practice multiple concepts we discussed in this article I have gone ahead and created a Jupiter notebook that you can download here. Good time practicing!!!" } ]
Swing Examples - Show Save File Dialog
Following example showcase how to create and show a save as file dialog in swing based application. We are using the following APIs. JFileChooser − To create a standard File chooser which allows user to save file/Folders. JFileChooser − To create a standard File chooser which allows user to save file/Folders. JFileChooser.showSaveDialog − To show the Save As dialog box. JFileChooser.showSaveDialog − To show the Save As dialog box. import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.LayoutManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class SwingTester { public static void main(String[] args) { createWindow(); } private static void createWindow() { JFrame frame = new JFrame("Swing Tester"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); createUI(frame); frame.setSize(560, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static void createUI(final JFrame frame){ JPanel panel = new JPanel(); LayoutManager layout = new FlowLayout(); panel.setLayout(layout); JButton button = new JButton("Click Me!"); final JLabel label = new JLabel(); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFileChooser fileChooser = new JFileChooser(); int option = fileChooser.showSaveDialog(frame); if(option == JFileChooser.APPROVE_OPTION){ File file = fileChooser.getSelectedFile(); label.setText("File Saved as: " + file.getName()); }else{ label.setText("Save command canceled"); } } }); panel.add(button); panel.add(label); frame.getContentPane().add(panel, BorderLayout.CENTER); } } Print Add Notes Bookmark this page
[ { "code": null, "e": 2139, "s": 2039, "text": "Following example showcase how to create and show a save as file dialog in swing based application." }, { "code": null, "e": 2172, "s": 2139, "text": "We are using the following APIs." }, { "code": null, "e": 2261, "s": 2172, "text": "JFileChooser − To create a standard File chooser which allows user to save file/Folders." }, { "code": null, "e": 2350, "s": 2261, "text": "JFileChooser − To create a standard File chooser which allows user to save file/Folders." }, { "code": null, "e": 2412, "s": 2350, "text": "JFileChooser.showSaveDialog − To show the Save As dialog box." }, { "code": null, "e": 2474, "s": 2412, "text": "JFileChooser.showSaveDialog − To show the Save As dialog box." }, { "code": null, "e": 4120, "s": 2474, "text": "import java.awt.BorderLayout;\nimport java.awt.FlowLayout;\nimport java.awt.LayoutManager;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.io.File;\n\nimport javax.swing.JButton;\nimport javax.swing.JFileChooser;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\n\npublic class SwingTester {\n public static void main(String[] args) {\n createWindow();\n }\n\n private static void createWindow() { \n JFrame frame = new JFrame(\"Swing Tester\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n createUI(frame);\n frame.setSize(560, 200); \n frame.setLocationRelativeTo(null); \n frame.setVisible(true);\n }\n\n private static void createUI(final JFrame frame){ \n JPanel panel = new JPanel();\n LayoutManager layout = new FlowLayout(); \n panel.setLayout(layout); \n\n JButton button = new JButton(\"Click Me!\");\n final JLabel label = new JLabel();\n\n button.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n JFileChooser fileChooser = new JFileChooser();\n int option = fileChooser.showSaveDialog(frame);\n if(option == JFileChooser.APPROVE_OPTION){\n File file = fileChooser.getSelectedFile();\n label.setText(\"File Saved as: \" + file.getName());\n }else{\n label.setText(\"Save command canceled\");\n }\n }\n });\n\n panel.add(button);\n panel.add(label);\n frame.getContentPane().add(panel, BorderLayout.CENTER); \n } \n}" }, { "code": null, "e": 4127, "s": 4120, "text": " Print" }, { "code": null, "e": 4138, "s": 4127, "text": " Add Notes" } ]
Visualizing Bike Mobility in London using Interactive Maps and Animations | by Eden Au | Towards Data Science
Bike sharing systems have become popular means of travel in recent years, providing a green and flexible transportation scheme to citizens in metropolitan areas. Many governments in the world have seen this as an innovative strategy that could potentially bring a number of societal benefits. For instance, it could reduce the use of automobiles and hence reduce greenhouse gas emission and alleviate traffic congestion in city centres. Reports have shown that 77% of Londoners agree that cycling is the fastest way to make short-distance journeys. In the long run, it might also help increase the life expectancy in the city. I have been working on a data-driven cost-effective algorithm for optimizing (re-balancing) the system of Santander Cycles, a public bicycle hire scheme in London, which I should make a post about it once my paper is published (more info here). Before really working on the algorithm, I had to delve into loads of data and it would really help if I could somehow visualize them. TL;DR — Let’s see how we can visualize a bike sharing system using graphs, maps, and animations. You can find web maps on this page. Most maps, animations, and source codes are available on GitHub. Data is now available on Kaggle. More about Data — the Boring Bit Bar Charts Interactive Maps Density Maps Connection Maps Animations Conclusions Remarks Originally published on my blog edenau.github.io. My work is inspired by Vincent Lonij and Dhrumil Patel. Check out their posts! I obtained data on bicycle journeys from Transport for London (TfL). Every single bike journey made in their system since 2012 was recorded and those open data are available online. A 36-day record of journeys made from 1 August to 13 September 2017 was analyzed. During this period, there were >1.5 million journeys made among >700 bike docking stations in London. From 2014, we have witnessed a >190% rise in bike trips made. The number of bicycles and docking stations in the system both increased more than twofold to accommodate the significant rise in cycling demand in central London and regional areas. Exact data will be shown in my soon-to-be-released paper. Stay tuned. I believed there would be a massive difference in journey patterns between weekdays and weekends. Let’s do some coding and see if this is true. We first import data of journeys by pd.read_csv(). # Load journey dataf = 'journeys.csv'j = pd.read_csv(f)date = j['date'].valuesmonth = j['month'].valuesyear = j['year'].valueshour = j['hour'].valuesminute = j['minute'].valuesstation_start = j['id_start'].valuesstation_end = j['id_end'].values Then we extract weekday data by date.weekday() and evenly divide a 24-hour day into 72 time slices, such that each time slice represents a 20-minute interval. # Compute IsWeekdayweekday = np.zeros(len(date))weekday[:] = np.nancnt = 0for _year, _month, _date, _hour, _minute in zip(year, month, date, hour, minute): _dt = datetime.datetime(_year, _month, _date, _hour, _minute) _weekday = _dt.weekday() weekday[cnt] = _weekday cnt += 1IsWeekday = weekday < 5j['IsWeekday'] = IsWeekday# Compute TimeSlicej['TimeSlice'] = (hour*3 + np.floor(minute/20)).astype(int) We also need to check if those bike trips were made from/to abolished stations, as there are no ways to obtain information of those stations, such as locations, station name etc. (good job TfL). We labelled them as ‘invalid’ journeys. # Load station dataf = 'stations.csv'stations = pd.read_csv(f)station_id = stations['station_id'].values# Extract valid journeysvalid = np.zeros(len(date))valid[:] = Falsecnt = 0for _start, _end in zip(station_start, station_end): if np.logical_and((_start in station_id), (_end in station_id)): valid[cnt] = True cnt += 1j['Valid'] = valid Finally, we only keep journeys that are ‘valid’ and made on weekdays, which turns out to be around 73% of the data. df = j[j["IsWeekday"] == True].drop(columns="IsWeekday")df = df[df["Valid"] == True].drop(columns="Valid")print('Ratio of valid journeys= {:.2f}%'.format(df.shape[0] / j.shape[0] * 100)) We finally delve into the visualization part! The simplest forms of data visualization are arguably charts. By a simple groupby('TimeSlice') function, we can see how frequent journeys were made in different hours. grp_by_timeslice = df.groupby('TimeSlice').count().values[:,0]plt.bar(range(0,72), grp_by_timeslice)plt.xlabel('Time Slice')plt.ylabel('Departures')plt.show() See? our hypothesis is right! Journey patterns on weekdays and weekends are so different, as we can see two peak hours on weekdays, where most people commute, but not on weekends. We can also observe the distribution of journey duration and speed in a similar fashion. Note that we assumed straight paths were taken due to data constraint (they don’t track your movement), which would be shorter than the actual paths, and therefore the speeds computed with distances between start and end stations would be underestimated. If customers return the bike at the same station it was rent, the computed speed would be 0, which explains the rather strange spike spotted at 0 km/h. If charts are fancy, maps are fancier. We will use folium, which is a Python wrapper of Leaflet.js that makes interactive maps. Make sure you install the latest version by $ pip install folium==0.7.0 (or its conda install equivalent). I worked on Google Colaboratory and the pre-installed version is 0.2.0 with minimal functionalities. I built a simple template for generating a map with circle markers (with different colours!) using clusters. import folium# Change coloursdef color_change(c): if(c < 15): return('red') elif(15 <= c < 30): return('orange') else: return('green')# Create base mapLondon = [51.506949, -0.122876]map = folium.Map(location = London, zoom_start = 12, tiles = "CartoDB positron")marker_cluster = MarkerCluster(locations=[lat, lon]).add_to(map)# Plot markersfor _lat, _lon, _cap, _name in zip(lat, lon, cap, name): folium.CircleMarker(location = [_lat, _lon], radius = 9, popup = "("+str(_cap)+") "+_name, fill_color = color_change(_cap), color = "gray", fill_opacity = 0.9).add_to(marker_cluster) f = 'map_station_cluster.html'map.save(f) Why clusters? MarkerCluster() enables markers to cluster together when they are too close when you zoom out. You do not want your maps to be too messy, with markers overlapping one another. It automatically de-clusters/unfolds when you zoom in: But I promised you interactive maps. You can set the popup parameter and display station name and its capacity when you click on it. Bravo! This map is available on https://edenau.github.io/maps/station-cluster/. The above code used a dynamic colour scheme that depends on the capacity of stations. We can also implement a dynamic radius scheme for those circle markers that is based on the number of departures and arrivals of each station. We can obtain what we called density maps that shows the net departures/arrivals of every station. def DensityMap(stations, cnt_departure, cnt_arrival):London = [51.506949, -0.122876] map = folium.Map(location = London, zoom_start = 12, tiles = "CartoDB dark_matter") stations['Total Departure'] = cnt_departure stations['Total Arrival'] = cnt_arrivalfor index, row in stations.iterrows(): net_departure = row['Total Departure'] - row['Total Arrival'] _radius = np.abs(net_departure) if np.isnan(_radius): _radius = 0 if net_departure > 0: _color= '#E80018' # target red else: _color= '#81D8D0' # tiffany blue lat, lon = row['lat'], row['lon'] _popup = '('+str(row['capacity'])+'/'+str(int(_radius))+') '+row['station_name'] folium.CircleMarker(location = [lat,lon], radius = _radius, popup = _popup, color = _color, fill_opacity = 0.5).add_to(map) return map I used a different colour scheme here (target red and tiffany blue are both trademarked colours in the United States) that shows if the number of departures at some station is more or less than the number of arrivals. Big circle markers represent a large departure-arrival difference. Let’s see how density maps look like in morning and evening peak hours: # Select peak hoursTimeSlice = [25,53] # morning and eveningkeyword = ['map_morning', 'map_evening']# Journeys depart between 0820 and 0859, and between 1740 and 1819for ts, kw in zip(TimeSlice, keyword): df_1 = df[df["TimeSlice"] == ts] df_2 = df[df["TimeSlice"] == (ts+1)] df_target = df_1.append(df_2) cnt_departure = df_target.groupby("id_start").count().iloc[:,0] cnt_arrival = df_target.groupby("id_end").count().iloc[:,0] vars()[kw] = DensityMap(stations, cnt_departure, cnt_arrival) Density maps are available on https://edenau.github.io/maps/density-morning/ and https://edenau.github.io/maps/density-evening/. All the aforementioned maps focus on stations but not journeys, but we can also visualize journeys by what we called connection maps, by simply drawing trips completed on the map. Without delving into many details: We can also add multiple layers of connection by folium.LayerControl() to separate layers of frequently and infrequently used paths. Connection maps are available on https://edenau.github.io/maps/connection-morning/ and https://edenau.github.io/maps/connection-morning-layers/. So far we have demonstrated how to visualize temporal and distributional information by charts, and spatial information by various kinds of maps. But what if we generate multiple maps on consecutive time instances? We can visualize spatio-temporal information using animations! The maps generated are web maps in .html files. The idea is to: Generate a map for every time instance, browse it on a web browser, take a screenshot and save the picture, and link all pictures together as a video or a .gif file. We are going to automate the web browsing and screen capturing process by selenium. We also need a web driver, and as a Chrome user I went for chromedriver. from selenium import webdriverdef a_frame(i, frame_time, data): my_frame = get_image_map(frame_time, data) # Save the web map delay = 5 # give it some loading time fn = 'frame_{:0>5}'.format(i) DIR = 'frames' f = DIR + '/' + fn + '.html' tmpurl='file://{path}/{mapfile}'.format(path=os.getcwd()+'/frames',mapfile=fn) my_frame.save(f) # Open the web map and take screenshot browser = webdriver.Chrome() browser.get(tmpurl) time.sleep(delay) f = DIR + '/' + fn + '.png' browser.save_screenshot(f) browser.quit() f = 'frames/frame_{:0>5}.png'.format(i) image = Image.open(io.BytesIO(f)) draw = ImageDraw.ImageDraw(image) font = ImageFont.truetype('Roboto-Light.ttf', 30) # Add text on picture draw.text((20, image.height - 50), 'Time: {}'.format(frame_time), fill=(255, 255, 255), font=font) # Write the .png file dir_name = "frames" if not os.path.exists(dir_name): os.mkdir(dir_name) image.save(os.path.join(dir_name, 'frame_{:0>5}.png'.format(i)), 'PNG') return image We can then make the video or gif by ffmpeg. For Mac user, installing ffmpeg can literally take minimal effort with the aid of Homebrew, as Homebrew installs the stuff you need that Apple didn’t. After installing Homebrew (with a single command), simply type $ brew install ffmpeg and voilà! To create a .mp4 file, try $ ffmpeg -r 10 -i frames/frame_%05d.png -c:v libx264 -vf fps=25 -crf 17 -pix_fmt yuv420p video.mp4 For .gif file, try $ ffmpeg -y -t 3 -i frames/frame_%05d.png \ -vf fps=10,scale=320:-1:flags=lanczos,palettegen palette.png$ ffmpeg -r 10 -i frames/frame_%05d.png -i palette.png -filter_complex \ "fps=10,scale=720:-1:flags=lanczos[x];[x][1:v]paletteuse" animation.gif Check out the animation of density maps throughout a day: And also the animation of journeys at different times: The bike sharing system in London is visualized using bar charts, density maps, connection maps, and animations. The abstraction of Python makes it a really nice and fancy tool for spatio-temporal data visualization (at the expense of computational time but whatever). I leveraged folium, selenium, chromedriver, brew, ffmpeg, and most importantly, part of the building blocks from Vincent’s code to make this happen. If you are interested in Python or programming in general, the following articles might be helpful: towardsdatascience.com towardsdatascience.com Once again, a shout-out to Vincent Lonij and Dhrumil Patel for their demonstration of relevant works. This work was based on my Master’s thesis regarding the optimization of station-based bike sharing systems. Stay tuned for my soon-to-be-published paper. Originally published on my blog edenau.github.io.
[ { "code": null, "e": 483, "s": 46, "text": "Bike sharing systems have become popular means of travel in recent years, providing a green and flexible transportation scheme to citizens in metropolitan areas. Many governments in the world have seen this as an innovative strategy that could potentially bring a number of societal benefits. For instance, it could reduce the use of automobiles and hence reduce greenhouse gas emission and alleviate traffic congestion in city centres." }, { "code": null, "e": 673, "s": 483, "text": "Reports have shown that 77% of Londoners agree that cycling is the fastest way to make short-distance journeys. In the long run, it might also help increase the life expectancy in the city." }, { "code": null, "e": 1052, "s": 673, "text": "I have been working on a data-driven cost-effective algorithm for optimizing (re-balancing) the system of Santander Cycles, a public bicycle hire scheme in London, which I should make a post about it once my paper is published (more info here). Before really working on the algorithm, I had to delve into loads of data and it would really help if I could somehow visualize them." }, { "code": null, "e": 1149, "s": 1052, "text": "TL;DR — Let’s see how we can visualize a bike sharing system using graphs, maps, and animations." }, { "code": null, "e": 1283, "s": 1149, "text": "You can find web maps on this page. Most maps, animations, and source codes are available on GitHub. Data is now available on Kaggle." }, { "code": null, "e": 1316, "s": 1283, "text": "More about Data — the Boring Bit" }, { "code": null, "e": 1327, "s": 1316, "text": "Bar Charts" }, { "code": null, "e": 1344, "s": 1327, "text": "Interactive Maps" }, { "code": null, "e": 1357, "s": 1344, "text": "Density Maps" }, { "code": null, "e": 1373, "s": 1357, "text": "Connection Maps" }, { "code": null, "e": 1384, "s": 1373, "text": "Animations" }, { "code": null, "e": 1396, "s": 1384, "text": "Conclusions" }, { "code": null, "e": 1404, "s": 1396, "text": "Remarks" }, { "code": null, "e": 1533, "s": 1404, "text": "Originally published on my blog edenau.github.io. My work is inspired by Vincent Lonij and Dhrumil Patel. Check out their posts!" }, { "code": null, "e": 1715, "s": 1533, "text": "I obtained data on bicycle journeys from Transport for London (TfL). Every single bike journey made in their system since 2012 was recorded and those open data are available online." }, { "code": null, "e": 2214, "s": 1715, "text": "A 36-day record of journeys made from 1 August to 13 September 2017 was analyzed. During this period, there were >1.5 million journeys made among >700 bike docking stations in London. From 2014, we have witnessed a >190% rise in bike trips made. The number of bicycles and docking stations in the system both increased more than twofold to accommodate the significant rise in cycling demand in central London and regional areas. Exact data will be shown in my soon-to-be-released paper. Stay tuned." }, { "code": null, "e": 2409, "s": 2214, "text": "I believed there would be a massive difference in journey patterns between weekdays and weekends. Let’s do some coding and see if this is true. We first import data of journeys by pd.read_csv()." }, { "code": null, "e": 2654, "s": 2409, "text": "# Load journey dataf = 'journeys.csv'j = pd.read_csv(f)date = j['date'].valuesmonth = j['month'].valuesyear = j['year'].valueshour = j['hour'].valuesminute = j['minute'].valuesstation_start = j['id_start'].valuesstation_end = j['id_end'].values" }, { "code": null, "e": 2813, "s": 2654, "text": "Then we extract weekday data by date.weekday() and evenly divide a 24-hour day into 72 time slices, such that each time slice represents a 20-minute interval." }, { "code": null, "e": 3220, "s": 2813, "text": "# Compute IsWeekdayweekday = np.zeros(len(date))weekday[:] = np.nancnt = 0for _year, _month, _date, _hour, _minute in zip(year, month, date, hour, minute): _dt = datetime.datetime(_year, _month, _date, _hour, _minute) _weekday = _dt.weekday() weekday[cnt] = _weekday cnt += 1IsWeekday = weekday < 5j['IsWeekday'] = IsWeekday# Compute TimeSlicej['TimeSlice'] = (hour*3 + np.floor(minute/20)).astype(int)" }, { "code": null, "e": 3455, "s": 3220, "text": "We also need to check if those bike trips were made from/to abolished stations, as there are no ways to obtain information of those stations, such as locations, station name etc. (good job TfL). We labelled them as ‘invalid’ journeys." }, { "code": null, "e": 3801, "s": 3455, "text": "# Load station dataf = 'stations.csv'stations = pd.read_csv(f)station_id = stations['station_id'].values# Extract valid journeysvalid = np.zeros(len(date))valid[:] = Falsecnt = 0for _start, _end in zip(station_start, station_end): if np.logical_and((_start in station_id), (_end in station_id)): valid[cnt] = True cnt += 1j['Valid'] = valid" }, { "code": null, "e": 3917, "s": 3801, "text": "Finally, we only keep journeys that are ‘valid’ and made on weekdays, which turns out to be around 73% of the data." }, { "code": null, "e": 4104, "s": 3917, "text": "df = j[j[\"IsWeekday\"] == True].drop(columns=\"IsWeekday\")df = df[df[\"Valid\"] == True].drop(columns=\"Valid\")print('Ratio of valid journeys= {:.2f}%'.format(df.shape[0] / j.shape[0] * 100))" }, { "code": null, "e": 4318, "s": 4104, "text": "We finally delve into the visualization part! The simplest forms of data visualization are arguably charts. By a simple groupby('TimeSlice') function, we can see how frequent journeys were made in different hours." }, { "code": null, "e": 4477, "s": 4318, "text": "grp_by_timeslice = df.groupby('TimeSlice').count().values[:,0]plt.bar(range(0,72), grp_by_timeslice)plt.xlabel('Time Slice')plt.ylabel('Departures')plt.show()" }, { "code": null, "e": 4746, "s": 4477, "text": "See? our hypothesis is right! Journey patterns on weekdays and weekends are so different, as we can see two peak hours on weekdays, where most people commute, but not on weekends. We can also observe the distribution of journey duration and speed in a similar fashion." }, { "code": null, "e": 5153, "s": 4746, "text": "Note that we assumed straight paths were taken due to data constraint (they don’t track your movement), which would be shorter than the actual paths, and therefore the speeds computed with distances between start and end stations would be underestimated. If customers return the bike at the same station it was rent, the computed speed would be 0, which explains the rather strange spike spotted at 0 km/h." }, { "code": null, "e": 5325, "s": 5153, "text": "If charts are fancy, maps are fancier. We will use folium, which is a Python wrapper of Leaflet.js that makes interactive maps. Make sure you install the latest version by" }, { "code": null, "e": 5353, "s": 5325, "text": "$ pip install folium==0.7.0" }, { "code": null, "e": 5489, "s": 5353, "text": "(or its conda install equivalent). I worked on Google Colaboratory and the pre-installed version is 0.2.0 with minimal functionalities." }, { "code": null, "e": 5598, "s": 5489, "text": "I built a simple template for generating a map with circle markers (with different colours!) using clusters." }, { "code": null, "e": 6409, "s": 5598, "text": "import folium# Change coloursdef color_change(c): if(c < 15): return('red') elif(15 <= c < 30): return('orange') else: return('green')# Create base mapLondon = [51.506949, -0.122876]map = folium.Map(location = London, zoom_start = 12, tiles = \"CartoDB positron\")marker_cluster = MarkerCluster(locations=[lat, lon]).add_to(map)# Plot markersfor _lat, _lon, _cap, _name in zip(lat, lon, cap, name): folium.CircleMarker(location = [_lat, _lon], radius = 9, popup = \"(\"+str(_cap)+\") \"+_name, fill_color = color_change(_cap), color = \"gray\", fill_opacity = 0.9).add_to(marker_cluster) f = 'map_station_cluster.html'map.save(f)" }, { "code": null, "e": 6599, "s": 6409, "text": "Why clusters? MarkerCluster() enables markers to cluster together when they are too close when you zoom out. You do not want your maps to be too messy, with markers overlapping one another." }, { "code": null, "e": 6654, "s": 6599, "text": "It automatically de-clusters/unfolds when you zoom in:" }, { "code": null, "e": 6794, "s": 6654, "text": "But I promised you interactive maps. You can set the popup parameter and display station name and its capacity when you click on it. Bravo!" }, { "code": null, "e": 6867, "s": 6794, "text": "This map is available on https://edenau.github.io/maps/station-cluster/." }, { "code": null, "e": 7195, "s": 6867, "text": "The above code used a dynamic colour scheme that depends on the capacity of stations. We can also implement a dynamic radius scheme for those circle markers that is based on the number of departures and arrivals of each station. We can obtain what we called density maps that shows the net departures/arrivals of every station." }, { "code": null, "e": 8152, "s": 7195, "text": "def DensityMap(stations, cnt_departure, cnt_arrival):London = [51.506949, -0.122876] map = folium.Map(location = London, zoom_start = 12, tiles = \"CartoDB dark_matter\") stations['Total Departure'] = cnt_departure stations['Total Arrival'] = cnt_arrivalfor index, row in stations.iterrows(): net_departure = row['Total Departure'] - row['Total Arrival'] _radius = np.abs(net_departure) if np.isnan(_radius): _radius = 0 if net_departure > 0: _color= '#E80018' # target red else: _color= '#81D8D0' # tiffany blue lat, lon = row['lat'], row['lon'] _popup = '('+str(row['capacity'])+'/'+str(int(_radius))+') '+row['station_name'] folium.CircleMarker(location = [lat,lon], radius = _radius, popup = _popup, color = _color, fill_opacity = 0.5).add_to(map) return map" }, { "code": null, "e": 8437, "s": 8152, "text": "I used a different colour scheme here (target red and tiffany blue are both trademarked colours in the United States) that shows if the number of departures at some station is more or less than the number of arrivals. Big circle markers represent a large departure-arrival difference." }, { "code": null, "e": 8509, "s": 8437, "text": "Let’s see how density maps look like in morning and evening peak hours:" }, { "code": null, "e": 9006, "s": 8509, "text": "# Select peak hoursTimeSlice = [25,53] # morning and eveningkeyword = ['map_morning', 'map_evening']# Journeys depart between 0820 and 0859, and between 1740 and 1819for ts, kw in zip(TimeSlice, keyword): df_1 = df[df[\"TimeSlice\"] == ts] df_2 = df[df[\"TimeSlice\"] == (ts+1)] df_target = df_1.append(df_2) cnt_departure = df_target.groupby(\"id_start\").count().iloc[:,0] cnt_arrival = df_target.groupby(\"id_end\").count().iloc[:,0] vars()[kw] = DensityMap(stations, cnt_departure, cnt_arrival)" }, { "code": null, "e": 9135, "s": 9006, "text": "Density maps are available on https://edenau.github.io/maps/density-morning/ and https://edenau.github.io/maps/density-evening/." }, { "code": null, "e": 9350, "s": 9135, "text": "All the aforementioned maps focus on stations but not journeys, but we can also visualize journeys by what we called connection maps, by simply drawing trips completed on the map. Without delving into many details:" }, { "code": null, "e": 9483, "s": 9350, "text": "We can also add multiple layers of connection by folium.LayerControl() to separate layers of frequently and infrequently used paths." }, { "code": null, "e": 9628, "s": 9483, "text": "Connection maps are available on https://edenau.github.io/maps/connection-morning/ and https://edenau.github.io/maps/connection-morning-layers/." }, { "code": null, "e": 9906, "s": 9628, "text": "So far we have demonstrated how to visualize temporal and distributional information by charts, and spatial information by various kinds of maps. But what if we generate multiple maps on consecutive time instances? We can visualize spatio-temporal information using animations!" }, { "code": null, "e": 9970, "s": 9906, "text": "The maps generated are web maps in .html files. The idea is to:" }, { "code": null, "e": 10136, "s": 9970, "text": "Generate a map for every time instance, browse it on a web browser, take a screenshot and save the picture, and link all pictures together as a video or a .gif file." }, { "code": null, "e": 10293, "s": 10136, "text": "We are going to automate the web browsing and screen capturing process by selenium. We also need a web driver, and as a Chrome user I went for chromedriver." }, { "code": null, "e": 11403, "s": 10293, "text": "from selenium import webdriverdef a_frame(i, frame_time, data): my_frame = get_image_map(frame_time, data) # Save the web map delay = 5 # give it some loading time fn = 'frame_{:0>5}'.format(i) DIR = 'frames' f = DIR + '/' + fn + '.html' tmpurl='file://{path}/{mapfile}'.format(path=os.getcwd()+'/frames',mapfile=fn) my_frame.save(f) # Open the web map and take screenshot browser = webdriver.Chrome() browser.get(tmpurl) time.sleep(delay) f = DIR + '/' + fn + '.png' browser.save_screenshot(f) browser.quit() f = 'frames/frame_{:0>5}.png'.format(i) image = Image.open(io.BytesIO(f)) draw = ImageDraw.ImageDraw(image) font = ImageFont.truetype('Roboto-Light.ttf', 30) # Add text on picture draw.text((20, image.height - 50), 'Time: {}'.format(frame_time), fill=(255, 255, 255), font=font) # Write the .png file dir_name = \"frames\" if not os.path.exists(dir_name): os.mkdir(dir_name) image.save(os.path.join(dir_name, 'frame_{:0>5}.png'.format(i)), 'PNG') return image" }, { "code": null, "e": 11543, "s": 11403, "text": "We can then make the video or gif by ffmpeg. For Mac user, installing ffmpeg can literally take minimal effort with the aid of Homebrew, as" }, { "code": null, "e": 11599, "s": 11543, "text": "Homebrew installs the stuff you need that Apple didn’t." }, { "code": null, "e": 11662, "s": 11599, "text": "After installing Homebrew (with a single command), simply type" }, { "code": null, "e": 11684, "s": 11662, "text": "$ brew install ffmpeg" }, { "code": null, "e": 11723, "s": 11684, "text": "and voilà! To create a .mp4 file, try" }, { "code": null, "e": 11822, "s": 11723, "text": "$ ffmpeg -r 10 -i frames/frame_%05d.png -c:v libx264 -vf fps=25 -crf 17 -pix_fmt yuv420p video.mp4" }, { "code": null, "e": 11841, "s": 11822, "text": "For .gif file, try" }, { "code": null, "e": 12092, "s": 11841, "text": "$ ffmpeg -y -t 3 -i frames/frame_%05d.png \\ -vf fps=10,scale=320:-1:flags=lanczos,palettegen palette.png$ ffmpeg -r 10 -i frames/frame_%05d.png -i palette.png -filter_complex \\ \"fps=10,scale=720:-1:flags=lanczos[x];[x][1:v]paletteuse\" animation.gif" }, { "code": null, "e": 12150, "s": 12092, "text": "Check out the animation of density maps throughout a day:" }, { "code": null, "e": 12205, "s": 12150, "text": "And also the animation of journeys at different times:" }, { "code": null, "e": 12318, "s": 12205, "text": "The bike sharing system in London is visualized using bar charts, density maps, connection maps, and animations." }, { "code": null, "e": 12623, "s": 12318, "text": "The abstraction of Python makes it a really nice and fancy tool for spatio-temporal data visualization (at the expense of computational time but whatever). I leveraged folium, selenium, chromedriver, brew, ffmpeg, and most importantly, part of the building blocks from Vincent’s code to make this happen." }, { "code": null, "e": 12723, "s": 12623, "text": "If you are interested in Python or programming in general, the following articles might be helpful:" }, { "code": null, "e": 12746, "s": 12723, "text": "towardsdatascience.com" }, { "code": null, "e": 12769, "s": 12746, "text": "towardsdatascience.com" }, { "code": null, "e": 12871, "s": 12769, "text": "Once again, a shout-out to Vincent Lonij and Dhrumil Patel for their demonstration of relevant works." }, { "code": null, "e": 13025, "s": 12871, "text": "This work was based on my Master’s thesis regarding the optimization of station-based bike sharing systems. Stay tuned for my soon-to-be-published paper." } ]
Intro to DeepMind’s Reinforcement Learning Framework “Acme” | by Andreas Stöffelbauer | Jun, 2021 | Towards Data Science | Towards Data Science
Acme is a Python-based research framework for reinforcement learning, open sourced by Google’s DeepMind in 2020. It was designed to simplify the development of novel RL agents and accelerate RL research. According to their own statement, Acme is used on a daily basis at DeepMind, which is spearheading research in reinforcement learning and artificial intelligence. For a recent university project, I decided to learn about Acme and use it to implement different RL algorithms. I found it to be brilliant and I really enjoyed working with it. Getting started with Acme is relatively easy too. This is because there are several points of entry, at different levels of complexity. In other words, the framework is not only meant for advanced researchers but also allows beginners to implement even simple algorithms — somewhat similar to how TensorFlow and PyTorch are used by both beginners and experts. On the downside, however, as the framework is still quite new, there isn’t really a thorough documentation available, and there aren’t any great tutorials out there either. This blog post can hopefully be a step in the right direction. It is not meant to be or replace a thorough documentation, but rather a concise, practical introduction to Acme. Above all, it should give you an idea of the design choices underlying the framework, and what that means for the implementation of RL algorithms. In particular, I am going to discuss my implementations of two simple algorithms, SARSA and Q learning, with the goal to play the game Blackjack. Once you understand what actors and agents are and how they are designed in Acme, I have no doubt that you will quickly get the idea of how to implement (probably) any reinforcement learning algorithm you can think of. Let’s dive into an actual example. As already mentioned, we want our agent to play Blackjack. Acme agents are not designed to interact with Gym environments. Instead, DeepMind has their own RL environment API. The difference is mainly in how the timesteps are represented. Fortunately, however, you can still make use of Gym environments too since Acme’s developers have provided wrapper functions for this. env = acme.wrappers.GymWrapper(gym.make('Blackjack-v0')) There are 32 x 11 x 2 states in Blackjack, although not all those states can actually occur during a game, and there are two actions, “hit” and “stick”. For a description of these dimensions and why not all states can occur, you can check out the environment on GitHub here. I know this is not really obvious at first. It is critical to understand that there is a distinction between actors, learners, and agents. Actors interact with the environment. That is, they observe states and take actions according to some action-selection policy. The image below illustrates this. The learner consumes the data collected by the actor in order to learn or improve the policy, usually in an iterative, online fashion. For example, learning might consist of updates to a neural network’s parameters. The new parameters are passed to the actor, who then behaves according to the updated policy. The agent simply combines both the acting and the learning component, but usually no additional reinforcement learning logic needs to be implemented. The image below includes all three components. One of the main reasons for this factorization into actors, learners, and agents is to facilitate distributed reinforcement learning. If we do not care about that and if the algorithm is simple enough, however, it can also be sufficient to only implement the actor and simply integrate the learning steps within the actor’s update method. For the sake of simplicity, this also the approach that I am taking here. For example, the random agent below inherits from the acme.Actor class. The methods that must be implemented by the developer (you) are select_action, observe_first, observe, and update. As just mentioned, the latter is where the learning happens without the additional learner component. Note that this agent would work the same way without subclassing acme.Actor. The base class simply determines the methods that you must overwrite. This also ensures that the agent integrates as intended with other Acme components such as the environment loop that I am going to introduce below. This agent uses a policy that simply chooses hit or stick randomly, but generally the framework allows you huge flexibility with respect to how you want to implement a policy. Later, you will see an epsilon-greedy policy. In other cases, the policy may include a neural network that you can implement with TensorFlow, PyTorch, or JAX. In that sense, Acme is framework agnostic, so you can combine it with whatever machine learning library you prefer. In the update method, the actor usually only pulls the most recent parameters from the learner. If you do not use a separate learner, however, the RL logic goes inside the update method (you will see that later). If you already know a bit about reinforcement learning and have already implemented an RL algorithm, the following loop will be very familiar to you. Each episode consists of four steps, which are repeated until a terminal state is reached. observe a statetake an action according to the behavior policyobserve a rewardupdate the policy observe a state take an action according to the behavior policy observe a reward update the policy In code ... Sometimes you may have to implement a loop like that, especially if you wish to customize it. But mostly, this loop will always be exactly the same. Conveniently, there is a shortcut in Acme: the EnvironmentLoop, which performs pretty much exactly the steps seen above. You just have to pass your environment and agent instances and then you can run either a single episode or as many as you want with a single line of code. There are also a number of loggers available that track important metrics such as the number of steps taken in each episode and the collected rewards. # init Acme's environment looploop = EnvironmentLoop(env, agent, logger=InMemoryLogger())# run a single episodeloop.run_episode()# or run multiple episodesloop.run(10) Of course, a random agent is not very useful. My promise was to show how to implement some actual reinforcement learning algorithms. So here we go. By the way, if you are not familiar with RL at all, check out the book Reinforcement Learning: An Introduction by Sutton and Barto (2018). The two algorithms you usually learn first — either in the book or if you take an RL course at university — are SARSA and Q learning. By now, you already know how Acme agents (or actors) are designed. Let’s look at how you can implement the SARSA algorithm in Acme. SARSA is an on-policy algorithm whose updates depend on the state, action, reward, next state, and next action (hence the name). Since this is not meant to be a theoretical RL tutorial, I do not go into the details of the algorithm itself here. First things first, inside the agent’s __init__ method, we initialize Q, the state-action value matrix, and the behavior policy, which is an epsilon greedy policy here. Note also that this agent must always store its last timestep, action, and next timestep as they are needed in the update step. So we also initialize them. In observe, there is usually not much you have to do. In this case, we simply store the observed timestep and the action that was taken. This is not always necessary, however. Sometimes, for example, you may want to store timesteps (and whole trajectories) in a dataset or a replay buffer instead. Acme also provides dataset and adder components for this purpose. In fact, there is also a library which was developed by DeepMind too. It’s called Reverb (see GitHub here). The transform_state method above is only a helper function to put states into the right format in order to correctly index the Q matrix. Finally, to train SARSA on the environment for 500,000 episodes, simply run agent = SarsaAgent()loop = EnvironmentLoop(env, agent, logger=InMemoryLogger())loop.run(500000) The Q learning agent below is very similar to the SARSA agent. They only differ in the way how updates to the Q matrix are made. This is because Q learning is an off-policy algorithm. To train the Q learning agent on the environment for 500,000 episodes, run agent = QLearningAgent()loop = EnvironmentLoop(env, agent, logger=InMemoryLogger())loop.run(500000) I think Acme is a really great framework for reinforcement learning because you don’t have to develop your algorithms from scratch. So instead of figuring out by yourself how to write readable and reproducible RL code, you can just rely on the undoubtedly smart researchers and developers at DeepMind, who have done that for you. Acme allows you to implement any reinforcement learning algorithm, and you can combine it with any other machine learning framework, including TensorFlow, PyTorch and JAX. If you want to learn more about Acme, you can read DeepMind’s research paper and check out their GitHub repository. There you will also find the implementation of some common algorithms such as Deep Q-Networks (DQN), Deep Deterministic Policy Gradient (DDPG), Monte Carlo Tree Search (MCTS), Behavior Cloning (BC), IMPALA, and so on. No matter if you are a advanced researcher or only a beginner interested in reinforcement learning, I encourage you to try it out. Thank you for reading. If you have any questions, let me know. My Jupyter Notebook containing the code can be found here. If you are interested, you can also check out my reinforcement learning course project. Besides SARSA and Q-learning, I also implemented dyna-Q, prioritized sweeping and a Mote Carlo Tree Search agent. Hoffman et al (2020): Acme: A Research Framework for Distributed Reinforcement Learning. ArXiv. Sutton and Barto (2018): Reinforcement Learning: An Introduction.
[ { "code": null, "e": 539, "s": 172, "text": "Acme is a Python-based research framework for reinforcement learning, open sourced by Google’s DeepMind in 2020. It was designed to simplify the development of novel RL agents and accelerate RL research. According to their own statement, Acme is used on a daily basis at DeepMind, which is spearheading research in reinforcement learning and artificial intelligence." }, { "code": null, "e": 716, "s": 539, "text": "For a recent university project, I decided to learn about Acme and use it to implement different RL algorithms. I found it to be brilliant and I really enjoyed working with it." }, { "code": null, "e": 1076, "s": 716, "text": "Getting started with Acme is relatively easy too. This is because there are several points of entry, at different levels of complexity. In other words, the framework is not only meant for advanced researchers but also allows beginners to implement even simple algorithms — somewhat similar to how TensorFlow and PyTorch are used by both beginners and experts." }, { "code": null, "e": 1249, "s": 1076, "text": "On the downside, however, as the framework is still quite new, there isn’t really a thorough documentation available, and there aren’t any great tutorials out there either." }, { "code": null, "e": 1572, "s": 1249, "text": "This blog post can hopefully be a step in the right direction. It is not meant to be or replace a thorough documentation, but rather a concise, practical introduction to Acme. Above all, it should give you an idea of the design choices underlying the framework, and what that means for the implementation of RL algorithms." }, { "code": null, "e": 1937, "s": 1572, "text": "In particular, I am going to discuss my implementations of two simple algorithms, SARSA and Q learning, with the goal to play the game Blackjack. Once you understand what actors and agents are and how they are designed in Acme, I have no doubt that you will quickly get the idea of how to implement (probably) any reinforcement learning algorithm you can think of." }, { "code": null, "e": 2031, "s": 1937, "text": "Let’s dive into an actual example. As already mentioned, we want our agent to play Blackjack." }, { "code": null, "e": 2210, "s": 2031, "text": "Acme agents are not designed to interact with Gym environments. Instead, DeepMind has their own RL environment API. The difference is mainly in how the timesteps are represented." }, { "code": null, "e": 2345, "s": 2210, "text": "Fortunately, however, you can still make use of Gym environments too since Acme’s developers have provided wrapper functions for this." }, { "code": null, "e": 2402, "s": 2345, "text": "env = acme.wrappers.GymWrapper(gym.make('Blackjack-v0'))" }, { "code": null, "e": 2721, "s": 2402, "text": "There are 32 x 11 x 2 states in Blackjack, although not all those states can actually occur during a game, and there are two actions, “hit” and “stick”. For a description of these dimensions and why not all states can occur, you can check out the environment on GitHub here. I know this is not really obvious at first." }, { "code": null, "e": 2977, "s": 2721, "text": "It is critical to understand that there is a distinction between actors, learners, and agents. Actors interact with the environment. That is, they observe states and take actions according to some action-selection policy. The image below illustrates this." }, { "code": null, "e": 3287, "s": 2977, "text": "The learner consumes the data collected by the actor in order to learn or improve the policy, usually in an iterative, online fashion. For example, learning might consist of updates to a neural network’s parameters. The new parameters are passed to the actor, who then behaves according to the updated policy." }, { "code": null, "e": 3484, "s": 3287, "text": "The agent simply combines both the acting and the learning component, but usually no additional reinforcement learning logic needs to be implemented. The image below includes all three components." }, { "code": null, "e": 3897, "s": 3484, "text": "One of the main reasons for this factorization into actors, learners, and agents is to facilitate distributed reinforcement learning. If we do not care about that and if the algorithm is simple enough, however, it can also be sufficient to only implement the actor and simply integrate the learning steps within the actor’s update method. For the sake of simplicity, this also the approach that I am taking here." }, { "code": null, "e": 4481, "s": 3897, "text": "For example, the random agent below inherits from the acme.Actor class. The methods that must be implemented by the developer (you) are select_action, observe_first, observe, and update. As just mentioned, the latter is where the learning happens without the additional learner component. Note that this agent would work the same way without subclassing acme.Actor. The base class simply determines the methods that you must overwrite. This also ensures that the agent integrates as intended with other Acme components such as the environment loop that I am going to introduce below." }, { "code": null, "e": 4932, "s": 4481, "text": "This agent uses a policy that simply chooses hit or stick randomly, but generally the framework allows you huge flexibility with respect to how you want to implement a policy. Later, you will see an epsilon-greedy policy. In other cases, the policy may include a neural network that you can implement with TensorFlow, PyTorch, or JAX. In that sense, Acme is framework agnostic, so you can combine it with whatever machine learning library you prefer." }, { "code": null, "e": 5145, "s": 4932, "text": "In the update method, the actor usually only pulls the most recent parameters from the learner. If you do not use a separate learner, however, the RL logic goes inside the update method (you will see that later)." }, { "code": null, "e": 5386, "s": 5145, "text": "If you already know a bit about reinforcement learning and have already implemented an RL algorithm, the following loop will be very familiar to you. Each episode consists of four steps, which are repeated until a terminal state is reached." }, { "code": null, "e": 5482, "s": 5386, "text": "observe a statetake an action according to the behavior policyobserve a rewardupdate the policy" }, { "code": null, "e": 5498, "s": 5482, "text": "observe a state" }, { "code": null, "e": 5546, "s": 5498, "text": "take an action according to the behavior policy" }, { "code": null, "e": 5563, "s": 5546, "text": "observe a reward" }, { "code": null, "e": 5581, "s": 5563, "text": "update the policy" }, { "code": null, "e": 5593, "s": 5581, "text": "In code ..." }, { "code": null, "e": 5742, "s": 5593, "text": "Sometimes you may have to implement a loop like that, especially if you wish to customize it. But mostly, this loop will always be exactly the same." }, { "code": null, "e": 6169, "s": 5742, "text": "Conveniently, there is a shortcut in Acme: the EnvironmentLoop, which performs pretty much exactly the steps seen above. You just have to pass your environment and agent instances and then you can run either a single episode or as many as you want with a single line of code. There are also a number of loggers available that track important metrics such as the number of steps taken in each episode and the collected rewards." }, { "code": null, "e": 6337, "s": 6169, "text": "# init Acme's environment looploop = EnvironmentLoop(env, agent, logger=InMemoryLogger())# run a single episodeloop.run_episode()# or run multiple episodesloop.run(10)" }, { "code": null, "e": 6485, "s": 6337, "text": "Of course, a random agent is not very useful. My promise was to show how to implement some actual reinforcement learning algorithms. So here we go." }, { "code": null, "e": 6758, "s": 6485, "text": "By the way, if you are not familiar with RL at all, check out the book Reinforcement Learning: An Introduction by Sutton and Barto (2018). The two algorithms you usually learn first — either in the book or if you take an RL course at university — are SARSA and Q learning." }, { "code": null, "e": 6890, "s": 6758, "text": "By now, you already know how Acme agents (or actors) are designed. Let’s look at how you can implement the SARSA algorithm in Acme." }, { "code": null, "e": 7135, "s": 6890, "text": "SARSA is an on-policy algorithm whose updates depend on the state, action, reward, next state, and next action (hence the name). Since this is not meant to be a theoretical RL tutorial, I do not go into the details of the algorithm itself here." }, { "code": null, "e": 7460, "s": 7135, "text": "First things first, inside the agent’s __init__ method, we initialize Q, the state-action value matrix, and the behavior policy, which is an epsilon greedy policy here. Note also that this agent must always store its last timestep, action, and next timestep as they are needed in the update step. So we also initialize them." }, { "code": null, "e": 7932, "s": 7460, "text": "In observe, there is usually not much you have to do. In this case, we simply store the observed timestep and the action that was taken. This is not always necessary, however. Sometimes, for example, you may want to store timesteps (and whole trajectories) in a dataset or a replay buffer instead. Acme also provides dataset and adder components for this purpose. In fact, there is also a library which was developed by DeepMind too. It’s called Reverb (see GitHub here)." }, { "code": null, "e": 8069, "s": 7932, "text": "The transform_state method above is only a helper function to put states into the right format in order to correctly index the Q matrix." }, { "code": null, "e": 8145, "s": 8069, "text": "Finally, to train SARSA on the environment for 500,000 episodes, simply run" }, { "code": null, "e": 8241, "s": 8145, "text": "agent = SarsaAgent()loop = EnvironmentLoop(env, agent, logger=InMemoryLogger())loop.run(500000)" }, { "code": null, "e": 8425, "s": 8241, "text": "The Q learning agent below is very similar to the SARSA agent. They only differ in the way how updates to the Q matrix are made. This is because Q learning is an off-policy algorithm." }, { "code": null, "e": 8500, "s": 8425, "text": "To train the Q learning agent on the environment for 500,000 episodes, run" }, { "code": null, "e": 8600, "s": 8500, "text": "agent = QLearningAgent()loop = EnvironmentLoop(env, agent, logger=InMemoryLogger())loop.run(500000)" }, { "code": null, "e": 8930, "s": 8600, "text": "I think Acme is a really great framework for reinforcement learning because you don’t have to develop your algorithms from scratch. So instead of figuring out by yourself how to write readable and reproducible RL code, you can just rely on the undoubtedly smart researchers and developers at DeepMind, who have done that for you." }, { "code": null, "e": 9102, "s": 8930, "text": "Acme allows you to implement any reinforcement learning algorithm, and you can combine it with any other machine learning framework, including TensorFlow, PyTorch and JAX." }, { "code": null, "e": 9218, "s": 9102, "text": "If you want to learn more about Acme, you can read DeepMind’s research paper and check out their GitHub repository." }, { "code": null, "e": 9436, "s": 9218, "text": "There you will also find the implementation of some common algorithms such as Deep Q-Networks (DQN), Deep Deterministic Policy Gradient (DDPG), Monte Carlo Tree Search (MCTS), Behavior Cloning (BC), IMPALA, and so on." }, { "code": null, "e": 9567, "s": 9436, "text": "No matter if you are a advanced researcher or only a beginner interested in reinforcement learning, I encourage you to try it out." }, { "code": null, "e": 9630, "s": 9567, "text": "Thank you for reading. If you have any questions, let me know." }, { "code": null, "e": 9689, "s": 9630, "text": "My Jupyter Notebook containing the code can be found here." }, { "code": null, "e": 9891, "s": 9689, "text": "If you are interested, you can also check out my reinforcement learning course project. Besides SARSA and Q-learning, I also implemented dyna-Q, prioritized sweeping and a Mote Carlo Tree Search agent." }, { "code": null, "e": 9987, "s": 9891, "text": "Hoffman et al (2020): Acme: A Research Framework for Distributed Reinforcement Learning. ArXiv." } ]
Addition and Blending of images using OpenCV in Python - GeeksforGeeks
06 Feb, 2018 When we talk about images, we know its all about the matrix either binary image(0, 1), gray scale image(0-255) or RGB image(255 255 255). So additions of the image is adding the numbers of two matrices. In OpenCV, we have a command cv2.add() to add the images. Below is code for Addition of two images using OpenCV : # Python program for adding# images using OpenCV # import OpenCV fileimport cv2 # Read Image1mountain = cv2.imread('F:\mountain.jpg', 1) # Read image2dog = cv2.imread('F:\dog.jpg', 1) # Add the imagesimg = cv2.add(mountain, dog) # Show the imagecv2.imshow('image', img) # Wait for a keycv2.waitKey(0) # Distroy all the window opencv2.distroyAllWindows() But sometimes we do not want to perform simple addition in image, so in this case we have blending. This is also image addition, but different weights are given to images so that it gives a feeling of blending or transparency. Images are added as per the equation below : g(x) = (1 - a)f(x) + af1(x) By varying a from 0 -> 1, you can perform a cool transition between one image to another. Here two images are taken to blend together. First image is given a weight of 0.3 and second image is given 0.7, cv2.addWeighted() applies following equation on the image : img = a . img1 + b . img 2 + y Here y is taken as zero. Below is code for Blending of images using OpenCV : # Python program for blending of# images using OpenCV # import OpenCV fileimport cv2 # Read Image1mountain = cv2.imread('F:\mountain.jpg', 1) # Read image2dog = cv2.imread('F:\dog.jpg', 1) # Blending the images with 0.3 and 0.7img = cv2.addWeighted(mountain, 0.3, dog, 0.7, 0) # Show the imagecv2.imshow('image', img) # Wait for a keycv2.waitKey(0) # Distroy all the window opencv2.distroyAllWindows() Image-Processing OpenCV 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 How to Install PIP on Windows ? Enumerate() in Python Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Create a Pandas DataFrame from Lists Reading and Writing to text files in Python
[ { "code": null, "e": 25174, "s": 25146, "text": "\n06 Feb, 2018" }, { "code": null, "e": 25435, "s": 25174, "text": "When we talk about images, we know its all about the matrix either binary image(0, 1), gray scale image(0-255) or RGB image(255 255 255). So additions of the image is adding the numbers of two matrices. In OpenCV, we have a command cv2.add() to add the images." }, { "code": null, "e": 25491, "s": 25435, "text": "Below is code for Addition of two images using OpenCV :" }, { "code": "# Python program for adding# images using OpenCV # import OpenCV fileimport cv2 # Read Image1mountain = cv2.imread('F:\\mountain.jpg', 1) # Read image2dog = cv2.imread('F:\\dog.jpg', 1) # Add the imagesimg = cv2.add(mountain, dog) # Show the imagecv2.imshow('image', img) # Wait for a keycv2.waitKey(0) # Distroy all the window opencv2.distroyAllWindows()", "e": 25852, "s": 25491, "text": null }, { "code": null, "e": 26124, "s": 25852, "text": "But sometimes we do not want to perform simple addition in image, so in this case we have blending. This is also image addition, but different weights are given to images so that it gives a feeling of blending or transparency. Images are added as per the equation below :" }, { "code": null, "e": 26152, "s": 26124, "text": "g(x) = (1 - a)f(x) + af1(x)" }, { "code": null, "e": 26415, "s": 26152, "text": "By varying a from 0 -> 1, you can perform a cool transition between one image to another. Here two images are taken to blend together. First image is given a weight of 0.3 and second image is given 0.7, cv2.addWeighted() applies following equation on the image :" }, { "code": null, "e": 26446, "s": 26415, "text": "img = a . img1 + b . img 2 + y" }, { "code": null, "e": 26471, "s": 26446, "text": "Here y is taken as zero." }, { "code": null, "e": 26523, "s": 26471, "text": "Below is code for Blending of images using OpenCV :" }, { "code": "# Python program for blending of# images using OpenCV # import OpenCV fileimport cv2 # Read Image1mountain = cv2.imread('F:\\mountain.jpg', 1) # Read image2dog = cv2.imread('F:\\dog.jpg', 1) # Blending the images with 0.3 and 0.7img = cv2.addWeighted(mountain, 0.3, dog, 0.7, 0) # Show the imagecv2.imshow('image', img) # Wait for a keycv2.waitKey(0) # Distroy all the window opencv2.distroyAllWindows()", "e": 26932, "s": 26523, "text": null }, { "code": null, "e": 26949, "s": 26932, "text": "Image-Processing" }, { "code": null, "e": 26956, "s": 26949, "text": "OpenCV" }, { "code": null, "e": 26963, "s": 26956, "text": "Python" }, { "code": null, "e": 27061, "s": 26963, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27070, "s": 27061, "text": "Comments" }, { "code": null, "e": 27083, "s": 27070, "text": "Old Comments" }, { "code": null, "e": 27101, "s": 27083, "text": "Python Dictionary" }, { "code": null, "e": 27136, "s": 27101, "text": "Read a file line by line in Python" }, { "code": null, "e": 27168, "s": 27136, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27190, "s": 27168, "text": "Enumerate() in Python" }, { "code": null, "e": 27220, "s": 27190, "text": "Iterate over a list in Python" }, { "code": null, "e": 27262, "s": 27220, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27288, "s": 27262, "text": "Python String | replace()" }, { "code": null, "e": 27331, "s": 27288, "text": "Python program to convert a list to string" }, { "code": null, "e": 27368, "s": 27331, "text": "Create a Pandas DataFrame from Lists" } ]
Arrange array elements such that last digit of an element is equal to first digit of the next element - GeeksforGeeks
05 Feb, 2021 Given an array arr[] of integers, the task is to arrange the array elements such that the last digit of an element is equal to first digit of the next element. Examples: Input: arr[] = {123, 321} Output: 123 321 Input: arr[] = {451, 378, 123, 1254} Output: 1254 451 123 378 Naive approach: Find all the permutations of the array elements and then print the arranged array which meets the required condition. The time complexity of this approach is O(N!) Efficient approach: Create a directed graph where there will be a directed edge from a node A to node B if the last digit of the number represented by Node A is equal to the first digit of the number represented by Node B. Now, find the Eulerian path for the graph formed. The complexity of the above algorithm is O(E * E) where E is the number of edges in the graph. Below is the implementation of the above approach: C++ Java Python3 C# // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // To store the array elementsvector<string> arr; // Adjacency list for the graph nodesvector<vector<int> > graph; // To store the euler pathvector<string> path; // Print eulerian pathbool print_euler(int i, int visited[], int count){ // Mark node as visited // and increase the count visited[i] = 1; count++; // If all the nodes are visited // then we have traversed the euler path if (count == graph.size()) { path.push_back(arr[i]); return true; } // Check if the node lies in euler path bool b = false; // Traverse through remaining edges for (int j = 0; j < graph[i].size(); j++) if (visited[graph[i][j]] == 0) { b |= print_euler(graph[i][j], visited, count); } // If the euler path is found if (b) { path.push_back(arr[i]); return true; } // Else unmark the node else { visited[i] = 0; count--; return false; }} // Function to create the graph and// print the required pathvoid connect(){ int n = arr.size(); graph.clear(); graph.resize(n); // Connect the nodes for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) continue; // If the last character matches with the // first character if (arr[i][arr[i].length() - 1] == arr[j][0]) { graph[i].push_back(j); } } } // Print the path for (int i = 0; i < n; i++) { int visited[n] = { 0 }, count = 0; // If the euler path starts // from the ith node if (print_euler(i, visited, count)) break; } // Print the euler path for (int i = path.size() - 1; i >= 0; i--) { cout << path[i]; if (i != 0) cout << " "; }}// Driver codeint main(){ arr.push_back("451"); arr.push_back("378"); arr.push_back("123"); arr.push_back("1254"); // Create graph and print the path connect(); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // To store the array elementsstatic List<String> arr = new ArrayList<String>(); // Adjacency list for the graph nodesstatic List<List<Integer>> graph = new ArrayList<List<Integer>>(); // To store the euler pathstatic List<String> path = new ArrayList<String>(); // Print eulerian pathstatic boolean print_euler(int i, int []visited, int count){ // Mark node as visited // and increase the count visited[i] = 1; count++; // If all the nodes are visited // then we have traversed the euler path if (count == graph.size()) { path.add(arr.get(i)); return true; } // Check if the node lies in euler path boolean b = false; // Traverse through remaining edges for(int j = 0; j < graph.get(i).size(); j++) if (visited[graph.get(i).get(j)] == 0) { b |= print_euler(graph.get(i).get(j), visited, count); } // If the euler path is found if (b) { path.add(arr.get(i)); return true; } // Else unmark the node else { visited[i] = 0; count--; return false; }} // Function to create the graph and// print the required pathstatic void connect(){ int n = arr.size(); graph = new ArrayList<List<Integer>>(n); for(int i = 0; i < n; i++) { graph.add(new ArrayList<Integer>()); } // Connect the nodes for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { if (i == j) continue; // If the last character matches with the // first character if (arr.get(i).charAt((arr.get(i).length()) - 1) == arr.get(j).charAt(0)) { graph.get(i).add(j); } } } // Print the path for(int i = 0; i < n; i++) { int []visited = new int[n]; int count = 0; // If the euler path starts // from the ith node if (print_euler(i, visited, count)) break; } // Print the euler path for(int i = path.size() - 1; i >= 0; i--) { System.out.print(path.get(i)); if (i != 0) System.out.print(" "); }} // Driver codepublic static void main(String []args){ arr.add("451"); arr.add("378"); arr.add("123"); arr.add("1254"); // Create graph and print the path connect();}} // This code is contributed by pratham76 # Python3 implementation of the approach # Print eulerian path def print_euler(i, visited, count): # Mark node as visited # and increase the count visited[i] = 1 count += 1 # If all the nodes are visited then # we have traversed the euler path if count == len(graph): path.append(arr[i]) return True # Check if the node lies in euler path b = False # Traverse through remaining edges for j in range(0, len(graph[i])): if visited[graph[i][j]] == 0: b |= print_euler(graph[i][j], visited, count) # If the euler path is found if b: path.append(arr[i]) return True # Else unmark the node else: visited[i] = 0 count -= 1 return False # Function to create the graph# and print the required path def connect(): n = len(arr) # Connect the nodes for i in range(0, n): for j in range(0, n): if i == j: continue # If the last character matches # with the first character if arr[i][-1] == arr[j][0]: graph[i].append(j) # Print the path for i in range(0, n): visited = [0] * n count = 0 # If the euler path starts # from the ith node if print_euler(i, visited, count): break # Print the euler path for i in range(len(path) - 1, -1, -1): print(path[i], end="") if i != 0: print(" ", end="") # Driver codeif __name__ == "__main__": # To store the array elements arr = [] arr.append("451") arr.append("378") arr.append("123") arr.append("1254") # Adjacency list for the graph nodes graph = [[] for i in range(len(arr))] # To store the euler path path = [] # Create graph and print the path connect() # This code is contributed by Rituraj Jain // C# implementation of the approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // To store the array elementsstatic List<string> arr = new List<string>(); // Adjacency list for the graph nodesstatic List<List<int> > graph= new List<List<int>>(); // To store the euler pathstatic List<string> path = new List<string>(); // Print eulerian pathstatic bool print_euler(int i, int []visited, int count){ // Mark node as visited // and increase the count visited[i] = 1; count++; // If all the nodes are visited // then we have traversed the euler path if (count == graph.Count) { path.Add(arr[i]); return true; } // Check if the node lies in euler path bool b = false; // Traverse through remaining edges for (int j = 0; j < graph[i].Count; j++) if (visited[graph[i][j]] == 0) { b |= print_euler(graph[i][j], visited, count); } // If the euler path is found if (b) { path.Add(arr[i]); return true; } // Else unmark the node else { visited[i] = 0; count--; return false; }} // Function to create the graph and// print the required pathstatic void connect(){ int n = arr.Count; graph=new List<List<int>>(n); for(int i = 0; i < n; i++) { graph.Add(new List<int>()); } // Connect the nodes for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) continue; // If the last character matches with the // first character if (arr[i][(arr[i].Length) - 1] == arr[j][0]) { graph[i].Add(j); } } } // Print the path for (int i = 0; i < n; i++) { int []visited = new int[n]; int count = 0; // If the euler path starts // from the ith node if (print_euler(i, visited, count)) break; } // Print the euler path for (int i = path.Count - 1; i >= 0; i--) { Console.Write(path[i]); if (i != 0) Console.Write(" "); }} // Driver codepublic static void Main(params string []args){ arr.Add("451"); arr.Add("378"); arr.Add("123"); arr.Add("1254"); // Create graph and print the path connect();}} // This code is contributed by rutvik_56. 1254 451 123 378 Time Complexity : O(N* log(N)) Auxiliary Space: O(N) rituraj_jain ujjwalgoel1103 rutvik_56 pratham76 Advanced Data Structure Arrays Graph Arrays Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Proof that Dominant Set of a Graph is NP-Complete 2-3 Trees | (Search, Insert and Deletion) Extendible Hashing (Dynamic approach to DBMS) Advantages of Trie Data Structure Cartesian Tree Arrays in Java Arrays in C/C++ Program for array rotation Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews
[ { "code": null, "e": 24462, "s": 24434, "text": "\n05 Feb, 2021" }, { "code": null, "e": 24622, "s": 24462, "text": "Given an array arr[] of integers, the task is to arrange the array elements such that the last digit of an element is equal to first digit of the next element." }, { "code": null, "e": 24633, "s": 24622, "text": "Examples: " }, { "code": null, "e": 24675, "s": 24633, "text": "Input: arr[] = {123, 321} Output: 123 321" }, { "code": null, "e": 24739, "s": 24675, "text": "Input: arr[] = {451, 378, 123, 1254} Output: 1254 451 123 378 " }, { "code": null, "e": 24919, "s": 24739, "text": "Naive approach: Find all the permutations of the array elements and then print the arranged array which meets the required condition. The time complexity of this approach is O(N!)" }, { "code": null, "e": 25287, "s": 24919, "text": "Efficient approach: Create a directed graph where there will be a directed edge from a node A to node B if the last digit of the number represented by Node A is equal to the first digit of the number represented by Node B. Now, find the Eulerian path for the graph formed. The complexity of the above algorithm is O(E * E) where E is the number of edges in the graph." }, { "code": null, "e": 25338, "s": 25287, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25342, "s": 25338, "text": "C++" }, { "code": null, "e": 25347, "s": 25342, "text": "Java" }, { "code": null, "e": 25355, "s": 25347, "text": "Python3" }, { "code": null, "e": 25358, "s": 25355, "text": "C#" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // To store the array elementsvector<string> arr; // Adjacency list for the graph nodesvector<vector<int> > graph; // To store the euler pathvector<string> path; // Print eulerian pathbool print_euler(int i, int visited[], int count){ // Mark node as visited // and increase the count visited[i] = 1; count++; // If all the nodes are visited // then we have traversed the euler path if (count == graph.size()) { path.push_back(arr[i]); return true; } // Check if the node lies in euler path bool b = false; // Traverse through remaining edges for (int j = 0; j < graph[i].size(); j++) if (visited[graph[i][j]] == 0) { b |= print_euler(graph[i][j], visited, count); } // If the euler path is found if (b) { path.push_back(arr[i]); return true; } // Else unmark the node else { visited[i] = 0; count--; return false; }} // Function to create the graph and// print the required pathvoid connect(){ int n = arr.size(); graph.clear(); graph.resize(n); // Connect the nodes for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) continue; // If the last character matches with the // first character if (arr[i][arr[i].length() - 1] == arr[j][0]) { graph[i].push_back(j); } } } // Print the path for (int i = 0; i < n; i++) { int visited[n] = { 0 }, count = 0; // If the euler path starts // from the ith node if (print_euler(i, visited, count)) break; } // Print the euler path for (int i = path.size() - 1; i >= 0; i--) { cout << path[i]; if (i != 0) cout << \" \"; }}// Driver codeint main(){ arr.push_back(\"451\"); arr.push_back(\"378\"); arr.push_back(\"123\"); arr.push_back(\"1254\"); // Create graph and print the path connect(); return 0;}", "e": 27450, "s": 25358, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // To store the array elementsstatic List<String> arr = new ArrayList<String>(); // Adjacency list for the graph nodesstatic List<List<Integer>> graph = new ArrayList<List<Integer>>(); // To store the euler pathstatic List<String> path = new ArrayList<String>(); // Print eulerian pathstatic boolean print_euler(int i, int []visited, int count){ // Mark node as visited // and increase the count visited[i] = 1; count++; // If all the nodes are visited // then we have traversed the euler path if (count == graph.size()) { path.add(arr.get(i)); return true; } // Check if the node lies in euler path boolean b = false; // Traverse through remaining edges for(int j = 0; j < graph.get(i).size(); j++) if (visited[graph.get(i).get(j)] == 0) { b |= print_euler(graph.get(i).get(j), visited, count); } // If the euler path is found if (b) { path.add(arr.get(i)); return true; } // Else unmark the node else { visited[i] = 0; count--; return false; }} // Function to create the graph and// print the required pathstatic void connect(){ int n = arr.size(); graph = new ArrayList<List<Integer>>(n); for(int i = 0; i < n; i++) { graph.add(new ArrayList<Integer>()); } // Connect the nodes for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { if (i == j) continue; // If the last character matches with the // first character if (arr.get(i).charAt((arr.get(i).length()) - 1) == arr.get(j).charAt(0)) { graph.get(i).add(j); } } } // Print the path for(int i = 0; i < n; i++) { int []visited = new int[n]; int count = 0; // If the euler path starts // from the ith node if (print_euler(i, visited, count)) break; } // Print the euler path for(int i = path.size() - 1; i >= 0; i--) { System.out.print(path.get(i)); if (i != 0) System.out.print(\" \"); }} // Driver codepublic static void main(String []args){ arr.add(\"451\"); arr.add(\"378\"); arr.add(\"123\"); arr.add(\"1254\"); // Create graph and print the path connect();}} // This code is contributed by pratham76", "e": 29980, "s": 27450, "text": null }, { "code": "# Python3 implementation of the approach # Print eulerian path def print_euler(i, visited, count): # Mark node as visited # and increase the count visited[i] = 1 count += 1 # If all the nodes are visited then # we have traversed the euler path if count == len(graph): path.append(arr[i]) return True # Check if the node lies in euler path b = False # Traverse through remaining edges for j in range(0, len(graph[i])): if visited[graph[i][j]] == 0: b |= print_euler(graph[i][j], visited, count) # If the euler path is found if b: path.append(arr[i]) return True # Else unmark the node else: visited[i] = 0 count -= 1 return False # Function to create the graph# and print the required path def connect(): n = len(arr) # Connect the nodes for i in range(0, n): for j in range(0, n): if i == j: continue # If the last character matches # with the first character if arr[i][-1] == arr[j][0]: graph[i].append(j) # Print the path for i in range(0, n): visited = [0] * n count = 0 # If the euler path starts # from the ith node if print_euler(i, visited, count): break # Print the euler path for i in range(len(path) - 1, -1, -1): print(path[i], end=\"\") if i != 0: print(\" \", end=\"\") # Driver codeif __name__ == \"__main__\": # To store the array elements arr = [] arr.append(\"451\") arr.append(\"378\") arr.append(\"123\") arr.append(\"1254\") # Adjacency list for the graph nodes graph = [[] for i in range(len(arr))] # To store the euler path path = [] # Create graph and print the path connect() # This code is contributed by Rituraj Jain", "e": 31846, "s": 29980, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // To store the array elementsstatic List<string> arr = new List<string>(); // Adjacency list for the graph nodesstatic List<List<int> > graph= new List<List<int>>(); // To store the euler pathstatic List<string> path = new List<string>(); // Print eulerian pathstatic bool print_euler(int i, int []visited, int count){ // Mark node as visited // and increase the count visited[i] = 1; count++; // If all the nodes are visited // then we have traversed the euler path if (count == graph.Count) { path.Add(arr[i]); return true; } // Check if the node lies in euler path bool b = false; // Traverse through remaining edges for (int j = 0; j < graph[i].Count; j++) if (visited[graph[i][j]] == 0) { b |= print_euler(graph[i][j], visited, count); } // If the euler path is found if (b) { path.Add(arr[i]); return true; } // Else unmark the node else { visited[i] = 0; count--; return false; }} // Function to create the graph and// print the required pathstatic void connect(){ int n = arr.Count; graph=new List<List<int>>(n); for(int i = 0; i < n; i++) { graph.Add(new List<int>()); } // Connect the nodes for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) continue; // If the last character matches with the // first character if (arr[i][(arr[i].Length) - 1] == arr[j][0]) { graph[i].Add(j); } } } // Print the path for (int i = 0; i < n; i++) { int []visited = new int[n]; int count = 0; // If the euler path starts // from the ith node if (print_euler(i, visited, count)) break; } // Print the euler path for (int i = path.Count - 1; i >= 0; i--) { Console.Write(path[i]); if (i != 0) Console.Write(\" \"); }} // Driver codepublic static void Main(params string []args){ arr.Add(\"451\"); arr.Add(\"378\"); arr.Add(\"123\"); arr.Add(\"1254\"); // Create graph and print the path connect();}} // This code is contributed by rutvik_56.", "e": 34192, "s": 31846, "text": null }, { "code": null, "e": 34209, "s": 34192, "text": "1254 451 123 378" }, { "code": null, "e": 34242, "s": 34211, "text": "Time Complexity : O(N* log(N))" }, { "code": null, "e": 34264, "s": 34242, "text": "Auxiliary Space: O(N)" }, { "code": null, "e": 34279, "s": 34266, "text": "rituraj_jain" }, { "code": null, "e": 34294, "s": 34279, "text": "ujjwalgoel1103" }, { "code": null, "e": 34304, "s": 34294, "text": "rutvik_56" }, { "code": null, "e": 34314, "s": 34304, "text": "pratham76" }, { "code": null, "e": 34338, "s": 34314, "text": "Advanced Data Structure" }, { "code": null, "e": 34345, "s": 34338, "text": "Arrays" }, { "code": null, "e": 34351, "s": 34345, "text": "Graph" }, { "code": null, "e": 34358, "s": 34351, "text": "Arrays" }, { "code": null, "e": 34364, "s": 34358, "text": "Graph" }, { "code": null, "e": 34462, "s": 34364, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34471, "s": 34462, "text": "Comments" }, { "code": null, "e": 34484, "s": 34471, "text": "Old Comments" }, { "code": null, "e": 34534, "s": 34484, "text": "Proof that Dominant Set of a Graph is NP-Complete" }, { "code": null, "e": 34576, "s": 34534, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 34622, "s": 34576, "text": "Extendible Hashing (Dynamic approach to DBMS)" }, { "code": null, "e": 34656, "s": 34622, "text": "Advantages of Trie Data Structure" }, { "code": null, "e": 34671, "s": 34656, "text": "Cartesian Tree" }, { "code": null, "e": 34686, "s": 34671, "text": "Arrays in Java" }, { "code": null, "e": 34702, "s": 34686, "text": "Arrays in C/C++" }, { "code": null, "e": 34729, "s": 34702, "text": "Program for array rotation" }, { "code": null, "e": 34777, "s": 34729, "text": "Stack Data Structure (Introduction and Program)" } ]
How to compare two dates in Java?
In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2. int compareTo(T o) import java.text.*; import java.util.Date; public class CompareTwoDatesTest { public static void main(String[] args) throws ParseException { SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd"); Date d1 = sdformat.parse("2019-04-15"); Date d2 = sdformat.parse("2019-08-10"); System.out.println("The date 1 is: " + sdformat.format(d1)); System.out.println("The date 2 is: " + sdformat.format(d2)); if(d1.compareTo(d2) > 0) { System.out.println("Date 1 occurs after Date 2"); } else if(d1.compareTo(d2) < 0) { System.out.println("Date 1 occurs before Date 2"); } else if(d1.compareTo(d2) == 0) { System.out.println("Both dates are equal"); } } } In the above example, the date d1 occurs before the date d2, so it can display "Date 1 occurs before Date 2" in the console. The date 1 is: 2019-04-15 The date 2 is: 2019-08-10 Date 1 occurs before Date 2
[ { "code": null, "e": 1327, "s": 1062, "text": "In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value \"greater than 0\" if date1 is after date2 and it returns a value \"less than 0\" if date1 is before date2." }, { "code": null, "e": 1346, "s": 1327, "text": "int compareTo(T o)" }, { "code": null, "e": 2087, "s": 1346, "text": "import java.text.*;\nimport java.util.Date;\npublic class CompareTwoDatesTest {\n public static void main(String[] args) throws ParseException {\n SimpleDateFormat sdformat = new SimpleDateFormat(\"yyyy-MM-dd\");\n Date d1 = sdformat.parse(\"2019-04-15\");\n Date d2 = sdformat.parse(\"2019-08-10\");\n System.out.println(\"The date 1 is: \" + sdformat.format(d1));\n System.out.println(\"The date 2 is: \" + sdformat.format(d2));\n if(d1.compareTo(d2) > 0) {\n System.out.println(\"Date 1 occurs after Date 2\");\n } else if(d1.compareTo(d2) < 0) {\n System.out.println(\"Date 1 occurs before Date 2\");\n } else if(d1.compareTo(d2) == 0) {\n System.out.println(\"Both dates are equal\");\n }\n }\n}" }, { "code": null, "e": 2212, "s": 2087, "text": "In the above example, the date d1 occurs before the date d2, so it can display \"Date 1 occurs before Date 2\" in the console." }, { "code": null, "e": 2292, "s": 2212, "text": "The date 1 is: 2019-04-15\nThe date 2 is: 2019-08-10\nDate 1 occurs before Date 2" } ]
Saving multiple figures to one PDF file in matplotlib
To save multiple figures in one PDF file at once, we can take follwong steps Set the figure size and adjust the padding between and around the subplots. Set the figure size and adjust the padding between and around the subplots. Create a new figure (fig1) or activate and existing figure using figure() method. Create a new figure (fig1) or activate and existing figure using figure() method. Plot the first line using plot() method. Plot the first line using plot() method. Create another figure (fig2) or activate and existing figure using figure() method. Create another figure (fig2) or activate and existing figure using figure() method. Plot the second line using plot() method. Plot the second line using plot() method. Initialize a variable, filename, to make a pdf file. Initialize a variable, filename, to make a pdf file. Create a user-defined function save_multi_image() to save multiple images in a PDF file. Create a user-defined function save_multi_image() to save multiple images in a PDF file. Call the save_multi_image() function with filename. Call the save_multi_image() function with filename. Create a new PdfPages object. Create a new PdfPages object. Get the number of open figures. Get the number of open figures. Iterate the opened figures and save them into the file. Iterate the opened figures and save them into the file. Close the created PDF object. Close the created PDF object. from matplotlib import pyplot as plt from matplotlib.backends.backend_pdf import PdfPages plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True fig1 = plt.figure() plt.plot([2, 1, 7, 1, 2], color='red', lw=5) fig2 = plt.figure() plt.plot([3, 5, 1, 5, 3], color='green', lw=5) def save_multi_image(filename): pp = PdfPages(filename) fig_nums = plt.get_fignums() figs = [plt.figure(n) for n in fig_nums] for fig in figs: fig.savefig(pp, format='pdf') pp.close() filename = "multi.pdf" save_multi_image(filename) Upon execution, it will create a PDF "multi.pdf" in the Project Directory and save the following two images in that file.
[ { "code": null, "e": 1139, "s": 1062, "text": "To save multiple figures in one PDF file at once, we can take follwong steps" }, { "code": null, "e": 1215, "s": 1139, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1291, "s": 1215, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1373, "s": 1291, "text": "Create a new figure (fig1) or activate and existing figure using figure() method." }, { "code": null, "e": 1455, "s": 1373, "text": "Create a new figure (fig1) or activate and existing figure using figure() method." }, { "code": null, "e": 1496, "s": 1455, "text": "Plot the first line using plot() method." }, { "code": null, "e": 1537, "s": 1496, "text": "Plot the first line using plot() method." }, { "code": null, "e": 1621, "s": 1537, "text": "Create another figure (fig2) or activate and existing figure using figure() method." }, { "code": null, "e": 1705, "s": 1621, "text": "Create another figure (fig2) or activate and existing figure using figure() method." }, { "code": null, "e": 1747, "s": 1705, "text": "Plot the second line using plot() method." }, { "code": null, "e": 1789, "s": 1747, "text": "Plot the second line using plot() method." }, { "code": null, "e": 1842, "s": 1789, "text": "Initialize a variable, filename, to make a pdf file." }, { "code": null, "e": 1895, "s": 1842, "text": "Initialize a variable, filename, to make a pdf file." }, { "code": null, "e": 1984, "s": 1895, "text": "Create a user-defined function save_multi_image() to save multiple images in a PDF file." }, { "code": null, "e": 2073, "s": 1984, "text": "Create a user-defined function save_multi_image() to save multiple images in a PDF file." }, { "code": null, "e": 2125, "s": 2073, "text": "Call the save_multi_image() function with filename." }, { "code": null, "e": 2177, "s": 2125, "text": "Call the save_multi_image() function with filename." }, { "code": null, "e": 2207, "s": 2177, "text": "Create a new PdfPages object." }, { "code": null, "e": 2237, "s": 2207, "text": "Create a new PdfPages object." }, { "code": null, "e": 2269, "s": 2237, "text": "Get the number of open figures." }, { "code": null, "e": 2301, "s": 2269, "text": "Get the number of open figures." }, { "code": null, "e": 2357, "s": 2301, "text": "Iterate the opened figures and save them into the file." }, { "code": null, "e": 2413, "s": 2357, "text": "Iterate the opened figures and save them into the file." }, { "code": null, "e": 2443, "s": 2413, "text": "Close the created PDF object." }, { "code": null, "e": 2473, "s": 2443, "text": "Close the created PDF object." }, { "code": null, "e": 3051, "s": 2473, "text": "from matplotlib import pyplot as plt\nfrom matplotlib.backends.backend_pdf import PdfPages\n\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nfig1 = plt.figure()\nplt.plot([2, 1, 7, 1, 2], color='red', lw=5)\n\nfig2 = plt.figure()\nplt.plot([3, 5, 1, 5, 3], color='green', lw=5)\n\n\ndef save_multi_image(filename):\n pp = PdfPages(filename)\n fig_nums = plt.get_fignums()\n figs = [plt.figure(n) for n in fig_nums]\n for fig in figs:\n fig.savefig(pp, format='pdf')\n pp.close()\n\nfilename = \"multi.pdf\"\nsave_multi_image(filename)\n" }, { "code": null, "e": 3173, "s": 3051, "text": "Upon execution, it will create a PDF \"multi.pdf\" in the Project Directory and save the following two images in that file." } ]
Spring Cloud - Streams with Apache Kafka
In a distributed environment, services need to communicate with each other. The communication can either happen synchronously or asynchronously. In this section, we will look at how services can communicate by asynchronously using message brokers. Two major benefits of performing asynchronous communication − Producer and Consumer speed can differ − If the consumer of the data is slow or fast, it does not affect the producer processing and vice versa. Both can work at their own individual speeds without affecting each other. Producer and Consumer speed can differ − If the consumer of the data is slow or fast, it does not affect the producer processing and vice versa. Both can work at their own individual speeds without affecting each other. Producer does not need to handle requests from various consumers − There maybe multiple consumers who want to read the same set of data from the producer. With a message broker in between, the producer does not need to take care of the load these consumers generate. Plus, any outages at producer level would not block the consumer from reading older producer data, as this data would be available in the message brokers. Producer does not need to handle requests from various consumers − There maybe multiple consumers who want to read the same set of data from the producer. With a message broker in between, the producer does not need to take care of the load these consumers generate. Plus, any outages at producer level would not block the consumer from reading older producer data, as this data would be available in the message brokers. Apache Kafka and RabbitMQ are two well-known message brokers used for making asynchronous communication. In this tutorial, we will use Apache Kafka. Let’s use the case of Restaurant that we have been using earlier. So, let us say we have our Customer Service and the Restaurant Service communicating via asynchronous communication. To do that, we will use Apache Kafka. And we will need to use that in both services, i.e., Customer Service and Restaurant Service. To use Apache Kafka, we will update the POM of both services and add the following dependency. <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-stream-kafka</artifactId> </dependency> We also need to have Kafka instances running. There are multiple ways through which it can be done,but we will prefer starting Kafka using Docker container. Here are a few images we can consider using − https://hub.docker.com/r/bitnami/kafka/ https://hub.docker.com/r/bitnami/kafka/ https://docs.confluent.io/platform/current/quickstart/ce-docker-quickstart.html https://docs.confluent.io/platform/current/quickstart/ce-docker-quickstart.html https://github.com/wurstmeister/kafka-docker https://github.com/wurstmeister/kafka-docker Whichever image we use, the important thing here to note is that once the image is up and running,please ensure that the Kafka cluster is accessible at localhost:9092 Now that we have the Kafka cluster running on our image, let's move to the core example. There are three important concepts when it comes to Spring Cloud streams − External Messaging System − This is the component which is managed externally and is responsible to store the events/messages produced by the application that can be read by their subscriber/consumer. Note that this is not managed within the app/Spring. Few examples being Apache Kafka, RabbitMQ External Messaging System − This is the component which is managed externally and is responsible to store the events/messages produced by the application that can be read by their subscriber/consumer. Note that this is not managed within the app/Spring. Few examples being Apache Kafka, RabbitMQ Binders − This is the component which provides integration with messaging system, for example, consisting of IP address of messaging system, authentication, etc. Binders − This is the component which provides integration with messaging system, for example, consisting of IP address of messaging system, authentication, etc. Bindings − This component uses the Binders to produce messages to the messaging system or consume the message from a specific topic/queue. Bindings − This component uses the Binders to produce messages to the messaging system or consume the message from a specific topic/queue. All the above properties are defined in the application properties file. Example Let us use the case of Restaurant that we have been using earlier. So, let us suppose whenever a new service is added to the Customer Service, we want to notify the customer info to the nearby Restaurants about him/her. For this purpose, let us update our Customer Service first to include and use Kafka. Note that we will use Customer Service as a producer of the data. That is, whenever we add the Customer via API, it will also be added to the Kafka. spring: application: name: customer-service cloud: stream: source: customerBinding-out-0 kafka: binder: brokers: localhost:9092 replicationFactor: 1 bindings: customerBinding-out-0: destination: customer producer: partitionCount: 3 server: port: ${app_port} eureka: client: serviceURL: defaultZone: http://localhost:8900/eureka Points to note − We have defined a binder with the address of our local Kafka instances. We have defined a binder with the address of our local Kafka instances. We have also defined the binding ‘customerBinding-out-0’ which uses ‘customer’ topic to output the messages in. We have also defined the binding ‘customerBinding-out-0’ which uses ‘customer’ topic to output the messages in. We have also mentioned our binding in the stream.source so that we can imperatively use that in our code. We have also mentioned our binding in the stream.source so that we can imperatively use that in our code. Once this is done, let us now update our controller by adding a new method ‘addCustomer’ which is responsible to serve the POST request. And then, from the post request, we send the data to the Kafka Broker. package com.tutorialspoint; import java.util.HashMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.stream.function.StreamBridge; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController class RestaurantCustomerInstancesController { @Autowired private StreamBridge streamBridge; static HashMap<Long, Customer> mockCustomerData = new HashMap(); static{ mockCustomerData.put(1L, new Customer(1, "Jane", "DC")); mockCustomerData.put(2L, new Customer(2, "John", "SFO")); mockCustomerData.put(3L, new Customer(3, "Kate", "NY")); } @RequestMapping("/customer/{id}") public Customer getCustomerInfo(@PathVariable("id") Long id) { System.out.println("Querying customer for id with: " + id); return mockCustomerData.get(id); } @RequestMapping(path = "/customer/{id}", method = RequestMethod.POST) public Customer addCustomer(@PathVariable("id") Long id) { // add default name Customer defaultCustomer = new Customer(id, "Dwayne", "NY"); streamBridge.send("customerBinding-out-0", defaultCustomer); return defaultCustomer; } } Points to note We are Autowiring StreamBridge which is what we will use to send the messages. We are Autowiring StreamBridge which is what we will use to send the messages. The parameters we use in the ‘send’ method also specify the binding we want to use to send the data to. The parameters we use in the ‘send’ method also specify the binding we want to use to send the data to. Now let us update our Restaurant Service to include and subscribe to ‘customer’ topic. Note that we will use Restaurant Service as a consumer of the data. That is, whenever we add the Customer via API, the Restaurant Service would come to know about it via Kafka. First, let us update the application properties file. spring: application: name: restaurant-service cloud: function: definition: customerBinding stream: kafka: binder: brokers: localhost:9092 replicationFactor: 1 bindings: customerBinding-in-0: destination: customer server: port: ${app_port} eureka: client: serviceURL: defaultZone: http://localhost:8900/eureka Once this is done, let us now update our controller by adding a new method ‘customerBinding’ which is responsible to fetch the request and provide a function which will print the request along with its metadata details. package com.tutorialspoint; import java.util.HashMap; import java.util.List; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.stream.annotation.StreamListener; import org.springframework.cloud.stream.function.StreamBridge; import org.springframework.context.annotation.Bean; import org.springframework.kafka.support.Acknowledgment; import org.springframework.kafka.support.KafkaHeaders; import org.springframework.messaging.Message; import org.springframework.messaging.support.MessageBuilder; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController class RestaurantController { @Autowired CustomerService customerService; @Autowired private StreamBridge streamBridge; static HashMap<Long, Restaurant> mockRestaurantData = new HashMap(); static{ mockRestaurantData.put(1L, new Restaurant(1, "Pandas", "DC")); mockRestaurantData.put(2L, new Restaurant(2, "Indies", "SFO")); mockRestaurantData.put(3L, new Restaurant(3, "Little Italy", "DC")); mockRestaurantData.put(4L, new Restaurant(4, "Pizeeria", "NY")); } @RequestMapping("/restaurant/customer/{id}") public List<Restaurant> getRestaurantForCustomer(@PathVariable("id") Long id) { System.out.println("Got request for customer with id: " + id); String customerCity = customerService.getCustomerById(id).getCity(); return mockRestaurantData.entrySet().stream().filter( entry -> entry.getValue().getCity().equals(customerCity)) .map(entry -> entry.getValue()) .collect(Collectors.toList()); } @RequestMapping("/restaurant/cust/{id}") public void getRestaurantForCust(@PathVariable("id") Long id) { streamBridge.send("ordersBinding-out-0", id); } @Bean public Consumer<Message<Customer>> customerBinding() { return msg -> { System.out.println(msg); }; } } Points to note − We are using ‘customerBinding’ which is supposed to pass on the function which would be called when a message arrives for this binding. We are using ‘customerBinding’ which is supposed to pass on the function which would be called when a message arrives for this binding. The name that we use for this function/bean also needs to be used in the YAML file while creating the bundling and specifying the topic. The name that we use for this function/bean also needs to be used in the YAML file while creating the bundling and specifying the topic. Now, let us execute the above code as always, start the Eureka Server. Note that this is not hard requirement and is present here for the sake of completeness. Then, let us compile and start updating Customer Service using the following command − mvn clean install ; java -Dapp_port=8083 -jar .\target\spring-cloud-eurekaclient- 1.0.jar --spring.config.location=classpath:application-kafka.yml Then, let us compile and start updating Restaurant Service using the following command − mvn clean install; java -Dapp_port=8082 -jar .\target\spring-cloud-feign-client- 1.0.jar --spring.config.location=classpath:application-kafka.yml And we are set, let us now test our code pieces by hitting the API − curl -X POST http://localhost:8083/customer/1 Here is the output that we will get for this API − { "id": 1, "name": "Dwayne", "city": "NY" } And now, let us check the logs for the Restaurant Service − GenericMessage [payload=Customer [id=1, name=Dwayne, city=NY], headers={kafka_offset=1,... So, effectively, you see that using Kafka Broker, Restaurant Service was notified about the newly added Customer. Partitions and Consumer Groups are two important concepts that you should be aware of while using Spring Cloud streams. Partitions − They are used to partition the data so that we can divide the work between multiple consumers. Let us see how to partition the data in Spring Cloud. Say, we want to partition the data based on the Customer ID. So, let us update our Customer Service for the same. For that, what we will need to tell Let us update our Customer Service application property to specify the key for our data. spring: application: name: customer-service cloud: function: definition: ordersBinding stream: source: customerBinding-out-0 kafka: binder: brokers: localhost:9092 replicationFactor: 1 bindings: customerBinding-out-0: destination: customer producer: partitionKeyExpression: 'getPayload().getId()' partitionCount: 3 server: port: ${app_port} eureka: client: serviceURL: defaultZone: http://localhost:8900/eureka For specifying the key, i.e., “partitionKeyExpression” we provide Spring Expression Language. The expression assumes the type as GenericMessage<Customer> since we are sending the Customer data in the message. Note that GenericMessage is the Spring Framework class used for wrapping the payload and the headers in a single object. So, we get the payload from this message which is of the type Customer and then we call the getId() method on the customer. Now, let us also update our consumer, i.e., the Restaurant Service to log more info while consuming the request. Now, let us execute the above code as always, start the Eureka Server. Note that this is not a hard requirement and is present here for the sake of completeness. Then, let us compile and start updating Customer Service using the following command − mvn clean install ; java -Dapp_port=8083 -jar .\target\spring-cloud-eurekaclient- 1.0.jar --spring.config.location=classpath:application-kafka.yml Then, let us compile and start updating Restaurant Service using the following command − mvn clean install; java -Dapp_port=8082 -jar .\target\spring-cloud-feign-client- 1.0.jar --spring.config.location=classpath:application-kafka.yml And we are set, let us now test our code pieces. As part of testing, here is what we will do − Insert a customer with Id 1: curl -X POST http://localhost:8083/customer/1 Insert a customer with Id 1: curl -X POST http://localhost:8083/customer/1 Insert a customer with Id 1: curl -X POST http://localhost:8083/customer/1 Insert a customer with Id 1: curl -X POST http://localhost:8083/customer/1 Insert a customer with Id 1: curl -X POST http://localhost:8083/customer/5 Insert a customer with Id 1: curl -X POST http://localhost:8083/customer/5 Insert a customer with Id 1: curl -X POST http://localhost:8083/customer/3 Insert a customer with Id 1: curl -X POST http://localhost:8083/customer/3 Insert a customer with Id 1: curl -X POST http://localhost:8083/customer/1 Insert a customer with Id 1: curl -X POST http://localhost:8083/customer/1 We do not care much about the output of the API. Rather, we care more about the partition to which the data is sent to. Since we are using customer ID as the key, we expect that the customer with the same ID would end up in the same partition. And now, let us check the logs for the Restaurant Service − Consumer: org.apache.kafka.clients.consumer.KafkaConsumer@7d6d8400 Consumer Group: anonymous.9108d02a-b1ee-4a7a-8707-7760581fa323 Partition Id: 1 Customer: Customer [id=1, name=Dwayne, city=NY] Consumer: org.apache.kafka.clients.consumer.KafkaConsumer@7d6d8400 Consumer Group: anonymous.9108d02a-b1ee-4a7a-8707-7760581fa323 Partition Id: 1 Customer: Customer [id=1, name=Dwayne, city=NY] Consumer: org.apache.kafka.clients.consumer.KafkaConsumer@7d6d8400 Consumer Group: anonymous.9108d02a-b1ee-4a7a-8707-7760581fa323 Partition Id: 2 Customer: Customer [id=5, name=Dwayne, city=NY] Consumer: org.apache.kafka.clients.consumer.KafkaConsumer@7d6d8400 Consumer Group: anonymous.9108d02a-b1ee-4a7a-8707-7760581fa323 Partition Id: 0 Customer: Customer [id=3, name=Dwayne, city=NY] Consumer Group: anonymous.9108d02a-b1ee-4a7a-8707-7760581fa323 Partition Id: 1 Customer: Customer [id=1, name=Dwayne, city=NY] So, as we see, Customer with Id 1 ended up in the same partition every time, i.e., partition 1. Consumer Group − A consumer group is the logical grouping of consumers reading the same topic for the same purpose. Data in a topic is partitioned between the consumers in a consumer group so that only one consumer from a given consumer group can read a partition of a topic. To define a consumer group, all we need to do is define a group in the bindings where we use the Kafka topic name. For example, let us define the consumer group name in our application file for our controller. spring: application: name: restaurant-service cloud: function: definition: customerBinding stream: kafka: binder: brokers: localhost:9092 replicationFactor: 1 bindings: customerBinding-in-0: destination: customer group: restController server: port: ${app_port} eureka: client: serviceURL: defaultZone: http://localhost:8900/eureka Let us recompile and start the Restaurant Service. Now, let us generate the event by hitting the POST API on the Customer Service − Insert a customer with Id 1: curl -X POST http://localhost:8083/customer/1 Now, if we check the logs of our Restaurant Service, we will see the following − Consumer: org.apache.kafka.clients.consumer.KafkaConsumer@7d6d8400 Consumer Group: restContoller Partition Id: 1 Customer: Customer [id=1, name=Dwayne, city=NY] So, as we see from the output, we have a consumer group called ‘rest-contoller’ created, whose consumers are responsible to read the topics. In the above case, we just had a single instance of the service running, so all the partition of the ‘customer’ topic was assigned to the same instance. But, if we have multiple partitions, we will have partitions distributed among the workers. 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2126, "s": 1878, "text": "In a distributed environment, services need to communicate with each other. The communication can either happen synchronously or asynchronously. In this section, we will look at how services can communicate by asynchronously using message brokers." }, { "code": null, "e": 2188, "s": 2126, "text": "Two major benefits of performing asynchronous communication −" }, { "code": null, "e": 2408, "s": 2188, "text": "Producer and Consumer speed can differ − If the consumer of the data is slow or fast, it does not affect the producer processing and vice versa. Both can work at their own individual speeds without affecting each other." }, { "code": null, "e": 2628, "s": 2408, "text": "Producer and Consumer speed can differ − If the consumer of the data is slow or fast, it does not affect the producer processing and vice versa. Both can work at their own individual speeds without affecting each other." }, { "code": null, "e": 3050, "s": 2628, "text": "Producer does not need to handle requests from various consumers − There maybe multiple consumers who want to read the same set of data from the producer. With a message broker in between, the producer does not need to take care of the load these consumers generate. Plus, any outages at producer level would not block the consumer from reading older producer data, as this data would be available in the message brokers." }, { "code": null, "e": 3472, "s": 3050, "text": "Producer does not need to handle requests from various consumers − There maybe multiple consumers who want to read the same set of data from the producer. With a message broker in between, the producer does not need to take care of the load these consumers generate. Plus, any outages at producer level would not block the consumer from reading older producer data, as this data would be available in the message brokers." }, { "code": null, "e": 3621, "s": 3472, "text": "Apache Kafka and RabbitMQ are two well-known message brokers used for making asynchronous communication. In this tutorial, we will use Apache Kafka." }, { "code": null, "e": 3936, "s": 3621, "text": "Let’s use the case of Restaurant that we have been using earlier. So, let us say we have our Customer Service and the Restaurant Service communicating via asynchronous communication. To do that, we will use Apache Kafka. And we will need to use that in both services, i.e., Customer Service and Restaurant Service." }, { "code": null, "e": 4031, "s": 3936, "text": "To use Apache Kafka, we will update the POM of both services and add the following dependency." }, { "code": null, "e": 4175, "s": 4031, "text": "<dependency>\n <groupId>org.springframework.cloud</groupId>\n <artifactId>spring-cloud-starter-stream-kafka</artifactId>\n</dependency>\n" }, { "code": null, "e": 4378, "s": 4175, "text": "We also need to have Kafka instances running. There are multiple ways through which it can be done,but we will prefer starting Kafka using Docker container. Here are a few images we can consider using −" }, { "code": null, "e": 4418, "s": 4378, "text": "https://hub.docker.com/r/bitnami/kafka/" }, { "code": null, "e": 4458, "s": 4418, "text": "https://hub.docker.com/r/bitnami/kafka/" }, { "code": null, "e": 4538, "s": 4458, "text": "https://docs.confluent.io/platform/current/quickstart/ce-docker-quickstart.html" }, { "code": null, "e": 4618, "s": 4538, "text": "https://docs.confluent.io/platform/current/quickstart/ce-docker-quickstart.html" }, { "code": null, "e": 4663, "s": 4618, "text": "https://github.com/wurstmeister/kafka-docker" }, { "code": null, "e": 4708, "s": 4663, "text": "https://github.com/wurstmeister/kafka-docker" }, { "code": null, "e": 4875, "s": 4708, "text": "Whichever image we use, the important thing here to note is that once the image is up and running,please ensure that the Kafka cluster is accessible at localhost:9092" }, { "code": null, "e": 4964, "s": 4875, "text": "Now that we have the Kafka cluster running on our image, let's move to the core example." }, { "code": null, "e": 5039, "s": 4964, "text": "There are three important concepts when it comes to Spring Cloud streams −" }, { "code": null, "e": 5335, "s": 5039, "text": "External Messaging System − This is the component which is managed externally and is responsible to store the events/messages produced by the application that can be read by their subscriber/consumer. Note that this is not managed within the app/Spring. Few examples being Apache Kafka, RabbitMQ" }, { "code": null, "e": 5631, "s": 5335, "text": "External Messaging System − This is the component which is managed externally and is responsible to store the events/messages produced by the application that can be read by their subscriber/consumer. Note that this is not managed within the app/Spring. Few examples being Apache Kafka, RabbitMQ" }, { "code": null, "e": 5793, "s": 5631, "text": "Binders − This is the component which provides integration with messaging system, for example, consisting of IP address of messaging system, authentication, etc." }, { "code": null, "e": 5955, "s": 5793, "text": "Binders − This is the component which provides integration with messaging system, for example, consisting of IP address of messaging system, authentication, etc." }, { "code": null, "e": 6094, "s": 5955, "text": "Bindings − This component uses the Binders to produce messages to the messaging system or consume the message from a specific topic/queue." }, { "code": null, "e": 6233, "s": 6094, "text": "Bindings − This component uses the Binders to produce messages to the messaging system or consume the message from a specific topic/queue." }, { "code": null, "e": 6306, "s": 6233, "text": "All the above properties are defined in the application properties file." }, { "code": null, "e": 6314, "s": 6306, "text": "Example" }, { "code": null, "e": 6534, "s": 6314, "text": "Let us use the case of Restaurant that we have been using earlier. So, let us suppose whenever a new service is added to the Customer Service, we want to notify the customer info to the nearby Restaurants about him/her." }, { "code": null, "e": 6768, "s": 6534, "text": "For this purpose, let us update our Customer Service first to include and use Kafka. Note that we will use Customer Service as a producer of the data. That is, whenever we add the Customer via API, it will also be added to the Kafka." }, { "code": null, "e": 7243, "s": 6768, "text": "spring:\n application:\n name: customer-service\n cloud:\n stream:\n source: customerBinding-out-0\n kafka:\n binder:\n brokers: localhost:9092\n replicationFactor: 1\n bindings:\n customerBinding-out-0:\n destination: customer\n producer:\n partitionCount: 3\nserver:\n port: ${app_port}\neureka:\n client:\n serviceURL:\n defaultZone: http://localhost:8900/eureka" }, { "code": null, "e": 7260, "s": 7243, "text": "Points to note −" }, { "code": null, "e": 7332, "s": 7260, "text": "We have defined a binder with the address of our local Kafka instances." }, { "code": null, "e": 7404, "s": 7332, "text": "We have defined a binder with the address of our local Kafka instances." }, { "code": null, "e": 7516, "s": 7404, "text": "We have also defined the binding ‘customerBinding-out-0’ which uses ‘customer’ topic to output the messages in." }, { "code": null, "e": 7628, "s": 7516, "text": "We have also defined the binding ‘customerBinding-out-0’ which uses ‘customer’ topic to output the messages in." }, { "code": null, "e": 7734, "s": 7628, "text": "We have also mentioned our binding in the stream.source so that we can imperatively use that in our code." }, { "code": null, "e": 7840, "s": 7734, "text": "We have also mentioned our binding in the stream.source so that we can imperatively use that in our code." }, { "code": null, "e": 8048, "s": 7840, "text": "Once this is done, let us now update our controller by adding a new method ‘addCustomer’ which is responsible to serve the POST request. And then, from the post request, we send the data to the Kafka Broker." }, { "code": null, "e": 9411, "s": 8048, "text": "package com.tutorialspoint;\nimport java.util.HashMap;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.cloud.stream.function.StreamBridge;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\nclass RestaurantCustomerInstancesController {\n @Autowired\n private StreamBridge streamBridge;\n static HashMap<Long, Customer> mockCustomerData = new HashMap();\n static{\n mockCustomerData.put(1L, new Customer(1, \"Jane\", \"DC\"));\n mockCustomerData.put(2L, new Customer(2, \"John\", \"SFO\"));\n mockCustomerData.put(3L, new Customer(3, \"Kate\", \"NY\"));\n }\n @RequestMapping(\"/customer/{id}\")\n public Customer getCustomerInfo(@PathVariable(\"id\") Long id) {\n System.out.println(\"Querying customer for id with: \" + id);\n return mockCustomerData.get(id);\n }\n @RequestMapping(path = \"/customer/{id}\", method = RequestMethod.POST)\n public Customer addCustomer(@PathVariable(\"id\") Long id) {\n // add default name\n Customer defaultCustomer = new Customer(id, \"Dwayne\", \"NY\");\n streamBridge.send(\"customerBinding-out-0\", defaultCustomer);\n return defaultCustomer;\n }\n}" }, { "code": null, "e": 9426, "s": 9411, "text": "Points to note" }, { "code": null, "e": 9505, "s": 9426, "text": "We are Autowiring StreamBridge which is what we will use to send the messages." }, { "code": null, "e": 9584, "s": 9505, "text": "We are Autowiring StreamBridge which is what we will use to send the messages." }, { "code": null, "e": 9688, "s": 9584, "text": "The parameters we use in the ‘send’ method also specify the binding we want to use to send the data to." }, { "code": null, "e": 9792, "s": 9688, "text": "The parameters we use in the ‘send’ method also specify the binding we want to use to send the data to." }, { "code": null, "e": 10056, "s": 9792, "text": "Now let us update our Restaurant Service to include and subscribe to ‘customer’ topic. Note that we will use Restaurant Service as a consumer of the data. That is, whenever we add the Customer via API, the Restaurant Service would come to know about it via Kafka." }, { "code": null, "e": 10110, "s": 10056, "text": "First, let us update the application properties file." }, { "code": null, "e": 10566, "s": 10110, "text": "spring:\n application:\n name: restaurant-service\n cloud:\n function:\n definition: customerBinding\n stream:\n kafka:\n binder:\n brokers: localhost:9092\n replicationFactor: 1\n bindings:\n customerBinding-in-0:\n destination: customer\nserver:\n port: ${app_port}\neureka:\n client:\n serviceURL:\n defaultZone: http://localhost:8900/eureka" }, { "code": null, "e": 10786, "s": 10566, "text": "Once this is done, let us now update our controller by adding a new method ‘customerBinding’ which is responsible to fetch the request and provide a function which will print the request along with its metadata details." }, { "code": null, "e": 12911, "s": 10786, "text": "package com.tutorialspoint;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.function.Consumer;\nimport java.util.function.Supplier;\nimport java.util.stream.Collectors;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.cloud.stream.annotation.StreamListener;\nimport org.springframework.cloud.stream.function.StreamBridge;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.kafka.support.Acknowledgment;\nimport org.springframework.kafka.support.KafkaHeaders;\nimport org.springframework.messaging.Message;\nimport org.springframework.messaging.support.MessageBuilder;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\nclass RestaurantController {\n @Autowired\n CustomerService customerService;\n @Autowired\n private StreamBridge streamBridge;\n static HashMap<Long, Restaurant> mockRestaurantData = new HashMap();\n static{\n mockRestaurantData.put(1L, new Restaurant(1, \"Pandas\", \"DC\"));\n mockRestaurantData.put(2L, new Restaurant(2, \"Indies\", \"SFO\"));\n mockRestaurantData.put(3L, new Restaurant(3, \"Little Italy\", \"DC\"));\n mockRestaurantData.put(4L, new Restaurant(4, \"Pizeeria\", \"NY\"));\n }\n @RequestMapping(\"/restaurant/customer/{id}\")\n public List<Restaurant> getRestaurantForCustomer(@PathVariable(\"id\") Long id) {\n System.out.println(\"Got request for customer with id: \" + id);\n String customerCity = customerService.getCustomerById(id).getCity();\n return mockRestaurantData.entrySet().stream().filter(\nentry -> entry.getValue().getCity().equals(customerCity))\n.map(entry -> entry.getValue())\n.collect(Collectors.toList());\n }\n @RequestMapping(\"/restaurant/cust/{id}\")\n public void getRestaurantForCust(@PathVariable(\"id\") Long id) {\n streamBridge.send(\"ordersBinding-out-0\", id);\n }\n @Bean\n public Consumer<Message<Customer>> customerBinding() {\n return msg -> {\n System.out.println(msg);\n };\n }\n}" }, { "code": null, "e": 12928, "s": 12911, "text": "Points to note −" }, { "code": null, "e": 13064, "s": 12928, "text": "We are using ‘customerBinding’ which is supposed to pass on the function which would be called when a message arrives for this binding." }, { "code": null, "e": 13200, "s": 13064, "text": "We are using ‘customerBinding’ which is supposed to pass on the function which would be called when a message arrives for this binding." }, { "code": null, "e": 13337, "s": 13200, "text": "The name that we use for this function/bean also needs to be used in the YAML file while creating the bundling and specifying the topic." }, { "code": null, "e": 13474, "s": 13337, "text": "The name that we use for this function/bean also needs to be used in the YAML file while creating the bundling and specifying the topic." }, { "code": null, "e": 13634, "s": 13474, "text": "Now, let us execute the above code as always, start the Eureka Server. Note that this is not hard requirement and is present here for the sake of completeness." }, { "code": null, "e": 13721, "s": 13634, "text": "Then, let us compile and start updating Customer Service using the following command −" }, { "code": null, "e": 13869, "s": 13721, "text": "mvn clean install ; java -Dapp_port=8083 -jar .\\target\\spring-cloud-eurekaclient-\n1.0.jar --spring.config.location=classpath:application-kafka.yml\n" }, { "code": null, "e": 13958, "s": 13869, "text": "Then, let us compile and start updating Restaurant Service using the following command −" }, { "code": null, "e": 14105, "s": 13958, "text": "mvn clean install; java -Dapp_port=8082 -jar .\\target\\spring-cloud-feign-client-\n1.0.jar --spring.config.location=classpath:application-kafka.yml\n" }, { "code": null, "e": 14174, "s": 14105, "text": "And we are set, let us now test our code pieces by hitting the API −" }, { "code": null, "e": 14221, "s": 14174, "text": "curl -X POST http://localhost:8083/customer/1\n" }, { "code": null, "e": 14272, "s": 14221, "text": "Here is the output that we will get for this API −" }, { "code": null, "e": 14326, "s": 14272, "text": "{\n \"id\": 1,\n \"name\": \"Dwayne\",\n \"city\": \"NY\"\n}\n" }, { "code": null, "e": 14386, "s": 14326, "text": "And now, let us check the logs for the Restaurant Service −" }, { "code": null, "e": 14478, "s": 14386, "text": "GenericMessage [payload=Customer [id=1, name=Dwayne, city=NY],\nheaders={kafka_offset=1,...\n" }, { "code": null, "e": 14592, "s": 14478, "text": "So, effectively, you see that using Kafka Broker, Restaurant Service was notified about the newly added Customer." }, { "code": null, "e": 14712, "s": 14592, "text": "Partitions and Consumer Groups are two important concepts that you should be aware of while using Spring Cloud streams." }, { "code": null, "e": 14820, "s": 14712, "text": "Partitions − They are used to partition the data so that we can divide the work between multiple consumers." }, { "code": null, "e": 15024, "s": 14820, "text": "Let us see how to partition the data in Spring Cloud. Say, we want to partition the data based on the Customer ID. So, let us update our Customer Service for the same. For that, what we will need to tell" }, { "code": null, "e": 15113, "s": 15024, "text": "Let us update our Customer Service application property to specify the key for our data." }, { "code": null, "e": 15725, "s": 15113, "text": "spring:\n application:\n name: customer-service\n cloud:\n function:\n definition: ordersBinding\n stream:\n source: customerBinding-out-0\n kafka:\n binder:\n brokers: localhost:9092\n replicationFactor: 1\n bindings:\n customerBinding-out-0:\n destination: customer\n producer:\n partitionKeyExpression: 'getPayload().getId()'\n partitionCount: 3\nserver:\n port: ${app_port}\neureka:\n client:\n serviceURL:\n defaultZone: http://localhost:8900/eureka" }, { "code": null, "e": 16179, "s": 15725, "text": "For specifying the key, i.e., “partitionKeyExpression” we provide Spring Expression Language. The expression assumes the type as GenericMessage<Customer> since we are sending the Customer data in the message. Note that GenericMessage is the Spring Framework class used for wrapping the payload and the headers in a single object. So, we get the payload from this message which is of the type Customer and then we call the getId() method on the customer." }, { "code": null, "e": 16292, "s": 16179, "text": "Now, let us also update our consumer, i.e., the Restaurant Service to log more info while consuming the request." }, { "code": null, "e": 16454, "s": 16292, "text": "Now, let us execute the above code as always, start the Eureka Server. Note that this is not a hard requirement and is present here for the sake of completeness." }, { "code": null, "e": 16541, "s": 16454, "text": "Then, let us compile and start updating Customer Service using the following command −" }, { "code": null, "e": 16689, "s": 16541, "text": "mvn clean install ; java -Dapp_port=8083 -jar .\\target\\spring-cloud-eurekaclient-\n1.0.jar --spring.config.location=classpath:application-kafka.yml\n" }, { "code": null, "e": 16778, "s": 16689, "text": "Then, let us compile and start updating Restaurant Service using the following command −" }, { "code": null, "e": 16925, "s": 16778, "text": "mvn clean install; java -Dapp_port=8082 -jar .\\target\\spring-cloud-feign-client-\n1.0.jar --spring.config.location=classpath:application-kafka.yml\n" }, { "code": null, "e": 17020, "s": 16925, "text": "And we are set, let us now test our code pieces. As part of testing, here is what we will do −" }, { "code": null, "e": 17095, "s": 17020, "text": "Insert a customer with Id 1: curl -X POST http://localhost:8083/customer/1" }, { "code": null, "e": 17170, "s": 17095, "text": "Insert a customer with Id 1: curl -X POST http://localhost:8083/customer/1" }, { "code": null, "e": 17245, "s": 17170, "text": "Insert a customer with Id 1: curl -X POST http://localhost:8083/customer/1" }, { "code": null, "e": 17320, "s": 17245, "text": "Insert a customer with Id 1: curl -X POST http://localhost:8083/customer/1" }, { "code": null, "e": 17395, "s": 17320, "text": "Insert a customer with Id 1: curl -X POST http://localhost:8083/customer/5" }, { "code": null, "e": 17470, "s": 17395, "text": "Insert a customer with Id 1: curl -X POST http://localhost:8083/customer/5" }, { "code": null, "e": 17545, "s": 17470, "text": "Insert a customer with Id 1: curl -X POST http://localhost:8083/customer/3" }, { "code": null, "e": 17620, "s": 17545, "text": "Insert a customer with Id 1: curl -X POST http://localhost:8083/customer/3" }, { "code": null, "e": 17695, "s": 17620, "text": "Insert a customer with Id 1: curl -X POST http://localhost:8083/customer/1" }, { "code": null, "e": 17770, "s": 17695, "text": "Insert a customer with Id 1: curl -X POST http://localhost:8083/customer/1" }, { "code": null, "e": 18014, "s": 17770, "text": "We do not care much about the output of the API. Rather, we care more about the partition to which the data is sent to. Since we are using customer ID as the key, we expect that the customer with the same ID would end up in the same partition." }, { "code": null, "e": 18074, "s": 18014, "text": "And now, let us check the logs for the Restaurant Service −" }, { "code": null, "e": 18977, "s": 18074, "text": "Consumer: org.apache.kafka.clients.consumer.KafkaConsumer@7d6d8400\nConsumer Group: anonymous.9108d02a-b1ee-4a7a-8707-7760581fa323\nPartition Id: 1\nCustomer: Customer [id=1, name=Dwayne, city=NY]\nConsumer: org.apache.kafka.clients.consumer.KafkaConsumer@7d6d8400\nConsumer Group: anonymous.9108d02a-b1ee-4a7a-8707-7760581fa323\nPartition Id: 1\nCustomer: Customer [id=1, name=Dwayne, city=NY]\nConsumer: org.apache.kafka.clients.consumer.KafkaConsumer@7d6d8400\nConsumer Group: anonymous.9108d02a-b1ee-4a7a-8707-7760581fa323\nPartition Id: 2\nCustomer: Customer [id=5, name=Dwayne, city=NY]\nConsumer: org.apache.kafka.clients.consumer.KafkaConsumer@7d6d8400\nConsumer Group: anonymous.9108d02a-b1ee-4a7a-8707-7760581fa323\nPartition Id: 0\nCustomer: Customer [id=3, name=Dwayne, city=NY]\nConsumer Group: anonymous.9108d02a-b1ee-4a7a-8707-7760581fa323\nPartition Id: 1\nCustomer: Customer [id=1, name=Dwayne, city=NY]" }, { "code": null, "e": 19073, "s": 18977, "text": "So, as we see, Customer with Id 1 ended up in the same partition every time, i.e., partition 1." }, { "code": null, "e": 19349, "s": 19073, "text": "Consumer Group − A consumer group is the logical grouping of consumers reading the same topic for the same purpose. Data in a topic is partitioned between the consumers in a consumer group so that only one consumer from a given consumer group can read a partition of a topic." }, { "code": null, "e": 19559, "s": 19349, "text": "To define a consumer group, all we need to do is define a group in the bindings where we use the Kafka topic name. For example, let us define the consumer group name in our application file for our controller." }, { "code": null, "e": 20052, "s": 19559, "text": "spring:\n application:\n name: restaurant-service\n cloud:\n function:\n definition: customerBinding\n stream:\n kafka:\n binder:\n brokers: localhost:9092\n replicationFactor: 1\n bindings:\n customerBinding-in-0:\n destination: customer\n group: restController\nserver:\n port: ${app_port}\neureka:\n client:\n serviceURL:\n defaultZone: http://localhost:8900/eureka" }, { "code": null, "e": 20184, "s": 20052, "text": "Let us recompile and start the Restaurant Service. Now, let us generate the event by hitting the POST API on the Customer Service −" }, { "code": null, "e": 20259, "s": 20184, "text": "Insert a customer with Id 1: curl -X POST http://localhost:8083/customer/1" }, { "code": null, "e": 20340, "s": 20259, "text": "Now, if we check the logs of our Restaurant Service, we will see the following −" }, { "code": null, "e": 20502, "s": 20340, "text": "Consumer: org.apache.kafka.clients.consumer.KafkaConsumer@7d6d8400\nConsumer Group: restContoller\nPartition Id: 1\nCustomer: Customer [id=1, name=Dwayne, city=NY]\n" }, { "code": null, "e": 20888, "s": 20502, "text": "So, as we see from the output, we have a consumer group called ‘rest-contoller’ created, whose consumers are responsible to read the topics. In the above case, we just had a single instance of the service running, so all the partition of the ‘customer’ topic was assigned to the same instance. But, if we have multiple partitions, we will have partitions distributed among the workers." }, { "code": null, "e": 20922, "s": 20888, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 20936, "s": 20922, "text": " Karthikeya T" }, { "code": null, "e": 20969, "s": 20936, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 20984, "s": 20969, "text": " Chaand Sheikh" }, { "code": null, "e": 21019, "s": 20984, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 21031, "s": 21019, "text": " Senol Atac" }, { "code": null, "e": 21066, "s": 21031, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 21078, "s": 21066, "text": " Senol Atac" }, { "code": null, "e": 21113, "s": 21078, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 21125, "s": 21113, "text": " Senol Atac" }, { "code": null, "e": 21158, "s": 21125, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 21170, "s": 21158, "text": " Senol Atac" }, { "code": null, "e": 21177, "s": 21170, "text": " Print" }, { "code": null, "e": 21188, "s": 21177, "text": " Add Notes" } ]
How to check whether a String is a Balanced String or not ?
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this example, we are going to see how to check whether a String is a balanced string or not? Input: ([{}{}{}]{}) Output: Given string is Balanced Input: {}[}[}} Output: Given string is Not Balanced I am going to solve this problem by using ArrayDeque; we can also use Stack either. Here I am sticking to (),[],{} characters, if you wish to have more characters you can free to add these characters into the logic. I am adding all open symbols into an array. Create a Map containing all corresponding open and close symbols. Read String from System.in Loop through each character from the String. Check each character, whether it contained in open symbol array or not. If it does not contain, insert the symbol into it ArrayDequeue (Stores only open symbols). So for a certain point in time, all the open symbols will sit into the ArrayDequeue. Now for closed symbols (else case), pop each element from ArrayDqueue and get the corresponding popped element value from the open_close map. If the map doesn’t contain the value of the popped element, we can say the provided string is not balanced. This loop will go through the end of the string length, so by the end of the loop, ArrayDeque should be empty, as we are popping for each iteration. If it is not empty, we can also say that the provided string is not balanced. Let’s see in practice. import java.util.*; public class BalancedString { private char smallOpen = '('; private char smallClose = ')'; private char midOpen = '['; private char midClose = ']'; private char bigOpen = '{'; private char bigClose = '}'; List<Character> openList = Arrays.asList(smallOpen, midOpen, bigOpen); Map<Character, Character> open_closeMap = new HashMap<>(); { open_closeMap.put(smallOpen, smallClose); open_closeMap.put(midOpen, midClose); open_closeMap.put(bigOpen, bigClose); } public static void main(String[] args) { BalancedString balancedString = new BalancedString(); Scanner sc = new Scanner(System.in); System.out.println("Enter any String.."); String s = sc.nextLine(); System.out.println(balancedString.isBalanced(s) ? "Given string is Balanced" : "Given string is Not Balanced"); } public boolean isBalanced(String str) { Deque<Character> deque = new ArrayDeque<>(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (openList.contains(c)) { deque.push(c); } else { if (deque.isEmpty()) { return false; } char pop = deque.pop(); if (open_closeMap.get(pop) != c) { return false; } } } return deque.isEmpty(); } } ([{}{}{}]{}) Given string is Balanced Happy Learning 🙂 Java Program to Find the characters count in String Java Program To Count number of words in a String Java Program for Reverse of String How Java 8 Stream generate random String and Numbers String sorting in Java Java Program for String Sorting Example Java Program for Check Octal Number Java Program To check a number is prime or not ? Java Program to Check the Number is Perfect or not ? Java Program to Check a Number is Palindrome or not ? C Program – Check a number is Palindrome or not How to check whether a file exists python ? Spring Boot Actuator Database Health Check String in Switch in Java 7 Example How to Convert Java String to Int Java Program to Find the characters count in String Java Program To Count number of words in a String Java Program for Reverse of String How Java 8 Stream generate random String and Numbers String sorting in Java Java Program for String Sorting Example Java Program for Check Octal Number Java Program To check a number is prime or not ? Java Program to Check the Number is Perfect or not ? Java Program to Check a Number is Palindrome or not ? C Program – Check a number is Palindrome or not How to check whether a file exists python ? Spring Boot Actuator Database Health Check String in Switch in Java 7 Example How to Convert Java String to Int Δ Install Java on Mac OS Install AWS CLI on Windows Install Minikube on Windows Install Docker Toolbox on Windows Install SOAPUI on Windows Install Gradle on Windows Install RabbitMQ on Windows Install PuTTY on windows Install Mysql on Windows Install Hibernate Tools in Eclipse Install Elasticsearch on Windows Install Maven on Windows Install Maven on Ubuntu Install Maven on Windows Command Add OJDBC jar to Maven Repository Install Ant on Windows Install RabbitMQ on Windows Install Apache Kafka on Ubuntu Install Apache Kafka on Windows Java8 – Install Windows Java8 – foreach Java8 – forEach with index Java8 – Stream Filter Objects Java8 – Comparator Userdefined Java8 – GroupingBy Java8 – SummingInt Java8 – walk ReadFiles Java8 – JAVA_HOME on Windows Howto – Install Java on Mac OS Howto – Convert Iterable to Stream Howto – Get common elements from two Lists Howto – Convert List to String Howto – Concatenate Arrays using Stream Howto – Remove duplicates from List Howto – Filter null values from Stream Howto – Convert List to Map Howto – Convert Stream to List Howto – Sort a Map Howto – Filter a Map Howto – Get Current UTC Time Howto – Verify an Array contains a specific value Howto – Convert ArrayList to Array Howto – Read File Line By Line Howto – Convert Date to LocalDate Howto – Merge Streams Howto – Resolve NullPointerException in toMap Howto -Get Stream count Howto – Get Min and Max values in a Stream Howto – Convert InputStream to String
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 494, "s": 398, "text": "In this example, we are going to see how to check whether a String is a balanced string or not?" }, { "code": null, "e": 600, "s": 494, "text": "Input: ([{}{}{}]{})\nOutput: Given string is Balanced\nInput: {}[}[}}\nOutput: Given string is Not Balanced\n" }, { "code": null, "e": 684, "s": 600, "text": "I am going to solve this problem by using ArrayDeque; we can also use Stack either." }, { "code": null, "e": 816, "s": 684, "text": "Here I am sticking to (),[],{} characters, if you wish to have more characters you can free to add these characters into the logic." }, { "code": null, "e": 860, "s": 816, "text": "I am adding all open symbols into an array." }, { "code": null, "e": 926, "s": 860, "text": "Create a Map containing all corresponding open and close symbols." }, { "code": null, "e": 953, "s": 926, "text": "Read String from System.in" }, { "code": null, "e": 998, "s": 953, "text": "Loop through each character from the String." }, { "code": null, "e": 1161, "s": 998, "text": "Check each character, whether it contained in open symbol array or not. If it does not contain, insert the symbol into it ArrayDequeue (Stores only open symbols)." }, { "code": null, "e": 1246, "s": 1161, "text": "So for a certain point in time, all the open symbols will sit into the ArrayDequeue." }, { "code": null, "e": 1496, "s": 1246, "text": "Now for closed symbols (else case), pop each element from ArrayDqueue and get the corresponding popped element value from the open_close map. If the map doesn’t contain the value of the popped element, we can say the provided string is not balanced." }, { "code": null, "e": 1645, "s": 1496, "text": "This loop will go through the end of the string length, so by the end of the loop, ArrayDeque should be empty, as we are popping for each iteration." }, { "code": null, "e": 1723, "s": 1645, "text": "If it is not empty, we can also say that the provided string is not balanced." }, { "code": null, "e": 1746, "s": 1723, "text": "Let’s see in practice." }, { "code": null, "e": 3229, "s": 1746, "text": "import java.util.*;\n\npublic class BalancedString {\n private char smallOpen = '(';\n private char smallClose = ')';\n\n private char midOpen = '[';\n private char midClose = ']';\n\n private char bigOpen = '{';\n private char bigClose = '}';\n\n List<Character> openList = Arrays.asList(smallOpen, midOpen, bigOpen);\n Map<Character, Character> open_closeMap = new HashMap<>();\n\n {\n open_closeMap.put(smallOpen, smallClose);\n open_closeMap.put(midOpen, midClose);\n open_closeMap.put(bigOpen, bigClose);\n }\n\n public static void main(String[] args) {\n BalancedString balancedString = new BalancedString();\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter any String..\");\n String s = sc.nextLine();\n System.out.println(balancedString.isBalanced(s) ? \"Given string is Balanced\" : \"Given string is Not Balanced\");\n }\n\n public boolean isBalanced(String str) {\n Deque<Character> deque = new ArrayDeque<>();\n for (int i = 0; i < str.length(); i++) {\n char c = str.charAt(i);\n if (openList.contains(c)) {\n deque.push(c);\n } else {\n if (deque.isEmpty()) {\n return false;\n }\n char pop = deque.pop();\n if (open_closeMap.get(pop) != c) {\n return false;\n }\n }\n }\n return deque.isEmpty();\n }\n}\n" }, { "code": null, "e": 3267, "s": 3229, "text": "([{}{}{}]{})\nGiven string is Balanced" }, { "code": null, "e": 3284, "s": 3267, "text": "Happy Learning 🙂" }, { "code": null, "e": 3936, "s": 3284, "text": "\nJava Program to Find the characters count in String\nJava Program To Count number of words in a String\nJava Program for Reverse of String\nHow Java 8 Stream generate random String and Numbers\nString sorting in Java\nJava Program for String Sorting Example\nJava Program for Check Octal Number\nJava Program To check a number is prime or not ?\nJava Program to Check the Number is Perfect or not ?\nJava Program to Check a Number is Palindrome or not ?\nC Program – Check a number is Palindrome or not\nHow to check whether a file exists python ?\nSpring Boot Actuator Database Health Check\nString in Switch in Java 7 Example\nHow to Convert Java String to Int\n" }, { "code": null, "e": 3988, "s": 3936, "text": "Java Program to Find the characters count in String" }, { "code": null, "e": 4039, "s": 3988, "text": "Java Program To Count number of words in a String" }, { "code": null, "e": 4074, "s": 4039, "text": "Java Program for Reverse of String" }, { "code": null, "e": 4127, "s": 4074, "text": "How Java 8 Stream generate random String and Numbers" }, { "code": null, "e": 4150, "s": 4127, "text": "String sorting in Java" }, { "code": null, "e": 4190, "s": 4150, "text": "Java Program for String Sorting Example" }, { "code": null, "e": 4226, "s": 4190, "text": "Java Program for Check Octal Number" }, { "code": null, "e": 4275, "s": 4226, "text": "Java Program To check a number is prime or not ?" }, { "code": null, "e": 4328, "s": 4275, "text": "Java Program to Check the Number is Perfect or not ?" }, { "code": null, "e": 4382, "s": 4328, "text": "Java Program to Check a Number is Palindrome or not ?" }, { "code": null, "e": 4430, "s": 4382, "text": "C Program – Check a number is Palindrome or not" }, { "code": null, "e": 4474, "s": 4430, "text": "How to check whether a file exists python ?" }, { "code": null, "e": 4517, "s": 4474, "text": "Spring Boot Actuator Database Health Check" }, { "code": null, "e": 4552, "s": 4517, "text": "String in Switch in Java 7 Example" }, { "code": null, "e": 4586, "s": 4552, "text": "How to Convert Java String to Int" }, { "code": null, "e": 4592, "s": 4590, "text": "Δ" }, { "code": null, "e": 4616, "s": 4592, "text": " Install Java on Mac OS" }, { "code": null, "e": 4644, "s": 4616, "text": " Install AWS CLI on Windows" }, { "code": null, "e": 4673, "s": 4644, "text": " Install Minikube on Windows" }, { "code": null, "e": 4708, "s": 4673, "text": " Install Docker Toolbox on Windows" }, { "code": null, "e": 4735, "s": 4708, "text": " Install SOAPUI on Windows" }, { "code": null, "e": 4762, "s": 4735, "text": " Install Gradle on Windows" }, { "code": null, "e": 4791, "s": 4762, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 4817, "s": 4791, "text": " Install PuTTY on windows" }, { "code": null, "e": 4843, "s": 4817, "text": " Install Mysql on Windows" }, { "code": null, "e": 4879, "s": 4843, "text": " Install Hibernate Tools in Eclipse" }, { "code": null, "e": 4913, "s": 4879, "text": " Install Elasticsearch on Windows" }, { "code": null, "e": 4939, "s": 4913, "text": " Install Maven on Windows" }, { "code": null, "e": 4964, "s": 4939, "text": " Install Maven on Ubuntu" }, { "code": null, "e": 4998, "s": 4964, "text": " Install Maven on Windows Command" }, { "code": null, "e": 5033, "s": 4998, "text": " Add OJDBC jar to Maven Repository" }, { "code": null, "e": 5057, "s": 5033, "text": " Install Ant on Windows" }, { "code": null, "e": 5086, "s": 5057, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 5118, "s": 5086, "text": " Install Apache Kafka on Ubuntu" }, { "code": null, "e": 5151, "s": 5118, "text": " Install Apache Kafka on Windows" }, { "code": null, "e": 5176, "s": 5151, "text": " Java8 – Install Windows" }, { "code": null, "e": 5193, "s": 5176, "text": " Java8 – foreach" }, { "code": null, "e": 5221, "s": 5193, "text": " Java8 – forEach with index" }, { "code": null, "e": 5252, "s": 5221, "text": " Java8 – Stream Filter Objects" }, { "code": null, "e": 5284, "s": 5252, "text": " Java8 – Comparator Userdefined" }, { "code": null, "e": 5304, "s": 5284, "text": " Java8 – GroupingBy" }, { "code": null, "e": 5324, "s": 5304, "text": " Java8 – SummingInt" }, { "code": null, "e": 5348, "s": 5324, "text": " Java8 – walk ReadFiles" }, { "code": null, "e": 5378, "s": 5348, "text": " Java8 – JAVA_HOME on Windows" }, { "code": null, "e": 5410, "s": 5378, "text": " Howto – Install Java on Mac OS" }, { "code": null, "e": 5446, "s": 5410, "text": " Howto – Convert Iterable to Stream" }, { "code": null, "e": 5490, "s": 5446, "text": " Howto – Get common elements from two Lists" }, { "code": null, "e": 5522, "s": 5490, "text": " Howto – Convert List to String" }, { "code": null, "e": 5563, "s": 5522, "text": " Howto – Concatenate Arrays using Stream" }, { "code": null, "e": 5600, "s": 5563, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 5640, "s": 5600, "text": " Howto – Filter null values from Stream" }, { "code": null, "e": 5669, "s": 5640, "text": " Howto – Convert List to Map" }, { "code": null, "e": 5701, "s": 5669, "text": " Howto – Convert Stream to List" }, { "code": null, "e": 5721, "s": 5701, "text": " Howto – Sort a Map" }, { "code": null, "e": 5743, "s": 5721, "text": " Howto – Filter a Map" }, { "code": null, "e": 5773, "s": 5743, "text": " Howto – Get Current UTC Time" }, { "code": null, "e": 5824, "s": 5773, "text": " Howto – Verify an Array contains a specific value" }, { "code": null, "e": 5860, "s": 5824, "text": " Howto – Convert ArrayList to Array" }, { "code": null, "e": 5892, "s": 5860, "text": " Howto – Read File Line By Line" }, { "code": null, "e": 5927, "s": 5892, "text": " Howto – Convert Date to LocalDate" }, { "code": null, "e": 5950, "s": 5927, "text": " Howto – Merge Streams" }, { "code": null, "e": 5997, "s": 5950, "text": " Howto – Resolve NullPointerException in toMap" }, { "code": null, "e": 6022, "s": 5997, "text": " Howto -Get Stream count" }, { "code": null, "e": 6066, "s": 6022, "text": " Howto – Get Min and Max values in a Stream" } ]
How to create a SplitMenuButton in JavaFX?
A menu is a list of options or commands presented to the user, typically menus contain items that perform some action. The contents of a menu are known as menu items and a menu bar holds multiple menus. A button controls in user interface applications, in general, on clicking the button it performs the respective action. A SplitMenuButton provides the functionality of both buttons and a Menu. It is divided into two areas − action area and, menu area. On clicking either of these areas it shows the respective functionality. You can create a split menu button by instantiating the javafx.scene.control.SplitMenuButton class. The following Example demonstrates the creation of a SplitMenuButton. import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.MenuItem; import javafx.scene.control.SplitMenuButton; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import javafx.stage.Stage; public class SplitMenuButtonExample extends Application { public void start(Stage stage) { //Creating an ImageView ImageView img = new ImageView("UIControls/globe.png"); img.setFitWidth(20); img.setFitHeight(20); //Creating a label Label label = new Label("Select A Language"); Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12); label.setFont(font); //Creating a menu SplitMenuButton menu = new SplitMenuButton(); //Setting text to the SplitMenuButton menu.setText("Language"); //Setting an image to the button menu.setGraphic(img); //Creating menu Items menu.setMnemonicParsing(true); MenuItem item1 = new MenuItem("Telugu"); MenuItem item2 = new MenuItem("Hindi"); MenuItem item3 = new MenuItem("English"); MenuItem item4 = new MenuItem("Tamil"); MenuItem item5 = new MenuItem("Malayalam"); //Adding all the menu items to the menu menu.getItems().addAll(item1, item2, item3, item4, item5); //Adding the choice box to the scene HBox layout = new HBox(25); layout.getChildren().addAll(label, menu); layout.setPadding(new Insets(15, 50, 50, 130)); layout.setStyle("-fx-background-color: BEIGE"); //Setting the stage Scene scene = new Scene(layout, 595, 200); stage.setTitle("Split Menu Button"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1265, "s": 1062, "text": "A menu is a list of options or commands presented to the user, typically menus contain items that perform some action. The contents of a menu are known as menu items and a menu bar holds multiple menus." }, { "code": null, "e": 1385, "s": 1265, "text": "A button controls in user interface applications, in general, on clicking the button it performs the respective action." }, { "code": null, "e": 1590, "s": 1385, "text": "A SplitMenuButton provides the functionality of both buttons and a Menu. It is divided into two areas − action area and, menu area. On clicking either of these areas it shows the respective functionality." }, { "code": null, "e": 1690, "s": 1590, "text": "You can create a split menu button by instantiating the javafx.scene.control.SplitMenuButton class." }, { "code": null, "e": 1760, "s": 1690, "text": "The following Example demonstrates the creation of a SplitMenuButton." }, { "code": null, "e": 3711, "s": 1760, "text": "import javafx.application.Application;\nimport javafx.geometry.Insets;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Label;\nimport javafx.scene.control.MenuItem;\nimport javafx.scene.control.SplitMenuButton;\nimport javafx.scene.image.ImageView;\nimport javafx.scene.layout.HBox;\nimport javafx.scene.text.Font;\nimport javafx.scene.text.FontPosture;\nimport javafx.scene.text.FontWeight;\nimport javafx.stage.Stage;\npublic class SplitMenuButtonExample extends Application {\n public void start(Stage stage) {\n //Creating an ImageView\n ImageView img = new ImageView(\"UIControls/globe.png\");\n img.setFitWidth(20);\n img.setFitHeight(20);\n //Creating a label\n Label label = new Label(\"Select A Language\");\n Font font = Font.font(\"verdana\", FontWeight.BOLD, FontPosture.REGULAR, 12);\n label.setFont(font);\n //Creating a menu\n SplitMenuButton menu = new SplitMenuButton();\n //Setting text to the SplitMenuButton\n menu.setText(\"Language\");\n //Setting an image to the button\n menu.setGraphic(img);\n //Creating menu Items\n menu.setMnemonicParsing(true);\n MenuItem item1 = new MenuItem(\"Telugu\");\n MenuItem item2 = new MenuItem(\"Hindi\");\n MenuItem item3 = new MenuItem(\"English\");\n MenuItem item4 = new MenuItem(\"Tamil\");\n MenuItem item5 = new MenuItem(\"Malayalam\");\n //Adding all the menu items to the menu\n menu.getItems().addAll(item1, item2, item3, item4, item5);\n //Adding the choice box to the scene\n HBox layout = new HBox(25);\n layout.getChildren().addAll(label, menu);\n layout.setPadding(new Insets(15, 50, 50, 130));\n layout.setStyle(\"-fx-background-color: BEIGE\");\n //Setting the stage\n Scene scene = new Scene(layout, 595, 200);\n stage.setTitle(\"Split Menu Button\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" } ]
Estimating Non-linear Correlation in R | by Chitta Ranjan | Towards Data Science
In this post, we will learn about using a nonlinear correlation estimation function in R. We will also look at a few examples. Correlation estimations are commonly used in various data mining applications. In my experience, nonlinear correlations are quite common in various processes. Due to this, nonlinear models, such as SVM, are employed for regression, classification, etc. However, there are not many approaches to estimate nonlinear correlations between two variables. Typically linear correlations are estimated. However, the data may have a nonlinear correlation but little to no linear correlation. In such cases, nonlinearly correlated variables are sometimes overlooked during data exploration or variable selection in high-dimensional data. We have developed a new nonlinear correlation estimator, nlcor. This estimator comes useful in data exploration and also variable selection for nonlinear predictive models, such as SVM. To install nlcor in R, follow these steps: Install the devtools package. You can do this from CRAN. You can do it directly in R console by typing, Install the devtools package. You can do this from CRAN. You can do it directly in R console by typing, > install.packages("devtools") 2. Load the devtools package. > library(devtools) 3. Install nlcor from its GitHub repository by typing this in R console. > install_github("ProcessMiner/nlcor") In this package, we provide an implementation of a nonlinear correlation estimation method using an adaptive local linear correlation computation in nlcor. The function nlcor returns the nonlinear correlation estimate, the corresponding adjusted p-value, and an optional plot visualizing the nonlinear relationships. The correlation estimate will be between 0 and 1. The higher the value the more is the nonlinear correlation. Unlike linear correlations, a negative value is not valid here. Due to multiple local correlation computations, the net p-value of the correlation estimate is adjusted (to avoid false positives). The plot visualizes the local linear correlations. In the following, we will show its usage with a few examples. In the given examples, the linear correlations between x and y is small, however, there is a visible nonlinear correlation between them. This package contains the data for these examples and can be used for testing the package. nlcor package has few sample x and y vectors that are demonstrated in the following examples. First, we will load the package. > library(nlcor) > plot(x1, y1) The linear correlation of the data is, > cor(x1, y1)[1] 0.008001837 As expected, the correlation is close to zero. We estimate the nonlinearcorrelation using nlcor. > c <- nlcor(x1, y1, plt = T)> c$cor.estimate[1] 0.8688784> c$adjusted.p.value[1] 0> print(c$cor.plot) The plot shows the piecewise linear correlations present in the data. > plot(x2, y2) The linear correlation of the data is, > cor(x2, y2)[1] 0.828596 The linear correlation is quite high in this data. However, there issignificant and higher nonlinear correlation present in the data. Thisdata emulates the scenario where the correlation changes its directionafter a point. Sometimes that change point is in the middle causing thelinear correlation to be close to zero. Here we show an example when thechange point is off center to show that the implementation works innon-uniform cases. We estimate the nonlinear correlation using nlcor. > c <- nlcor(x2, y2, plt = T)> c$cor.estimate[1] 0.897205> c$adjusted.p.value[1] 0> print(c$cor.plot) It is visible from the plot that nlcor could estimate the piecewise correlations in a non-uniform scenario. Also, the nonlinear correlation comes out to be higher than the linear correlation. > plot(x3, y3) The linear correlation of the data is, > cor(x3, y3)[1] -0.1337304 The linear correlation is expectedly small, albeit not close to zero dueto some linearity. Here we show we can refine the granularity of the correlationcomputation. Under default settings, the output of nlcor will be, > c <- nlcor(x3, y3, plt = T)> c$cor.estimate[1] 0.7090148> c$adjusted.p.value[1] 0> print(c$cor.plot) As can be seen in the figure, nlcor overlooked some of the local relationships. We can refine the correlation estimation by changing the refine parameter. The default value of refine is set as 0.5. It can be set as any value between 0 and 1. A higher value enforces higher refinement. However, higher refinement adversely affects the p-value. Meaning, the resultant correlation estimate may be statistically insignificant (similar to overfitting). Therefore, it is recommended to avoid over refinement. For this data, we rerun the correlation estimation with refine = 0.9. > c <- nlcor(x3, y3, refine = 0.9, plt = T)> c$cor.estimate[1] 0.8534956> c$adjusted.p.value[1] 2.531456e-06> print(c$cor.plot)Warning: Removed 148 rows containing missing values (geom_path). As can be seen in the figure, nlcor could identify the granular piecewise correlations. In this data, the p-value still remains extremely small—the correlation is statistically significant. This package provides an implementation of an efficient heuristic to compute the nonlinear correlations between numeric vectors. The heuristic works by adaptively identifying multiple local regions of linear correlations to estimate the overall nonlinear correlation. Its usages are demonstrated here with few examples. Package ‘nlcor’: Compute Nonlinear Correlations @article{ranjan2020packagenlcor, title={Package ‘nlcor’: Compute Nonlinear Correlations}, author={Ranjan, Chitta and Najari, Vahab}, journal={Research Gate}, year={2020}, doi={10.13140/RG.2.2.33716.68480}} Chitta Ranjan and Vahab Najari. “Package ’nlcor’: Compute Nonlinear Correlations”. In:Research Gate(2020).doi:10.13140/RG.2.2.33716.68480. nlcor: Nonlinear Correlation @article{ranjan2019nlcor, title={nlcor: Nonlinear Correlation}, author={Ranjan, Chitta and Najari, Vahab}, journal={Research Gate}, year={2019}, doi={10.13140/RG.2.2.10123.72488}} Chitta Ranjan and Vahab Najari. “nlcor: Nonlinear Correlation”. In:Research Gate(2019).doi:10.13140/RG.2.2.10123.72488.
[ { "code": null, "e": 299, "s": 172, "text": "In this post, we will learn about using a nonlinear correlation estimation function in R. We will also look at a few examples." }, { "code": null, "e": 649, "s": 299, "text": "Correlation estimations are commonly used in various data mining applications. In my experience, nonlinear correlations are quite common in various processes. Due to this, nonlinear models, such as SVM, are employed for regression, classification, etc. However, there are not many approaches to estimate nonlinear correlations between two variables." }, { "code": null, "e": 927, "s": 649, "text": "Typically linear correlations are estimated. However, the data may have a nonlinear correlation but little to no linear correlation. In such cases, nonlinearly correlated variables are sometimes overlooked during data exploration or variable selection in high-dimensional data." }, { "code": null, "e": 1113, "s": 927, "text": "We have developed a new nonlinear correlation estimator, nlcor. This estimator comes useful in data exploration and also variable selection for nonlinear predictive models, such as SVM." }, { "code": null, "e": 1156, "s": 1113, "text": "To install nlcor in R, follow these steps:" }, { "code": null, "e": 1260, "s": 1156, "text": "Install the devtools package. You can do this from CRAN. You can do it directly in R console by typing," }, { "code": null, "e": 1364, "s": 1260, "text": "Install the devtools package. You can do this from CRAN. You can do it directly in R console by typing," }, { "code": null, "e": 1395, "s": 1364, "text": "> install.packages(\"devtools\")" }, { "code": null, "e": 1425, "s": 1395, "text": "2. Load the devtools package." }, { "code": null, "e": 1446, "s": 1425, "text": "> library(devtools) " }, { "code": null, "e": 1519, "s": 1446, "text": "3. Install nlcor from its GitHub repository by typing this in R console." }, { "code": null, "e": 1558, "s": 1519, "text": "> install_github(\"ProcessMiner/nlcor\")" }, { "code": null, "e": 1875, "s": 1558, "text": "In this package, we provide an implementation of a nonlinear correlation estimation method using an adaptive local linear correlation computation in nlcor. The function nlcor returns the nonlinear correlation estimate, the corresponding adjusted p-value, and an optional plot visualizing the nonlinear relationships." }, { "code": null, "e": 2232, "s": 1875, "text": "The correlation estimate will be between 0 and 1. The higher the value the more is the nonlinear correlation. Unlike linear correlations, a negative value is not valid here. Due to multiple local correlation computations, the net p-value of the correlation estimate is adjusted (to avoid false positives). The plot visualizes the local linear correlations." }, { "code": null, "e": 2522, "s": 2232, "text": "In the following, we will show its usage with a few examples. In the given examples, the linear correlations between x and y is small, however, there is a visible nonlinear correlation between them. This package contains the data for these examples and can be used for testing the package." }, { "code": null, "e": 2616, "s": 2522, "text": "nlcor package has few sample x and y vectors that are demonstrated in the following examples." }, { "code": null, "e": 2649, "s": 2616, "text": "First, we will load the package." }, { "code": null, "e": 2666, "s": 2649, "text": "> library(nlcor)" }, { "code": null, "e": 2681, "s": 2666, "text": "> plot(x1, y1)" }, { "code": null, "e": 2720, "s": 2681, "text": "The linear correlation of the data is," }, { "code": null, "e": 2749, "s": 2720, "text": "> cor(x1, y1)[1] 0.008001837" }, { "code": null, "e": 2846, "s": 2749, "text": "As expected, the correlation is close to zero. We estimate the nonlinearcorrelation using nlcor." }, { "code": null, "e": 2949, "s": 2846, "text": "> c <- nlcor(x1, y1, plt = T)> c$cor.estimate[1] 0.8688784> c$adjusted.p.value[1] 0> print(c$cor.plot)" }, { "code": null, "e": 3019, "s": 2949, "text": "The plot shows the piecewise linear correlations present in the data." }, { "code": null, "e": 3034, "s": 3019, "text": "> plot(x2, y2)" }, { "code": null, "e": 3073, "s": 3034, "text": "The linear correlation of the data is," }, { "code": null, "e": 3099, "s": 3073, "text": "> cor(x2, y2)[1] 0.828596" }, { "code": null, "e": 3536, "s": 3099, "text": "The linear correlation is quite high in this data. However, there issignificant and higher nonlinear correlation present in the data. Thisdata emulates the scenario where the correlation changes its directionafter a point. Sometimes that change point is in the middle causing thelinear correlation to be close to zero. Here we show an example when thechange point is off center to show that the implementation works innon-uniform cases." }, { "code": null, "e": 3587, "s": 3536, "text": "We estimate the nonlinear correlation using nlcor." }, { "code": null, "e": 3689, "s": 3587, "text": "> c <- nlcor(x2, y2, plt = T)> c$cor.estimate[1] 0.897205> c$adjusted.p.value[1] 0> print(c$cor.plot)" }, { "code": null, "e": 3881, "s": 3689, "text": "It is visible from the plot that nlcor could estimate the piecewise correlations in a non-uniform scenario. Also, the nonlinear correlation comes out to be higher than the linear correlation." }, { "code": null, "e": 3896, "s": 3881, "text": "> plot(x3, y3)" }, { "code": null, "e": 3935, "s": 3896, "text": "The linear correlation of the data is," }, { "code": null, "e": 3963, "s": 3935, "text": "> cor(x3, y3)[1] -0.1337304" }, { "code": null, "e": 4054, "s": 3963, "text": "The linear correlation is expectedly small, albeit not close to zero dueto some linearity." }, { "code": null, "e": 4128, "s": 4054, "text": "Here we show we can refine the granularity of the correlationcomputation." }, { "code": null, "e": 4181, "s": 4128, "text": "Under default settings, the output of nlcor will be," }, { "code": null, "e": 4284, "s": 4181, "text": "> c <- nlcor(x3, y3, plt = T)> c$cor.estimate[1] 0.7090148> c$adjusted.p.value[1] 0> print(c$cor.plot)" }, { "code": null, "e": 4569, "s": 4284, "text": "As can be seen in the figure, nlcor overlooked some of the local relationships. We can refine the correlation estimation by changing the refine parameter. The default value of refine is set as 0.5. It can be set as any value between 0 and 1. A higher value enforces higher refinement." }, { "code": null, "e": 4787, "s": 4569, "text": "However, higher refinement adversely affects the p-value. Meaning, the resultant correlation estimate may be statistically insignificant (similar to overfitting). Therefore, it is recommended to avoid over refinement." }, { "code": null, "e": 4857, "s": 4787, "text": "For this data, we rerun the correlation estimation with refine = 0.9." }, { "code": null, "e": 5049, "s": 4857, "text": "> c <- nlcor(x3, y3, refine = 0.9, plt = T)> c$cor.estimate[1] 0.8534956> c$adjusted.p.value[1] 2.531456e-06> print(c$cor.plot)Warning: Removed 148 rows containing missing values (geom_path)." }, { "code": null, "e": 5239, "s": 5049, "text": "As can be seen in the figure, nlcor could identify the granular piecewise correlations. In this data, the p-value still remains extremely small—the correlation is statistically significant." }, { "code": null, "e": 5559, "s": 5239, "text": "This package provides an implementation of an efficient heuristic to compute the nonlinear correlations between numeric vectors. The heuristic works by adaptively identifying multiple local regions of linear correlations to estimate the overall nonlinear correlation. Its usages are demonstrated here with few examples." }, { "code": null, "e": 5607, "s": 5559, "text": "Package ‘nlcor’: Compute Nonlinear Correlations" }, { "code": null, "e": 5813, "s": 5607, "text": "@article{ranjan2020packagenlcor, title={Package ‘nlcor’: Compute Nonlinear Correlations}, author={Ranjan, Chitta and Najari, Vahab}, journal={Research Gate}, year={2020}, doi={10.13140/RG.2.2.33716.68480}}" }, { "code": null, "e": 5952, "s": 5813, "text": "Chitta Ranjan and Vahab Najari. “Package ’nlcor’: Compute Nonlinear Correlations”. In:Research Gate(2020).doi:10.13140/RG.2.2.33716.68480." }, { "code": null, "e": 5981, "s": 5952, "text": "nlcor: Nonlinear Correlation" }, { "code": null, "e": 6161, "s": 5981, "text": "@article{ranjan2019nlcor, title={nlcor: Nonlinear Correlation}, author={Ranjan, Chitta and Najari, Vahab}, journal={Research Gate}, year={2019}, doi={10.13140/RG.2.2.10123.72488}}" } ]
C++ if-else (Decision Making) | Practice | GeeksforGeeks
Given an integer N. Your task is to check if the integer is greater than, less than or equal to 5. If the integer is greater than 5, then print "Greater than 5" (without quotes). If the integer is less than 5, then print "Less than 5". If the integer is equal to 5, then print "Equal to 5". Example 1: Input: N = 8 Output: Greater than 5 Example 2: Input: N = 4 Output: Less than 5 Your Task: You don't need to read input or print anything. Your task is to complete the function compareFive() which takes the number N and returns "Greater than 5" if the integer is greater than 5 or "Less than 5" if the integer is less than 5 otherwise print "Equal to 5" if the integer equals to 5. Expected Time Complexity: O(1) Expected Auxiliary Space: O(1) Constraints: 1 <= N <= 100000 0 sourabhy12626 days ago For C++ #include<iostream>using namespace std; int main(){ int number; cout<<"Enter the number is"<<endl; cin>>number; if(number > 5){ cout<<"Greater than 5" <<endl; }else if(number < 5){ cout<<"Smaller than 5" <<endl; }else if(number = 5){ cout<<"Equal to 5"<<endl; } return 0;} 0 mehereanuj5702 weeks ago string compareFive(int n){ // code here if(n<5) { return "Less than 5"; } else if(n==5) { return "Equal to 5"; } else { return "Greater than 5"; } } +1 harshsainilcw3 weeks ago #include<iostream> using namespace std; int main() { int N; cin>>N; if(N<5) cout<<"N is smaller then 5"; else if(N>5) cout<<“N is greater then 5”; else cout<<"N is equal to 5"; } 0 shaunak5424 This comment was deleted. 0 janvisahotra174 weeks ago // { Driver Code Starts#include<bits/stdc++.h> using namespace std; // } Driver Code Ends#include<iostream>Using namespace std; int main() // { Driver Code Starts.int main() { int t; cin>>t; while(t--) { int N; cin >> N; Solution ob; cout << ob.compareFive(N) << endl; } return 0; } 0 saurabhsingh16b1 month ago #include<iostream> using namespace std; int main() { int N; cout<<"Enter a number"<<endl; cin>>N; if(N>5){ cout<<"Greater than 5"<<endl; } else if(N<5){ cout<<"Less than 5"<<endl; } else{ cout<<"Equal to 5"<<endl; } } 0 as52448391 month ago int main(){ int N; cin>>N; if (N>5){ cout<<"Greater than 5"; }else if(5<N){ cout<<"less than 5"; }else if (N=5){ cout<<"5"; }} 0 0niharika22 months ago if(n>5) cout<<"Greater than 5"; else if(n<5) cout<<"Less than 5"; else cout<<"Equal to 5"; 0 shaghayeghm6282 months ago // { Driver Code Starts#include<bits/stdc++.h> using namespace std; // } Driver Code Endsclass Solution{ public: string compareFive(int n){ // code here }}; // { Driver Code Starts.int main() { int t; cin>>t; while(t--) { int N; cin >> N; Solution ob; cout << ob.compareFive(N) << endl; } return 0; } // } Driver Code Ends 0 chhavinderjeetsinghec21b728 This comment was deleted. We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 529, "s": 238, "text": "Given an integer N. Your task is to check if the integer is greater than, less than or equal to 5.\nIf the integer is greater than 5, then print \"Greater than 5\" (without quotes).\nIf the integer is less than 5, then print \"Less than 5\".\nIf the integer is equal to 5, then print \"Equal to 5\"." }, { "code": null, "e": 542, "s": 531, "text": "Example 1:" }, { "code": null, "e": 579, "s": 542, "text": "Input:\nN = 8\nOutput:\nGreater than 5\n" }, { "code": null, "e": 592, "s": 581, "text": "Example 2:" }, { "code": null, "e": 626, "s": 592, "text": "Input:\nN = 4\nOutput:\nLess than 5\n" }, { "code": null, "e": 639, "s": 628, "text": "Your Task:" }, { "code": null, "e": 930, "s": 639, "text": "You don't need to read input or print anything. Your task is to complete the function compareFive() which takes the number N and returns \"Greater than 5\" if the integer is greater than 5 or \"Less than 5\" if the integer is less than 5 otherwise print \"Equal to 5\" if the integer equals to 5." }, { "code": null, "e": 994, "s": 932, "text": "Expected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1026, "s": 996, "text": "Constraints:\n1 <= N <= 100000" }, { "code": null, "e": 1030, "s": 1028, "text": "0" }, { "code": null, "e": 1053, "s": 1030, "text": "sourabhy12626 days ago" }, { "code": null, "e": 1061, "s": 1053, "text": "For C++" }, { "code": null, "e": 1100, "s": 1061, "text": "#include<iostream>using namespace std;" }, { "code": null, "e": 1373, "s": 1100, "text": "int main(){ int number; cout<<\"Enter the number is\"<<endl; cin>>number; if(number > 5){ cout<<\"Greater than 5\" <<endl; }else if(number < 5){ cout<<\"Smaller than 5\" <<endl; }else if(number = 5){ cout<<\"Equal to 5\"<<endl; } return 0;}" }, { "code": null, "e": 1375, "s": 1373, "text": "0" }, { "code": null, "e": 1400, "s": 1375, "text": "mehereanuj5702 weeks ago" }, { "code": null, "e": 1642, "s": 1400, "text": "string compareFive(int n){ // code here if(n<5) { return \"Less than 5\"; } else if(n==5) { return \"Equal to 5\"; } else { return \"Greater than 5\"; } }" }, { "code": null, "e": 1645, "s": 1642, "text": "+1" }, { "code": null, "e": 1670, "s": 1645, "text": "harshsainilcw3 weeks ago" }, { "code": null, "e": 1689, "s": 1670, "text": "#include<iostream>" }, { "code": null, "e": 1710, "s": 1689, "text": "using namespace std;" }, { "code": null, "e": 1721, "s": 1710, "text": "int main()" }, { "code": null, "e": 1723, "s": 1721, "text": "{" }, { "code": null, "e": 1732, "s": 1723, "text": " int N;" }, { "code": null, "e": 1742, "s": 1732, "text": " cin>>N;" }, { "code": null, "e": 1752, "s": 1742, "text": " if(N<5)" }, { "code": null, "e": 1783, "s": 1752, "text": " cout<<\"N is smaller then 5\";" }, { "code": null, "e": 1798, "s": 1783, "text": " else if(N>5)" }, { "code": null, "e": 1829, "s": 1798, "text": " cout<<“N is greater then 5”;" }, { "code": null, "e": 1837, "s": 1829, "text": " else " }, { "code": null, "e": 1864, "s": 1837, "text": " cout<<\"N is equal to 5\";" }, { "code": null, "e": 1866, "s": 1864, "text": "}" }, { "code": null, "e": 1868, "s": 1866, "text": "0" }, { "code": null, "e": 1880, "s": 1868, "text": "shaunak5424" }, { "code": null, "e": 1906, "s": 1880, "text": "This comment was deleted." }, { "code": null, "e": 1908, "s": 1906, "text": "0" }, { "code": null, "e": 1934, "s": 1908, "text": "janvisahotra174 weeks ago" }, { "code": null, "e": 2002, "s": 1934, "text": "// { Driver Code Starts#include<bits/stdc++.h> using namespace std;" }, { "code": null, "e": 2062, "s": 2002, "text": "// } Driver Code Ends#include<iostream>Using namespace std;" }, { "code": null, "e": 2073, "s": 2062, "text": "int main()" }, { "code": null, "e": 2256, "s": 2073, "text": "// { Driver Code Starts.int main() { int t; cin>>t; while(t--) { int N; cin >> N; Solution ob; cout << ob.compareFive(N) << endl; } return 0; } " }, { "code": null, "e": 2258, "s": 2256, "text": "0" }, { "code": null, "e": 2285, "s": 2258, "text": "saurabhsingh16b1 month ago" }, { "code": null, "e": 2304, "s": 2285, "text": "#include<iostream>" }, { "code": null, "e": 2325, "s": 2304, "text": "using namespace std;" }, { "code": null, "e": 2336, "s": 2325, "text": "int main()" }, { "code": null, "e": 2338, "s": 2336, "text": "{" }, { "code": null, "e": 2345, "s": 2338, "text": "int N;" }, { "code": null, "e": 2375, "s": 2345, "text": "cout<<\"Enter a number\"<<endl;" }, { "code": null, "e": 2383, "s": 2375, "text": "cin>>N;" }, { "code": null, "e": 2392, "s": 2383, "text": "if(N>5){" }, { "code": null, "e": 2422, "s": 2392, "text": "cout<<\"Greater than 5\"<<endl;" }, { "code": null, "e": 2424, "s": 2422, "text": "}" }, { "code": null, "e": 2438, "s": 2424, "text": "else if(N<5){" }, { "code": null, "e": 2465, "s": 2438, "text": "cout<<\"Less than 5\"<<endl;" }, { "code": null, "e": 2467, "s": 2465, "text": "}" }, { "code": null, "e": 2473, "s": 2467, "text": "else{" }, { "code": null, "e": 2499, "s": 2473, "text": "cout<<\"Equal to 5\"<<endl;" }, { "code": null, "e": 2501, "s": 2499, "text": "}" }, { "code": null, "e": 2503, "s": 2501, "text": "}" }, { "code": null, "e": 2505, "s": 2503, "text": "0" }, { "code": null, "e": 2526, "s": 2505, "text": "as52448391 month ago" }, { "code": null, "e": 2686, "s": 2526, "text": "int main(){ int N; cin>>N; if (N>5){ cout<<\"Greater than 5\"; }else if(5<N){ cout<<\"less than 5\"; }else if (N=5){ cout<<\"5\"; }}" }, { "code": null, "e": 2688, "s": 2686, "text": "0" }, { "code": null, "e": 2711, "s": 2688, "text": "0niharika22 months ago" }, { "code": null, "e": 2840, "s": 2711, "text": "if(n>5) cout<<\"Greater than 5\"; else if(n<5) cout<<\"Less than 5\"; else cout<<\"Equal to 5\";" }, { "code": null, "e": 2842, "s": 2840, "text": "0" }, { "code": null, "e": 2869, "s": 2842, "text": "shaghayeghm6282 months ago" }, { "code": null, "e": 2937, "s": 2869, "text": "// { Driver Code Starts#include<bits/stdc++.h> using namespace std;" }, { "code": null, "e": 3039, "s": 2937, "text": "// } Driver Code Endsclass Solution{ public: string compareFive(int n){ // code here }};" }, { "code": null, "e": 3243, "s": 3039, "text": "// { Driver Code Starts.int main() { int t; cin>>t; while(t--) { int N; cin >> N; Solution ob; cout << ob.compareFive(N) << endl; } return 0; } // } Driver Code Ends" }, { "code": null, "e": 3245, "s": 3243, "text": "0" }, { "code": null, "e": 3273, "s": 3245, "text": "chhavinderjeetsinghec21b728" }, { "code": null, "e": 3299, "s": 3273, "text": "This comment was deleted." }, { "code": null, "e": 3445, "s": 3299, "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": 3481, "s": 3445, "text": " Login to access your submissions. " }, { "code": null, "e": 3491, "s": 3481, "text": "\nProblem\n" }, { "code": null, "e": 3501, "s": 3491, "text": "\nContest\n" }, { "code": null, "e": 3564, "s": 3501, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3712, "s": 3564, "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": 3920, "s": 3712, "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": 4026, "s": 3920, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Clone a linked list with next and random pointer | Practice | GeeksforGeeks
You are given a special linked list with N nodes where each node has a next pointer pointing to its next node. You are also given M random pointers, where you will be given M number of pairs denoting two nodes a and b i.e. a->arb = b. Construct a copy of the given list. The copy should consist of exactly N new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list. For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y. Return the head of the copied linked list. Example 1: Input: N = 4, M = 2 value = {1,2,3,4} pairs = {{1,2},{2,4}} Output: 1 Explanation: In this test case, there are 4 nodes in linked list. Among these 4 nodes, 2 nodes have arbitrary pointer set, rest two nodes have arbitrary pointer as NULL. Second line tells us the value of four nodes. The third line gives the information about arbitrary pointers. The first node arbitrary pointer is set to node 2. The second node arbitrary pointer is set to node 4. Example 2: Input: N = 4, M = 2 value[] = {1,3,5,9} pairs[] = {{1,1},{3,4}} Output: 1 Explanation: In the given testcase , applying the method as stated in the above example, the output will be 1. Your Task: The task is to complete the function copyList() which takes one argument the head of the linked list to be cloned and should return the head of the cloned linked list. NOTE : 1. If there is any node whose arbitrary pointer is not given then it's by default NULL. 2. Your solution return an output 1 if your clone linked list is correct, else it returns 0. Expected Time Complexity : O(n) Expected Auxilliary Space : O(1) Constraints: 1 <= N <= 100 1 <= M <= N 1 <= a, b <= 100 0 fauzansiddiqui13 hours ago Node *copyList(Node *head) { Node* originalNode = head; Node* cloneHead = NULL; Node* cloneTail = NULL; // Step 1: Simple Cloning while(originalNode != NULL){ insertAtTail(cloneHead,cloneTail,originalNode->data); originalNode = originalNode->next; } originalNode = head; Node* dupNode = cloneHead; // Step 2 : Chaining both LL together while(originalNode != NULL && dupNode != NULL){ Node* next = originalNode->next; originalNode->next = dupNode; originalNode = next; next = dupNode->next; dupNode->next = originalNode; dupNode = next; } // Step 3: Linking Random pointers originalNode = head; while(originalNode != NULL){ if(originalNode->next != NULL) originalNode->next->arb = originalNode->arb ? originalNode->arb->next : originalNode->arb; originalNode = originalNode->next->next; } // Step 4: Revert Changes originalNode = head; dupNode = cloneHead; while(originalNode != NULL && dupNode != NULL){ originalNode->next = dupNode->next; originalNode = originalNode->next; if(originalNode != NULL) dupNode->next = originalNode->next; dupNode = dupNode->next; } // Step 5: Return Ans return cloneHead; //Write your code here } 0 chiraga581 This comment was deleted. 0 harisrashid41212034 days ago void arrangeChains(Node *head,Node *cloneHead){ Node *current = head; Node *forward = cloneHead; while(current != NULL && forward != NULL){ if(current->arb != NULL) forward->arb = current->arb->next; else forward->arb = current->arb; current->next = forward->next; current = current->next; if(current != NULL) forward->next = current->next; forward = forward->next; } // why few test cases are failing 0 tthakare731 week ago //java solution class Clone { //Function to clone a linked list with next and random pointer. Node copyList(Node head) { //create linking in origin an copy Node dummy = head; while(dummy != null){ Node temp = dummy.next; dummy.next = new Node(dummy.data); dummy.next.next = temp; dummy = temp; } //set random pointer dummy = head; while(dummy != null){ if(dummy.next != null){ dummy.next.arb = dummy.arb != null ? dummy.arb.next : null; } dummy = dummy.next.next; } //seprate original and copy dummy = head; Node result = head.next, copy = head.next; while(dummy != null){ dummy.next = dummy.next.next; result.next = result.next != null ? result.next.next : null; dummy = dummy.next; result = result.next; } return copy; } } 0 khushbugarg791 week ago private: void insertAtTail(Node *head,Node *tail,int data){ Node* newdata = new Node(data); if(head==NULL){ head=newdata; tail=newdata; return; } else{ tail->next=newdata; tail=newdata; } } public: Node *copyList(Node *head) { //clone the list Node* originalHead=head; Node* cloneHead=NULL; Node* cloneTail=NULL; while(originalHead!=NULL){ insertAtTail(cloneHead,cloneTail,originalHead->data); originalHead=originalHead->next; } //create map unordered_map<Node* , Node*> myMap; originalHead=head; Node* temp = cloneHead; while(originalHead!=NULL){ myMap[originalHead]=temp; originalHead=originalHead->next; temp=temp->next; } //random the ptr originalHead=head; temp = cloneHead; while(originalHead!=NULL){ temp->arb= myMap[originalHead->arb]; originalHead=originalHead->next; temp=temp->next; } return cloneHead; } please help. why is this not working. segmentation fault 0 ns2847192 weeks ago Firstly i am modify the original linkedlist .We have to set the random pointer We have to seperate the original linked list Firstly i am modify the original linkedlist . We have to set the random pointer We have to seperate the original linked list CODE : - Node *copyList(Node *head) { //Write your code here Node* curr = head; while(curr!=NULL) { Node* temp = curr->next; curr->next = new Node(curr->data); curr->next->next = temp; curr = temp; } curr = head; // Set arb(random) pointers while(curr!= NULL) { if(curr->next!= NULL) { curr->next->arb = curr->arb != NULL ? curr->arb->next : NULL; } curr = curr->next->next; } // Separate two linked list Node* ori = head; Node* copy = head->next; Node* temp = copy; while(ori!= NULL) { ori->next = ori->next->next; copy->next = (copy->next != NULL) ? copy->next->next : copy->next; ori = ori->next; copy = copy->next; } return temp; } +1 madhajaswanth3 weeks ago Node copyList(Node head) { Map<Node,Node> map = new HashMap<Node,Node>(); Node ptr = head; // just store a new node corresponding to the current node while(ptr != null){ map.put(ptr,new Node(ptr.data)); ptr = ptr.next; } ptr = head; // this is the head of the result Node myHead = null; while(ptr != null){ // getting the next of current node Node next = ptr.next; // getting the random of current node Node random = ptr.arb; // getting the next of my list Node myNext = map.get(next); // getting the random of my list Node myRandom = map.get(random); // getting the current node of my list Node myCurr = map.get(ptr); // update the head if(myHead == null){ myHead = curr; } // update my list myCurr.next = myNext; myCurr.arb = myRandom; // move the pointer ptr = ptr.next; } return myHead; } +1 sangrambachu3 weeks ago class Clone { //Function to clone a linked list with next and random pointer. Node copyList(Node head) { // your code here //Insert new node Node curr = head; while(curr != null) { Node temp = curr.next; curr.next = new Node(curr.data); curr.next.next = temp; curr = temp; } curr = head; // Set arb pointers while(curr != null) { if(curr.next != null) { curr.next.arb = curr.arb != null ? curr.arb.next : null; } curr = curr.next.next; } // Separate two linked list Node ori = head; Node copy = head.next; Node temp = copy; while(ori != null) { ori.next = ori.next.next; copy.next = (copy.next != null) ? copy.next.next : copy.next; ori = ori.next; copy = copy.next; } return temp; } } +1 mandeepjain004 weeks ago Method 1 :- O(n)TS O(n)AS Create a newList by using next abhi dont use random store the address of given node and newly created node in map like given list k node ka address will be the key and new node ka address will be value (sab nodes ka liye) now thing left is to place random by using map iterate both the list simultaneously map me given list ka jo random hai vo (mean ye key ki value ) vo cloneList ka random hoga if you understand what i share please practice First :) code.. Node *copyList(Node *head) { Node *cloneHead = NULL, *cloneTail = NULL, *temp = head; unordered_map<Node*,Node*> um; //creating new list while(temp){ Node *newnode = new Node(temp->data); //mapping address um.insert({temp,newnode}); if(cloneHead == NULL){ cloneHead = newnode; cloneTail = newnode; }else{ cloneTail->next = newnode; cloneTail = newnode; } temp=temp->next; } //just placing rigt random temp = head; Node *temp2 = cloneHead; while(temp && temp2){ temp2->arb = um[temp->arb]; temp = temp->next; temp2 = temp2->next; } return cloneHead; } Method2 first we copy original List as it and we will skip random pointers merge both list such way each next of original list pointing to clone list node. and next of clone list pointing to next of original list node now set-up random pointertravel original list and for eacj nodeorignal list ka next (means clone list ka node) == orignal list k random ka next travel original list and for eacj node orignal list ka next (means clone list ka node) = = orignal list k random ka next revert the changes done in step2 means jo next me changes kiya tha dono list me usko revert kroorignal ka next hojayga clone ka nextclone ka next hojayga orignal k next ka next orignal ka next hojayga clone ka next clone ka next hojayga orignal k next ka next return head Code ..... Node *copyList(Node *head) { //Method 2 Node *temp = head, *cloneHead = NULL, *cloneTail = NULL, *upcoming = NULL; //creating copy of orignal lis while(temp){ Node *newNode = new Node(temp->data); if(cloneHead == NULL){ cloneHead = newNode; cloneTail = newNode; }else{ cloneTail->next = newNode; cloneTail = newNode; } temp = temp->next; } //conecting orignal node with clone node(zig zag) Node *orignalNode = head, *cloneNode = cloneHead; while(orignalNode!=NULL && cloneNode!=NULL){ upcoming = orignalNode->next; orignalNode->next = cloneNode; orignalNode = upcoming; upcoming = cloneNode->next; cloneNode->next = orignalNode; cloneNode = upcoming; } //setting up random temp = head; while(temp != NULL){ if(temp->next != NULL){ temp->next->arb = (temp->arb != NULL) ? temp->arb->next : NULL; } temp=temp->next->next; } //remove changes done in orignal list orignalNode = head; cloneNode = cloneHead; while(cloneNode && orignalNode){ orignalNode->next = cloneNode->next; orignalNode = orignalNode->next; if(orignalNode != NULL) cloneNode->next = orignalNode->next; cloneNode = cloneNode->next; } return cloneHead; } 0 akshayaneja4 weeks ago copyList(head) { let original = head; let copy, copyHead; let o_c = new Map(); while(original){ if(!copy){ copy = new Node(original.data); copyHead = copy; }else{ copy.next = new Node(original.data); copy = copy.next; } o_c.set(original, copy); original = original.next; } while(head){ if(head.arb){ o_c.get(head).arb = o_c.get(head.arb); } head = head.next; } return copyHead; } 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": 474, "s": 238, "text": "You are given a special linked list with N nodes where each node has a next pointer pointing to its next node. You are also given M random pointers, where you will be given M number of pairs denoting two nodes a and b i.e. a->arb = b." }, { "code": null, "e": 912, "s": 474, "text": "Construct a copy of the given list. The copy should consist of exactly N new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list." }, { "code": null, "e": 1081, "s": 912, "text": "For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y." }, { "code": null, "e": 1124, "s": 1081, "text": "Return the head of the copied linked list." }, { "code": null, "e": 1135, "s": 1124, "text": "Example 1:" }, { "code": null, "e": 1591, "s": 1135, "text": "Input:\nN = 4, M = 2\nvalue = {1,2,3,4}\npairs = {{1,2},{2,4}}\nOutput: 1\nExplanation: In this test case, there\nare 4 nodes in linked list. Among these\n4 nodes, 2 nodes have arbitrary pointer\nset, rest two nodes have arbitrary pointer\nas NULL. Second line tells us the value\nof four nodes. The third line gives the\ninformation about arbitrary pointers.\nThe first node arbitrary pointer is set to\nnode 2. The second node arbitrary pointer\nis set to node 4.\n" }, { "code": null, "e": 1602, "s": 1591, "text": "Example 2:" }, { "code": null, "e": 1789, "s": 1602, "text": "Input:\nN = 4, M = 2\nvalue[] = {1,3,5,9}\npairs[] = {{1,1},{3,4}}\nOutput: 1\nExplanation: In the given testcase ,\napplying the method as stated in the\nabove example, the output will be 1.\n\n" }, { "code": null, "e": 1968, "s": 1789, "text": "Your Task:\nThe task is to complete the function copyList() which takes one argument the head of the linked list to be cloned and should return the head of the cloned linked list." }, { "code": null, "e": 2158, "s": 1968, "text": "NOTE : \n1. If there is any node whose arbitrary pointer is not given then it's by default NULL. \n2. Your solution return an output 1 if your clone linked list is correct, else it returns 0." }, { "code": null, "e": 2223, "s": 2158, "text": "Expected Time Complexity : O(n)\nExpected Auxilliary Space : O(1)" }, { "code": null, "e": 2279, "s": 2223, "text": "Constraints:\n1 <= N <= 100\n1 <= M <= N\n1 <= a, b <= 100" }, { "code": null, "e": 2281, "s": 2279, "text": "0" }, { "code": null, "e": 2308, "s": 2281, "text": "fauzansiddiqui13 hours ago" }, { "code": null, "e": 3776, "s": 2308, "text": "Node *copyList(Node *head) { Node* originalNode = head; Node* cloneHead = NULL; Node* cloneTail = NULL; // Step 1: Simple Cloning while(originalNode != NULL){ insertAtTail(cloneHead,cloneTail,originalNode->data); originalNode = originalNode->next; } originalNode = head; Node* dupNode = cloneHead; // Step 2 : Chaining both LL together while(originalNode != NULL && dupNode != NULL){ Node* next = originalNode->next; originalNode->next = dupNode; originalNode = next; next = dupNode->next; dupNode->next = originalNode; dupNode = next; } // Step 3: Linking Random pointers originalNode = head; while(originalNode != NULL){ if(originalNode->next != NULL) originalNode->next->arb = originalNode->arb ? originalNode->arb->next : originalNode->arb; originalNode = originalNode->next->next; } // Step 4: Revert Changes originalNode = head; dupNode = cloneHead; while(originalNode != NULL && dupNode != NULL){ originalNode->next = dupNode->next; originalNode = originalNode->next; if(originalNode != NULL) dupNode->next = originalNode->next; dupNode = dupNode->next; } // Step 5: Return Ans return cloneHead; //Write your code here }" }, { "code": null, "e": 3778, "s": 3776, "text": "0" }, { "code": null, "e": 3789, "s": 3778, "text": "chiraga581" }, { "code": null, "e": 3815, "s": 3789, "text": "This comment was deleted." }, { "code": null, "e": 3817, "s": 3815, "text": "0" }, { "code": null, "e": 3846, "s": 3817, "text": "harisrashid41212034 days ago" }, { "code": null, "e": 4449, "s": 3846, "text": " void arrangeChains(Node *head,Node *cloneHead){ Node *current = head; Node *forward = cloneHead; while(current != NULL && forward != NULL){ if(current->arb != NULL) forward->arb = current->arb->next; else forward->arb = current->arb; current->next = forward->next; current = current->next; if(current != NULL) forward->next = current->next; forward = forward->next; } // why few test cases are failing" }, { "code": null, "e": 4451, "s": 4449, "text": "0" }, { "code": null, "e": 4472, "s": 4451, "text": "tthakare731 week ago" }, { "code": null, "e": 5489, "s": 4472, "text": "//java solution \nclass Clone {\n //Function to clone a linked list with next and random pointer.\n Node copyList(Node head) {\n //create linking in origin an copy\n Node dummy = head;\n while(dummy != null){\n Node temp = dummy.next;\n dummy.next = new Node(dummy.data);\n dummy.next.next = temp;\n dummy = temp;\n }\n \n //set random pointer\n dummy = head;\n while(dummy != null){\n if(dummy.next != null){\n dummy.next.arb = dummy.arb != null ? dummy.arb.next : null;\n }\n dummy = dummy.next.next;\n }\n \n //seprate original and copy\n dummy = head;\n Node result = head.next, copy = head.next;\n while(dummy != null){\n dummy.next = dummy.next.next;\n result.next = result.next != null ? result.next.next : null;\n dummy = dummy.next;\n result = result.next;\n }\n\n return copy;\n }\n}" }, { "code": null, "e": 5491, "s": 5489, "text": "0" }, { "code": null, "e": 5515, "s": 5491, "text": "khushbugarg791 week ago" }, { "code": null, "e": 6731, "s": 5515, "text": " private:\n void insertAtTail(Node *head,Node *tail,int data){\n Node* newdata = new Node(data);\n if(head==NULL){\n head=newdata;\n tail=newdata;\n return;\n }\n else{\n tail->next=newdata;\n tail=newdata;\n }\n \n }\n public:\n Node *copyList(Node *head)\n {\n //clone the list\n Node* originalHead=head;\n Node* cloneHead=NULL;\n Node* cloneTail=NULL;\n while(originalHead!=NULL){\n insertAtTail(cloneHead,cloneTail,originalHead->data);\n originalHead=originalHead->next;\n }\n \n //create map\n \n unordered_map<Node* , Node*> myMap;\n originalHead=head;\n Node* temp = cloneHead;\n while(originalHead!=NULL){\n myMap[originalHead]=temp;\n originalHead=originalHead->next;\n temp=temp->next;\n }\n \n //random the ptr\n originalHead=head;\n temp = cloneHead;\n while(originalHead!=NULL){\n temp->arb= myMap[originalHead->arb];\n originalHead=originalHead->next;\n temp=temp->next;\n }\n return cloneHead;\n }" }, { "code": null, "e": 6788, "s": 6731, "text": "please help. why is this not working. segmentation fault" }, { "code": null, "e": 6790, "s": 6788, "text": "0" }, { "code": null, "e": 6810, "s": 6790, "text": "ns2847192 weeks ago" }, { "code": null, "e": 6936, "s": 6810, "text": "Firstly i am modify the original linkedlist .We have to set the random pointer We have to seperate the original linked list " }, { "code": null, "e": 6982, "s": 6936, "text": "Firstly i am modify the original linkedlist ." }, { "code": null, "e": 7018, "s": 6982, "text": "We have to set the random pointer " }, { "code": null, "e": 7064, "s": 7018, "text": "We have to seperate the original linked list " }, { "code": null, "e": 7074, "s": 7064, "text": "CODE : - " }, { "code": null, "e": 7962, "s": 7074, "text": " Node *copyList(Node *head) { //Write your code here Node* curr = head; while(curr!=NULL) { Node* temp = curr->next; curr->next = new Node(curr->data); curr->next->next = temp; curr = temp; } curr = head; // Set arb(random) pointers while(curr!= NULL) { if(curr->next!= NULL) { curr->next->arb = curr->arb != NULL ? curr->arb->next : NULL; } curr = curr->next->next; } // Separate two linked list Node* ori = head; Node* copy = head->next; Node* temp = copy; while(ori!= NULL) { ori->next = ori->next->next; copy->next = (copy->next != NULL) ? copy->next->next : copy->next; ori = ori->next; copy = copy->next; } return temp; }" }, { "code": null, "e": 7969, "s": 7966, "text": "+1" }, { "code": null, "e": 7994, "s": 7969, "text": "madhajaswanth3 weeks ago" }, { "code": null, "e": 9213, "s": 7994, "text": "Node copyList(Node head) { Map<Node,Node> map = new HashMap<Node,Node>(); Node ptr = head; // just store a new node corresponding to the current node while(ptr != null){ map.put(ptr,new Node(ptr.data)); ptr = ptr.next; } ptr = head; // this is the head of the result Node myHead = null; while(ptr != null){ // getting the next of current node Node next = ptr.next; // getting the random of current node Node random = ptr.arb; // getting the next of my list Node myNext = map.get(next); // getting the random of my list Node myRandom = map.get(random); // getting the current node of my list Node myCurr = map.get(ptr); // update the head if(myHead == null){ myHead = curr; } // update my list myCurr.next = myNext; myCurr.arb = myRandom; // move the pointer ptr = ptr.next; } return myHead; }" }, { "code": null, "e": 9216, "s": 9213, "text": "+1" }, { "code": null, "e": 9240, "s": 9216, "text": "sangrambachu3 weeks ago" }, { "code": null, "e": 10273, "s": 9240, "text": "class Clone {\n //Function to clone a linked list with next and random pointer.\n Node copyList(Node head) {\n // your code here\n \n //Insert new node\n Node curr = head;\n while(curr != null) {\n Node temp = curr.next;\n curr.next = new Node(curr.data);\n curr.next.next = temp;\n curr = temp;\n }\n \n curr = head;\n \n // Set arb pointers\n while(curr != null) {\n if(curr.next != null) {\n curr.next.arb = curr.arb != null ? curr.arb.next : null;\n }\n \n curr = curr.next.next;\n }\n \n // Separate two linked list\n Node ori = head;\n Node copy = head.next;\n Node temp = copy;\n while(ori != null) {\n ori.next = ori.next.next;\n copy.next = (copy.next != null) ? copy.next.next : copy.next;\n ori = ori.next;\n copy = copy.next;\n }\n \n return temp;\n }\n}" }, { "code": null, "e": 10276, "s": 10273, "text": "+1" }, { "code": null, "e": 10301, "s": 10276, "text": "mandeepjain004 weeks ago" }, { "code": null, "e": 10327, "s": 10301, "text": "Method 1 :- O(n)TS O(n)AS" }, { "code": null, "e": 10379, "s": 10327, "text": "Create a newList by using next abhi dont use random" }, { "code": null, "e": 10550, "s": 10379, "text": "store the address of given node and newly created node in map like given list k node ka address will be the key and new node ka address will be value (sab nodes ka liye)" }, { "code": null, "e": 10598, "s": 10550, "text": "now thing left is to place random by using map" }, { "code": null, "e": 10635, "s": 10598, "text": "iterate both the list simultaneously" }, { "code": null, "e": 10725, "s": 10635, "text": "map me given list ka jo random hai vo (mean ye key ki value ) vo cloneList ka random hoga" }, { "code": null, "e": 10784, "s": 10727, "text": "if you understand what i share please practice First :) " }, { "code": null, "e": 10793, "s": 10786, "text": "code.." }, { "code": null, "e": 11677, "s": 10795, "text": " Node *copyList(Node *head)\n {\n Node *cloneHead = NULL, *cloneTail = NULL, *temp = head;\n unordered_map<Node*,Node*> um;\n //creating new list \n while(temp){\n Node *newnode = new Node(temp->data);\n //mapping address\n um.insert({temp,newnode});\n if(cloneHead == NULL){\n cloneHead = newnode;\n cloneTail = newnode;\n }else{\n cloneTail->next = newnode;\n cloneTail = newnode;\n }\n temp=temp->next;\n }\n //just placing rigt random\n temp = head;\n Node *temp2 = cloneHead;\n while(temp && temp2){\n temp2->arb = um[temp->arb];\n temp = temp->next;\n temp2 = temp2->next;\n }\n \n return cloneHead;\n }" }, { "code": null, "e": 11687, "s": 11679, "text": "Method2" }, { "code": null, "e": 11756, "s": 11689, "text": "first we copy original List as it and we will skip random pointers" }, { "code": null, "e": 11900, "s": 11756, "text": "merge both list such way each next of original list pointing to clone list node. and next of clone list pointing to next of original list node" }, { "code": null, "e": 12044, "s": 11900, "text": "now set-up random pointertravel original list and for eacj nodeorignal list ka next (means clone list ka node) == orignal list k random ka next" }, { "code": null, "e": 12083, "s": 12044, "text": "travel original list and for eacj node" }, { "code": null, "e": 12133, "s": 12083, "text": "orignal list ka next (means clone list ka node) =" }, { "code": null, "e": 12165, "s": 12133, "text": "= orignal list k random ka next" }, { "code": null, "e": 12342, "s": 12165, "text": "revert the changes done in step2 means jo next me changes kiya tha dono list me usko revert kroorignal ka next hojayga clone ka nextclone ka next hojayga orignal k next ka next" }, { "code": null, "e": 12380, "s": 12342, "text": "orignal ka next hojayga clone ka next" }, { "code": null, "e": 12425, "s": 12380, "text": "clone ka next hojayga orignal k next ka next" }, { "code": null, "e": 12437, "s": 12425, "text": "return head" }, { "code": null, "e": 12442, "s": 12437, "text": "Code" }, { "code": null, "e": 12448, "s": 12442, "text": "....." }, { "code": null, "e": 14051, "s": 12448, "text": " Node *copyList(Node *head)\n {\n //Method 2\n Node *temp = head, *cloneHead = NULL, *cloneTail = NULL, *upcoming = NULL;\n //creating copy of orignal lis\n while(temp){\n Node *newNode = new Node(temp->data);\n if(cloneHead == NULL){\n cloneHead = newNode;\n cloneTail = newNode;\n }else{\n cloneTail->next = newNode;\n cloneTail = newNode;\n }\n temp = temp->next;\n }\n //conecting orignal node with clone node(zig zag)\n Node *orignalNode = head, *cloneNode = cloneHead;\n while(orignalNode!=NULL && cloneNode!=NULL){\n upcoming = orignalNode->next;\n orignalNode->next = cloneNode;\n orignalNode = upcoming;\n \n upcoming = cloneNode->next;\n cloneNode->next = orignalNode;\n cloneNode = upcoming;\n }\n //setting up random\n temp = head;\n while(temp != NULL){\n if(temp->next != NULL){\n temp->next->arb = (temp->arb != NULL) ? temp->arb->next : NULL;\n }\n temp=temp->next->next;\n }\n \n \n //remove changes done in orignal list\n orignalNode = head;\n cloneNode = cloneHead;\n while(cloneNode && orignalNode){\n orignalNode->next = cloneNode->next;\n orignalNode = orignalNode->next;\n if(orignalNode != NULL) cloneNode->next = orignalNode->next;\n cloneNode = cloneNode->next;\n }\n return cloneHead;\n }" }, { "code": null, "e": 14053, "s": 14051, "text": "0" }, { "code": null, "e": 14076, "s": 14053, "text": "akshayaneja4 weeks ago" }, { "code": null, "e": 14727, "s": 14076, "text": " copyList(head)\n {\n let original = head;\n let copy, copyHead;\n let o_c = new Map();\n \n while(original){\n if(!copy){\n copy = new Node(original.data);\n copyHead = copy;\n }else{\n copy.next = new Node(original.data);\n copy = copy.next;\n }\n o_c.set(original, copy);\n original = original.next;\n }\n \n\n while(head){\n if(head.arb){\n o_c.get(head).arb = o_c.get(head.arb);\n }\n head = head.next;\n }\n return copyHead;\n }" }, { "code": null, "e": 14873, "s": 14727, "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": 14909, "s": 14873, "text": " Login to access your submissions. " }, { "code": null, "e": 14919, "s": 14909, "text": "\nProblem\n" }, { "code": null, "e": 14929, "s": 14919, "text": "\nContest\n" }, { "code": null, "e": 14992, "s": 14929, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 15140, "s": 14992, "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": 15348, "s": 15140, "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": 15454, "s": 15348, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Comparing dates in MySQL ignoring time portion of a DateTime field?
To compare dates in MySQL except time portion of a datetime field, you can use DATE() function. The syntax is as follows − select *from yourTableName where date(yourColumName) = yourDate; To understand the above concept, let us create a table. The query to create a table is as follows − mysql> create table ComparingDate −> ( −> Name varchar(100), −> Login datetime −> ); Query OK, 0 rows affected (0.50 sec) Now you can insert some records in the table using insert command. The query is as follows − mysql> insert into ComparingDate values('John','2014-04-06 22:50:45'); Query OK, 1 row affected (0.15 sec) mysql> insert into ComparingDate values('Bob','2018-12-15 15:07:46'); Query OK, 1 row affected (0.14 sec) mysql> insert into ComparingDate values('Carol','2016-03-10 21:50:40'); Query OK, 1 row affected (0.18 sec) mysql> insert into ComparingDate values('David','1995-08-08 23:40:47'); Query OK, 1 row affected (0.14 sec) Display all records from table using select statement. The query is as follows − mysql> select *from ComparingDate; The following is the output − +-------+---------------------+ | Name | Login | +-------+---------------------+ | John | 2014-04-06 22:50:45 | | Bob | 2018-12-15 15:07:46 | | Carol | 2016-03-10 21:50:40 | | David | 1995-08-08 23:40:47 | +-------+---------------------+ 4 rows in set (0.00 sec) Here is the query to compare only date, not time − mysql> select *from ComparingDate where date(Login) = '2016-03-10'; The following is the output − +-------+---------------------+ | Name | Login | +-------+---------------------+ | Carol | 2016-03-10 21:50:40 | +-------+---------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1185, "s": 1062, "text": "To compare dates in MySQL except time portion of a datetime field, you can use DATE() function. The syntax is as follows −" }, { "code": null, "e": 1250, "s": 1185, "text": "select *from yourTableName where date(yourColumName) = yourDate;" }, { "code": null, "e": 1350, "s": 1250, "text": "To understand the above concept, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1484, "s": 1350, "text": "mysql> create table ComparingDate\n −> (\n −> Name varchar(100),\n −> Login datetime\n −> );\nQuery OK, 0 rows affected (0.50 sec)" }, { "code": null, "e": 1577, "s": 1484, "text": "Now you can insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2009, "s": 1577, "text": "mysql> insert into ComparingDate values('John','2014-04-06 22:50:45');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into ComparingDate values('Bob','2018-12-15 15:07:46');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into ComparingDate values('Carol','2016-03-10 21:50:40');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into ComparingDate values('David','1995-08-08 23:40:47');\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 2090, "s": 2009, "text": "Display all records from table using select statement. The query is as follows −" }, { "code": null, "e": 2125, "s": 2090, "text": "mysql> select *from ComparingDate;" }, { "code": null, "e": 2155, "s": 2125, "text": "The following is the output −" }, { "code": null, "e": 2436, "s": 2155, "text": "+-------+---------------------+\n| Name | Login |\n+-------+---------------------+\n| John | 2014-04-06 22:50:45 |\n| Bob | 2018-12-15 15:07:46 |\n| Carol | 2016-03-10 21:50:40 |\n| David | 1995-08-08 23:40:47 |\n+-------+---------------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2487, "s": 2436, "text": "Here is the query to compare only date, not time −" }, { "code": null, "e": 2555, "s": 2487, "text": "mysql> select *from ComparingDate where date(Login) = '2016-03-10';" }, { "code": null, "e": 2585, "s": 2555, "text": "The following is the output −" }, { "code": null, "e": 2769, "s": 2585, "text": "+-------+---------------------+\n| Name | Login |\n+-------+---------------------+\n| Carol | 2016-03-10 21:50:40 |\n+-------+---------------------+\n1 row in set (0.00 sec)" } ]
Find all reachable nodes from every node present in a given set in C++
Suppose we have one undirected graph and a set of vertices; we have to find all reachable nodes from every vertex present in the given set. So, if the input is like then the output will be [1,2,3] and [4,5] as these are two connected components. To solve this, we will follow these steps − nodes := number of nodes in the graph Define an array visited of size: nodes+1. And fill with 0 Define one map m comp_sum := 0 for initialize i := 0, when i < n, update (increase i by 1), do −u := arr[i]if visited[u] is false, then −(increase comp_sum by 1)m[visited[u]] := bfs traversal of g from node u, also calculate comp_sumprint traversal of m[visited[u]] u := arr[i] if visited[u] is false, then −(increase comp_sum by 1)m[visited[u]] := bfs traversal of g from node u, also calculate comp_sum (increase comp_sum by 1) m[visited[u]] := bfs traversal of g from node u, also calculate comp_sum print traversal of m[visited[u]] Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Graph{ public: int nodes; list<int> *adj_list; Graph(int); void insert_edge(int, int); vector<int> BFS(int, int, int []); }; Graph::Graph(int nodes) { this->nodes = nodes; adj_list = new list<int>[nodes+1]; } void Graph::insert_edge(int u, int v) { adj_list[u].push_back(v); adj_list[v].push_back(u); } vector<int> Graph::BFS(int comp_sum, int src,int visited[]){ queue<int> queue; queue.push(src); visited[src] = comp_sum; vector<int> reachableNodes; while(!queue.empty()) { int u = queue.front(); queue.pop(); reachableNodes.push_back(u); for (auto itr = adj_list[u].begin(); itr != adj_list[u].end(); itr++) { if (!visited[*itr]) { visited[*itr] = comp_sum; queue.push(*itr); } } } return reachableNodes; } void displayReachableNodes(int n, unordered_map <int, vector<int> > m) { vector<int> temp = m[n]; for (int i=0; i<temp.size(); i++) cout << temp[i] << " "; cout << endl; } void get_all_reachable(Graph g, int arr[], int n) { int nodes = g.nodes; int visited[nodes+1]; memset(visited, 0, sizeof(visited)); unordered_map <int, vector<int> > m; int comp_sum = 0; for (int i = 0 ; i < n ; i++) { int u = arr[i]; if (!visited[u]) { comp_sum++; m[visited[u]] = g.BFS(comp_sum, u, visited); } cout << "Reachable Nodes from " << u <<" are\n"; displayReachableNodes(visited[u], m); } } int main() { int nodes = 5; Graph g(nodes); g.insert_edge(1, 2); g.insert_edge(2, 3); g.insert_edge(4, 5); int arr[] = {2, 4, 1}; int n = sizeof(arr)/sizeof(int); get_all_reachable(g, arr, n); } g.insert_edge(1, 2); g.insert_edge(2, 3); g.insert_edge(4, 5); Reachable Nodes from 2 are 2 1 3 Reachable Nodes from 4 are 4 5 Reachable Nodes from 1 are 2 1 3
[ { "code": null, "e": 1202, "s": 1062, "text": "Suppose we have one undirected graph and a set of vertices; we have to find all reachable nodes from every vertex present in the given set." }, { "code": null, "e": 1227, "s": 1202, "text": "So, if the input is like" }, { "code": null, "e": 1308, "s": 1227, "text": "then the output will be [1,2,3] and [4,5] as these are two connected components." }, { "code": null, "e": 1352, "s": 1308, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1390, "s": 1352, "text": "nodes := number of nodes in the graph" }, { "code": null, "e": 1448, "s": 1390, "text": "Define an array visited of size: nodes+1. And fill with 0" }, { "code": null, "e": 1465, "s": 1448, "text": "Define one map m" }, { "code": null, "e": 1479, "s": 1465, "text": "comp_sum := 0" }, { "code": null, "e": 1714, "s": 1479, "text": "for initialize i := 0, when i < n, update (increase i by 1), do −u := arr[i]if visited[u] is false, then −(increase comp_sum by 1)m[visited[u]] := bfs traversal of g from node u, also calculate comp_sumprint traversal of m[visited[u]]" }, { "code": null, "e": 1726, "s": 1714, "text": "u := arr[i]" }, { "code": null, "e": 1853, "s": 1726, "text": "if visited[u] is false, then −(increase comp_sum by 1)m[visited[u]] := bfs traversal of g from node u, also calculate comp_sum" }, { "code": null, "e": 1878, "s": 1853, "text": "(increase comp_sum by 1)" }, { "code": null, "e": 1951, "s": 1878, "text": "m[visited[u]] := bfs traversal of g from node u, also calculate comp_sum" }, { "code": null, "e": 1984, "s": 1951, "text": "print traversal of m[visited[u]]" }, { "code": null, "e": 2054, "s": 1984, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2065, "s": 2054, "text": " Live Demo" }, { "code": null, "e": 3844, "s": 2065, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Graph{\n public:\n int nodes;\n list<int> *adj_list;\n Graph(int);\n void insert_edge(int, int);\n vector<int> BFS(int, int, int []);\n};\nGraph::Graph(int nodes) {\n this->nodes = nodes;\n adj_list = new list<int>[nodes+1];\n}\nvoid Graph::insert_edge(int u, int v) {\n adj_list[u].push_back(v);\n adj_list[v].push_back(u);\n}\nvector<int> Graph::BFS(int comp_sum, int src,int visited[]){\n queue<int> queue;\n queue.push(src);\n visited[src] = comp_sum;\n vector<int> reachableNodes;\n while(!queue.empty()) {\n int u = queue.front();\n queue.pop();\n reachableNodes.push_back(u);\n for (auto itr = adj_list[u].begin(); itr != adj_list[u].end(); itr++) {\n if (!visited[*itr]) {\n visited[*itr] = comp_sum;\n queue.push(*itr);\n }\n }\n }\n return reachableNodes;\n}\nvoid displayReachableNodes(int n, unordered_map <int, vector<int> > m) {\n vector<int> temp = m[n];\n for (int i=0; i<temp.size(); i++)\n cout << temp[i] << \" \";\n cout << endl;\n}\nvoid get_all_reachable(Graph g, int arr[], int n) {\n int nodes = g.nodes;\n int visited[nodes+1];\n memset(visited, 0, sizeof(visited));\n unordered_map <int, vector<int> > m;\n int comp_sum = 0;\n for (int i = 0 ; i < n ; i++) {\n int u = arr[i];\n if (!visited[u]) {\n comp_sum++;\n m[visited[u]] = g.BFS(comp_sum, u, visited);\n }\n cout << \"Reachable Nodes from \" << u <<\" are\\n\";\n displayReachableNodes(visited[u], m);\n }\n}\nint main() {\n int nodes = 5;\n Graph g(nodes);\n g.insert_edge(1, 2);\n g.insert_edge(2, 3);\n g.insert_edge(4, 5);\n int arr[] = {2, 4, 1};\n int n = sizeof(arr)/sizeof(int);\n get_all_reachable(g, arr, n);\n}" }, { "code": null, "e": 3907, "s": 3844, "text": "g.insert_edge(1, 2);\ng.insert_edge(2, 3);\ng.insert_edge(4, 5);" }, { "code": null, "e": 4004, "s": 3907, "text": "Reachable Nodes from 2 are\n2 1 3\nReachable Nodes from 4 are\n4 5\nReachable Nodes from 1 are\n2 1 3" } ]
Generate table DDL via a query on MySQL and SQL Server?
The DDL stands for Data Definition Language. To generate the table DDL via query, you can use show create command. The syntax is as follows SHOW CREATE TABLE yourTableName; The above syntax is MySQL specific. Suppose, we have a table with the name ‘DDLOfTableStudent’. First, create a table with the name ‘DDLOfTableStudent’. The query to create a table is as follows mysql> create table DDLOfTableStudent -> ( -> StudentId int, -> StudentFirstName varchar(100), -> StudentLastName varchar(100), -> StudentAddress varchar(200), -> StudentAge int, -> StudentMarks int -> ); Query OK, 0 rows affected (0.84 sec) Use the above syntax to know the DDL of a table. The query is as follows mysql> SHOW CREATE TABLE DDLOfTableStudent; The following is the output displaying the DDL +-------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +-------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | DDLOfTableStudent | CREATE TABLE `ddloftablestudent` (`StudentId` int(11) DEFAULT NULL,`StudentFirstName` varchar(100) DEFAULT NULL,`StudentLastName` varchar(100) DEFAULT NULL,`StudentAddress` varchar(200) DEFAULT NULL,`StudentAge` int(11) DEFAULT NULL,`StudentMarks` int(11) DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci | +-------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1177, "s": 1062, "text": "The DDL stands for Data Definition Language. To generate the table DDL via query, you can\nuse show create command." }, { "code": null, "e": 1202, "s": 1177, "text": "The syntax is as follows" }, { "code": null, "e": 1235, "s": 1202, "text": "SHOW CREATE TABLE yourTableName;" }, { "code": null, "e": 1331, "s": 1235, "text": "The above syntax is MySQL specific. Suppose, we have a table with the name\n‘DDLOfTableStudent’." }, { "code": null, "e": 1430, "s": 1331, "text": "First, create a table with the name ‘DDLOfTableStudent’. The query to create a table is as\nfollows" }, { "code": null, "e": 1696, "s": 1430, "text": "mysql> create table DDLOfTableStudent\n -> (\n -> StudentId int,\n -> StudentFirstName varchar(100),\n -> StudentLastName varchar(100),\n -> StudentAddress varchar(200),\n -> StudentAge int,\n -> StudentMarks int\n -> );\nQuery OK, 0 rows affected (0.84 sec)" }, { "code": null, "e": 1769, "s": 1696, "text": "Use the above syntax to know the DDL of a table. The query is as follows" }, { "code": null, "e": 1813, "s": 1769, "text": "mysql> SHOW CREATE TABLE DDLOfTableStudent;" }, { "code": null, "e": 1860, "s": 1813, "text": "The following is the output displaying the DDL" }, { "code": null, "e": 3752, "s": 1860, "text": "+-------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| Table | Create Table |\n+-------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| DDLOfTableStudent | CREATE TABLE `ddloftablestudent` (`StudentId` int(11) DEFAULT NULL,`StudentFirstName` varchar(100) DEFAULT NULL,`StudentLastName` varchar(100) DEFAULT NULL,`StudentAddress` varchar(200) DEFAULT NULL,`StudentAge` int(11) DEFAULT NULL,`StudentMarks` int(11) DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |\n+-------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n1 row in set (0.00 sec)" } ]
How do I get email-id from a MongoDB document and display with print()
For this, use forEach() along with print() to display the email-id values. Let us create a collection with documents − > db.demo690.insertOne({"UserName":"John","UserEmailId":"John@gmail.com"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6db31551299a9f98c939c") } > db.demo690.insertOne({"UserName":"Bob","UserEmailId":"Bob@gmail.com"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6db3c551299a9f98c939d") } > db.demo690.insertOne({"UserName":"David","UserEmailId":"David@gmail.com"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6db47551299a9f98c939e") } Display all documents from a collection with the help of find() method − > db.demo690.find(); This will produce the following output − { "_id" : ObjectId("5ea6db31551299a9f98c939c"), "UserName" : "John", "UserEmailId" : "John@gmail.com" } { "_id" : ObjectId("5ea6db3c551299a9f98c939d"), "UserName" : "Bob", "UserEmailId" : "Bob@gmail.com" } { "_id" : ObjectId("5ea6db47551299a9f98c939e"), "UserName" : "David", "UserEmailId" : "David@gmail.com" } Following is the query to get email-id from a MongoDB document and print using print() − > db.demo690.find().forEach(function(document) { ... print(document.UserEmailId); ... }); This will produce the following output − John@gmail.com Bob@gmail.com David@gmail.com
[ { "code": null, "e": 1181, "s": 1062, "text": "For this, use forEach() along with print() to display the email-id values. Let us create a collection with documents −" }, { "code": null, "e": 1664, "s": 1181, "text": "> db.demo690.insertOne({\"UserName\":\"John\",\"UserEmailId\":\"John@gmail.com\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ea6db31551299a9f98c939c\")\n}\n> db.demo690.insertOne({\"UserName\":\"Bob\",\"UserEmailId\":\"Bob@gmail.com\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ea6db3c551299a9f98c939d\")\n}\n> db.demo690.insertOne({\"UserName\":\"David\",\"UserEmailId\":\"David@gmail.com\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ea6db47551299a9f98c939e\")\n}" }, { "code": null, "e": 1737, "s": 1664, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1758, "s": 1737, "text": "> db.demo690.find();" }, { "code": null, "e": 1799, "s": 1758, "text": "This will produce the following output −" }, { "code": null, "e": 2111, "s": 1799, "text": "{ \"_id\" : ObjectId(\"5ea6db31551299a9f98c939c\"), \"UserName\" : \"John\", \"UserEmailId\" : \"John@gmail.com\" }\n{ \"_id\" : ObjectId(\"5ea6db3c551299a9f98c939d\"), \"UserName\" : \"Bob\", \"UserEmailId\" : \"Bob@gmail.com\" }\n{ \"_id\" : ObjectId(\"5ea6db47551299a9f98c939e\"), \"UserName\" : \"David\", \"UserEmailId\" : \"David@gmail.com\" }" }, { "code": null, "e": 2200, "s": 2111, "text": "Following is the query to get email-id from a MongoDB document and print using print() −" }, { "code": null, "e": 2293, "s": 2200, "text": "> db.demo690.find().forEach(function(document) {\n... print(document.UserEmailId);\n... });" }, { "code": null, "e": 2334, "s": 2293, "text": "This will produce the following output −" }, { "code": null, "e": 2379, "s": 2334, "text": "John@gmail.com\nBob@gmail.com\nDavid@gmail.com" } ]
std::iota in C++ - GeeksforGeeks
01 Sep, 2021 Store increasing sequence Assigns to every element in the range [first, last] successive values of val, as if incremented with ++val after each element is written. Template : void iota (ForwardIterator first, ForwardIterator last, T val); Parameters : first, last Forward iterators to the initial and final positions of the sequence to be written. The range used is [first, last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last. val Initial value for the accumulator. Return Type : None C++ // C++ program to illustrate// std :: iota#include <iostream> // std::cout#include <numeric> // std::iota // Driver codeint main(){ int numbers[10]; // Initialising starting value as 100 int st = 100; std::iota(numbers, numbers + 10, st); std::cout << "Elements are :"; for (auto i : numbers) std::cout << ' ' << i; std::cout << '\n'; return 0;} Output: Elements are : 100 101 102 103 104 105 106 107 108 109 Application : It can be used to generate a sequence of consecutive numbers. C++ // C++ program to generate// a sequence of numbers using std :: iota#include <iostream> // std::cout#include <numeric> // std::iota // Driver codeint main(){ int numbers[11]; // Initialising starting value as 10 int st = 10; std::iota(numbers, numbers + 11, st); std::cout << "Elements are :"; for (auto i : numbers) std::cout << ' ' << i; std::cout << '\n'; return 0;} Output: Elements are : 10 11 12 13 14 15 16 17 18 19 20 This article is contributed by Sachin Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. anikakapoor cpp-numerics-library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ List in C++ Standard Template Library (STL) Convert string to char array in C++ new and delete operators in C++ for dynamic memory Destructors in C++ Pair in C++ Standard Template Library (STL) Inline Functions in C++
[ { "code": null, "e": 23732, "s": 23704, "text": "\n01 Sep, 2021" }, { "code": null, "e": 23896, "s": 23732, "text": "Store increasing sequence Assigns to every element in the range [first, last] successive values of val, as if incremented with ++val after each element is written." }, { "code": null, "e": 23908, "s": 23896, "text": "Template : " }, { "code": null, "e": 24309, "s": 23908, "text": "void iota (ForwardIterator first, ForwardIterator last, T val);\n\nParameters :\n\nfirst, last\nForward iterators to the initial and final positions of the sequence\nto be written. The range used is [first, last), which contains all the\nelements between first and last, including the element pointed by\nfirst but not the element pointed by last.\n\nval\nInitial value for the accumulator. \n\nReturn Type :\nNone" }, { "code": null, "e": 24313, "s": 24309, "text": "C++" }, { "code": "// C++ program to illustrate// std :: iota#include <iostream> // std::cout#include <numeric> // std::iota // Driver codeint main(){ int numbers[10]; // Initialising starting value as 100 int st = 100; std::iota(numbers, numbers + 10, st); std::cout << \"Elements are :\"; for (auto i : numbers) std::cout << ' ' << i; std::cout << '\\n'; return 0;}", "e": 24693, "s": 24313, "text": null }, { "code": null, "e": 24702, "s": 24693, "text": "Output: " }, { "code": null, "e": 24757, "s": 24702, "text": "Elements are : 100 101 102 103 104 105 106 107 108 109" }, { "code": null, "e": 24834, "s": 24757, "text": "Application : It can be used to generate a sequence of consecutive numbers. " }, { "code": null, "e": 24838, "s": 24834, "text": "C++" }, { "code": "// C++ program to generate// a sequence of numbers using std :: iota#include <iostream> // std::cout#include <numeric> // std::iota // Driver codeint main(){ int numbers[11]; // Initialising starting value as 10 int st = 10; std::iota(numbers, numbers + 11, st); std::cout << \"Elements are :\"; for (auto i : numbers) std::cout << ' ' << i; std::cout << '\\n'; return 0;}", "e": 25242, "s": 24838, "text": null }, { "code": null, "e": 25250, "s": 25242, "text": "Output:" }, { "code": null, "e": 25298, "s": 25250, "text": "Elements are : 10 11 12 13 14 15 16 17 18 19 20" }, { "code": null, "e": 25719, "s": 25298, "text": "This article is contributed by Sachin Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 25731, "s": 25719, "text": "anikakapoor" }, { "code": null, "e": 25752, "s": 25731, "text": "cpp-numerics-library" }, { "code": null, "e": 25756, "s": 25752, "text": "STL" }, { "code": null, "e": 25760, "s": 25756, "text": "C++" }, { "code": null, "e": 25764, "s": 25760, "text": "STL" }, { "code": null, "e": 25768, "s": 25764, "text": "CPP" }, { "code": null, "e": 25866, "s": 25768, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25875, "s": 25866, "text": "Comments" }, { "code": null, "e": 25888, "s": 25875, "text": "Old Comments" }, { "code": null, "e": 25916, "s": 25888, "text": "Operator Overloading in C++" }, { "code": null, "e": 25940, "s": 25916, "text": "Sorting a vector in C++" }, { "code": null, "e": 25960, "s": 25940, "text": "Polymorphism in C++" }, { "code": null, "e": 25993, "s": 25960, "text": "Friend class and function in C++" }, { "code": null, "e": 26037, "s": 25993, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 26073, "s": 26037, "text": "Convert string to char array in C++" }, { "code": null, "e": 26124, "s": 26073, "text": "new and delete operators in C++ for dynamic memory" }, { "code": null, "e": 26143, "s": 26124, "text": "Destructors in C++" }, { "code": null, "e": 26187, "s": 26143, "text": "Pair in C++ Standard Template Library (STL)" } ]
JavaScript TypeError - 'X' is not iterable - GeeksforGeeks
29 Jul, 2020 This JavaScript exception is not iterable occurs if the value present at the right-hand-side of for...of or as argument of a function such as Promise.all or TypedArray.from, can not be iterated or is not an iterable object. Message: TypeError: 'x' is not iterable (Firefox, Chrome) TypeError: 'x' is not a function or its return value is not iterable (Chrome) Error Type: TypeError Cause of Error: Somewhere in the code, the value present at the right-hand-side of for...of or as argument of a function such as Promise.all or TypedArray.from, is used like it can be iterated or is an iterable object. Example 1: In this example, the GFG_Obj is not iterable, So the error has occurred. HTML <script> var GFG_Obj = { 'prop1': 'val1', 'prop2': 'val2' }; // TypeError: GFG_Obj is not iterable for (let x of GFG_Obj) { // Do Anything. }</script> Output(in console): TypeError: GFG_Obj is not iterable Example 2: In this example, the GFG is not iterable, So the error has occurred. HTML <script> function* GFG(a, b) { yield a; yield b; } // TypeError: GFG is not iterable for (let y of GFG) console.log(x);</script> Output(in console): TypeError: GFG is not iterable JavaScript-Errors JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request Remove elements from a JavaScript Array How to get character array from string in JavaScript? How to get selected value in dropdown list using JavaScript ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24909, "s": 24881, "text": "\n29 Jul, 2020" }, { "code": null, "e": 25133, "s": 24909, "text": "This JavaScript exception is not iterable occurs if the value present at the right-hand-side of for...of or as argument of a function such as Promise.all or TypedArray.from, can not be iterated or is not an iterable object." }, { "code": null, "e": 25142, "s": 25133, "text": "Message:" }, { "code": null, "e": 25270, "s": 25142, "text": "TypeError: 'x' is not iterable (Firefox, Chrome)\nTypeError: 'x' is not a function or its return value is not iterable (Chrome)\n" }, { "code": null, "e": 25282, "s": 25270, "text": "Error Type:" }, { "code": null, "e": 25293, "s": 25282, "text": "TypeError\n" }, { "code": null, "e": 25512, "s": 25293, "text": "Cause of Error: Somewhere in the code, the value present at the right-hand-side of for...of or as argument of a function such as Promise.all or TypedArray.from, is used like it can be iterated or is an iterable object." }, { "code": null, "e": 25596, "s": 25512, "text": "Example 1: In this example, the GFG_Obj is not iterable, So the error has occurred." }, { "code": null, "e": 25601, "s": 25596, "text": "HTML" }, { "code": "<script> var GFG_Obj = { 'prop1': 'val1', 'prop2': 'val2' }; // TypeError: GFG_Obj is not iterable for (let x of GFG_Obj) { // Do Anything. }</script>", "e": 25772, "s": 25601, "text": null }, { "code": null, "e": 25792, "s": 25772, "text": "Output(in console):" }, { "code": null, "e": 25828, "s": 25792, "text": "TypeError: GFG_Obj is not iterable\n" }, { "code": null, "e": 25908, "s": 25828, "text": "Example 2: In this example, the GFG is not iterable, So the error has occurred." }, { "code": null, "e": 25913, "s": 25908, "text": "HTML" }, { "code": "<script> function* GFG(a, b) { yield a; yield b; } // TypeError: GFG is not iterable for (let y of GFG) console.log(x);</script>", "e": 26072, "s": 25913, "text": null }, { "code": null, "e": 26092, "s": 26072, "text": "Output(in console):" }, { "code": null, "e": 26124, "s": 26092, "text": "TypeError: GFG is not iterable\n" }, { "code": null, "e": 26142, "s": 26124, "text": "JavaScript-Errors" }, { "code": null, "e": 26153, "s": 26142, "text": "JavaScript" }, { "code": null, "e": 26170, "s": 26153, "text": "Web Technologies" }, { "code": null, "e": 26268, "s": 26170, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26277, "s": 26268, "text": "Comments" }, { "code": null, "e": 26290, "s": 26277, "text": "Old Comments" }, { "code": null, "e": 26351, "s": 26290, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26392, "s": 26351, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 26432, "s": 26392, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 26486, "s": 26432, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 26548, "s": 26486, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 26604, "s": 26548, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26637, "s": 26604, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26699, "s": 26637, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26742, "s": 26699, "text": "How to fetch data from an API in ReactJS ?" } ]
Ints contains() function in Java
The contains() function of the Ints class is used to check whether an element is present in the array or not. Following is the syntax − public static boolean contains(int[] arr, int target) Here, arr is the array wherein the element is to be checked. The target is the element to be checked. Following is an example to implement the contains() method of the Ints class − import com.google.common.primitives.Ints; import java.util.*; class Demo { public static void main(String[] args) { int[] myArr1 = { 100, 150, 230, 300, 400 }; int[] myArr2 = { 450, 550, 700, 800, 1000 }; System.out.println("Array 1 = "); for(int i=0; i < myArr1.length; i++) { System.out.println(myArr1[i]); } System.out.println("Array 2 = "); for(int i=0; i < myArr2.length; i++) { System.out.println(myArr2[i]); } int[] arr = Ints.concat(myArr1, myArr2); System.out.println("Concatenated arrays = "+Arrays.toString(arr)); if (Ints.contains(arr, 800)) System.out.println("Element 800 is in the array!"); else System.out.println("Element 800 is not in the array!"); } } Array 1 = 100 150 230 300 400 Array 2 = 450 550 700 800 1000 Concatenated arrays = [100, 150, 230, 300, 400, 450, 550, 700, 800, 1000] Element 800 is in the array!
[ { "code": null, "e": 1172, "s": 1062, "text": "The contains() function of the Ints class is used to check whether an element is present in the array or not." }, { "code": null, "e": 1198, "s": 1172, "text": "Following is the syntax −" }, { "code": null, "e": 1252, "s": 1198, "text": "public static boolean\ncontains(int[] arr, int target)" }, { "code": null, "e": 1354, "s": 1252, "text": "Here, arr is the array wherein the element is to be checked. The target is the element to be checked." }, { "code": null, "e": 1433, "s": 1354, "text": "Following is an example to implement the contains() method of the Ints class −" }, { "code": null, "e": 2218, "s": 1433, "text": "import com.google.common.primitives.Ints;\nimport java.util.*;\nclass Demo {\n public static void main(String[] args) {\n int[] myArr1 = { 100, 150, 230, 300, 400 };\n int[] myArr2 = { 450, 550, 700, 800, 1000 };\n System.out.println(\"Array 1 = \");\n for(int i=0; i < myArr1.length; i++) {\n System.out.println(myArr1[i]);\n }\n System.out.println(\"Array 2 = \");\n for(int i=0; i < myArr2.length; i++) {\n System.out.println(myArr2[i]);\n }\n int[] arr = Ints.concat(myArr1, myArr2);\n System.out.println(\"Concatenated arrays = \"+Arrays.toString(arr));\n if (Ints.contains(arr, 800))\n System.out.println(\"Element 800 is in the array!\");\n else\n System.out.println(\"Element 800 is not in the array!\");\n }\n}" }, { "code": null, "e": 2382, "s": 2218, "text": "Array 1 =\n100\n150\n230\n300\n400\nArray 2 =\n450\n550\n700\n800\n1000\nConcatenated arrays = [100, 150, 230, 300, 400, 450, 550, 700, 800, 1000]\nElement 800 is in the array!" } ]
Break Statement in Dart Programming
The break statement is used to take the control out of a construct. Using break in a loop causes the program to exit the loop. Following is an example of the break statement. void main() { var i = 1; while(i<=10) { if (i % 5 == 0) { print("The first multiple of 5 between 1 and 10 is : ${i}"); break ; //exit the loop if the first multiple is found } i++; } } The above code prints the first multiple of 5 for the range of numbers within 1 to 10. If a number is found to be divisible by 5, the if construct forces the control to exit the loop using the break statement. The following output is displayed on successful execution of the above code. The first multiple of 5 between 1 and 10 is: 5 44 Lectures 4.5 hours Sriyank Siddhartha 34 Lectures 4 hours Sriyank Siddhartha 69 Lectures 4 hours Frahaan Hussain 117 Lectures 10 hours Frahaan Hussain 22 Lectures 1.5 hours Pranjal Srivastava 34 Lectures 3 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2700, "s": 2525, "text": "The break statement is used to take the control out of a construct. Using break in a loop causes the program to exit the loop. Following is an example of the break statement." }, { "code": null, "e": 2954, "s": 2700, "text": "void main() { \n var i = 1; \n while(i<=10) { \n if (i % 5 == 0) { \n print(\"The first multiple of 5 between 1 and 10 is : ${i}\"); \n break ; \n //exit the loop if the first multiple is found \n } \n i++; \n }\n} " }, { "code": null, "e": 3041, "s": 2954, "text": "The above code prints the first multiple of 5 for the range of numbers within 1 to 10." }, { "code": null, "e": 3241, "s": 3041, "text": "If a number is found to be divisible by 5, the if construct forces the control to exit the loop using the break statement. The following output is displayed on successful execution of the above code." }, { "code": null, "e": 3290, "s": 3241, "text": "The first multiple of 5 between 1 and 10 is: 5 \n" }, { "code": null, "e": 3325, "s": 3290, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3345, "s": 3325, "text": " Sriyank Siddhartha" }, { "code": null, "e": 3378, "s": 3345, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 3398, "s": 3378, "text": " Sriyank Siddhartha" }, { "code": null, "e": 3431, "s": 3398, "text": "\n 69 Lectures \n 4 hours \n" }, { "code": null, "e": 3448, "s": 3431, "text": " Frahaan Hussain" }, { "code": null, "e": 3483, "s": 3448, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 3500, "s": 3483, "text": " Frahaan Hussain" }, { "code": null, "e": 3535, "s": 3500, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3555, "s": 3535, "text": " Pranjal Srivastava" }, { "code": null, "e": 3588, "s": 3555, "text": "\n 34 Lectures \n 3 hours \n" }, { "code": null, "e": 3608, "s": 3588, "text": " Pranjal Srivastava" }, { "code": null, "e": 3615, "s": 3608, "text": " Print" }, { "code": null, "e": 3626, "s": 3615, "text": " Add Notes" } ]
Node.js - Introduction
Node.js is a server-side platform built on Google Chrome's JavaScript Engine (V8 Engine). Node.js was developed by Ryan Dahl in 2009 and its latest version is v0.10.36. The definition of Node.js as supplied by its official documentation is as follows − Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. Node.js is an open source, cross-platform runtime environment for developing server-side and networking applications. Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows, and Linux. Node.js also provides a rich library of various JavaScript modules which simplifies the development of web applications using Node.js to a great extent. Node.js = Runtime Environment + JavaScript Library Following are some of the important features that make Node.js the first choice of software architects. Asynchronous and Event Driven − All APIs of Node.js library are asynchronous, that is, non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call. Asynchronous and Event Driven − All APIs of Node.js library are asynchronous, that is, non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call. Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution. Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution. Single Threaded but Highly Scalable − Node.js uses a single threaded model with event looping. Event mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and the same program can provide service to a much larger number of requests than traditional servers like Apache HTTP Server. Single Threaded but Highly Scalable − Node.js uses a single threaded model with event looping. Event mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and the same program can provide service to a much larger number of requests than traditional servers like Apache HTTP Server. No Buffering − Node.js applications never buffer any data. These applications simply output the data in chunks. No Buffering − Node.js applications never buffer any data. These applications simply output the data in chunks. License − Node.js is released under the MIT license. License − Node.js is released under the MIT license. Following is the link on github wiki containing an exhaustive list of projects, application and companies which are using Node.js. This list includes eBay, General Electric, GoDaddy, Microsoft, PayPal, Uber, Wikipins, Yahoo!, and Yammer to name a few. Projects, Applications, and Companies Using Node Projects, Applications, and Companies Using Node The following diagram depicts some important parts of Node.js which we will discuss in detail in the subsequent chapters. Following are the areas where Node.js is proving itself as a perfect technology partner. I/O bound Applications Data Streaming Applications Data Intensive Real-time Applications (DIRT) JSON APIs based Applications Single Page Applications It is not advisable to use Node.js for CPU intensive applications. 44 Lectures 7.5 hours Eduonix Learning Solutions 88 Lectures 17 hours Eduonix Learning Solutions 32 Lectures 1.5 hours Richard Wells 8 Lectures 33 mins Anant Rungta 9 Lectures 2.5 hours SHIVPRASAD KOIRALA 97 Lectures 6 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2271, "s": 2018, "text": "Node.js is a server-side platform built on Google Chrome's JavaScript Engine (V8 Engine). Node.js was developed by Ryan Dahl in 2009 and its latest version is v0.10.36. The definition of Node.js as supplied by its official documentation is as follows −" }, { "code": null, "e": 2571, "s": 2271, "text": "Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices." }, { "code": null, "e": 2818, "s": 2571, "text": "Node.js is an open source, cross-platform runtime environment for developing server-side and networking applications. Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows, and Linux." }, { "code": null, "e": 2971, "s": 2818, "text": "Node.js also provides a rich library of various JavaScript modules which simplifies the development of web applications using Node.js to a great extent." }, { "code": null, "e": 3023, "s": 2971, "text": "Node.js = Runtime Environment + JavaScript Library\n" }, { "code": null, "e": 3127, "s": 3023, "text": "Following are some of the important features that make Node.js the first choice of software architects." }, { "code": null, "e": 3474, "s": 3127, "text": "Asynchronous and Event Driven − All APIs of Node.js library are asynchronous, that is, non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call." }, { "code": null, "e": 3821, "s": 3474, "text": "Asynchronous and Event Driven − All APIs of Node.js library are asynchronous, that is, non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call." }, { "code": null, "e": 3934, "s": 3821, "text": "Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution." }, { "code": null, "e": 4047, "s": 3934, "text": "Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution." }, { "code": null, "e": 4494, "s": 4047, "text": "Single Threaded but Highly Scalable − Node.js uses a single threaded model with event looping. Event mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and the same program can provide service to a much larger number of requests than traditional servers like Apache HTTP Server." }, { "code": null, "e": 4941, "s": 4494, "text": "Single Threaded but Highly Scalable − Node.js uses a single threaded model with event looping. Event mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and the same program can provide service to a much larger number of requests than traditional servers like Apache HTTP Server." }, { "code": null, "e": 5053, "s": 4941, "text": "No Buffering − Node.js applications never buffer any data. These applications simply output the data in chunks." }, { "code": null, "e": 5165, "s": 5053, "text": "No Buffering − Node.js applications never buffer any data. These applications simply output the data in chunks." }, { "code": null, "e": 5218, "s": 5165, "text": "License − Node.js is released under the MIT license." }, { "code": null, "e": 5271, "s": 5218, "text": "License − Node.js is released under the MIT license." }, { "code": null, "e": 5523, "s": 5271, "text": "Following is the link on github wiki containing an exhaustive list of projects, application and companies which are using Node.js. This list includes eBay, General Electric, GoDaddy, Microsoft, PayPal, Uber, Wikipins, Yahoo!, and Yammer to name a few." }, { "code": null, "e": 5572, "s": 5523, "text": "Projects, Applications, and Companies Using Node" }, { "code": null, "e": 5621, "s": 5572, "text": "Projects, Applications, and Companies Using Node" }, { "code": null, "e": 5743, "s": 5621, "text": "The following diagram depicts some important parts of Node.js which we will discuss in detail in the subsequent chapters." }, { "code": null, "e": 5832, "s": 5743, "text": "Following are the areas where Node.js is proving itself as a perfect technology partner." }, { "code": null, "e": 5855, "s": 5832, "text": "I/O bound Applications" }, { "code": null, "e": 5883, "s": 5855, "text": "Data Streaming Applications" }, { "code": null, "e": 5928, "s": 5883, "text": "Data Intensive Real-time Applications (DIRT)" }, { "code": null, "e": 5957, "s": 5928, "text": "JSON APIs based Applications" }, { "code": null, "e": 5982, "s": 5957, "text": "Single Page Applications" }, { "code": null, "e": 6049, "s": 5982, "text": "It is not advisable to use Node.js for CPU intensive applications." }, { "code": null, "e": 6084, "s": 6049, "text": "\n 44 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6112, "s": 6084, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6146, "s": 6112, "text": "\n 88 Lectures \n 17 hours \n" }, { "code": null, "e": 6174, "s": 6146, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6209, "s": 6174, "text": "\n 32 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6224, "s": 6209, "text": " Richard Wells" }, { "code": null, "e": 6255, "s": 6224, "text": "\n 8 Lectures \n 33 mins\n" }, { "code": null, "e": 6269, "s": 6255, "text": " Anant Rungta" }, { "code": null, "e": 6303, "s": 6269, "text": "\n 9 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6323, "s": 6303, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 6356, "s": 6323, "text": "\n 97 Lectures \n 6 hours \n" }, { "code": null, "e": 6376, "s": 6356, "text": " Skillbakerystudios" }, { "code": null, "e": 6383, "s": 6376, "text": " Print" }, { "code": null, "e": 6394, "s": 6383, "text": " Add Notes" } ]
Convert a list of objects to JSON using the Gson library in Java?
A Gson is a library that can be used to convert Java Objects to JSON representation. It can also be used to convert a JSON string to an equivalent Java object. The primary class to use is Gson which we can create by calling the new Gson() and the GsonBuilder class can be used to create a Gson instance. We can convert a list of objects by first creating a Person class and convert a list of Person objects to JSON. import java.util.*; import java.util.stream.*; import com.google.gson.*; public class JSONConverterTest { public static void main( String[] args ) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); List list = Stream.of(new Person("Raja", "Ramesh", 30, "9959984800"), new Person("Jai", "Dev", 25, "7702144400"), new Person("Adithya", "Sai", 21, "7013536200"), new Person("Chaitanya", "Sai", 28, "9656444150")) .collect(Collectors.toList()); System.out.println("Convert list of person objects to Json:"); String json = gson.toJson(list); // converts to json System.out.println(json); } } // Person class class Person { private String firstName, lastName, contact; private int age; public Person(String firstName, String lastName, int age, String contact) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.contact = contact; } public String toString() { return "[" + firstName + " " + lastName + " " + age + " " +contact +"]"; } } Convert list of person objects to Json: [ { "firstName": "Raja", "lastName": "Ramesh", "contact": "9959984800", "age": 30 }, { "firstName": "Jai", "lastName": "Dev", "contact": "7702144400", "age": 25 }, { "firstName": "Adithya", "lastName": "Sai", "contact": "7013536200", "age": 21 }, { "firstName": "Chaitanya", "lastName": "Sai", "contact": "9656444150", "age": 28 } ]
[ { "code": null, "e": 1366, "s": 1062, "text": "A Gson is a library that can be used to convert Java Objects to JSON representation. It can also be used to convert a JSON string to an equivalent Java object. The primary class to use is Gson which we can create by calling the new Gson() and the GsonBuilder class can be used to create a Gson instance." }, { "code": null, "e": 1478, "s": 1366, "text": "We can convert a list of objects by first creating a Person class and convert a list of Person objects to JSON." }, { "code": null, "e": 2641, "s": 1478, "text": "import java.util.*;\nimport java.util.stream.*;\nimport com.google.gson.*;\npublic class JSONConverterTest {\n public static void main( String[] args ) {\n Gson gson = new GsonBuilder().setPrettyPrinting().create();\n List list = Stream.of(new Person(\"Raja\", \"Ramesh\", 30, \"9959984800\"),\n new Person(\"Jai\", \"Dev\", 25, \"7702144400\"),\n new Person(\"Adithya\", \"Sai\", 21, \"7013536200\"),\n new Person(\"Chaitanya\", \"Sai\", 28, \"9656444150\"))\n .collect(Collectors.toList());\n System.out.println(\"Convert list of person objects to Json:\");\n String json = gson.toJson(list); // converts to json\n System.out.println(json);\n }\n}\n// Person class\nclass Person {\n private String firstName, lastName, contact;\n private int age;\n public Person(String firstName, String lastName, int age, String contact) {\n this.firstName = firstName;\n this.lastName = lastName;\n this.age = age;\n this.contact = contact;\n }\n public String toString() {\n return \"[\" + firstName + \" \" + lastName + \" \" + age + \" \" +contact +\"]\";\n }\n}" }, { "code": null, "e": 3062, "s": 2641, "text": "Convert list of person objects to Json:\n[\n{\n \"firstName\": \"Raja\",\n \"lastName\": \"Ramesh\",\n \"contact\": \"9959984800\",\n \"age\": 30\n},\n{\n \"firstName\": \"Jai\",\n \"lastName\": \"Dev\",\n \"contact\": \"7702144400\",\n \"age\": 25\n},\n{\n \"firstName\": \"Adithya\",\n \"lastName\": \"Sai\",\n \"contact\": \"7013536200\",\n \"age\": 21\n},\n{\n \"firstName\": \"Chaitanya\",\n \"lastName\": \"Sai\",\n \"contact\": \"9656444150\",\n \"age\": 28\n}\n]" } ]
TypeORM - Relations
Relations are used to refer the relationship between table in database. In general, a relationship exists between two tables when one of them has a foreign key that references the primary key of the other table. This feature makes relational database more powerful and efficiently store information. TypeORM allows the entities to be related to each other and subsequently database tables. In general, relationship can be classified into four broader categories. They are as follows, one-to-one − One object of the given entity relates to only one object of the target entity and vice versa. For example, a country will have only one capital city and similarly a city will be capital of only one country. many-to-one − Multiple object of the given entity relates to one object of the target entity. For example, city comes under only one country but country can have multiple cities. one-to-many − Same as many-to-one except the relationship is reversed. many-to-many − Multiple object of the given entity relates to multiple object of the target entity. For example, an article may be tagged under multiple topic like programming language, finance, etc., and at the same time a particular tag may have multiple articles as well. TypeORM also provides options to enhance the relationship of the entities. They are as follows − eager − Source entity object loads the target entity objects as well. cascade − Target entity object gets inserted or updated while the source entity object is inserted or updated. onDelete − Target entity objects get deleted as well while the source entity object is deleted. primary − Used to specify that the relation column is primary key or not. nullable − Used to specify that the relation column is nullable or not. Let us go through different types of relation mapping in detail. As we learned earlier, it is referred by the instance of one table field contains the instance of another table field and vice versa. Let us create a Details table − import {Entity, PrimaryGeneratedColumn, Column} from "typeorm"; @Entity() export class Details { @PrimaryGeneratedColumn() id: number; @Column() gender: string; @Column() country: string; } Let’s create an another entity Customer as follows − import {Entity, PrimaryGeneratedColumn, Column, OneToOne, JoinColumn} from "typeorm"; import {Details} from "./Details"; @Entity() export class Customer { @PrimaryGeneratedColumn() id: number; @Column() name: string; @OneToOne(type => Details) @JoinColumn() details: Details; } Here, We have added mapping OneToOne to Details table. @JoinColumn() contain a “relation id” and foreign key to Customer table. We can save the relation in index.ts as follows − const details = new Details(); details.gender = "female"; details.country = "india" await connection.manager.save(details); const customer = new Customer(); customer.name = 'customer1'; customer.details = Details; await connection.manager.save(Customer); As we learned earlier, it is referred by the instance of first table field contains the multiple instances of second table field called One-to-Many mapping and multiple instances of first table contains only one instance of second table called Many-to-One mapping. Consider an example of Student and project entities whereas, student can work on more than one project but each project is handled by only one student. Let’s create a Project entity as follows − import {Entity, PrimaryGeneratedColumn, Column, ManyToOne} from "typeorm"; import {Student} from "./Student"; @Entity() export class Project { @PrimaryGeneratedColumn() id: number; @Column() projects: string; @ManyToOne(type => Student, student => student.projects) student: Student; } Now, we create Student entity as below − import {Entity, PrimaryGeneratedColumn, Column, OneToMany} from "typeorm"; import {Project} from "./Project"; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; @OneToMany(type => Project, project => project.student) projects: Project[]; } Here, @OneToMany property mapped Project and @ManyToOne property mapped to Student. However, @OneToMany cannot exist without @ManyToOne and @ManyToOne property contain “relation id” and foreign key. We can save the connection in index.ts as follows − const proj1 = new Project(); proj1.projects = "database management"; await connection.manager.save(proj1); const proj2 = new Project(); proj2.projects = "web application"; await connection.manager.save(proj2); const stud = new Student(); stud.name = "Student1"; stud.projects = [proj1, proj2]; await connection.manager.save(stud); As we learned earlier, it is referred by multiple records in one table are related to multiple records in another table. Consider an example, University student can be enrolled in multiple classes at a time which means student may have four or five classes per semester and a class can have many students. We can simply conclude, a student has many classes, and a class has many students. Let’s create an entity for Classes as follows − import {Entity, PrimaryGeneratedColumn, Column} from "typeorm"; @Entity() export class Classes { @PrimaryGeneratedColumn() id: number; @Column() name: string; } Now, we create Student entity as below − import {Entity, PrimaryGeneratedColumn, Column, ManyToMany, JoinTable} from "typeorm"; import {Classes} from "./Classes"; @Entity() export class Student { @PrimaryGeneratedColumn() id: number; @Column() name: string; @Column() subjects: string; @ManyToMany(type => Classes) @JoinTable() classes: Classes[]; } 19 Lectures 50 mins James Coonce Print Add Notes Bookmark this page
[ { "code": null, "e": 2351, "s": 2051, "text": "Relations are used to refer the relationship between table in database. In general, a relationship exists between two tables when one of them has a foreign key that references the primary key of the other table. This feature makes relational database more powerful and efficiently store information." }, { "code": null, "e": 2535, "s": 2351, "text": "TypeORM allows the entities to be related to each other and subsequently database tables. In general, relationship can be classified into four broader categories. They are as follows," }, { "code": null, "e": 2756, "s": 2535, "text": "one-to-one − One object of the given entity relates to only one object of the target entity and vice versa. For example, a country will have only one capital city and similarly a city will be capital of only one country." }, { "code": null, "e": 2935, "s": 2756, "text": "many-to-one − Multiple object of the given entity relates to one object of the target entity. For example, city comes under only one country but country can have multiple cities." }, { "code": null, "e": 3006, "s": 2935, "text": "one-to-many − Same as many-to-one except the relationship is reversed." }, { "code": null, "e": 3281, "s": 3006, "text": "many-to-many − Multiple object of the given entity relates to multiple object of the target entity. For example, an article may be tagged under multiple topic like programming language, finance, etc., and at the same time a particular tag may have multiple articles as well." }, { "code": null, "e": 3378, "s": 3281, "text": "TypeORM also provides options to enhance the relationship of the entities. They are as follows −" }, { "code": null, "e": 3448, "s": 3378, "text": "eager − Source entity object loads the target entity objects as well." }, { "code": null, "e": 3559, "s": 3448, "text": "cascade − Target entity object gets inserted or updated while the source entity object is inserted or updated." }, { "code": null, "e": 3655, "s": 3559, "text": "onDelete − Target entity objects get deleted as well while the source entity object is deleted." }, { "code": null, "e": 3729, "s": 3655, "text": "primary − Used to specify that the relation column is primary key or not." }, { "code": null, "e": 3801, "s": 3729, "text": "nullable − Used to specify that the relation column is nullable or not." }, { "code": null, "e": 3866, "s": 3801, "text": "Let us go through different types of relation mapping in detail." }, { "code": null, "e": 4032, "s": 3866, "text": "As we learned earlier, it is referred by the instance of one table field contains the instance of another table field and vice versa. Let us create a Details table −" }, { "code": null, "e": 4256, "s": 4032, "text": "import {Entity, PrimaryGeneratedColumn, Column} from \"typeorm\";\n\n@Entity() \nexport class Details {\n @PrimaryGeneratedColumn() \n id: number; \n \n @Column() \n gender: string; \n \n @Column() \n country: string; \n}" }, { "code": null, "e": 4309, "s": 4256, "text": "Let’s create an another entity Customer as follows −" }, { "code": null, "e": 4625, "s": 4309, "text": "import {Entity, PrimaryGeneratedColumn, Column, OneToOne, JoinColumn} from \"typeorm\"; \n\nimport {Details} from \"./Details\"; \n\n@Entity() \nexport class Customer { \n\n @PrimaryGeneratedColumn() \n id: number; \n \n @Column() \n name: string; \n \n @OneToOne(type => Details) @JoinColumn() \n details: Details;\n}" }, { "code": null, "e": 4631, "s": 4625, "text": "Here," }, { "code": null, "e": 4803, "s": 4631, "text": "We have added mapping OneToOne to Details table. @JoinColumn() contain a “relation id” and foreign key to Customer table. We can save the relation in index.ts as follows −" }, { "code": null, "e": 5059, "s": 4803, "text": "const details = new Details(); details.gender = \"female\"; details.country = \"india\" await connection.manager.save(details);\n\nconst customer = new Customer(); customer.name = 'customer1'; customer.details = Details; await connection.manager.save(Customer);" }, { "code": null, "e": 5324, "s": 5059, "text": "As we learned earlier, it is referred by the instance of first table field contains the multiple instances of second table field called One-to-Many mapping and multiple instances of first table contains only one instance of second table called Many-to-One mapping." }, { "code": null, "e": 5476, "s": 5324, "text": "Consider an example of Student and project entities whereas, student can work on more than one project but each project is handled by only one student." }, { "code": null, "e": 5519, "s": 5476, "text": "Let’s create a Project entity as follows −" }, { "code": null, "e": 5838, "s": 5519, "text": "import {Entity, PrimaryGeneratedColumn, Column, ManyToOne} from \"typeorm\"; import {Student} from \"./Student\"; \n@Entity() \nexport class Project { \n\n @PrimaryGeneratedColumn() \n id: number; \n \n @Column() \n projects: string; \n \n @ManyToOne(type => Student, student => student.projects) student: Student; \n}" }, { "code": null, "e": 5879, "s": 5838, "text": "Now, we create Student entity as below −" }, { "code": null, "e": 6198, "s": 5879, "text": "import {Entity, PrimaryGeneratedColumn, Column, OneToMany} from \"typeorm\"; import {Project} from \"./Project\"; \n\n@Entity() \nexport class User { \n \n @PrimaryGeneratedColumn() \n id: number; \n \n @Column() \n name: string; \n \n @OneToMany(type => Project, project => project.student) projects: Project[]; \n}" }, { "code": null, "e": 6204, "s": 6198, "text": "Here," }, { "code": null, "e": 6397, "s": 6204, "text": "@OneToMany property mapped Project and @ManyToOne property mapped to Student. However, @OneToMany cannot exist without @ManyToOne and @ManyToOne property contain “relation id” and foreign key." }, { "code": null, "e": 6449, "s": 6397, "text": "We can save the connection in index.ts as follows −" }, { "code": null, "e": 6784, "s": 6449, "text": "const proj1 = new Project(); proj1.projects = \"database management\"; await connection.manager.save(proj1); \n\nconst proj2 = new Project(); proj2.projects = \"web application\"; await connection.manager.save(proj2); \n\nconst stud = new Student(); stud.name = \"Student1\"; stud.projects = [proj1, proj2]; await connection.manager.save(stud);" }, { "code": null, "e": 7090, "s": 6784, "text": "As we learned earlier, it is referred by multiple records in one table are related to multiple records in another table. Consider an example, University student can be enrolled in multiple classes at a time which means student may have four or five classes per semester and a class can have many students." }, { "code": null, "e": 7221, "s": 7090, "text": "We can simply conclude, a student has many classes, and a class has many students. Let’s create an entity for Classes as follows −" }, { "code": null, "e": 7407, "s": 7221, "text": "import {Entity, PrimaryGeneratedColumn, Column} from \"typeorm\"; \n\n@Entity() \nexport class Classes { \n\n @PrimaryGeneratedColumn() \n id: number; \n \n @Column() \n name: string; \n}" }, { "code": null, "e": 7448, "s": 7407, "text": "Now, we create Student entity as below −" }, { "code": null, "e": 7801, "s": 7448, "text": "import {Entity, PrimaryGeneratedColumn, Column, ManyToMany, JoinTable} from \"typeorm\"; \nimport {Classes} from \"./Classes\";\n\n@Entity() \nexport class Student { \n\n @PrimaryGeneratedColumn() \n id: number; \n \n @Column() \n name: string;\n\n @Column() \n subjects: string; \n \n @ManyToMany(type => Classes) @JoinTable() \n classes: Classes[];\n}" }, { "code": null, "e": 7833, "s": 7801, "text": "\n 19 Lectures \n 50 mins\n" }, { "code": null, "e": 7847, "s": 7833, "text": " James Coonce" }, { "code": null, "e": 7854, "s": 7847, "text": " Print" }, { "code": null, "e": 7865, "s": 7854, "text": " Add Notes" } ]
PHP mysqli_connect() Function
The mysqli_connect() function establishes a connection with MySQL server and returns the connection as an object. mysqli_connect([$host, $username, $passwd, $dname, $port, $socket] ) host(Optional) This represents a host name or an IP address. If you pass Null or localhost as a value to this parameter, the local host is considered as host. username(Optional) This represents a user name in MySQL. passwd(Optional) This is represents the password to the given user. dname(Optional) This represents the default database in which the queries should be performed. port(Optional) This represents the port number at which you want to establish a connection to MySQL Server. socket(Optional) This represents the socket that is to be used. If a connection got established successfully to the MySQL server. The PHP mysqli_connect() function returns the connection object. Incase of an unsuccessful connection this function returns the boolean value false. This function was first introduced in PHP Version 5 and works works in all the later versions. Following example demonstrates the usage of the mysqli_connect() function (in procedural style) − <?php $host = "localhost"; $username = "root"; $passwd = "password"; $dbname = "mydb"; //Creating a connection $con = mysqli_connect($host, $username, $passwd, $dbname); if($con){ print("Connection Established Successfully"); }else{ print("Connection Failed "); } ?> This will produce following result − Connection Established Successfully In object oriented style you can use the new mysqli() construct to create a connection as follows $minus; <?php $host = "localhost"; $username = "root"; $passwd = "password"; $dbname = "mydb"; //Creating a connection $con = new mysqli($host, $username, $passwd, $dbname); if($con->connect_errno){ print("Connection Failed "); }else{ print("Connection Established Successfully"); } //Closing the connection $con -> close(); ?> This will produce following result − Connection Established Successfully You can also invoke this function without passing any parameters as shown below − <?php //Creating a connection $con = @mysqli_connect(); if($con){ print("Connection Established Successfully"); }else{ print("Connection Failed "); } ?> This will produce following result − Connection Failed <?php $connection_mysql = @mysqli_connect("localhost", "root", "wrong_password", "mydb"); if (mysqli_connect_errno($connection_mysql)){ echo "Failed to connect to MySQL: " . mysqli_connect_error(); exit(); } echo ("Connection established successfully"); mysqli_close($connection_mysql); ?> This will produce following result − Failed to connect to MySQL: Access denied for user 'root'@'localhost' (using password: YES) 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2871, "s": 2757, "text": "The mysqli_connect() function establishes a connection with MySQL server and returns the connection as an object." }, { "code": null, "e": 2941, "s": 2871, "text": "mysqli_connect([$host, $username, $passwd, $dname, $port, $socket] )\n" }, { "code": null, "e": 2956, "s": 2941, "text": "host(Optional)" }, { "code": null, "e": 3100, "s": 2956, "text": "This represents a host name or an IP address. If you pass Null or localhost as a value to this parameter, the local host is considered as host." }, { "code": null, "e": 3119, "s": 3100, "text": "username(Optional)" }, { "code": null, "e": 3158, "s": 3119, "text": "This represents a user name in MySQL." }, { "code": null, "e": 3175, "s": 3158, "text": "passwd(Optional)" }, { "code": null, "e": 3226, "s": 3175, "text": "This is represents the password to the given user." }, { "code": null, "e": 3242, "s": 3226, "text": "dname(Optional)" }, { "code": null, "e": 3321, "s": 3242, "text": "This represents the default database in which the queries should be performed." }, { "code": null, "e": 3336, "s": 3321, "text": "port(Optional)" }, { "code": null, "e": 3429, "s": 3336, "text": "This represents the port number at which you want to establish a connection to MySQL Server." }, { "code": null, "e": 3446, "s": 3429, "text": "socket(Optional)" }, { "code": null, "e": 3493, "s": 3446, "text": "This represents the socket that is to be used." }, { "code": null, "e": 3708, "s": 3493, "text": "If a connection got established successfully to the MySQL server. The PHP mysqli_connect() function returns the connection object. Incase of an unsuccessful connection this function returns the boolean value false." }, { "code": null, "e": 3803, "s": 3708, "text": "This function was first introduced in PHP Version 5 and works works in all the later versions." }, { "code": null, "e": 3901, "s": 3803, "text": "Following example demonstrates the usage of the mysqli_connect() function (in procedural style) −" }, { "code": null, "e": 4210, "s": 3901, "text": "<?php\n $host = \"localhost\";\n $username = \"root\";\n $passwd = \"password\";\n $dbname = \"mydb\";\n\n //Creating a connection\n $con = mysqli_connect($host, $username, $passwd, $dbname);\n\n if($con){\n print(\"Connection Established Successfully\");\n }else{\n print(\"Connection Failed \");\n }\n?>" }, { "code": null, "e": 4247, "s": 4210, "text": "This will produce following result −" }, { "code": null, "e": 4284, "s": 4247, "text": "Connection Established Successfully\n" }, { "code": null, "e": 4390, "s": 4284, "text": "In object oriented style you can use the new mysqli() construct to create a connection as follows $minus;" }, { "code": null, "e": 4759, "s": 4390, "text": "<?php\n $host = \"localhost\";\n $username = \"root\";\n $passwd = \"password\";\n $dbname = \"mydb\";\n\n //Creating a connection\n $con = new mysqli($host, $username, $passwd, $dbname);\n\n if($con->connect_errno){\n print(\"Connection Failed \");\n }else{\n print(\"Connection Established Successfully\");\n }\n\n //Closing the connection\n $con -> close();\n?>" }, { "code": null, "e": 4796, "s": 4759, "text": "This will produce following result −" }, { "code": null, "e": 4833, "s": 4796, "text": "Connection Established Successfully\n" }, { "code": null, "e": 4915, "s": 4833, "text": "You can also invoke this function without passing any parameters as shown below −" }, { "code": null, "e": 5096, "s": 4915, "text": "<?php\n //Creating a connection\n $con = @mysqli_connect();\n\n if($con){\n print(\"Connection Established Successfully\");\n }else{\n print(\"Connection Failed \");\n }\n?>" }, { "code": null, "e": 5133, "s": 5096, "text": "This will produce following result −" }, { "code": null, "e": 5152, "s": 5133, "text": "Connection Failed\n" }, { "code": null, "e": 5477, "s": 5152, "text": "<?php\n $connection_mysql = @mysqli_connect(\"localhost\", \"root\", \"wrong_password\", \"mydb\");\n \n if (mysqli_connect_errno($connection_mysql)){\n echo \"Failed to connect to MySQL: \" . mysqli_connect_error();\n\t exit();\n } \n echo (\"Connection established successfully\"); \n mysqli_close($connection_mysql);\n?>" }, { "code": null, "e": 5514, "s": 5477, "text": "This will produce following result −" }, { "code": null, "e": 5607, "s": 5514, "text": "Failed to connect to MySQL: Access denied for user 'root'@'localhost' (using password: YES)\n" }, { "code": null, "e": 5640, "s": 5607, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 5656, "s": 5640, "text": " Malhar Lathkar" }, { "code": null, "e": 5689, "s": 5656, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 5700, "s": 5689, "text": " Syed Raza" }, { "code": null, "e": 5735, "s": 5700, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5752, "s": 5735, "text": " Frahaan Hussain" }, { "code": null, "e": 5785, "s": 5752, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 5800, "s": 5785, "text": " Nivedita Jain" }, { "code": null, "e": 5835, "s": 5800, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 5847, "s": 5835, "text": " Azaz Patel" }, { "code": null, "e": 5882, "s": 5847, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5910, "s": 5882, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 5917, "s": 5910, "text": " Print" }, { "code": null, "e": 5928, "s": 5917, "text": " Add Notes" } ]
Longest Common Prefix in Python
Suppose we have a set of strings in an array. We have to find the Longest Common Prefix amongst the string in the array. Here we will assume that all strings are lower case strings. And if there is no common prefix, then return “”. So if the array of a string is like ["school", "schedule","Scotland"], then the Longest Common Prefix is “sc” as this is present in all of these string. To solve this, we will take the first string as curr, now take each string from the array and read them character by character, and check the characters between curr, and the taken string one by one. If they are same go for next character, otherwise break the loop, and update the curr as the substring that has matched. Let us see the implementation to get a better understanding Live Demo class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if len(strs) == 0: return "" current = strs[0] for i in range(1,len(strs)): temp = "" if len(current) == 0: break for j in range(len(strs[i])): if j<len(current) and current[j] == strs[i][j]: temp+=current[j] else: break current = temp return current input_list = ["school","schedule","scotland"] ob1 = Solution() print(ob1.longestCommonPrefix(input_list)) ["school","schedule","scotland"] "sc"
[ { "code": null, "e": 1294, "s": 1062, "text": "Suppose we have a set of strings in an array. We have to find the Longest Common Prefix amongst the string in the array. Here we will assume that all strings are lower case strings. And if there is no common prefix, then return “”." }, { "code": null, "e": 1447, "s": 1294, "text": "So if the array of a string is like [\"school\", \"schedule\",\"Scotland\"], then the Longest Common Prefix is “sc” as this is present in all of these string." }, { "code": null, "e": 1768, "s": 1447, "text": "To solve this, we will take the first string as curr, now take each string from the array and read them character by character, and check the characters between curr, and the taken string one by one. If they are same go for next character, otherwise break the loop, and update the curr as the substring that has matched." }, { "code": null, "e": 1828, "s": 1768, "text": "Let us see the implementation to get a better understanding" }, { "code": null, "e": 1839, "s": 1828, "text": " Live Demo" }, { "code": null, "e": 2461, "s": 1839, "text": "class Solution(object):\n def longestCommonPrefix(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: str\n \"\"\"\n if len(strs) == 0:\n return \"\"\n current = strs[0]\n for i in range(1,len(strs)):\n temp = \"\"\n if len(current) == 0:\n break\n for j in range(len(strs[i])):\n if j<len(current) and current[j] == strs[i][j]:\n temp+=current[j]\n else:\n break\n current = temp\n return current\ninput_list = [\"school\",\"schedule\",\"scotland\"]\nob1 = Solution()\nprint(ob1.longestCommonPrefix(input_list))" }, { "code": null, "e": 2494, "s": 2461, "text": "[\"school\",\"schedule\",\"scotland\"]" }, { "code": null, "e": 2499, "s": 2494, "text": "\"sc\"" } ]
Python Number sin() Method
Python number method sin() returns the sine of x, in radians. Following is the syntax for sin() method − sin(x) Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object. x − This must be a numeric value. x − This must be a numeric value. This method returns a numeric value between -1 and 1, which represents the sine of the parameter x. The following example shows the usage of sin() method. #!/usr/bin/python import math print "sin(3) : ", math.sin(3) print "sin(-3) : ", math.sin(-3) print "sin(0) : ", math.sin(0) print "sin(math.pi) : ", math.sin(math.pi) print "sin(math.pi/2) : ", math.sin(math.pi/2) When we run above program, it produces following result − sin(3) : 0.14112000806 sin(-3) : -0.14112000806 sin(0) : 0.0 sin(math.pi) : 1.22464679915e-16 sin(math.pi/2) : 1.0 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": 2306, "s": 2244, "text": "Python number method sin() returns the sine of x, in radians." }, { "code": null, "e": 2349, "s": 2306, "text": "Following is the syntax for sin() method −" }, { "code": null, "e": 2357, "s": 2349, "text": "sin(x)\n" }, { "code": null, "e": 2504, "s": 2357, "text": "Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object." }, { "code": null, "e": 2538, "s": 2504, "text": "x − This must be a numeric value." }, { "code": null, "e": 2572, "s": 2538, "text": "x − This must be a numeric value." }, { "code": null, "e": 2672, "s": 2572, "text": "This method returns a numeric value between -1 and 1, which represents the sine of the parameter x." }, { "code": null, "e": 2727, "s": 2672, "text": "The following example shows the usage of sin() method." }, { "code": null, "e": 2948, "s": 2727, "text": "#!/usr/bin/python\nimport math\n\nprint \"sin(3) : \", math.sin(3)\nprint \"sin(-3) : \", math.sin(-3)\nprint \"sin(0) : \", math.sin(0)\nprint \"sin(math.pi) : \", math.sin(math.pi)\nprint \"sin(math.pi/2) : \", math.sin(math.pi/2)" }, { "code": null, "e": 3006, "s": 2948, "text": "When we run above program, it produces following result −" }, { "code": null, "e": 3127, "s": 3006, "text": "sin(3) : 0.14112000806\nsin(-3) : -0.14112000806\nsin(0) : 0.0\nsin(math.pi) : 1.22464679915e-16\nsin(math.pi/2) : 1.0\n" }, { "code": null, "e": 3164, "s": 3127, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3180, "s": 3164, "text": " Malhar Lathkar" }, { "code": null, "e": 3213, "s": 3180, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3232, "s": 3213, "text": " Arnab Chakraborty" }, { "code": null, "e": 3267, "s": 3232, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3289, "s": 3267, "text": " In28Minutes Official" }, { "code": null, "e": 3323, "s": 3289, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3351, "s": 3323, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3386, "s": 3351, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3400, "s": 3386, "text": " Lets Kode It" }, { "code": null, "e": 3433, "s": 3400, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3450, "s": 3433, "text": " Abhilash Nelson" }, { "code": null, "e": 3457, "s": 3450, "text": " Print" }, { "code": null, "e": 3468, "s": 3457, "text": " Add Notes" } ]
How to Create Liquid Filling Effect on Text using HTML and CSS ? - GeeksforGeeks
28 Mar, 2022 The liquid fill text animation can be done using CSS | ::before selector. We will use key frames to set height for each frame of animation. Please make sure you know about both CSS | ::before selector and CSS | @keyframes Rule before try this code.The basic styling of the text can be done differently that totally depends on you how you want your text to look like. The main thing is with keyframes. For the first half percentages, we are increasing the height and for the next half, we are decreasing the height. We have used 25% as the minimum value for height. You can play around with the values of a percentage to change the minimum and maximum height and look and feel of the animation according to your needs. Creating structure: In this section, we will create the text where we will apply the liquid filling effect. To create structure normal HTML will be required. HTML Code: HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title></head><body> <center> <h1>GeeksforGeeks</h1> </center></body></html> Design structure: Before starting the design you have to be familiar with the few concepts from CSS like CSS | ::before selector and CSS | @keyframes Rule. Other effects are totally depends on the designer. CSS Code: CSS <style> body { margin: 0; padding: 0; } h1 { margin: 200px 0; padding: 0; font-size: 80px; position: relative; color:green; } h1:before { content: "GeeksforGeeks"; position: absolute; top: 0; left: 0; width: 100%; height: 100%; color:white; overflow: hidden; animation: animate 6s infinite; } @keyframes animate { 0% { height: 25%; } 25% { height: 50%; } 50% { height: 65%; } 75% { height: 40%; } 100% { height: 25%; } }</style> Final solution: In this section, we will combine the above two sections into one section and achieve the liquid filling effect on text. Program: html <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <title> How to Create Liquid Filling Effect on Text using HTML and CSS ? </title> <style> body { margin: 0; padding: 0; } h1 { margin: 200px 0; padding: 0; font-size: 80px; position: relative; color:green; } h1:before { content: "GeeksforGeeks"; position: absolute; top: 0; left: 0; width: 100%; height: 100%; color:white; overflow: hidden; animation: animate 6s infinite; } @keyframes animate { 0% { height: 25%; } 25% { height: 50%; } 50% { height: 65%; } 75% { height: 40%; } 100% { height: 25%; } } </style></head> <body> <center> <h1>GeeksforGeeks</h1> </center></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. adnanirshad158 simranarora5sos CSS-Misc CSS-Selectors 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. How to apply style to parent if it has child with CSS? How to set space between the flexbox ? Design a web page using HTML and CSS Create a Responsive Navbar using ReactJS Form validation using jQuery How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26057, "s": 26029, "text": "\n28 Mar, 2022" }, { "code": null, "e": 26775, "s": 26057, "text": "The liquid fill text animation can be done using CSS | ::before selector. We will use key frames to set height for each frame of animation. Please make sure you know about both CSS | ::before selector and CSS | @keyframes Rule before try this code.The basic styling of the text can be done differently that totally depends on you how you want your text to look like. The main thing is with keyframes. For the first half percentages, we are increasing the height and for the next half, we are decreasing the height. We have used 25% as the minimum value for height. You can play around with the values of a percentage to change the minimum and maximum height and look and feel of the animation according to your needs." }, { "code": null, "e": 26934, "s": 26775, "text": "Creating structure: In this section, we will create the text where we will apply the liquid filling effect. To create structure normal HTML will be required. " }, { "code": null, "e": 26945, "s": 26934, "text": "HTML Code:" }, { "code": null, "e": 26950, "s": 26945, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Document</title></head><body> <center> <h1>GeeksforGeeks</h1> </center></body></html>", "e": 27208, "s": 26950, "text": null }, { "code": null, "e": 27415, "s": 27208, "text": "Design structure: Before starting the design you have to be familiar with the few concepts from CSS like CSS | ::before selector and CSS | @keyframes Rule. Other effects are totally depends on the designer." }, { "code": null, "e": 27425, "s": 27415, "text": "CSS Code:" }, { "code": null, "e": 27429, "s": 27425, "text": "CSS" }, { "code": "<style> body { margin: 0; padding: 0; } h1 { margin: 200px 0; padding: 0; font-size: 80px; position: relative; color:green; } h1:before { content: \"GeeksforGeeks\"; position: absolute; top: 0; left: 0; width: 100%; height: 100%; color:white; overflow: hidden; animation: animate 6s infinite; } @keyframes animate { 0% { height: 25%; } 25% { height: 50%; } 50% { height: 65%; } 75% { height: 40%; } 100% { height: 25%; } }</style>", "e": 28105, "s": 27429, "text": null }, { "code": null, "e": 28242, "s": 28105, "text": "Final solution: In this section, we will combine the above two sections into one section and achieve the liquid filling effect on text. " }, { "code": null, "e": 28251, "s": 28242, "text": "Program:" }, { "code": null, "e": 28256, "s": 28251, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <title> How to Create Liquid Filling Effect on Text using HTML and CSS ? </title> <style> body { margin: 0; padding: 0; } h1 { margin: 200px 0; padding: 0; font-size: 80px; position: relative; color:green; } h1:before { content: \"GeeksforGeeks\"; position: absolute; top: 0; left: 0; width: 100%; height: 100%; color:white; overflow: hidden; animation: animate 6s infinite; } @keyframes animate { 0% { height: 25%; } 25% { height: 50%; } 50% { height: 65%; } 75% { height: 40%; } 100% { height: 25%; } } </style></head> <body> <center> <h1>GeeksforGeeks</h1> </center></body> </html>", "e": 29456, "s": 28256, "text": null }, { "code": null, "e": 29464, "s": 29456, "text": "Output:" }, { "code": null, "e": 29601, "s": 29464, "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": 29616, "s": 29601, "text": "adnanirshad158" }, { "code": null, "e": 29632, "s": 29616, "text": "simranarora5sos" }, { "code": null, "e": 29641, "s": 29632, "text": "CSS-Misc" }, { "code": null, "e": 29655, "s": 29641, "text": "CSS-Selectors" }, { "code": null, "e": 29665, "s": 29655, "text": "HTML-Misc" }, { "code": null, "e": 29669, "s": 29665, "text": "CSS" }, { "code": null, "e": 29674, "s": 29669, "text": "HTML" }, { "code": null, "e": 29691, "s": 29674, "text": "Web Technologies" }, { "code": null, "e": 29718, "s": 29691, "text": "Web technologies Questions" }, { "code": null, "e": 29723, "s": 29718, "text": "HTML" }, { "code": null, "e": 29821, "s": 29723, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29876, "s": 29821, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 29915, "s": 29876, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 29952, "s": 29915, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29993, "s": 29952, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 30022, "s": 29993, "text": "Form validation using jQuery" }, { "code": null, "e": 30082, "s": 30022, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 30135, "s": 30082, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 30196, "s": 30135, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 30220, "s": 30196, "text": "REST API (Introduction)" } ]
Factorial of a number using JavaScript - GeeksforGeeks
11 Oct, 2019 Given a positive integer n and the task is to find the factorial of that number with the help of javaScript. Examples: Input : 4 Output : 24 Input : 5 Output : 120 Approach 1: Iterative Method In this approach, we are using a for loop to iterate over the sequence of numbers and get the factorial. Example: <!DOCTYPE HTML> <html> <head> <title> Factorial of a number using JavaScript </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> Click Here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var n = 5; up.innerHTML = "Click on the button to calculate" + " the factorial of n.<br>n = " + n; function Factorial(n) { var ans=1; for (var i = 2; i <= n; i++) ans = ans * i; return ans; } function GFG_Fun() { down.innerHTML = Factorial(n); } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Approach 2: Recursive Method: In this approach, we are calling the same function again and again to get the factorial of a number. Example: <!DOCTYPE HTML> <html> <head> <title> Factorial of a number using JavaScript </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> Click Here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var n = 10; up.innerHTML = "Click on the button to calculate" + " the factorial of n.<br>n = " + n; function Factorial(n) { if (n === 0) { return 1; } else { return n * Factorial( n - 1 ); } } function GFG_Fun() { down.innerHTML = Factorial(n); } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: 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 append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25759, "s": 25731, "text": "\n11 Oct, 2019" }, { "code": null, "e": 25868, "s": 25759, "text": "Given a positive integer n and the task is to find the factorial of that number with the help of javaScript." }, { "code": null, "e": 25878, "s": 25868, "text": "Examples:" }, { "code": null, "e": 25925, "s": 25878, "text": "Input : 4\nOutput : 24\n\nInput : 5\nOutput : 120\n" }, { "code": null, "e": 26059, "s": 25925, "text": "Approach 1: Iterative Method In this approach, we are using a for loop to iterate over the sequence of numbers and get the factorial." }, { "code": null, "e": 26068, "s": 26059, "text": "Example:" }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Factorial of a number using JavaScript </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> Click Here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var n = 5; up.innerHTML = \"Click on the button to calculate\" + \" the factorial of n.<br>n = \" + n; function Factorial(n) { var ans=1; for (var i = 2; i <= n; i++) ans = ans * i; return ans; } function GFG_Fun() { down.innerHTML = Factorial(n); } </script> </body> </html>", "e": 27122, "s": 26068, "text": null }, { "code": null, "e": 27130, "s": 27122, "text": "Output:" }, { "code": null, "e": 27161, "s": 27130, "text": "Before clicking on the button:" }, { "code": null, "e": 27191, "s": 27161, "text": "After clicking on the button:" }, { "code": null, "e": 27322, "s": 27191, "text": "Approach 2: Recursive Method: In this approach, we are calling the same function again and again to get the factorial of a number." }, { "code": null, "e": 27331, "s": 27322, "text": "Example:" }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Factorial of a number using JavaScript </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> Click Here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var n = 10; up.innerHTML = \"Click on the button to calculate\" + \" the factorial of n.<br>n = \" + n; function Factorial(n) { if (n === 0) { return 1; } else { return n * Factorial( n - 1 ); } } function GFG_Fun() { down.innerHTML = Factorial(n); } </script> </body> </html>", "e": 28403, "s": 27331, "text": null }, { "code": null, "e": 28411, "s": 28403, "text": "Output:" }, { "code": null, "e": 28442, "s": 28411, "text": "Before clicking on the button:" }, { "code": null, "e": 28472, "s": 28442, "text": "After clicking on the button:" }, { "code": null, "e": 28483, "s": 28472, "text": "JavaScript" }, { "code": null, "e": 28500, "s": 28483, "text": "Web Technologies" }, { "code": null, "e": 28527, "s": 28500, "text": "Web technologies Questions" }, { "code": null, "e": 28625, "s": 28527, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28665, "s": 28625, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28710, "s": 28665, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28771, "s": 28710, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28843, "s": 28771, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28895, "s": 28843, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 28935, "s": 28895, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28968, "s": 28935, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29013, "s": 28968, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29056, "s": 29013, "text": "How to fetch data from an API in ReactJS ?" } ]
Maximum Sum Increasing Subsequence | DP-14 - GeeksforGeeks
21 Feb, 2022 Given an array of n positive integers. Write a program to find the sum of maximum sum subsequence of the given array such that the integers in the subsequence are sorted in increasing order. For example, if input is {1, 101, 2, 3, 100, 4, 5}, then output should be 106 (1 + 2 + 3 + 100), if the input array is {3, 4, 5, 10}, then output should be 22 (3 + 4 + 5 + 10) and if the input array is {10, 5, 4, 3}, then output should be 10 Solution This problem is a variation of standard Longest Increasing Subsequence (LIS) problem. We need a slight change in the Dynamic Programming solution of LIS problem. All we need to change is to use sum as a criteria instead of length of increasing subsequence. Following are the Dynamic Programming solution to the problem : C++ C Java Python3 C# PHP Javascript /* Dynamic Programming implementation of Maximum Sum Increasing Subsequence (MSIS) problem */#include <bits/stdc++.h>using namespace std; /* maxSumIS() returns the maximum sum of increasing subsequence in arr[] of size n */int maxSumIS(int arr[], int n) { int i, j, max = 0; int msis[n]; /* Initialize msis values for all indexes */ for ( i = 0; i < n; i++ ) msis[i] = arr[i]; /* Compute maximum sum values in bottom up manner */ for ( i = 1; i < n; i++ ) for ( j = 0; j < i; j++ ) if (arr[i] > arr[j] && msis[i] < msis[j] + arr[i]) msis[i] = msis[j] + arr[i]; /* Pick maximum of all msis values */ for ( i = 0; i < n; i++ ) if ( max < msis[i] ) max = msis[i]; return max; } // Driver Code int main() { int arr[] = {1, 101, 2, 3, 100, 4, 5}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Sum of maximum sum increasing " "subsequence is " << maxSumIS( arr, n ) << endl; return 0; } // This is code is contributed by rathbhupendra /* Dynamic Programming implementation of Maximum Sum Increasing Subsequence (MSIS) problem */#include<stdio.h> /* maxSumIS() returns the maximum sum of increasing subsequence in arr[] of size n */int maxSumIS(int arr[], int n){ int i, j, max = 0; int msis[n]; /* Initialize msis values for all indexes */ for ( i = 0; i < n; i++ ) msis[i] = arr[i]; /* Compute maximum sum values in bottom up manner */ for ( i = 1; i < n; i++ ) for ( j = 0; j < i; j++ ) if (arr[i] > arr[j] && msis[i] < msis[j] + arr[i]) msis[i] = msis[j] + arr[i]; /* Pick maximum of all msis values */ for ( i = 0; i < n; i++ ) if ( max < msis[i] ) max = msis[i]; return max;} // Driver Codeint main(){ int arr[] = {1, 101, 2, 3, 100, 4, 5}; int n = sizeof(arr)/sizeof(arr[0]); printf("Sum of maximum sum increasing " "subsequence is %d\n", maxSumIS( arr, n ) ); return 0;} /* Dynamic Programming Java implementation of Maximum Sum Increasing Subsequence (MSIS) problem */class GFG{ /* maxSumIS() returns the maximum sum of increasing subsequence in arr[] of size n */ static int maxSumIS(int arr[], int n) { int i, j, max = 0; int msis[] = new int[n]; /* Initialize msis values for all indexes */ for (i = 0; i < n; i++) msis[i] = arr[i]; /* Compute maximum sum values in bottom up manner */ for (i = 1; i < n; i++) for (j = 0; j < i; j++) if (arr[i] > arr[j] && msis[i] < msis[j] + arr[i]) msis[i] = msis[j] + arr[i]; /* Pick maximum of all msis values */ for (i = 0; i < n; i++) if (max < msis[i]) max = msis[i]; return max; } // Driver code public static void main(String args[]) { int arr[] = new int[]{1, 101, 2, 3, 100, 4, 5}; int n = arr.length; System.out.println("Sum of maximum sum "+ "increasing subsequence is "+ maxSumIS(arr, n)); }} // This code is contributed // by Rajat Mishra # Dynamic Programming based Python # implementation of Maximum Sum # Increasing Subsequence (MSIS)# problem # maxSumIS() returns the maximum # sum of increasing subsequence # in arr[] of size ndef maxSumIS(arr, n): max = 0 msis = [0 for x in range(n)] # Initialize msis values # for all indexes for i in range(n): msis[i] = arr[i] # Compute maximum sum # values in bottom up manner for i in range(1, n): for j in range(i): if (arr[i] > arr[j] and msis[i] < msis[j] + arr[i]): msis[i] = msis[j] + arr[i] # Pick maximum of # all msis values for i in range(n): if max < msis[i]: max = msis[i] return max # Driver Codearr = [1, 101, 2, 3, 100, 4, 5]n = len(arr)print("Sum of maximum sum increasing " + "subsequence is " + str(maxSumIS(arr, n))) # This code is contributed # by Bhavya Jain // Dynamic Programming C# implementation// of Maximum Sum Increasing Subsequence// (MSIS) problem using System;class GFG { // maxSumIS() returns the // maximum sum of increasing // subsequence in arr[] of size n static int maxSumIS( int []arr, int n ) { int i, j, max = 0; int []msis = new int[n]; /* Initialize msis values for all indexes */ for ( i = 0; i < n; i++ ) msis[i] = arr[i]; /* Compute maximum sum values in bottom up manner */ for ( i = 1; i < n; i++ ) for ( j = 0; j < i; j++ ) if ( arr[i] > arr[j] && msis[i] < msis[j] + arr[i]) msis[i] = msis[j] + arr[i]; /* Pick maximum of all msis values */ for ( i = 0; i < n; i++ ) if ( max < msis[i] ) max = msis[i]; return max; } // Driver Code public static void Main() { int []arr = new int[]{1, 101, 2, 3, 100, 4, 5}; int n = arr.Length; Console.WriteLine("Sum of maximum sum increasing "+ " subsequence is "+ maxSumIS(arr, n)); }} // This code is contributed by Sam007 <?php// Dynamic Programming implementation// of Maximum Sum Increasing// Subsequence (MSIS) problem // maxSumIS() returns the maximum // sum of increasing subsequence// in arr[] of size n function maxSumIS($arr, $n){ $max = 0; $msis= array($n); // Initialize msis values // for all indexes for($i = 0; $i < $n; $i++ ) $msis[$i] = $arr[$i]; // Compute maximum sum values // in bottom up manner for($i = 1; $i < $n; $i++) for($j = 0; $j < $i; $j++) if ($arr[$i] > $arr[$j] && $msis[$i] < $msis[$j] + $arr[$i]) $msis[$i] = $msis[$j] + $arr[$i]; // Pick maximum of all msis values for($i = 0;$i < $n; $i++ ) if ($max < $msis[$i] ) $max = $msis[$i]; return $max;} // Driver Code $arr = array(1, 101, 2, 3, 100, 4, 5); $n = count($arr); echo "Sum of maximum sum increasing subsequence is " .maxSumIS( $arr, $n ); // This code is contributed by Sam007?> <script> // Dynamic Programming implementation // of Maximum Sum Increasing Subsequence // (MSIS) problem // maxSumIS() returns the maximum // sum of increasing subsequence // in arr[] of size n function maxSumIS(arr, n) { let i, j, max = 0; let msis = new Array(n); // Initialize msis values // for all indexes for(i = 0; i < n; i++) msis[i] = arr[i]; // Compute maximum sum values // in bottom up manner for(i = 1; i < n; i++) for(j = 0; j < i; j++) if (arr[i] > arr[j] && msis[i] < msis[j] + arr[i]) msis[i] = msis[j] + arr[i]; // Pick maximum of // all msis values for(i = 0; i < n; i++) if (max < msis[i]) max = msis[i]; return max; } // Driver Code let arr = [ 1, 101, 2, 3, 100, 4, 5 ]; let n = arr.length; document.write("Sum of maximum sum increasing " + "subsequence is " + maxSumIS(arr, n)); // This code is contributed by rishavmahato348 </script> Output : Sum of maximum sum increasing subsequence is 106 Time Complexity: O(n^2) Space Complexity O(n) YouTubeGeeksforGeeks507K subscribersMaximum Sum Increasing Subsequence | Dynamic Programming | Set 14 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:59•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=0NPYcQQWJ3Q" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sam007 ParulShandilya NikhilKumar23 rathbhupendra rishavmahato348 saimayank2001 amartyaghoshgfg simmytarika5 Amazon LIS Morgan Stanley Arrays Dynamic Programming Morgan Stanley Amazon Arrays Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Linear Search 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 26581, "s": 26553, "text": "\n21 Feb, 2022" }, { "code": null, "e": 27014, "s": 26581, "text": "Given an array of n positive integers. Write a program to find the sum of maximum sum subsequence of the given array such that the integers in the subsequence are sorted in increasing order. For example, if input is {1, 101, 2, 3, 100, 4, 5}, then output should be 106 (1 + 2 + 3 + 100), if the input array is {3, 4, 5, 10}, then output should be 22 (3 + 4 + 5 + 10) and if the input array is {10, 5, 4, 3}, then output should be 10" }, { "code": null, "e": 27282, "s": 27014, "text": " Solution This problem is a variation of standard Longest Increasing Subsequence (LIS) problem. We need a slight change in the Dynamic Programming solution of LIS problem. All we need to change is to use sum as a criteria instead of length of increasing subsequence." }, { "code": null, "e": 27348, "s": 27282, "text": "Following are the Dynamic Programming solution to the problem : " }, { "code": null, "e": 27352, "s": 27348, "text": "C++" }, { "code": null, "e": 27354, "s": 27352, "text": "C" }, { "code": null, "e": 27359, "s": 27354, "text": "Java" }, { "code": null, "e": 27367, "s": 27359, "text": "Python3" }, { "code": null, "e": 27370, "s": 27367, "text": "C#" }, { "code": null, "e": 27374, "s": 27370, "text": "PHP" }, { "code": null, "e": 27385, "s": 27374, "text": "Javascript" }, { "code": "/* Dynamic Programming implementation of Maximum Sum Increasing Subsequence (MSIS) problem */#include <bits/stdc++.h>using namespace std; /* maxSumIS() returns the maximum sum of increasing subsequence in arr[] of size n */int maxSumIS(int arr[], int n) { int i, j, max = 0; int msis[n]; /* Initialize msis values for all indexes */ for ( i = 0; i < n; i++ ) msis[i] = arr[i]; /* Compute maximum sum values in bottom up manner */ for ( i = 1; i < n; i++ ) for ( j = 0; j < i; j++ ) if (arr[i] > arr[j] && msis[i] < msis[j] + arr[i]) msis[i] = msis[j] + arr[i]; /* Pick maximum of all msis values */ for ( i = 0; i < n; i++ ) if ( max < msis[i] ) max = msis[i]; return max; } // Driver Code int main() { int arr[] = {1, 101, 2, 3, 100, 4, 5}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Sum of maximum sum increasing \" \"subsequence is \" << maxSumIS( arr, n ) << endl; return 0; } // This is code is contributed by rathbhupendra", "e": 28478, "s": 27385, "text": null }, { "code": "/* Dynamic Programming implementation of Maximum Sum Increasing Subsequence (MSIS) problem */#include<stdio.h> /* maxSumIS() returns the maximum sum of increasing subsequence in arr[] of size n */int maxSumIS(int arr[], int n){ int i, j, max = 0; int msis[n]; /* Initialize msis values for all indexes */ for ( i = 0; i < n; i++ ) msis[i] = arr[i]; /* Compute maximum sum values in bottom up manner */ for ( i = 1; i < n; i++ ) for ( j = 0; j < i; j++ ) if (arr[i] > arr[j] && msis[i] < msis[j] + arr[i]) msis[i] = msis[j] + arr[i]; /* Pick maximum of all msis values */ for ( i = 0; i < n; i++ ) if ( max < msis[i] ) max = msis[i]; return max;} // Driver Codeint main(){ int arr[] = {1, 101, 2, 3, 100, 4, 5}; int n = sizeof(arr)/sizeof(arr[0]); printf(\"Sum of maximum sum increasing \" \"subsequence is %d\\n\", maxSumIS( arr, n ) ); return 0;}", "e": 29493, "s": 28478, "text": null }, { "code": "/* Dynamic Programming Java implementation of Maximum Sum Increasing Subsequence (MSIS) problem */class GFG{ /* maxSumIS() returns the maximum sum of increasing subsequence in arr[] of size n */ static int maxSumIS(int arr[], int n) { int i, j, max = 0; int msis[] = new int[n]; /* Initialize msis values for all indexes */ for (i = 0; i < n; i++) msis[i] = arr[i]; /* Compute maximum sum values in bottom up manner */ for (i = 1; i < n; i++) for (j = 0; j < i; j++) if (arr[i] > arr[j] && msis[i] < msis[j] + arr[i]) msis[i] = msis[j] + arr[i]; /* Pick maximum of all msis values */ for (i = 0; i < n; i++) if (max < msis[i]) max = msis[i]; return max; } // Driver code public static void main(String args[]) { int arr[] = new int[]{1, 101, 2, 3, 100, 4, 5}; int n = arr.length; System.out.println(\"Sum of maximum sum \"+ \"increasing subsequence is \"+ maxSumIS(arr, n)); }} // This code is contributed // by Rajat Mishra ", "e": 30736, "s": 29493, "text": null }, { "code": "# Dynamic Programming based Python # implementation of Maximum Sum # Increasing Subsequence (MSIS)# problem # maxSumIS() returns the maximum # sum of increasing subsequence # in arr[] of size ndef maxSumIS(arr, n): max = 0 msis = [0 for x in range(n)] # Initialize msis values # for all indexes for i in range(n): msis[i] = arr[i] # Compute maximum sum # values in bottom up manner for i in range(1, n): for j in range(i): if (arr[i] > arr[j] and msis[i] < msis[j] + arr[i]): msis[i] = msis[j] + arr[i] # Pick maximum of # all msis values for i in range(n): if max < msis[i]: max = msis[i] return max # Driver Codearr = [1, 101, 2, 3, 100, 4, 5]n = len(arr)print(\"Sum of maximum sum increasing \" + \"subsequence is \" + str(maxSumIS(arr, n))) # This code is contributed # by Bhavya Jain", "e": 31680, "s": 30736, "text": null }, { "code": "// Dynamic Programming C# implementation// of Maximum Sum Increasing Subsequence// (MSIS) problem using System;class GFG { // maxSumIS() returns the // maximum sum of increasing // subsequence in arr[] of size n static int maxSumIS( int []arr, int n ) { int i, j, max = 0; int []msis = new int[n]; /* Initialize msis values for all indexes */ for ( i = 0; i < n; i++ ) msis[i] = arr[i]; /* Compute maximum sum values in bottom up manner */ for ( i = 1; i < n; i++ ) for ( j = 0; j < i; j++ ) if ( arr[i] > arr[j] && msis[i] < msis[j] + arr[i]) msis[i] = msis[j] + arr[i]; /* Pick maximum of all msis values */ for ( i = 0; i < n; i++ ) if ( max < msis[i] ) max = msis[i]; return max; } // Driver Code public static void Main() { int []arr = new int[]{1, 101, 2, 3, 100, 4, 5}; int n = arr.Length; Console.WriteLine(\"Sum of maximum sum increasing \"+ \" subsequence is \"+ maxSumIS(arr, n)); }} // This code is contributed by Sam007", "e": 32924, "s": 31680, "text": null }, { "code": "<?php// Dynamic Programming implementation// of Maximum Sum Increasing// Subsequence (MSIS) problem // maxSumIS() returns the maximum // sum of increasing subsequence// in arr[] of size n function maxSumIS($arr, $n){ $max = 0; $msis= array($n); // Initialize msis values // for all indexes for($i = 0; $i < $n; $i++ ) $msis[$i] = $arr[$i]; // Compute maximum sum values // in bottom up manner for($i = 1; $i < $n; $i++) for($j = 0; $j < $i; $j++) if ($arr[$i] > $arr[$j] && $msis[$i] < $msis[$j] + $arr[$i]) $msis[$i] = $msis[$j] + $arr[$i]; // Pick maximum of all msis values for($i = 0;$i < $n; $i++ ) if ($max < $msis[$i] ) $max = $msis[$i]; return $max;} // Driver Code $arr = array(1, 101, 2, 3, 100, 4, 5); $n = count($arr); echo \"Sum of maximum sum increasing subsequence is \" .maxSumIS( $arr, $n ); // This code is contributed by Sam007?>", "e": 33948, "s": 32924, "text": null }, { "code": "<script> // Dynamic Programming implementation // of Maximum Sum Increasing Subsequence // (MSIS) problem // maxSumIS() returns the maximum // sum of increasing subsequence // in arr[] of size n function maxSumIS(arr, n) { let i, j, max = 0; let msis = new Array(n); // Initialize msis values // for all indexes for(i = 0; i < n; i++) msis[i] = arr[i]; // Compute maximum sum values // in bottom up manner for(i = 1; i < n; i++) for(j = 0; j < i; j++) if (arr[i] > arr[j] && msis[i] < msis[j] + arr[i]) msis[i] = msis[j] + arr[i]; // Pick maximum of // all msis values for(i = 0; i < n; i++) if (max < msis[i]) max = msis[i]; return max; } // Driver Code let arr = [ 1, 101, 2, 3, 100, 4, 5 ]; let n = arr.length; document.write(\"Sum of maximum sum increasing \" + \"subsequence is \" + maxSumIS(arr, n)); // This code is contributed by rishavmahato348 </script>", "e": 34982, "s": 33948, "text": null }, { "code": null, "e": 34992, "s": 34982, "text": "Output : " }, { "code": null, "e": 35041, "s": 34992, "text": "Sum of maximum sum increasing subsequence is 106" }, { "code": null, "e": 35066, "s": 35041, "text": "Time Complexity: O(n^2) " }, { "code": null, "e": 35089, "s": 35066, "text": "Space Complexity O(n) " }, { "code": null, "e": 35953, "s": 35089, "text": "YouTubeGeeksforGeeks507K subscribersMaximum Sum Increasing Subsequence | Dynamic Programming | Set 14 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:59•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=0NPYcQQWJ3Q\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 36079, "s": 35953, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 36086, "s": 36079, "text": "Sam007" }, { "code": null, "e": 36101, "s": 36086, "text": "ParulShandilya" }, { "code": null, "e": 36115, "s": 36101, "text": "NikhilKumar23" }, { "code": null, "e": 36129, "s": 36115, "text": "rathbhupendra" }, { "code": null, "e": 36145, "s": 36129, "text": "rishavmahato348" }, { "code": null, "e": 36159, "s": 36145, "text": "saimayank2001" }, { "code": null, "e": 36175, "s": 36159, "text": "amartyaghoshgfg" }, { "code": null, "e": 36188, "s": 36175, "text": "simmytarika5" }, { "code": null, "e": 36195, "s": 36188, "text": "Amazon" }, { "code": null, "e": 36199, "s": 36195, "text": "LIS" }, { "code": null, "e": 36214, "s": 36199, "text": "Morgan Stanley" }, { "code": null, "e": 36221, "s": 36214, "text": "Arrays" }, { "code": null, "e": 36241, "s": 36221, "text": "Dynamic Programming" }, { "code": null, "e": 36256, "s": 36241, "text": "Morgan Stanley" }, { "code": null, "e": 36263, "s": 36256, "text": "Amazon" }, { "code": null, "e": 36270, "s": 36263, "text": "Arrays" }, { "code": null, "e": 36290, "s": 36270, "text": "Dynamic Programming" }, { "code": null, "e": 36388, "s": 36290, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36432, "s": 36388, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 36480, "s": 36432, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 36503, "s": 36480, "text": "Introduction to Arrays" }, { "code": null, "e": 36535, "s": 36503, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 36549, "s": 36535, "text": "Linear Search" }, { "code": null, "e": 36578, "s": 36549, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 36608, "s": 36578, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 36642, "s": 36608, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 36673, "s": 36642, "text": "Bellman–Ford Algorithm | DP-23" } ]
Number of flips to make binary string alternate | Set 1 - GeeksforGeeks
11 Aug, 2021 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. Examples : Input : str = “001” Output : 1 Minimum number of flips required = 1 We can flip 1st bit from 0 to 1 Input : str = “0001010111” Output : 2 Minimum number of flips required = 2 We can flip 2nd bit from 0 to 1 and 9th bit from 1 to 0 to make alternate string “0101010101”. Expected time complexity : O(n) where n is length of input string. We can solve this problem by considering all possible results, As we are supposed to get alternate string, there are only 2 possibilities, alternate string starting with 0 and alternate string starting with 1. We will try both cases and choose the string which will require minimum number of flips as our final answer. Trying a case requires O(n) time in which we will loop over all characters of given string, if current character is expected character according to alternation then we will do nothing otherwise we will increase flip count by 1. After trying strings starting with 0 and starting with 1, we will choose the string with minimum flip count. Total time complexity of solution will be O(n) C++ Java Python 3 C# PHP Javascript // C/C++ program to find minimum number of// flip to make binary string alternate#include <bits/stdc++.h>using namespace std; // Utility method to flip a characterchar flip(char ch){ return (ch == '0') ? '1' : '0';} // Utility method to get minimum flips when// alternate string starts with expected charint getFlipWithStartingCharcter(string str, char expected){ int flipCount = 0; for (int i = 0; i < str.length(); i++) { // if current character is not expected, // increase flip count if (str[i] != expected) flipCount++; // flip expected character each time expected = flip(expected); } return flipCount;} // method return minimum flip to make binary// string alternateint minFlipToMakeStringAlternate(string str){ // return minimum of following two // 1) flips when alternate string starts with 0 // 2) flips when alternate string starts with 1 return min(getFlipWithStartingCharcter(str, '0'), getFlipWithStartingCharcter(str, '1'));} // Driver code to test above methodint main(){ string str = "0001010111"; cout << minFlipToMakeStringAlternate(str); return 0;} // Java program to find minimum number of// flip to make binary string alternateclass GFG{ // Utility method to flip a character public static char flip(char ch) { return (ch == '0') ? '1' : '0'; } // Utility method to get minimum flips when // alternate string starts with expected char public static int getFlipWithStartingCharcter(String str, char expected) { int flipCount = 0; for (int i = 0; i < str.length(); i++) { // if current character is not expected, // increase flip count if (str.charAt(i) != expected) flipCount++; // flip expected character each time expected = flip(expected); } return flipCount; } // method return minimum flip to make binary // string alternate public static int minFlipToMakeStringAlternate(String str) { // return minimum of following two // 1) flips when alternate string starts with 0 // 2) flips when alternate string starts with 1 return Math.min(getFlipWithStartingCharcter(str, '0'), getFlipWithStartingCharcter(str, '1')); } // Driver code to test above method public static void main(String args[]) { String str = "0001010111"; System.out.println(minFlipToMakeStringAlternate(str)); }} // This code is contributed by Sumit Ghosh # Python 3 program to find minimum number of# flip to make binary string alternate # Utility method to flip a characterdef flip( ch): return '1' if (ch == '0') else '0' # Utility method to get minimum flips when# alternate string starts with expected chardef getFlipWithStartingCharcter(str, expected): flipCount = 0 for i in range(len( str)): # if current character is not expected, # increase flip count if (str[i] != expected): flipCount += 1 # flip expected character each time expected = flip(expected) return flipCount # method return minimum flip to make binary# string alternatedef minFlipToMakeStringAlternate(str): # return minimum of following two # 1) flips when alternate string starts with 0 # 2) flips when alternate string starts with 1 return min(getFlipWithStartingCharcter(str, '0'), getFlipWithStartingCharcter(str, '1')) # Driver code to test above methodif __name__ == "__main__": str = "0001010111" print(minFlipToMakeStringAlternate(str)) // C# program to find minimum number of// flip to make binary string alternateusing System; class GFG{ // Utility method to // flip a character public static char flip(char ch) { return (ch == '0') ? '1' : '0'; } // Utility method to get minimum flips // when alternate string starts with // expected char public static int getFlipWithStartingCharcter(String str, char expected) { int flipCount = 0; for (int i = 0; i < str.Length; i++) { // if current character is not // expected, increase flip count if (str[i] != expected) flipCount++; // flip expected character each time expected = flip(expected); } return flipCount; } // method return minimum flip to // make binary string alternate public static int minFlipToMakeStringAlternate(string str) { // return minimum of following two // 1) flips when alternate string starts with 0 // 2) flips when alternate string starts with 1 return Math.Min(getFlipWithStartingCharcter(str, '0'), getFlipWithStartingCharcter(str, '1')); } // Driver Code public static void Main() { string str = "0001010111"; Console.Write(minFlipToMakeStringAlternate(str)); }} // This code is contributed by nitin mittal. <?php// PHP program to find minimum number of// flip to make binary string alternate // Utility method to flip a characterfunction flip( $ch){ return ($ch == '0') ? '1' : '0';} // Utility method to get minimum flips when// alternate string starts with expected charfunction getFlipWithStartingCharcter($str, $expected){ $flipCount = 0; for ($i = 0; $i < strlen($str); $i++) { // if current character is not expected, // increase flip count if ($str[$i] != $expected) $flipCount++; // flip expected character each time $expected = flip($expected); } return $flipCount;} // method return minimum flip to make binary// string alternatefunction minFlipToMakeStringAlternate( $str){ // return minimum of following two // 1) flips when alternate string starts with 0 // 2) flips when alternate string starts with 1 return min(getFlipWithStartingCharcter($str, '0'), getFlipWithStartingCharcter($str, '1'));} // Driver code to test above method$str = "0001010111";echo minFlipToMakeStringAlternate($str); // This code is contributed by anuj_67.?> <script> // Javascript program to find minimum number of// flip to make binary string alternate // Utility method to flip a character function flip(ch) { return (ch == '0') ? '1' : '0'; } // Utility method to get minimum flips when // alternate string starts with expected char function getFlipWithStartingCharcter(str,expected) { let flipCount = 0; for (let i = 0; i < str.length; i++) { // if current character is not expected, // increase flip count if (str.charAt(i) != expected) flipCount++; // flip expected character each time expected = flip(expected); } return flipCount; } // method return minimum flip to make binary // string alternate function minFlipToMakeStringAlternate(str) { // return minimum of following two // 1) flips when alternate string starts with 0 // 2) flips when alternate string starts with 1 return Math.min(getFlipWithStartingCharcter(str, '0'), getFlipWithStartingCharcter(str, '1')); } // Driver code to test above method let str = "0001010111"; document.write(minFlipToMakeStringAlternate(str)); // This code is contributed by avanitrachhadiya2155 </script> Output : 2 Time Complexity: O(N)Auxiliary Space: O(1) Minimum number of replacements to make the binary string alternating | Set 2 YouTubeGeeksforGeeks507K subscribersNumber of flips to make binary string alternate | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:00•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=3jxxC7959jY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal vt_m ukasp BhawanaGupta3 avanitrachhadiya2155 simmytarika5 pankajsharmagfg binary-string Algorithms Strings Strings Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar How to write a Pseudo Code? Understanding Time Complexity with Simple Examples How to Start Learning DSA? Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4
[ { "code": null, "e": 26239, "s": 26211, "text": "\n11 Aug, 2021" }, { "code": null, "e": 26462, "s": 26239, "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. Examples : " }, { "code": null, "e": 26736, "s": 26462, "text": "Input : str = “001”\nOutput : 1\nMinimum number of flips required = 1\nWe can flip 1st bit from 0 to 1 \n\nInput : str = “0001010111”\nOutput : 2\nMinimum number of flips required = 2\nWe can flip 2nd bit from 0 to 1 and 9th \nbit from 1 to 0 to make alternate \nstring “0101010101”." }, { "code": null, "e": 26804, "s": 26736, "text": "Expected time complexity : O(n) where n is length of input string. " }, { "code": null, "e": 27509, "s": 26804, "text": "We can solve this problem by considering all possible results, As we are supposed to get alternate string, there are only 2 possibilities, alternate string starting with 0 and alternate string starting with 1. We will try both cases and choose the string which will require minimum number of flips as our final answer. Trying a case requires O(n) time in which we will loop over all characters of given string, if current character is expected character according to alternation then we will do nothing otherwise we will increase flip count by 1. After trying strings starting with 0 and starting with 1, we will choose the string with minimum flip count. Total time complexity of solution will be O(n) " }, { "code": null, "e": 27513, "s": 27509, "text": "C++" }, { "code": null, "e": 27518, "s": 27513, "text": "Java" }, { "code": null, "e": 27527, "s": 27518, "text": "Python 3" }, { "code": null, "e": 27530, "s": 27527, "text": "C#" }, { "code": null, "e": 27534, "s": 27530, "text": "PHP" }, { "code": null, "e": 27545, "s": 27534, "text": "Javascript" }, { "code": "// C/C++ program to find minimum number of// flip to make binary string alternate#include <bits/stdc++.h>using namespace std; // Utility method to flip a characterchar flip(char ch){ return (ch == '0') ? '1' : '0';} // Utility method to get minimum flips when// alternate string starts with expected charint getFlipWithStartingCharcter(string str, char expected){ int flipCount = 0; for (int i = 0; i < str.length(); i++) { // if current character is not expected, // increase flip count if (str[i] != expected) flipCount++; // flip expected character each time expected = flip(expected); } return flipCount;} // method return minimum flip to make binary// string alternateint minFlipToMakeStringAlternate(string str){ // return minimum of following two // 1) flips when alternate string starts with 0 // 2) flips when alternate string starts with 1 return min(getFlipWithStartingCharcter(str, '0'), getFlipWithStartingCharcter(str, '1'));} // Driver code to test above methodint main(){ string str = \"0001010111\"; cout << minFlipToMakeStringAlternate(str); return 0;}", "e": 28754, "s": 27545, "text": null }, { "code": "// Java program to find minimum number of// flip to make binary string alternateclass GFG{ // Utility method to flip a character public static char flip(char ch) { return (ch == '0') ? '1' : '0'; } // Utility method to get minimum flips when // alternate string starts with expected char public static int getFlipWithStartingCharcter(String str, char expected) { int flipCount = 0; for (int i = 0; i < str.length(); i++) { // if current character is not expected, // increase flip count if (str.charAt(i) != expected) flipCount++; // flip expected character each time expected = flip(expected); } return flipCount; } // method return minimum flip to make binary // string alternate public static int minFlipToMakeStringAlternate(String str) { // return minimum of following two // 1) flips when alternate string starts with 0 // 2) flips when alternate string starts with 1 return Math.min(getFlipWithStartingCharcter(str, '0'), getFlipWithStartingCharcter(str, '1')); } // Driver code to test above method public static void main(String args[]) { String str = \"0001010111\"; System.out.println(minFlipToMakeStringAlternate(str)); }} // This code is contributed by Sumit Ghosh", "e": 30224, "s": 28754, "text": null }, { "code": "# Python 3 program to find minimum number of# flip to make binary string alternate # Utility method to flip a characterdef flip( ch): return '1' if (ch == '0') else '0' # Utility method to get minimum flips when# alternate string starts with expected chardef getFlipWithStartingCharcter(str, expected): flipCount = 0 for i in range(len( str)): # if current character is not expected, # increase flip count if (str[i] != expected): flipCount += 1 # flip expected character each time expected = flip(expected) return flipCount # method return minimum flip to make binary# string alternatedef minFlipToMakeStringAlternate(str): # return minimum of following two # 1) flips when alternate string starts with 0 # 2) flips when alternate string starts with 1 return min(getFlipWithStartingCharcter(str, '0'), getFlipWithStartingCharcter(str, '1')) # Driver code to test above methodif __name__ == \"__main__\": str = \"0001010111\" print(minFlipToMakeStringAlternate(str))", "e": 31291, "s": 30224, "text": null }, { "code": "// C# program to find minimum number of// flip to make binary string alternateusing System; class GFG{ // Utility method to // flip a character public static char flip(char ch) { return (ch == '0') ? '1' : '0'; } // Utility method to get minimum flips // when alternate string starts with // expected char public static int getFlipWithStartingCharcter(String str, char expected) { int flipCount = 0; for (int i = 0; i < str.Length; i++) { // if current character is not // expected, increase flip count if (str[i] != expected) flipCount++; // flip expected character each time expected = flip(expected); } return flipCount; } // method return minimum flip to // make binary string alternate public static int minFlipToMakeStringAlternate(string str) { // return minimum of following two // 1) flips when alternate string starts with 0 // 2) flips when alternate string starts with 1 return Math.Min(getFlipWithStartingCharcter(str, '0'), getFlipWithStartingCharcter(str, '1')); } // Driver Code public static void Main() { string str = \"0001010111\"; Console.Write(minFlipToMakeStringAlternate(str)); }} // This code is contributed by nitin mittal.", "e": 32735, "s": 31291, "text": null }, { "code": "<?php// PHP program to find minimum number of// flip to make binary string alternate // Utility method to flip a characterfunction flip( $ch){ return ($ch == '0') ? '1' : '0';} // Utility method to get minimum flips when// alternate string starts with expected charfunction getFlipWithStartingCharcter($str, $expected){ $flipCount = 0; for ($i = 0; $i < strlen($str); $i++) { // if current character is not expected, // increase flip count if ($str[$i] != $expected) $flipCount++; // flip expected character each time $expected = flip($expected); } return $flipCount;} // method return minimum flip to make binary// string alternatefunction minFlipToMakeStringAlternate( $str){ // return minimum of following two // 1) flips when alternate string starts with 0 // 2) flips when alternate string starts with 1 return min(getFlipWithStartingCharcter($str, '0'), getFlipWithStartingCharcter($str, '1'));} // Driver code to test above method$str = \"0001010111\";echo minFlipToMakeStringAlternate($str); // This code is contributed by anuj_67.?>", "e": 33916, "s": 32735, "text": null }, { "code": "<script> // Javascript program to find minimum number of// flip to make binary string alternate // Utility method to flip a character function flip(ch) { return (ch == '0') ? '1' : '0'; } // Utility method to get minimum flips when // alternate string starts with expected char function getFlipWithStartingCharcter(str,expected) { let flipCount = 0; for (let i = 0; i < str.length; i++) { // if current character is not expected, // increase flip count if (str.charAt(i) != expected) flipCount++; // flip expected character each time expected = flip(expected); } return flipCount; } // method return minimum flip to make binary // string alternate function minFlipToMakeStringAlternate(str) { // return minimum of following two // 1) flips when alternate string starts with 0 // 2) flips when alternate string starts with 1 return Math.min(getFlipWithStartingCharcter(str, '0'), getFlipWithStartingCharcter(str, '1')); } // Driver code to test above method let str = \"0001010111\"; document.write(minFlipToMakeStringAlternate(str)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 35269, "s": 33916, "text": null }, { "code": null, "e": 35279, "s": 35269, "text": "Output : " }, { "code": null, "e": 35281, "s": 35279, "text": "2" }, { "code": null, "e": 35403, "s": 35281, "text": "Time Complexity: O(N)Auxiliary Space: O(1) Minimum number of replacements to make the binary string alternating | Set 2 " }, { "code": null, "e": 36249, "s": 35403, "text": "YouTubeGeeksforGeeks507K subscribersNumber of flips to make binary string alternate | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:00•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=3jxxC7959jY\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 36673, "s": 36249, "text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 36686, "s": 36673, "text": "nitin mittal" }, { "code": null, "e": 36691, "s": 36686, "text": "vt_m" }, { "code": null, "e": 36697, "s": 36691, "text": "ukasp" }, { "code": null, "e": 36711, "s": 36697, "text": "BhawanaGupta3" }, { "code": null, "e": 36732, "s": 36711, "text": "avanitrachhadiya2155" }, { "code": null, "e": 36745, "s": 36732, "text": "simmytarika5" }, { "code": null, "e": 36761, "s": 36745, "text": "pankajsharmagfg" }, { "code": null, "e": 36775, "s": 36761, "text": "binary-string" }, { "code": null, "e": 36786, "s": 36775, "text": "Algorithms" }, { "code": null, "e": 36794, "s": 36786, "text": "Strings" }, { "code": null, "e": 36802, "s": 36794, "text": "Strings" }, { "code": null, "e": 36813, "s": 36802, "text": "Algorithms" }, { "code": null, "e": 36911, "s": 36813, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36960, "s": 36911, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 36985, "s": 36960, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 37013, "s": 36985, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 37064, "s": 37013, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 37091, "s": 37064, "text": "How to Start Learning DSA?" }, { "code": null, "e": 37137, "s": 37091, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 37162, "s": 37137, "text": "Reverse a string in Java" }, { "code": null, "e": 37222, "s": 37162, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 37237, "s": 37222, "text": "C++ Data Types" } ]
Python | Multiply Dictionary Value by Constant - GeeksforGeeks
29 Dec, 2019 Sometimes, while working with dictionaries, we can have a use-case in which we require to multiply a particular key’s value by K in dictionary. It may seem a quite straight forward problem, but catch comes when the existence of a key is not known, hence becomes a 2 step process at times. Let’s discuss certain ways in which this task can be performed. Method #1 : Using get()The get function can be used to initialize a non-existing key with 1 and then the product is possible. By this way the problem of non-existing key can be avoided. # Python3 code to demonstrate working of# Multiply Dictionary Value by Constant# Using get() # Initialize dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'for' : 4, 'CS' : 5} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # Initialize K K = 5 # Using get()# Multiply Dictionary Value by Constanttest_dict['best'] = test_dict.get('best', 1) * K # printing result print("Dictionary after the multiplication of key : " + str(test_dict)) The original dictionary : {'for': 4, 'is': 2, 'CS': 5, 'gfg': 1} Dictionary after the multiplication of key : {'for': 4, 'is': 2, 'CS': 5, 'best': 5, 'gfg': 1} Method #2 : Using defaultdict()This problem can also be solved by using a defaultdict method, which initializes the potential keys and doesn’t throw an exception in case of non-existence of keys. # Python3 code to demonstrate working of# Multiply Dictionary Value by Constant# Using defaultdict()from collections import defaultdict # Initialize dictionarytest_dict = defaultdict(int) # printing original dictionaryprint("The original dictionary : " + str(dict(test_dict))) # Initialize K K = 5 # Using defaultdict()# Multiply Dictionary Value by Constanttest_dict['best'] *= K # printing result print("Dictionary after the multiplication of key : " + str(dict(test_dict))) The original dictionary : {} Dictionary after the multiplication of key : {'best': 0} Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python 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": 25739, "s": 25711, "text": "\n29 Dec, 2019" }, { "code": null, "e": 26092, "s": 25739, "text": "Sometimes, while working with dictionaries, we can have a use-case in which we require to multiply a particular key’s value by K in dictionary. It may seem a quite straight forward problem, but catch comes when the existence of a key is not known, hence becomes a 2 step process at times. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 26278, "s": 26092, "text": "Method #1 : Using get()The get function can be used to initialize a non-existing key with 1 and then the product is possible. By this way the problem of non-existing key can be avoided." }, { "code": "# Python3 code to demonstrate working of# Multiply Dictionary Value by Constant# Using get() # Initialize dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'for' : 4, 'CS' : 5} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # Initialize K K = 5 # Using get()# Multiply Dictionary Value by Constanttest_dict['best'] = test_dict.get('best', 1) * K # printing result print(\"Dictionary after the multiplication of key : \" + str(test_dict))", "e": 26753, "s": 26278, "text": null }, { "code": null, "e": 26914, "s": 26753, "text": "The original dictionary : {'for': 4, 'is': 2, 'CS': 5, 'gfg': 1}\nDictionary after the multiplication of key : {'for': 4, 'is': 2, 'CS': 5, 'best': 5, 'gfg': 1}\n" }, { "code": null, "e": 27112, "s": 26916, "text": "Method #2 : Using defaultdict()This problem can also be solved by using a defaultdict method, which initializes the potential keys and doesn’t throw an exception in case of non-existence of keys." }, { "code": "# Python3 code to demonstrate working of# Multiply Dictionary Value by Constant# Using defaultdict()from collections import defaultdict # Initialize dictionarytest_dict = defaultdict(int) # printing original dictionaryprint(\"The original dictionary : \" + str(dict(test_dict))) # Initialize K K = 5 # Using defaultdict()# Multiply Dictionary Value by Constanttest_dict['best'] *= K # printing result print(\"Dictionary after the multiplication of key : \" + str(dict(test_dict)))", "e": 27598, "s": 27112, "text": null }, { "code": null, "e": 27685, "s": 27598, "text": "The original dictionary : {}\nDictionary after the multiplication of key : {'best': 0}\n" }, { "code": null, "e": 27712, "s": 27685, "text": "Python dictionary-programs" }, { "code": null, "e": 27719, "s": 27712, "text": "Python" }, { "code": null, "e": 27735, "s": 27719, "text": "Python Programs" }, { "code": null, "e": 27833, "s": 27735, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27851, "s": 27833, "text": "Python Dictionary" }, { "code": null, "e": 27883, "s": 27851, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27905, "s": 27883, "text": "Enumerate() in Python" }, { "code": null, "e": 27947, "s": 27905, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27977, "s": 27947, "text": "Iterate over a list in Python" }, { "code": null, "e": 28020, "s": 27977, "text": "Python program to convert a list to string" }, { "code": null, "e": 28042, "s": 28020, "text": "Defaultdict in Python" }, { "code": null, "e": 28081, "s": 28042, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28127, "s": 28081, "text": "Python | Split string into list of characters" } ]
How to swap or exchange objects in Java? - GeeksforGeeks
19 Nov, 2021 In order to understand how to swap objects in Java, let us consider an illustration below as follows: Illustration: Let’s say we have a class called “Car” with some attributes. And we create two objects of Car, say car1 and car2, how to exchange the data of car1 and car2? Methods: Using concepts of OOPSUsing Wrapper classes of java Using concepts of OOPS Using Wrapper classes of java Method 1: Using concepts of OOPS Here we will be simply swapping members for which let us directly take a sample ‘Car’ illustration with which we will play. So if the class ‘Car’ has only one integer attribute say “no” (car number), we can swap cars by simply swapping the members of two cars. Example 1-A Java // Java program to demonstrate that we can swap two// objects be swapping members // Class 1// Number class Carclass Car { // Attributes associated with car int no; Car(int no) { this.no = no; }} // Class 2// Uses Car objectsclass GFG { // Method 1 // To swap public static void swap(Car c1, Car c2) { int temp = c1.no; c1.no = c2.no; c2.no = temp; } // Method 2 // Main driver method public static void main(String[] args) { // Creating car class objects(creating cars) Car c1 = new Car(1); Car c2 = new Car(2); // Calling method 1 swap(c1, c2); // Print and display commands System.out.println("c1.no = " + c1.no); System.out.println("c2.no = " + c2.no); }} c1.no = 2 c2.no = 1 Note: Geek, what if we don’t know members of Car? The above solution worked as we knew that there is one member “no” in Car. What if we don’t know members of Car or the member list is too big. This is a very common situation as a class that uses some other class may not access members of other class. Does below solution work? Example 1-B Java // Java program to demonstrate that we can swap two// objects be swapping members// Where it does not work // Class 1// A car with number and nameclass Car { // Attributes of Car class int model, no; // Constructor Car(int model, int no) { // This keyword is used to refer // current instance itself this.model = model; this.no = no; } // Method of this class // To print Car void print() { // Printing number and model of car System.out.println("no = " + no + ", model = " + model); }} // Class 2// A class that uses Carclass Main{ // swap() doesn't swap c1 and c2 public static void swap(Car c1, Car c2) { Car temp = c1; c1 = c2; c2 = temp; } // Driver method public static void main(String[] args) { Car c1 = new Car(101, 1); Car c2 = new Car(202, 2); swap(c1, c2); c1.print(); c2.print(); }} no = 1, model = 101 no = 2, model = 202 Output explanation: As we can see from the above output, the objects are not swapped. We have discussed in a previous post that parameters are passed by value in Java. So when we pass c1 and c2 to swap(), the function swap() creates a copy of these references. Method 2: Wrapper Class If we create a wrapper class that contains references of Car, we can swap cars by swapping references of the wrapper class. Example Java // Java program to Demonstrate that Wrapper Classes// Can be Used to Swap two Objects // Class 1// A car with model and no.class Car { // Attributes associated with car int model, no; // Constructor of class 1 Car(int model, int no) { // This refers to current instance itself this.model = model; this.no = no; } // Method // To print object details void print() { System.out.println("no = " + no + ", model = " + model); }} // Class 2// Wrapper over class that is used for swappingclass CarWrapper { Car c; // Constructor CarWrapper(Car c) { this.c = c; }} // Class 3// Uses Car class and swaps objects of Car// using CarWrapperclass GFG { // This method swaps car objects in wrappers // cw1 and cw2 public static void swap(CarWrapper cw1, CarWrapper cw2) { Car temp = cw1.c; cw1.c = cw2.c; cw2.c = temp; } // Main driver method public static void main(String[] args) { Car c1 = new Car(101, 1); Car c2 = new Car(202, 2); CarWrapper cw1 = new CarWrapper(c1); CarWrapper cw2 = new CarWrapper(c2); swap(cw1, cw2); cw1.c.print(); cw2.c.print(); }} Output: no = 2, model = 202 no = 1, model = 101 So a wrapper class solution works even if the user class doesn’t have access to members of the class whose objects are to be swapped.This article is contributed by Anurag Rai. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. solankimayank anikakapoor surindertarika1234 java-basics Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Interfaces in Java ArrayList in Java Stack Class in Java Singleton Class in Java Set in Java Multithreading in Java Collections in Java Queue Interface In Java Initializing a List in Java
[ { "code": null, "e": 25517, "s": 25489, "text": "\n19 Nov, 2021" }, { "code": null, "e": 25619, "s": 25517, "text": "In order to understand how to swap objects in Java, let us consider an illustration below as follows:" }, { "code": null, "e": 25634, "s": 25619, "text": "Illustration: " }, { "code": null, "e": 25791, "s": 25634, "text": "Let’s say we have a class called “Car” with some attributes. And we create two objects of Car, say car1 and car2, how to exchange the data of car1 and car2?" }, { "code": null, "e": 25801, "s": 25791, "text": "Methods: " }, { "code": null, "e": 25853, "s": 25801, "text": "Using concepts of OOPSUsing Wrapper classes of java" }, { "code": null, "e": 25876, "s": 25853, "text": "Using concepts of OOPS" }, { "code": null, "e": 25906, "s": 25876, "text": "Using Wrapper classes of java" }, { "code": null, "e": 25940, "s": 25906, "text": "Method 1: Using concepts of OOPS " }, { "code": null, "e": 26201, "s": 25940, "text": "Here we will be simply swapping members for which let us directly take a sample ‘Car’ illustration with which we will play. So if the class ‘Car’ has only one integer attribute say “no” (car number), we can swap cars by simply swapping the members of two cars." }, { "code": null, "e": 26213, "s": 26201, "text": "Example 1-A" }, { "code": null, "e": 26218, "s": 26213, "text": "Java" }, { "code": "// Java program to demonstrate that we can swap two// objects be swapping members // Class 1// Number class Carclass Car { // Attributes associated with car int no; Car(int no) { this.no = no; }} // Class 2// Uses Car objectsclass GFG { // Method 1 // To swap public static void swap(Car c1, Car c2) { int temp = c1.no; c1.no = c2.no; c2.no = temp; } // Method 2 // Main driver method public static void main(String[] args) { // Creating car class objects(creating cars) Car c1 = new Car(1); Car c2 = new Car(2); // Calling method 1 swap(c1, c2); // Print and display commands System.out.println(\"c1.no = \" + c1.no); System.out.println(\"c2.no = \" + c2.no); }}", "e": 26997, "s": 26218, "text": null }, { "code": null, "e": 27017, "s": 26997, "text": "c1.no = 2\nc2.no = 1" }, { "code": null, "e": 27068, "s": 27017, "text": "Note: Geek, what if we don’t know members of Car? " }, { "code": null, "e": 27348, "s": 27068, "text": "The above solution worked as we knew that there is one member “no” in Car. What if we don’t know members of Car or the member list is too big. This is a very common situation as a class that uses some other class may not access members of other class. Does below solution work? " }, { "code": null, "e": 27360, "s": 27348, "text": "Example 1-B" }, { "code": null, "e": 27365, "s": 27360, "text": "Java" }, { "code": "// Java program to demonstrate that we can swap two// objects be swapping members// Where it does not work // Class 1// A car with number and nameclass Car { // Attributes of Car class int model, no; // Constructor Car(int model, int no) { // This keyword is used to refer // current instance itself this.model = model; this.no = no; } // Method of this class // To print Car void print() { // Printing number and model of car System.out.println(\"no = \" + no + \", model = \" + model); }} // Class 2// A class that uses Carclass Main{ // swap() doesn't swap c1 and c2 public static void swap(Car c1, Car c2) { Car temp = c1; c1 = c2; c2 = temp; } // Driver method public static void main(String[] args) { Car c1 = new Car(101, 1); Car c2 = new Car(202, 2); swap(c1, c2); c1.print(); c2.print(); }}", "e": 28346, "s": 27365, "text": null }, { "code": null, "e": 28386, "s": 28346, "text": "no = 1, model = 101\nno = 2, model = 202" }, { "code": null, "e": 28648, "s": 28386, "text": "Output explanation: As we can see from the above output, the objects are not swapped. We have discussed in a previous post that parameters are passed by value in Java. So when we pass c1 and c2 to swap(), the function swap() creates a copy of these references." }, { "code": null, "e": 28673, "s": 28648, "text": "Method 2: Wrapper Class " }, { "code": null, "e": 28797, "s": 28673, "text": "If we create a wrapper class that contains references of Car, we can swap cars by swapping references of the wrapper class." }, { "code": null, "e": 28806, "s": 28797, "text": "Example " }, { "code": null, "e": 28811, "s": 28806, "text": "Java" }, { "code": "// Java program to Demonstrate that Wrapper Classes// Can be Used to Swap two Objects // Class 1// A car with model and no.class Car { // Attributes associated with car int model, no; // Constructor of class 1 Car(int model, int no) { // This refers to current instance itself this.model = model; this.no = no; } // Method // To print object details void print() { System.out.println(\"no = \" + no + \", model = \" + model); }} // Class 2// Wrapper over class that is used for swappingclass CarWrapper { Car c; // Constructor CarWrapper(Car c) { this.c = c; }} // Class 3// Uses Car class and swaps objects of Car// using CarWrapperclass GFG { // This method swaps car objects in wrappers // cw1 and cw2 public static void swap(CarWrapper cw1, CarWrapper cw2) { Car temp = cw1.c; cw1.c = cw2.c; cw2.c = temp; } // Main driver method public static void main(String[] args) { Car c1 = new Car(101, 1); Car c2 = new Car(202, 2); CarWrapper cw1 = new CarWrapper(c1); CarWrapper cw2 = new CarWrapper(c2); swap(cw1, cw2); cw1.c.print(); cw2.c.print(); }}", "e": 30054, "s": 28811, "text": null }, { "code": null, "e": 30063, "s": 30054, "text": "Output: " }, { "code": null, "e": 30103, "s": 30063, "text": "no = 2, model = 202\nno = 1, model = 101" }, { "code": null, "e": 30627, "s": 30103, "text": "So a wrapper class solution works even if the user class doesn’t have access to members of the class whose objects are to be swapped.This article is contributed by Anurag Rai. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 30641, "s": 30627, "text": "solankimayank" }, { "code": null, "e": 30653, "s": 30641, "text": "anikakapoor" }, { "code": null, "e": 30672, "s": 30653, "text": "surindertarika1234" }, { "code": null, "e": 30684, "s": 30672, "text": "java-basics" }, { "code": null, "e": 30689, "s": 30684, "text": "Java" }, { "code": null, "e": 30694, "s": 30689, "text": "Java" }, { "code": null, "e": 30792, "s": 30694, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30807, "s": 30792, "text": "Stream In Java" }, { "code": null, "e": 30826, "s": 30807, "text": "Interfaces in Java" }, { "code": null, "e": 30844, "s": 30826, "text": "ArrayList in Java" }, { "code": null, "e": 30864, "s": 30844, "text": "Stack Class in Java" }, { "code": null, "e": 30888, "s": 30864, "text": "Singleton Class in Java" }, { "code": null, "e": 30900, "s": 30888, "text": "Set in Java" }, { "code": null, "e": 30923, "s": 30900, "text": "Multithreading in Java" }, { "code": null, "e": 30943, "s": 30923, "text": "Collections in Java" }, { "code": null, "e": 30967, "s": 30943, "text": "Queue Interface In Java" } ]
Minimum pair sum operations to make array each element divisible by 4 - GeeksforGeeks
03 May, 2021 Given an array of positive integers of length n. Our task is to find minimum number of operations to convert an array so that arr[i] % 4 is zero for each i. In each operation, we can take any two elements from the array, remove both of them and put back their sum in the array.Examples: Input : arr = {2 , 2 , 2 , 3 , 3} Output : 3 Explanation: In 1 operation we pick 2 and 2 and put their sum back to the array , In 2 operation we pick 3 and 3 and do same for that ,now in 3 operation we pick 6 and 2 so overall 3 operation are required. Input: arr = {4, 2, 2, 6, 6} Output: 2 Explanation: In operation 1, we can take 2 and 2 and put back their sum i.e. 4. In operation 2, we can take 6 and 6 and put back their sum i.e. 12. And array becomes {4, 4, 12}. Approach : Assume the count of elements leaving remainder 1, 2, 3 when divided by 4 are brr[1], brr[2] and brr[3]. If (brr[1] + 2 * brr[2] + 3 * brr[3]) is not a multiple of 4, solution does not exist.Now greedily pair elements of brr[2] with brr[2] and elements of brr[1] with brr[3]. This helps us to achieve fixing a maximum of 2 elements at a time. Now, we can either we left with only 1 brr[2] element or none. If we are left with 1 brr[2] element, then we can pair with 2 remaining brr[1] or brr[3] elements. This will incur a total of 2 operations.At last, we would be only left with brr[1] or brr[3] elements (if possible). This can only we fixed in one way. That is taking 4 of them and fixing them all together in 3 operations. Thus, we are able to fix all the elements of the array.Below is the implementation: C++ Java Python3 C# PHP Javascript // CPP program to find Minimum number// of operations to convert an array// so that arr[i] % 4 is zero.#include <bits/stdc++.h>using namespace std; // Function to find minimum operations.int minimumOperations(int arr[], int n){ // Counting of all the elements // leaving remainder 1, 2, 3 when // divided by 4 in the array brr. // at positions 1, 2 and 3 respectively. int brr[] = { 0, 0, 0, 0 }; for (int i = 0; i < n; i++) brr[arr[i] % 4]++; // If it is possible to convert the // array so that arr[i] % 4 is zero. if ((brr[1] + 2 * brr[2] + 3 * brr[3]) % 4 == 0) { // Pairing the elements of brr3 and brr1. int min_opr = min(brr[3], brr[1]); brr[3] -= min_opr; brr[1] -= min_opr; // Pairing the brr2 elements. min_opr += brr[2] / 2; // Assigning the remaining brr2 elements. brr[2] %= 2; // If we are left with one brr2 element. if (brr[2]) { // Here we need only two operations // to convert the remaining one // brr2 element to convert it. min_opr += 2; // Now there is no brr2 element. brr[2] = 0; // Remaining brr3 elements. if (brr[3]) brr[3] -= 2; // Remaining brr1 elements. if (brr[1]) brr[1] -= 2; } // If we are left with brr1 and brr2 // elements then, we have to take four // of them and fixing them all together // in 3 operations. if (brr[1]) min_opr += (brr[1] / 4) * 3; if (brr[3]) min_opr += (brr[3] / 4) * 3; // Returns the minimum operations. return min_opr; } // If it is not possible to convert the array. return -1; } // Driver functionint main(){ int arr[] = { 1, 2, 3, 1, 2, 3, 8 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minimumOperations(arr, n);} // Java program to find Minimum number// of operations to convert an array// so that arr[i] % 4 is zero. class GFG { // Function to find minimum operations.static int minimumOperations(int arr[], int n){ // Counting of all the elements // leaving remainder 1, 2, 3 when // divided by 4 in the array brr. // at positions 1, 2 and 3 respectively. int brr[] = { 0, 0, 0, 0 }; for (int i = 0; i < n; i++) brr[arr[i] % 4]++; // If it is possible to convert the // array so that arr[i] % 4 is zero. if ((brr[1] + 2 * brr[2] + 3 * brr[3]) % 4 == 0) { // Pairing the elements of brr3 and brr1. int min_opr = Math.min(brr[3], brr[1]); brr[3] -= min_opr; brr[1] -= min_opr; // Pairing the brr2 elements. min_opr += brr[2] / 2; // Assigning the remaining brr2 elements. brr[2] %= 2; // If we are left with one brr2 element. if (brr[2] == 1) { // Here we need only two operations // to convert the remaining one // brr2 element to convert it. min_opr += 2; // Now there is no brr2 element. brr[2] = 0; // Remaining brr3 elements. if (brr[3] == 1) brr[3] -= 2; // Remaining brr1 elements. if (brr[1]== 1) brr[1] -= 2; } // If we are left with brr1 and brr2 // elements then, we have to take four // of them and fixing them all together // in 3 operations. if (brr[1] == 1) min_opr += (brr[1] / 4) * 3; if (brr[3] == 1) min_opr += (brr[3] / 4) * 3; // Returns the minimum operations. return min_opr; } // If it is not possible to convert the array. return -1; } // Driver functionpublic static void main(String[] args){ int arr[] = { 1, 2, 3, 1, 2, 3, 8 }; int n = arr.length; System.out.println(minimumOperations(arr, n));}} // This code is contributed by Prerna Saini. # Python program to# find Minimum number# of operations to# convert an array# so that arr[i] % 4 is zero. # Function to find# minimum operations.def minimumOperations(arr,n): # Counting of all the elements # leaving remainder 1, 2, 3 when # divided by 4 in the array brr. # at positions 1, 2 and 3 respectively. brr = [ 0, 0, 0, 0 ] for i in range(n): brr[arr[i] % 4]+=1; # If it is possible to convert the # array so that arr[i] % 4 is zero. if ((brr[1] + 2 * brr[2] + 3 * brr[3]) % 4 == 0): # Pairing the elements # of brr3 and brr1. min_opr = min(brr[3], brr[1]) brr[3] -= min_opr brr[1] -= min_opr # Pairing the brr2 elements. min_opr += brr[2] // 2 # Assigning the remaining # brr2 elements. brr[2] %= 2 # If we are left with # one brr2 element. if (brr[2]): # Here we need only two operations # to convert the remaining one # brr2 element to convert it. min_opr += 2 # Now there is no brr2 element. brr[2] = 0 # Remaining brr3 elements. if (brr[3]): brr[3] -= 2 # Remaining brr1 elements. if (brr[1]): brr[1] -= 2 # If we are left with brr1 and brr2 # elements then, we have to take four # of them and fixing them all together # in 3 operations. if (brr[1]): min_opr += (brr[1] // 4) * 3 if (brr[3]): min_opr += (brr[3] // 4) * 3 # Returns the minimum operations. return min_opr # If it is not possible to convert the array. return -1 # Driver function arr = [ 1, 2, 3, 1, 2, 3, 8 ]n =len(arr) print(minimumOperations(arr, n)) # This code is contributed# by Anant Agarwal. // C# program to find Minimum number// of operations to convert an array// so that arr[i] % 4 is zero.using System; class GFG { // Function to find minimum operations. static int minimumOperations(int []arr, int n) { // Counting of all the elements // leaving remainder 1, 2, 3 when // divided by 4 in the array brr. // at positions 1, 2 and 3 respectively. int []brr = { 0, 0, 0, 0 }; for (int i = 0; i < n; i++) brr[arr[i] % 4]++; // If it is possible to convert the // array so that arr[i] % 4 is zero. if ((brr[1] + 2 * brr[2] + 3 * brr[3]) % 4 == 0) { // Pairing the elements of brr3 and brr1. int min_opr = Math.Min(brr[3], brr[1]); brr[3] -= min_opr; brr[1] -= min_opr; // Pairing the brr2 elements. min_opr += brr[2] / 2; // Assigning the remaining brr2 elements. brr[2] %= 2; // If we are left with one brr2 element. if (brr[2] == 1) { // Here we need only two operations // to convert the remaining one // brr2 element to convert it. min_opr += 2; // Now there is no brr2 element. brr[2] = 0; // Remaining brr3 elements. if (brr[3] == 1) brr[3] -= 2; // Remaining brr1 elements. if (brr[1]== 1) brr[1] -= 2; } // If we are left with brr1 and brr2 // elements then, we have to take four // of them and fixing them all together // in 3 operations. if (brr[1] == 1) min_opr += (brr[1] / 4) * 3; if (brr[3] == 1) min_opr += (brr[3] / 4) * 3; // Returns the minimum operations. return min_opr; } // If it is not possible to convert the array. return -1; } // Driver function public static void Main() { int []arr = { 1, 2, 3, 1, 2, 3, 8 }; int n = arr.Length; Console.WriteLine(minimumOperations(arr, n)); }} // This code is contributed by vt_m <?php// PHP program to find// Minimum number of// operations to convert// an array so that// arr[i] % 4 is zero. // Function to find// minimum operations.function minimumOperations($arr, $n){ // Counting of all the // elements leaving remainder // 1, 2, 3 when divided by 4 // in the array brr at positions // 1, 2 and 3 respectively. $brr = array(0, 0, 0, 0); for ($i = 0; $i < $n; $i++) $brr[$arr[$i] % 4]++; // If it is possible to // convert the array so // that arr[i] % 4 is zero. if (($brr[1] + 2 * $brr[2] + 3 * $brr[3]) % 4 == 0) { // Pairing the elements // of brr3 and brr1. $min_opr = min($brr[3], $brr[1]); $brr[3] -= $min_opr; $brr[1] -= $min_opr; // Pairing the // brr2 elements. $min_opr += $brr[2] / 2; // Assigning the remaining // brr2 elements. $brr[2] %= 2; // If we are left with // one brr2 element. if ($brr[2]) { // Here we need only two // operations to convert // the remaining one brr2 // element to convert it. $min_opr += 2; // Now there is no // brr2 element. $brr[2] = 0; // Remaining brr3 elements. if ($brr[3]) $brr[3] -= 2; // Remaining brr1 elements. if ($brr[1]) $brr[1] -= 2; } // If we are left with brr1 // and brr2 elements then, // we have to take four of // them and fixing them all // together in 3 operations. if ($brr[1]) $min_opr += ($brr[1] / 4) * 3; if ($brr[3]) $min_opr += ($brr[3] / 4) * 3; // Returns the // minimum operations. return $min_opr; } // If it is not possible // to convert the array. return -1;} // Driver Code$arr = array(1, 2, 3, 1, 2, 3, 8);$n = count($arr);echo (minimumOperations($arr, $n)); // This code is contributed by// Manish Shaw(manishshaw1)?> <script>// Java Script program to find Minimum number// of operations to convert an array// so that arr[i] % 4 is zero. // Function to find minimum operations.function minimumOperations(arr,n){ // Counting of all the elements // leaving remainder 1, 2, 3 when // divided by 4 in the array brr. // at positions 1, 2 and 3 respectively. let brr = [0, 0, 0, 0 ]; for (let i = 0; i < n; i++) brr[arr[i] % 4]++; // If it is possible to convert the // array so that arr[i] % 4 is zero. if ((brr[1] + 2 * brr[2] + 3 * brr[3]) % 4 == 0) { // Pairing the elements of brr3 and brr1. let min_opr = Math.min(brr[3], brr[1]); brr[3] -= min_opr; brr[1] -= min_opr; // Pairing the brr2 elements. min_opr += brr[2] / 2; // Assigning the remaining brr2 elements. brr[2] %= 2; // If we are left with one brr2 element. if (brr[2] == 1) { // Here we need only two operations // to convert the remaining one // brr2 element to convert it. min_opr += 2; // Now there is no brr2 element. brr[2] = 0; // Remaining brr3 elements. if (brr[3] == 1) brr[3] -= 2; // Remaining brr1 elements. if (brr[1]== 1) brr[1] -= 2; } // If we are left with brr1 and brr2 // elements then, we have to take four // of them and fixing them all together // in 3 operations. if (brr[1] == 1) min_opr += (brr[1] / 4) * 3; if (brr[3] == 1) min_opr += (brr[3] / 4) * 3; // Returns the minimum operations. return min_opr; } // If it is not possible to convert the array. return -1; } // Driver function let arr= [1, 2, 3, 1, 2, 3, 8 ]; let n = arr.length; document.write(minimumOperations(arr, n)); // This code is contributed by Bobby</script> Output: 3 manishshaw1 gottumukkalabobby divisibility Arrays Arrays 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 Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Python | Using 2D arrays/lists the right way Search an element in a sorted and rotated array Array of Strings in C++ (5 Different Ways to Create) Queue | Set 1 (Introduction and Array Implementation)
[ { "code": null, "e": 26309, "s": 26281, "text": "\n03 May, 2021" }, { "code": null, "e": 26598, "s": 26309, "text": "Given an array of positive integers of length n. Our task is to find minimum number of operations to convert an array so that arr[i] % 4 is zero for each i. In each operation, we can take any two elements from the array, remove both of them and put back their sum in the array.Examples: " }, { "code": null, "e": 27069, "s": 26598, "text": "Input : arr = {2 , 2 , 2 , 3 , 3} Output : 3 Explanation: In 1 operation we pick 2 and 2 and put their sum back to the array , In 2 operation we pick 3 and 3 and do same for that ,now in 3 operation we pick 6 and 2 so overall 3 operation are required. Input: arr = {4, 2, 2, 6, 6} Output: 2 Explanation: In operation 1, we can take 2 and 2 and put back their sum i.e. 4. In operation 2, we can take 6 and 6 and put back their sum i.e. 12. And array becomes {4, 4, 12}. " }, { "code": null, "e": 27895, "s": 27071, "text": "Approach : Assume the count of elements leaving remainder 1, 2, 3 when divided by 4 are brr[1], brr[2] and brr[3]. If (brr[1] + 2 * brr[2] + 3 * brr[3]) is not a multiple of 4, solution does not exist.Now greedily pair elements of brr[2] with brr[2] and elements of brr[1] with brr[3]. This helps us to achieve fixing a maximum of 2 elements at a time. Now, we can either we left with only 1 brr[2] element or none. If we are left with 1 brr[2] element, then we can pair with 2 remaining brr[1] or brr[3] elements. This will incur a total of 2 operations.At last, we would be only left with brr[1] or brr[3] elements (if possible). This can only we fixed in one way. That is taking 4 of them and fixing them all together in 3 operations. Thus, we are able to fix all the elements of the array.Below is the implementation: " }, { "code": null, "e": 27899, "s": 27895, "text": "C++" }, { "code": null, "e": 27904, "s": 27899, "text": "Java" }, { "code": null, "e": 27912, "s": 27904, "text": "Python3" }, { "code": null, "e": 27915, "s": 27912, "text": "C#" }, { "code": null, "e": 27919, "s": 27915, "text": "PHP" }, { "code": null, "e": 27930, "s": 27919, "text": "Javascript" }, { "code": "// CPP program to find Minimum number// of operations to convert an array// so that arr[i] % 4 is zero.#include <bits/stdc++.h>using namespace std; // Function to find minimum operations.int minimumOperations(int arr[], int n){ // Counting of all the elements // leaving remainder 1, 2, 3 when // divided by 4 in the array brr. // at positions 1, 2 and 3 respectively. int brr[] = { 0, 0, 0, 0 }; for (int i = 0; i < n; i++) brr[arr[i] % 4]++; // If it is possible to convert the // array so that arr[i] % 4 is zero. if ((brr[1] + 2 * brr[2] + 3 * brr[3]) % 4 == 0) { // Pairing the elements of brr3 and brr1. int min_opr = min(brr[3], brr[1]); brr[3] -= min_opr; brr[1] -= min_opr; // Pairing the brr2 elements. min_opr += brr[2] / 2; // Assigning the remaining brr2 elements. brr[2] %= 2; // If we are left with one brr2 element. if (brr[2]) { // Here we need only two operations // to convert the remaining one // brr2 element to convert it. min_opr += 2; // Now there is no brr2 element. brr[2] = 0; // Remaining brr3 elements. if (brr[3]) brr[3] -= 2; // Remaining brr1 elements. if (brr[1]) brr[1] -= 2; } // If we are left with brr1 and brr2 // elements then, we have to take four // of them and fixing them all together // in 3 operations. if (brr[1]) min_opr += (brr[1] / 4) * 3; if (brr[3]) min_opr += (brr[3] / 4) * 3; // Returns the minimum operations. return min_opr; } // If it is not possible to convert the array. return -1; } // Driver functionint main(){ int arr[] = { 1, 2, 3, 1, 2, 3, 8 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minimumOperations(arr, n);}", "e": 29941, "s": 27930, "text": null }, { "code": "// Java program to find Minimum number// of operations to convert an array// so that arr[i] % 4 is zero. class GFG { // Function to find minimum operations.static int minimumOperations(int arr[], int n){ // Counting of all the elements // leaving remainder 1, 2, 3 when // divided by 4 in the array brr. // at positions 1, 2 and 3 respectively. int brr[] = { 0, 0, 0, 0 }; for (int i = 0; i < n; i++) brr[arr[i] % 4]++; // If it is possible to convert the // array so that arr[i] % 4 is zero. if ((brr[1] + 2 * brr[2] + 3 * brr[3]) % 4 == 0) { // Pairing the elements of brr3 and brr1. int min_opr = Math.min(brr[3], brr[1]); brr[3] -= min_opr; brr[1] -= min_opr; // Pairing the brr2 elements. min_opr += brr[2] / 2; // Assigning the remaining brr2 elements. brr[2] %= 2; // If we are left with one brr2 element. if (brr[2] == 1) { // Here we need only two operations // to convert the remaining one // brr2 element to convert it. min_opr += 2; // Now there is no brr2 element. brr[2] = 0; // Remaining brr3 elements. if (brr[3] == 1) brr[3] -= 2; // Remaining brr1 elements. if (brr[1]== 1) brr[1] -= 2; } // If we are left with brr1 and brr2 // elements then, we have to take four // of them and fixing them all together // in 3 operations. if (brr[1] == 1) min_opr += (brr[1] / 4) * 3; if (brr[3] == 1) min_opr += (brr[3] / 4) * 3; // Returns the minimum operations. return min_opr; } // If it is not possible to convert the array. return -1; } // Driver functionpublic static void main(String[] args){ int arr[] = { 1, 2, 3, 1, 2, 3, 8 }; int n = arr.length; System.out.println(minimumOperations(arr, n));}} // This code is contributed by Prerna Saini.", "e": 32039, "s": 29941, "text": null }, { "code": "# Python program to# find Minimum number# of operations to# convert an array# so that arr[i] % 4 is zero. # Function to find# minimum operations.def minimumOperations(arr,n): # Counting of all the elements # leaving remainder 1, 2, 3 when # divided by 4 in the array brr. # at positions 1, 2 and 3 respectively. brr = [ 0, 0, 0, 0 ] for i in range(n): brr[arr[i] % 4]+=1; # If it is possible to convert the # array so that arr[i] % 4 is zero. if ((brr[1] + 2 * brr[2] + 3 * brr[3]) % 4 == 0): # Pairing the elements # of brr3 and brr1. min_opr = min(brr[3], brr[1]) brr[3] -= min_opr brr[1] -= min_opr # Pairing the brr2 elements. min_opr += brr[2] // 2 # Assigning the remaining # brr2 elements. brr[2] %= 2 # If we are left with # one brr2 element. if (brr[2]): # Here we need only two operations # to convert the remaining one # brr2 element to convert it. min_opr += 2 # Now there is no brr2 element. brr[2] = 0 # Remaining brr3 elements. if (brr[3]): brr[3] -= 2 # Remaining brr1 elements. if (brr[1]): brr[1] -= 2 # If we are left with brr1 and brr2 # elements then, we have to take four # of them and fixing them all together # in 3 operations. if (brr[1]): min_opr += (brr[1] // 4) * 3 if (brr[3]): min_opr += (brr[3] // 4) * 3 # Returns the minimum operations. return min_opr # If it is not possible to convert the array. return -1 # Driver function arr = [ 1, 2, 3, 1, 2, 3, 8 ]n =len(arr) print(minimumOperations(arr, n)) # This code is contributed# by Anant Agarwal.", "e": 33968, "s": 32039, "text": null }, { "code": "// C# program to find Minimum number// of operations to convert an array// so that arr[i] % 4 is zero.using System; class GFG { // Function to find minimum operations. static int minimumOperations(int []arr, int n) { // Counting of all the elements // leaving remainder 1, 2, 3 when // divided by 4 in the array brr. // at positions 1, 2 and 3 respectively. int []brr = { 0, 0, 0, 0 }; for (int i = 0; i < n; i++) brr[arr[i] % 4]++; // If it is possible to convert the // array so that arr[i] % 4 is zero. if ((brr[1] + 2 * brr[2] + 3 * brr[3]) % 4 == 0) { // Pairing the elements of brr3 and brr1. int min_opr = Math.Min(brr[3], brr[1]); brr[3] -= min_opr; brr[1] -= min_opr; // Pairing the brr2 elements. min_opr += brr[2] / 2; // Assigning the remaining brr2 elements. brr[2] %= 2; // If we are left with one brr2 element. if (brr[2] == 1) { // Here we need only two operations // to convert the remaining one // brr2 element to convert it. min_opr += 2; // Now there is no brr2 element. brr[2] = 0; // Remaining brr3 elements. if (brr[3] == 1) brr[3] -= 2; // Remaining brr1 elements. if (brr[1]== 1) brr[1] -= 2; } // If we are left with brr1 and brr2 // elements then, we have to take four // of them and fixing them all together // in 3 operations. if (brr[1] == 1) min_opr += (brr[1] / 4) * 3; if (brr[3] == 1) min_opr += (brr[3] / 4) * 3; // Returns the minimum operations. return min_opr; } // If it is not possible to convert the array. return -1; } // Driver function public static void Main() { int []arr = { 1, 2, 3, 1, 2, 3, 8 }; int n = arr.Length; Console.WriteLine(minimumOperations(arr, n)); }} // This code is contributed by vt_m", "e": 36303, "s": 33968, "text": null }, { "code": "<?php// PHP program to find// Minimum number of// operations to convert// an array so that// arr[i] % 4 is zero. // Function to find// minimum operations.function minimumOperations($arr, $n){ // Counting of all the // elements leaving remainder // 1, 2, 3 when divided by 4 // in the array brr at positions // 1, 2 and 3 respectively. $brr = array(0, 0, 0, 0); for ($i = 0; $i < $n; $i++) $brr[$arr[$i] % 4]++; // If it is possible to // convert the array so // that arr[i] % 4 is zero. if (($brr[1] + 2 * $brr[2] + 3 * $brr[3]) % 4 == 0) { // Pairing the elements // of brr3 and brr1. $min_opr = min($brr[3], $brr[1]); $brr[3] -= $min_opr; $brr[1] -= $min_opr; // Pairing the // brr2 elements. $min_opr += $brr[2] / 2; // Assigning the remaining // brr2 elements. $brr[2] %= 2; // If we are left with // one brr2 element. if ($brr[2]) { // Here we need only two // operations to convert // the remaining one brr2 // element to convert it. $min_opr += 2; // Now there is no // brr2 element. $brr[2] = 0; // Remaining brr3 elements. if ($brr[3]) $brr[3] -= 2; // Remaining brr1 elements. if ($brr[1]) $brr[1] -= 2; } // If we are left with brr1 // and brr2 elements then, // we have to take four of // them and fixing them all // together in 3 operations. if ($brr[1]) $min_opr += ($brr[1] / 4) * 3; if ($brr[3]) $min_opr += ($brr[3] / 4) * 3; // Returns the // minimum operations. return $min_opr; } // If it is not possible // to convert the array. return -1;} // Driver Code$arr = array(1, 2, 3, 1, 2, 3, 8);$n = count($arr);echo (minimumOperations($arr, $n)); // This code is contributed by// Manish Shaw(manishshaw1)?>", "e": 38456, "s": 36303, "text": null }, { "code": "<script>// Java Script program to find Minimum number// of operations to convert an array// so that arr[i] % 4 is zero. // Function to find minimum operations.function minimumOperations(arr,n){ // Counting of all the elements // leaving remainder 1, 2, 3 when // divided by 4 in the array brr. // at positions 1, 2 and 3 respectively. let brr = [0, 0, 0, 0 ]; for (let i = 0; i < n; i++) brr[arr[i] % 4]++; // If it is possible to convert the // array so that arr[i] % 4 is zero. if ((brr[1] + 2 * brr[2] + 3 * brr[3]) % 4 == 0) { // Pairing the elements of brr3 and brr1. let min_opr = Math.min(brr[3], brr[1]); brr[3] -= min_opr; brr[1] -= min_opr; // Pairing the brr2 elements. min_opr += brr[2] / 2; // Assigning the remaining brr2 elements. brr[2] %= 2; // If we are left with one brr2 element. if (brr[2] == 1) { // Here we need only two operations // to convert the remaining one // brr2 element to convert it. min_opr += 2; // Now there is no brr2 element. brr[2] = 0; // Remaining brr3 elements. if (brr[3] == 1) brr[3] -= 2; // Remaining brr1 elements. if (brr[1]== 1) brr[1] -= 2; } // If we are left with brr1 and brr2 // elements then, we have to take four // of them and fixing them all together // in 3 operations. if (brr[1] == 1) min_opr += (brr[1] / 4) * 3; if (brr[3] == 1) min_opr += (brr[3] / 4) * 3; // Returns the minimum operations. return min_opr; } // If it is not possible to convert the array. return -1; } // Driver function let arr= [1, 2, 3, 1, 2, 3, 8 ]; let n = arr.length; document.write(minimumOperations(arr, n)); // This code is contributed by Bobby</script>", "e": 40496, "s": 38456, "text": null }, { "code": null, "e": 40506, "s": 40496, "text": "Output: " }, { "code": null, "e": 40508, "s": 40506, "text": "3" }, { "code": null, "e": 40522, "s": 40510, "text": "manishshaw1" }, { "code": null, "e": 40540, "s": 40522, "text": "gottumukkalabobby" }, { "code": null, "e": 40553, "s": 40540, "text": "divisibility" }, { "code": null, "e": 40560, "s": 40553, "text": "Arrays" }, { "code": null, "e": 40567, "s": 40560, "text": "Arrays" }, { "code": null, "e": 40665, "s": 40567, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40733, "s": 40665, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 40756, "s": 40733, "text": "Introduction to Arrays" }, { "code": null, "e": 40788, "s": 40756, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 40802, "s": 40788, "text": "Linear Search" }, { "code": null, "e": 40823, "s": 40802, "text": "Linked List vs Array" }, { "code": null, "e": 40908, "s": 40823, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 40953, "s": 40908, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 41001, "s": 40953, "text": "Search an element in a sorted and rotated array" }, { "code": null, "e": 41054, "s": 41001, "text": "Array of Strings in C++ (5 Different Ways to Create)" } ]
How to implement Swipe to Refresh in React Native ? - GeeksforGeeks
19 Jul, 2021 In this article, we will look at how we can use the Swipe Down to Refresh feature in React Native. In applications that show real-time data to the users such as crypto values or availability of a food item in a Food Ordering app, users can do a vertical swipe down on the app to manually refresh the data from the server. We will use RefreshControl component inside a Scroll View to add the pull to refresh functionality. Creating React Native App and Installing Module: Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli Step 1: Open your terminal and install expo-cli by the following command. npm install -g expo-cli Step 2: Now create a project by the following command.expo init demo-app Step 2: Now create a project by the following command. expo init demo-app Step 3: Now go into your project folder i.e. demo-appcd demo-app Step 3: Now go into your project folder i.e. demo-app cd demo-app Project Structure: It will look like the following. Implementation: In this example, we will create a Text component inside a ScrollView which will change its color when the user swipes down on the app. When the user swipes down, the onRefresh function is called which turns the refreshing controlled prop to be true. Hence, the user can now see a loading icon and after 2000 ms i.e. 2 seconds, the color of the button is changed to green and the refreshing controlled prop is changed to be false. This stops the loading icon to disappear after the execution of the function. Filename: App.js App.js import React, {useState} from 'react';import {ScrollView, StyleSheet, Text, View, RefreshControl} from 'react-native'; const App = () => { const [color, changeColor] = useState('red'); const [refreshing, setRefreshing] = React.useState(false); const onRefresh = () => { setRefreshing(true); setTimeout(() => { changeColor('green'); setRefreshing(false); }, 2000); }; return ( <ScrollView refreshControl={ <RefreshControl refreshing={refreshing} onRefresh={onRefresh} /> } style={styles.container}> <View style={{ marginTop: 200, alignSelf: 'center', padding: 20, backgroundColor: color, }}> <Text style={{color: 'white'}}> Swipe Down to Change Color ! </Text> </View> </ScrollView> );}; const styles = StyleSheet.create({ container: { flex: 1, },}); export default App; Start the server by using the following command. npm run android Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again. React-Native Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to apply style to parent if it has child with CSS? How to execute PHP code using command line ? Difference Between PUT and PATCH Request REST API (Introduction) How to redirect to another page in ReactJS ?
[ { "code": null, "e": 26169, "s": 26141, "text": "\n19 Jul, 2021" }, { "code": null, "e": 26492, "s": 26169, "text": "In this article, we will look at how we can use the Swipe Down to Refresh feature in React Native. In applications that show real-time data to the users such as crypto values or availability of a food item in a Food Ordering app, users can do a vertical swipe down on the app to manually refresh the data from the server. " }, { "code": null, "e": 26592, "s": 26492, "text": "We will use RefreshControl component inside a Scroll View to add the pull to refresh functionality." }, { "code": null, "e": 26641, "s": 26592, "text": "Creating React Native App and Installing Module:" }, { "code": null, "e": 26739, "s": 26641, "text": "Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli " }, { "code": null, "e": 26813, "s": 26739, "text": "Step 1: Open your terminal and install expo-cli by the following command." }, { "code": null, "e": 26837, "s": 26813, "text": "npm install -g expo-cli" }, { "code": null, "e": 26912, "s": 26839, "text": "Step 2: Now create a project by the following command.expo init demo-app" }, { "code": null, "e": 26967, "s": 26912, "text": "Step 2: Now create a project by the following command." }, { "code": null, "e": 26986, "s": 26967, "text": "expo init demo-app" }, { "code": null, "e": 27051, "s": 26986, "text": "Step 3: Now go into your project folder i.e. demo-appcd demo-app" }, { "code": null, "e": 27105, "s": 27051, "text": "Step 3: Now go into your project folder i.e. demo-app" }, { "code": null, "e": 27117, "s": 27105, "text": "cd demo-app" }, { "code": null, "e": 27169, "s": 27117, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 27693, "s": 27169, "text": "Implementation: In this example, we will create a Text component inside a ScrollView which will change its color when the user swipes down on the app. When the user swipes down, the onRefresh function is called which turns the refreshing controlled prop to be true. Hence, the user can now see a loading icon and after 2000 ms i.e. 2 seconds, the color of the button is changed to green and the refreshing controlled prop is changed to be false. This stops the loading icon to disappear after the execution of the function." }, { "code": null, "e": 27710, "s": 27693, "text": "Filename: App.js" }, { "code": null, "e": 27717, "s": 27710, "text": "App.js" }, { "code": "import React, {useState} from 'react';import {ScrollView, StyleSheet, Text, View, RefreshControl} from 'react-native'; const App = () => { const [color, changeColor] = useState('red'); const [refreshing, setRefreshing] = React.useState(false); const onRefresh = () => { setRefreshing(true); setTimeout(() => { changeColor('green'); setRefreshing(false); }, 2000); }; return ( <ScrollView refreshControl={ <RefreshControl refreshing={refreshing} onRefresh={onRefresh} /> } style={styles.container}> <View style={{ marginTop: 200, alignSelf: 'center', padding: 20, backgroundColor: color, }}> <Text style={{color: 'white'}}> Swipe Down to Change Color ! </Text> </View> </ScrollView> );}; const styles = StyleSheet.create({ container: { flex: 1, },}); export default App;", "e": 28646, "s": 27717, "text": null }, { "code": null, "e": 28695, "s": 28646, "text": "Start the server by using the following command." }, { "code": null, "e": 28711, "s": 28695, "text": "npm run android" }, { "code": null, "e": 28879, "s": 28711, "text": "Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again." }, { "code": null, "e": 28892, "s": 28879, "text": "React-Native" }, { "code": null, "e": 28909, "s": 28892, "text": "Web Technologies" }, { "code": null, "e": 29007, "s": 28909, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29047, "s": 29007, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29092, "s": 29047, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29135, "s": 29092, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29196, "s": 29135, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29268, "s": 29196, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29323, "s": 29268, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 29368, "s": 29323, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 29409, "s": 29368, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29433, "s": 29409, "text": "REST API (Introduction)" } ]