title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Adobe Interview | Set 10 (Software Engineer) - GeeksforGeeks
22 May, 2019 Written:Aptitude: Objective 50 min 45 questionsLR- 2 passages-5 eachDI- 1 paragraph- 5 eachMathematical Easy only. Just time concern for those who are out of touch. My suggestion will be to do the LR in the end. Java WhiteBox test: Subjective 45 min 20 questionsjava-15j2ee-5What is package and how is it used.When is thread’s run method invoked?What are the synchronised method and synchronised statements?What is the difference in class hierarchies of Reader/Writer and InputStream and OutputStreamWhat is transientWhich is illegalint i=0;float f=45.0;double d=49.0; StringBuffer sb1 = new StringBuffer("Amit"); StringBuffer sb2 = new StringBuffer("Amit"); String ss1 = "Amit"; System.out.println(sb1==sb2); System.out.println(sb1.equals(sb2)); System.out.println(sb1.equals(ss1)); System.out.println("Poddar".substring(3)); What are wait(),notify(),notifyAll()what is finally in try-catch-finally blocksWhat is thin-client applicationDifference between >> and >>>O/P questions related to string. concat, equals methods. Error pointing codes with options What is package and how is it used.When is thread’s run method invoked?What are the synchronised method and synchronised statements?What is the difference in class hierarchies of Reader/Writer and InputStream and OutputStreamWhat is transientWhich is illegalint i=0;float f=45.0;double d=49.0; StringBuffer sb1 = new StringBuffer("Amit"); StringBuffer sb2 = new StringBuffer("Amit"); String ss1 = "Amit"; System.out.println(sb1==sb2); System.out.println(sb1.equals(sb2)); System.out.println(sb1.equals(ss1)); System.out.println("Poddar".substring(3)); What are wait(),notify(),notifyAll()what is finally in try-catch-finally blocksWhat is thin-client applicationDifference between >> and >>> What is package and how is it used. When is thread’s run method invoked? What are the synchronised method and synchronised statements? What is the difference in class hierarchies of Reader/Writer and InputStream and OutputStream What is transient Which is illegalint i=0;float f=45.0;double d=49.0; StringBuffer sb1 = new StringBuffer("Amit"); StringBuffer sb2 = new StringBuffer("Amit"); String ss1 = "Amit"; System.out.println(sb1==sb2); System.out.println(sb1.equals(sb2)); System.out.println(sb1.equals(ss1)); System.out.println("Poddar".substring(3)); StringBuffer sb1 = new StringBuffer("Amit"); StringBuffer sb2 = new StringBuffer("Amit"); String ss1 = "Amit"; System.out.println(sb1==sb2); System.out.println(sb1.equals(sb2)); System.out.println(sb1.equals(ss1)); System.out.println("Poddar".substring(3)); What are wait(),notify(),notifyAll() what is finally in try-catch-finally blocks What is thin-client application Difference between >> and >>> O/P questions related to string. concat, equals methods. Error pointing codes with options F2F Round 1:(1.2 hr)Brief intro about work.Why do you want to shift when Mobile (and e-commerce) are already the most happening things.Test cases for mail attachment(word doc) not being opened scenarioWAP to convert a binary to decimal.(I wrote by taking the parameter as String, he asked me to do by taking as int)WAP to print sum of first ‘n’ prime numbersString s = "Hello "; s+ = "Adobe "; s.trim(); System.out.print(s); What is the output?Explain a project you have been recently been part of and what are the test cases you have gone through.What is the testing framework you have used in Android? What is the approach you follow while testing any product? How do you test a method which does not return any value?What are the operating systems you have worked on? Do you know Unix?What are the main things that you need to look at while making a mobile application to that of a desktop applicationWhat is the toughest bug you have fixed?What is a memory leak?What is the difference between instance variable and local variableIf I write java in command prompt from anywhere in the system, will it work? If not, how to make it work.Why is the class name the same as the filename in Java? Is there any use?Can a file have more than two classes? What will be the name of that file?How many class files will be generated when we compile.Why is Java platform independent?Is the JVM platform dependent? On what factors it depends?What are the best practices you have followed in your project?He asked me if I have any questions. I asked more about the role and team. He explained in detail about the team and also about Adobe subscription model. We had a general discussion over this business decision. Brief intro about work.Why do you want to shift when Mobile (and e-commerce) are already the most happening things.Test cases for mail attachment(word doc) not being opened scenarioWAP to convert a binary to decimal.(I wrote by taking the parameter as String, he asked me to do by taking as int)WAP to print sum of first ‘n’ prime numbersString s = "Hello "; s+ = "Adobe "; s.trim(); System.out.print(s); What is the output?Explain a project you have been recently been part of and what are the test cases you have gone through.What is the testing framework you have used in Android? What is the approach you follow while testing any product? How do you test a method which does not return any value?What are the operating systems you have worked on? Do you know Unix?What are the main things that you need to look at while making a mobile application to that of a desktop applicationWhat is the toughest bug you have fixed?What is a memory leak?What is the difference between instance variable and local variableIf I write java in command prompt from anywhere in the system, will it work? If not, how to make it work.Why is the class name the same as the filename in Java? Is there any use?Can a file have more than two classes? What will be the name of that file?How many class files will be generated when we compile.Why is Java platform independent?Is the JVM platform dependent? On what factors it depends?What are the best practices you have followed in your project? Brief intro about work. Why do you want to shift when Mobile (and e-commerce) are already the most happening things. Test cases for mail attachment(word doc) not being opened scenario WAP to convert a binary to decimal.(I wrote by taking the parameter as String, he asked me to do by taking as int) WAP to print sum of first ‘n’ prime numbers String s = "Hello "; s+ = "Adobe "; s.trim(); System.out.print(s); What is the output? String s = "Hello "; s+ = "Adobe "; s.trim(); System.out.print(s); What is the output? Explain a project you have been recently been part of and what are the test cases you have gone through. What is the testing framework you have used in Android? What is the approach you follow while testing any product? How do you test a method which does not return any value? What are the operating systems you have worked on? Do you know Unix? What are the main things that you need to look at while making a mobile application to that of a desktop application What is the toughest bug you have fixed? What is a memory leak? What is the difference between instance variable and local variable If I write java in command prompt from anywhere in the system, will it work? If not, how to make it work. Why is the class name the same as the filename in Java? Is there any use?Can a file have more than two classes? What will be the name of that file?How many class files will be generated when we compile. Why is Java platform independent? Is the JVM platform dependent? On what factors it depends? What are the best practices you have followed in your project? He asked me if I have any questions. I asked more about the role and team. He explained in detail about the team and also about Adobe subscription model. We had a general discussion over this business decision. F2F Round 2:(30 min)Brief introWAP to find out factorial of a numberHe asked for recursion as well.Asked me to write the testcases and handle the overflow condition and border cases in the code.Discussed which approach is better and when to use which.Do you know UnixDo you know any other mobile platform apart from Android? Do you know any application platform which enables building apps across channels (desktop, android, ios, cloud...)He asked me if I have heard about PhoneGap and later explained it. He asked me if I have any questions. I asked if they have a mobile team separately. He said yes and explained their work a bit. Brief introWAP to find out factorial of a numberHe asked for recursion as well.Asked me to write the testcases and handle the overflow condition and border cases in the code.Discussed which approach is better and when to use which.Do you know UnixDo you know any other mobile platform apart from Android? Do you know any application platform which enables building apps across channels (desktop, android, ios, cloud...) Brief intro WAP to find out factorial of a numberHe asked for recursion as well.Asked me to write the testcases and handle the overflow condition and border cases in the code.Discussed which approach is better and when to use which. Do you know Unix Do you know any other mobile platform apart from Android? Do you know any application platform which enables building apps across channels (desktop, android, ios, cloud...) He asked me if I have heard about PhoneGap and later explained it. He asked me if I have any questions. I asked if they have a mobile team separately. He said yes and explained their work a bit. F2F Round 3:(1 hr)Brief introWhat is the binary search?Write a code for ternary search. Is it better than Binary? He asked me to generalize the search and asked me which is the optimum.What is the registry?Do you know UnixI have a hard disk of 100 Gb. It has one and only file of 80 GB (database backup).What happens if I delete it and it goes to recycle bin.Follow-up questions:Is the memory freed from the hard disk?What happens if I move it from one drive to another.What happens in case of permanent delete.What happens when we format the disk.What is virtual memory?Puzzle:10 containers with 100 balls each but one container defective. Find out the defective container in minimum weighings.He asked me for questions. I asked them if there will be an option to shift to a developer position. He said yes and explained about their open culture. Also explained how they interact and work closely with developers. Brief introWhat is the binary search?Write a code for ternary search. Is it better than Binary? He asked me to generalize the search and asked me which is the optimum.What is the registry?Do you know UnixI have a hard disk of 100 Gb. It has one and only file of 80 GB (database backup).What happens if I delete it and it goes to recycle bin.Follow-up questions:Is the memory freed from the hard disk?What happens if I move it from one drive to another.What happens in case of permanent delete.What happens when we format the disk.What is virtual memory?Puzzle:10 containers with 100 balls each but one container defective. Find out the defective container in minimum weighings. Brief intro What is the binary search? Write a code for ternary search. Is it better than Binary? He asked me to generalize the search and asked me which is the optimum. What is the registry? Do you know Unix I have a hard disk of 100 Gb. It has one and only file of 80 GB (database backup).What happens if I delete it and it goes to recycle bin.Follow-up questions:Is the memory freed from the hard disk?What happens if I move it from one drive to another.What happens in case of permanent delete.What happens when we format the disk. What is virtual memory? Puzzle:10 containers with 100 balls each but one container defective. Find out the defective container in minimum weighings. He asked me for questions. I asked them if there will be an option to shift to a developer position. He said yes and explained about their open culture. Also explained how they interact and work closely with developers. Director round:(40 min)How was the day?What is the most interesting question you have been posed today?What is it that you have learnt today.Give me a brief about your work.Why do you want to shift from Development to Testing?He said he will concentrate on only problem solving, aptitude and attitude-Gmail wants to provide a new enhanced service which offers auto-backup, promotional emails filtered, extra space for mailbox etc which costs 50 rs per month.They want to run a provisioning program which shows a popup to certain customers having options-Yes and then redirected to payment and allRemind me after 2 weeks.NoNot happy with the service offered.Asked me to test this model.Later he asked me the factors which I will consider for choosing a set of customers for this program.Have you worked on Unix?What is the registry?I have installed msword in my pc. Copied the C/program files/ folder into a pen drive and pasted in another pc. Will it work? Why /Why not?What is SaaS? How was the day?What is the most interesting question you have been posed today?What is it that you have learnt today.Give me a brief about your work.Why do you want to shift from Development to Testing? How was the day? What is the most interesting question you have been posed today? What is it that you have learnt today. Give me a brief about your work. Why do you want to shift from Development to Testing? He said he will concentrate on only problem solving, aptitude and attitude-Gmail wants to provide a new enhanced service which offers auto-backup, promotional emails filtered, extra space for mailbox etc which costs 50 rs per month.They want to run a provisioning program which shows a popup to certain customers having options- Yes and then redirected to payment and allRemind me after 2 weeks.NoNot happy with the service offered. Yes and then redirected to payment and all Remind me after 2 weeks. No Not happy with the service offered. Asked me to test this model.Later he asked me the factors which I will consider for choosing a set of customers for this program. Have you worked on Unix?What is the registry?I have installed msword in my pc. Copied the C/program files/ folder into a pen drive and pasted in another pc. Will it work? Why /Why not?What is SaaS? Have you worked on Unix? What is the registry?I have installed msword in my pc. Copied the C/program files/ folder into a pen drive and pasted in another pc. Will it work? Why /Why not? What is SaaS? Examples.There is one FB user in India and another in the US. When they communicate, do they connect to the same server? If not then how does the communication happen? What is the data that is being transferred?This round felt like a stress test and went very badly. Couldn’t ask for any good questions when he offered. (My suggestion will be, answer only if you know and you are sure about it otherwise don’t even try) If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Adobe Interview Experiences Adobe Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience Amazon Interview Experience for SDE-1 (On-Campus) Microsoft Interview Experience for Internship (Via Engage) Amazon Interview Experience for SDE-1 Difference between ANN, CNN and RNN Amazon Interview Experience for SDE-1 (Off-Campus) Amazon Interview Experience (Off-Campus) 2022 Amazon Interview Experience for SDE-1(Off-Campus) Amazon Interview Experience for SDE-1 Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
[ { "code": null, "e": 25218, "s": 25190, "text": "\n22 May, 2019" }, { "code": null, "e": 25322, "s": 25218, "text": "Written:Aptitude: Objective 50 min 45 questionsLR- 2 passages-5 eachDI- 1 paragraph- 5 eachMathematical" }, { "code": null, "e": 25430, "s": 25322, "text": "Easy only. Just time concern for those who are out of touch. My suggestion will be to do the LR in the end." }, { "code": null, "e": 26288, "s": 25430, "text": "Java WhiteBox test: Subjective 45 min 20 questionsjava-15j2ee-5What is package and how is it used.When is thread’s run method invoked?What are the synchronised method and synchronised statements?What is the difference in class hierarchies of Reader/Writer and InputStream and OutputStreamWhat is transientWhich is illegalint i=0;float f=45.0;double d=49.0; StringBuffer sb1 = new StringBuffer(\"Amit\");\n StringBuffer sb2 = new StringBuffer(\"Amit\");\n String ss1 = \"Amit\";\n System.out.println(sb1==sb2);\n System.out.println(sb1.equals(sb2));\n System.out.println(sb1.equals(ss1));\n System.out.println(\"Poddar\".substring(3)); What are wait(),notify(),notifyAll()what is finally in try-catch-finally blocksWhat is thin-client applicationDifference between >> and >>>O/P questions related to string. concat, equals methods. Error pointing codes with options" }, { "code": null, "e": 26993, "s": 26288, "text": "What is package and how is it used.When is thread’s run method invoked?What are the synchronised method and synchronised statements?What is the difference in class hierarchies of Reader/Writer and InputStream and OutputStreamWhat is transientWhich is illegalint i=0;float f=45.0;double d=49.0; StringBuffer sb1 = new StringBuffer(\"Amit\");\n StringBuffer sb2 = new StringBuffer(\"Amit\");\n String ss1 = \"Amit\";\n System.out.println(sb1==sb2);\n System.out.println(sb1.equals(sb2));\n System.out.println(sb1.equals(ss1));\n System.out.println(\"Poddar\".substring(3)); What are wait(),notify(),notifyAll()what is finally in try-catch-finally blocksWhat is thin-client applicationDifference between >> and >>>" }, { "code": null, "e": 27029, "s": 26993, "text": "What is package and how is it used." }, { "code": null, "e": 27066, "s": 27029, "text": "When is thread’s run method invoked?" }, { "code": null, "e": 27128, "s": 27066, "text": "What are the synchronised method and synchronised statements?" }, { "code": null, "e": 27222, "s": 27128, "text": "What is the difference in class hierarchies of Reader/Writer and InputStream and OutputStream" }, { "code": null, "e": 27240, "s": 27222, "text": "What is transient" }, { "code": null, "e": 27292, "s": 27240, "text": "Which is illegalint i=0;float f=45.0;double d=49.0;" }, { "code": null, "e": 27565, "s": 27292, "text": " StringBuffer sb1 = new StringBuffer(\"Amit\");\n StringBuffer sb2 = new StringBuffer(\"Amit\");\n String ss1 = \"Amit\";\n System.out.println(sb1==sb2);\n System.out.println(sb1.equals(sb2));\n System.out.println(sb1.equals(ss1));\n System.out.println(\"Poddar\".substring(3)); " }, { "code": null, "e": 27838, "s": 27565, "text": " StringBuffer sb1 = new StringBuffer(\"Amit\");\n StringBuffer sb2 = new StringBuffer(\"Amit\");\n String ss1 = \"Amit\";\n System.out.println(sb1==sb2);\n System.out.println(sb1.equals(sb2));\n System.out.println(sb1.equals(ss1));\n System.out.println(\"Poddar\".substring(3)); " }, { "code": null, "e": 27875, "s": 27838, "text": "What are wait(),notify(),notifyAll()" }, { "code": null, "e": 27919, "s": 27875, "text": "what is finally in try-catch-finally blocks" }, { "code": null, "e": 27951, "s": 27919, "text": "What is thin-client application" }, { "code": null, "e": 27981, "s": 27951, "text": "Difference between >> and >>>" }, { "code": null, "e": 28072, "s": 27981, "text": "O/P questions related to string. concat, equals methods. Error pointing codes with options" }, { "code": null, "e": 29779, "s": 28072, "text": "F2F Round 1:(1.2 hr)Brief intro about work.Why do you want to shift when Mobile (and e-commerce) are already the most happening things.Test cases for mail attachment(word doc) not being opened scenarioWAP to convert a binary to decimal.(I wrote by taking the parameter as String, he asked me to do by taking as int)WAP to print sum of first ‘n’ prime numbersString s = \"Hello \";\ns+ = \"Adobe \";\ns.trim(); \nSystem.out.print(s); What is the output?Explain a project you have been recently been part of and what are the test cases you have gone through.What is the testing framework you have used in Android? What is the approach you follow while testing any product? How do you test a method which does not return any value?What are the operating systems you have worked on? Do you know Unix?What are the main things that you need to look at while making a mobile application to that of a desktop applicationWhat is the toughest bug you have fixed?What is a memory leak?What is the difference between instance variable and local variableIf I write java in command prompt from anywhere in the system, will it work? If not, how to make it work.Why is the class name the same as the filename in Java? Is there any use?Can a file have more than two classes? What will be the name of that file?How many class files will be generated when we compile.Why is Java platform independent?Is the JVM platform dependent? On what factors it depends?What are the best practices you have followed in your project?He asked me if I have any questions. I asked more about the role and team. He explained in detail about the team and also about Adobe subscription model. We had a general discussion over this business decision." }, { "code": null, "e": 31256, "s": 29779, "text": "Brief intro about work.Why do you want to shift when Mobile (and e-commerce) are already the most happening things.Test cases for mail attachment(word doc) not being opened scenarioWAP to convert a binary to decimal.(I wrote by taking the parameter as String, he asked me to do by taking as int)WAP to print sum of first ‘n’ prime numbersString s = \"Hello \";\ns+ = \"Adobe \";\ns.trim(); \nSystem.out.print(s); What is the output?Explain a project you have been recently been part of and what are the test cases you have gone through.What is the testing framework you have used in Android? What is the approach you follow while testing any product? How do you test a method which does not return any value?What are the operating systems you have worked on? Do you know Unix?What are the main things that you need to look at while making a mobile application to that of a desktop applicationWhat is the toughest bug you have fixed?What is a memory leak?What is the difference between instance variable and local variableIf I write java in command prompt from anywhere in the system, will it work? If not, how to make it work.Why is the class name the same as the filename in Java? Is there any use?Can a file have more than two classes? What will be the name of that file?How many class files will be generated when we compile.Why is Java platform independent?Is the JVM platform dependent? On what factors it depends?What are the best practices you have followed in your project?" }, { "code": null, "e": 31280, "s": 31256, "text": "Brief intro about work." }, { "code": null, "e": 31373, "s": 31280, "text": "Why do you want to shift when Mobile (and e-commerce) are already the most happening things." }, { "code": null, "e": 31440, "s": 31373, "text": "Test cases for mail attachment(word doc) not being opened scenario" }, { "code": null, "e": 31555, "s": 31440, "text": "WAP to convert a binary to decimal.(I wrote by taking the parameter as String, he asked me to do by taking as int)" }, { "code": null, "e": 31599, "s": 31555, "text": "WAP to print sum of first ‘n’ prime numbers" }, { "code": null, "e": 31689, "s": 31599, "text": "String s = \"Hello \";\ns+ = \"Adobe \";\ns.trim(); \nSystem.out.print(s); What is the output?" }, { "code": null, "e": 31760, "s": 31689, "text": "String s = \"Hello \";\ns+ = \"Adobe \";\ns.trim(); \nSystem.out.print(s); " }, { "code": null, "e": 31780, "s": 31760, "text": "What is the output?" }, { "code": null, "e": 31885, "s": 31780, "text": "Explain a project you have been recently been part of and what are the test cases you have gone through." }, { "code": null, "e": 32058, "s": 31885, "text": "What is the testing framework you have used in Android? What is the approach you follow while testing any product? How do you test a method which does not return any value?" }, { "code": null, "e": 32127, "s": 32058, "text": "What are the operating systems you have worked on? Do you know Unix?" }, { "code": null, "e": 32244, "s": 32127, "text": "What are the main things that you need to look at while making a mobile application to that of a desktop application" }, { "code": null, "e": 32285, "s": 32244, "text": "What is the toughest bug you have fixed?" }, { "code": null, "e": 32308, "s": 32285, "text": "What is a memory leak?" }, { "code": null, "e": 32376, "s": 32308, "text": "What is the difference between instance variable and local variable" }, { "code": null, "e": 32482, "s": 32376, "text": "If I write java in command prompt from anywhere in the system, will it work? If not, how to make it work." }, { "code": null, "e": 32685, "s": 32482, "text": "Why is the class name the same as the filename in Java? Is there any use?Can a file have more than two classes? What will be the name of that file?How many class files will be generated when we compile." }, { "code": null, "e": 32719, "s": 32685, "text": "Why is Java platform independent?" }, { "code": null, "e": 32778, "s": 32719, "text": "Is the JVM platform dependent? On what factors it depends?" }, { "code": null, "e": 32841, "s": 32778, "text": "What are the best practices you have followed in your project?" }, { "code": null, "e": 33052, "s": 32841, "text": "He asked me if I have any questions. I asked more about the role and team. He explained in detail about the team and also about Adobe subscription model. We had a general discussion over this business decision." }, { "code": null, "e": 33686, "s": 33052, "text": "F2F Round 2:(30 min)Brief introWAP to find out factorial of a numberHe asked for recursion as well.Asked me to write the testcases and handle the overflow condition and border cases in the code.Discussed which approach is better and when to use which.Do you know UnixDo you know any other mobile platform apart from Android? Do you know any application platform which enables building apps across channels (desktop, android, ios, cloud...)He asked me if I have heard about PhoneGap and later explained it. He asked me if I have any questions. I asked if they have a mobile team separately. He said yes and explained their work a bit." }, { "code": null, "e": 34106, "s": 33686, "text": "Brief introWAP to find out factorial of a numberHe asked for recursion as well.Asked me to write the testcases and handle the overflow condition and border cases in the code.Discussed which approach is better and when to use which.Do you know UnixDo you know any other mobile platform apart from Android? Do you know any application platform which enables building apps across channels (desktop, android, ios, cloud...)" }, { "code": null, "e": 34118, "s": 34106, "text": "Brief intro" }, { "code": null, "e": 34339, "s": 34118, "text": "WAP to find out factorial of a numberHe asked for recursion as well.Asked me to write the testcases and handle the overflow condition and border cases in the code.Discussed which approach is better and when to use which." }, { "code": null, "e": 34356, "s": 34339, "text": "Do you know Unix" }, { "code": null, "e": 34529, "s": 34356, "text": "Do you know any other mobile platform apart from Android? Do you know any application platform which enables building apps across channels (desktop, android, ios, cloud...)" }, { "code": null, "e": 34724, "s": 34529, "text": "He asked me if I have heard about PhoneGap and later explained it. He asked me if I have any questions. I asked if they have a mobile team separately. He said yes and explained their work a bit." }, { "code": null, "e": 35639, "s": 34724, "text": "F2F Round 3:(1 hr)Brief introWhat is the binary search?Write a code for ternary search. Is it better than Binary? He asked me to generalize the search and asked me which is the optimum.What is the registry?Do you know UnixI have a hard disk of 100 Gb. It has one and only file of 80 GB (database backup).What happens if I delete it and it goes to recycle bin.Follow-up questions:Is the memory freed from the hard disk?What happens if I move it from one drive to another.What happens in case of permanent delete.What happens when we format the disk.What is virtual memory?Puzzle:10 containers with 100 balls each but one container defective. Find out the defective container in minimum weighings.He asked me for questions. I asked them if there will be an option to shift to a developer position. He said yes and explained about their open culture. Also explained how they interact and work closely with developers." }, { "code": null, "e": 36317, "s": 35639, "text": "Brief introWhat is the binary search?Write a code for ternary search. Is it better than Binary? He asked me to generalize the search and asked me which is the optimum.What is the registry?Do you know UnixI have a hard disk of 100 Gb. It has one and only file of 80 GB (database backup).What happens if I delete it and it goes to recycle bin.Follow-up questions:Is the memory freed from the hard disk?What happens if I move it from one drive to another.What happens in case of permanent delete.What happens when we format the disk.What is virtual memory?Puzzle:10 containers with 100 balls each but one container defective. Find out the defective container in minimum weighings." }, { "code": null, "e": 36329, "s": 36317, "text": "Brief intro" }, { "code": null, "e": 36356, "s": 36329, "text": "What is the binary search?" }, { "code": null, "e": 36487, "s": 36356, "text": "Write a code for ternary search. Is it better than Binary? He asked me to generalize the search and asked me which is the optimum." }, { "code": null, "e": 36509, "s": 36487, "text": "What is the registry?" }, { "code": null, "e": 36526, "s": 36509, "text": "Do you know Unix" }, { "code": null, "e": 36853, "s": 36526, "text": "I have a hard disk of 100 Gb. It has one and only file of 80 GB (database backup).What happens if I delete it and it goes to recycle bin.Follow-up questions:Is the memory freed from the hard disk?What happens if I move it from one drive to another.What happens in case of permanent delete.What happens when we format the disk." }, { "code": null, "e": 36877, "s": 36853, "text": "What is virtual memory?" }, { "code": null, "e": 37002, "s": 36877, "text": "Puzzle:10 containers with 100 balls each but one container defective. Find out the defective container in minimum weighings." }, { "code": null, "e": 37222, "s": 37002, "text": "He asked me for questions. I asked them if there will be an option to shift to a developer position. He said yes and explained about their open culture. Also explained how they interact and work closely with developers." }, { "code": null, "e": 38206, "s": 37222, "text": "Director round:(40 min)How was the day?What is the most interesting question you have been posed today?What is it that you have learnt today.Give me a brief about your work.Why do you want to shift from Development to Testing?He said he will concentrate on only problem solving, aptitude and attitude-Gmail wants to provide a new enhanced service which offers auto-backup, promotional emails filtered, extra space for mailbox etc which costs 50 rs per month.They want to run a provisioning program which shows a popup to certain customers having options-Yes and then redirected to payment and allRemind me after 2 weeks.NoNot happy with the service offered.Asked me to test this model.Later he asked me the factors which I will consider for choosing a set of customers for this program.Have you worked on Unix?What is the registry?I have installed msword in my pc. Copied the C/program files/ folder into a pen drive and pasted in another pc. Will it work? Why /Why not?What is SaaS?" }, { "code": null, "e": 38410, "s": 38206, "text": "How was the day?What is the most interesting question you have been posed today?What is it that you have learnt today.Give me a brief about your work.Why do you want to shift from Development to Testing?" }, { "code": null, "e": 38427, "s": 38410, "text": "How was the day?" }, { "code": null, "e": 38492, "s": 38427, "text": "What is the most interesting question you have been posed today?" }, { "code": null, "e": 38531, "s": 38492, "text": "What is it that you have learnt today." }, { "code": null, "e": 38564, "s": 38531, "text": "Give me a brief about your work." }, { "code": null, "e": 38618, "s": 38564, "text": "Why do you want to shift from Development to Testing?" }, { "code": null, "e": 38947, "s": 38618, "text": "He said he will concentrate on only problem solving, aptitude and attitude-Gmail wants to provide a new enhanced service which offers auto-backup, promotional emails filtered, extra space for mailbox etc which costs 50 rs per month.They want to run a provisioning program which shows a popup to certain customers having options-" }, { "code": null, "e": 39051, "s": 38947, "text": "Yes and then redirected to payment and allRemind me after 2 weeks.NoNot happy with the service offered." }, { "code": null, "e": 39094, "s": 39051, "text": "Yes and then redirected to payment and all" }, { "code": null, "e": 39119, "s": 39094, "text": "Remind me after 2 weeks." }, { "code": null, "e": 39122, "s": 39119, "text": "No" }, { "code": null, "e": 39158, "s": 39122, "text": "Not happy with the service offered." }, { "code": null, "e": 39288, "s": 39158, "text": "Asked me to test this model.Later he asked me the factors which I will consider for choosing a set of customers for this program." }, { "code": null, "e": 39486, "s": 39288, "text": "Have you worked on Unix?What is the registry?I have installed msword in my pc. Copied the C/program files/ folder into a pen drive and pasted in another pc. Will it work? Why /Why not?What is SaaS?" }, { "code": null, "e": 39511, "s": 39486, "text": "Have you worked on Unix?" }, { "code": null, "e": 39672, "s": 39511, "text": "What is the registry?I have installed msword in my pc. Copied the C/program files/ folder into a pen drive and pasted in another pc. Will it work? Why /Why not?" }, { "code": null, "e": 39686, "s": 39672, "text": "What is SaaS?" }, { "code": null, "e": 40106, "s": 39686, "text": "Examples.There is one FB user in India and another in the US. When they communicate, do they connect to the same server? If not then how does the communication happen? What is the data that is being transferred?This round felt like a stress test and went very badly. Couldn’t ask for any good questions when he offered. (My suggestion will be, answer only if you know and you are sure about it otherwise don’t even try)" }, { "code": null, "e": 40327, "s": 40106, "text": "If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 40333, "s": 40327, "text": "Adobe" }, { "code": null, "e": 40355, "s": 40333, "text": "Interview Experiences" }, { "code": null, "e": 40361, "s": 40355, "text": "Adobe" }, { "code": null, "e": 40459, "s": 40361, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40487, "s": 40459, "text": "Amazon Interview Experience" }, { "code": null, "e": 40537, "s": 40487, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" }, { "code": null, "e": 40596, "s": 40537, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 40634, "s": 40596, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 40670, "s": 40634, "text": "Difference between ANN, CNN and RNN" }, { "code": null, "e": 40721, "s": 40670, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 40767, "s": 40721, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 40817, "s": 40767, "text": "Amazon Interview Experience for SDE-1(Off-Campus)" }, { "code": null, "e": 40855, "s": 40817, "text": "Amazon Interview Experience for SDE-1" } ]
Find maximum length sub-list in a nested list in Python
we often deal with nested lists when doing data analysis in python. In this article, we will see how to find out the longest list among the elements in a nested list and then print this along with its length. We declare a nested list and give it as input to the lambda function along with its length. Finally, we apply the max function to get the list with maximum length as well as the length of such list. Live Demo def longest(lst): longestList = max(lst, key = lambda i: len(i)) maxLength = max(map(len, listA)) return longestList, maxLength # Driver Code listA = [[1,2], [2,45,6,7], [11,65,2]] print("Longest List and its length:\n",longest(listA)) Running the above code gives us the following result − Longest List and its length: ([2, 45, 6, 7], 4) In this approach, we first find the sub-list with maximum length and then loop through the elements of the list to find out which sublist match that length. We use the max and len function to do this calculation. Live Demo def longest(lst): longestList = [] maxLength = max(len(x) for x in listA) for i in listA: if len(i) == maxLength : longestList = i return longestList, maxLength # Driver Code listA = [[1,2], [2,45,6,7], [11,6,2]] print("Longest List and its length:\n",longest(listA)) Running the above code gives us the following result − Longest List and its length: ([2, 45, 6, 7], 4) This is a similar approach as the above program but we are using the map function to find out the sublist with maximum length. Live Demo def longest(lst): longestList = [] maxLength = max(map(len,listA)) for i in listA: if len(i) == maxLength : longestList = i return longestList, maxLength # Driver Code listA = [[1,2], [2,45,6,7], [11,6,2]] print("Longest List and its length:\n",longest(listA)) Running the above code gives us the following result − Longest List and its length: ([2, 45, 6, 7], 4)
[ { "code": null, "e": 1271, "s": 1062, "text": "we often deal with nested lists when doing data analysis in python. In this article, we will see how to find out the longest list among the elements in a nested list and then print this along with its length." }, { "code": null, "e": 1470, "s": 1271, "text": "We declare a nested list and give it as input to the lambda function along with its length. Finally, we apply the max function to get the list with maximum length as well as the length of such list." }, { "code": null, "e": 1481, "s": 1470, "text": " Live Demo" }, { "code": null, "e": 1727, "s": 1481, "text": "def longest(lst):\n longestList = max(lst, key = lambda i: len(i))\n maxLength = max(map(len, listA))\n return longestList, maxLength\n# Driver Code\nlistA = [[1,2], [2,45,6,7], [11,65,2]]\nprint(\"Longest List and its length:\\n\",longest(listA))\n" }, { "code": null, "e": 1782, "s": 1727, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1830, "s": 1782, "text": "Longest List and its length:\n([2, 45, 6, 7], 4)" }, { "code": null, "e": 2043, "s": 1830, "text": "In this approach, we first find the sub-list with maximum length and then loop through the elements of the list to find out which sublist match that length. We use the max and len function to do this calculation." }, { "code": null, "e": 2054, "s": 2043, "text": " Live Demo" }, { "code": null, "e": 2350, "s": 2054, "text": "def longest(lst):\n longestList = []\n maxLength = max(len(x) for x in listA)\n for i in listA:\n if len(i) == maxLength :\n longestList = i\n return longestList, maxLength\n# Driver Code\nlistA = [[1,2], [2,45,6,7], [11,6,2]]\nprint(\"Longest List and its length:\\n\",longest(listA))\n" }, { "code": null, "e": 2405, "s": 2350, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2453, "s": 2405, "text": "Longest List and its length:\n([2, 45, 6, 7], 4)" }, { "code": null, "e": 2580, "s": 2453, "text": "This is a similar approach as the above program but we are using the map function to find out the sublist with maximum length." }, { "code": null, "e": 2591, "s": 2580, "text": " Live Demo" }, { "code": null, "e": 2879, "s": 2591, "text": "def longest(lst):\n longestList = []\n maxLength = max(map(len,listA))\n for i in listA:\n if len(i) == maxLength :\n longestList = i\n return longestList, maxLength\n# Driver Code\nlistA = [[1,2], [2,45,6,7], [11,6,2]]\nprint(\"Longest List and its length:\\n\",longest(listA))" }, { "code": null, "e": 2934, "s": 2879, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2982, "s": 2934, "text": "Longest List and its length:\n([2, 45, 6, 7], 4)" } ]
Bootstrap 3 Tutorial
Bootstrap is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites. Bootstrap is completely free to download and use! This Bootstrap tutorial contains hundreds of Bootstrap examples. With our online editor, you can edit the code, and click on a button to view the result. Click on the "Try it Yourself" button to see how it works. Add the correct class name to transform the list below into a pagination menu. <ul class=""> <li><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> <li><a href="#">5</a></li> </ul> Start the Exercise Test your Bootstrap skills at W3Schools! Start Bootstrap Quiz! At W3Schools you will find a complete Bootstrap reference of all CSS classes, Components, and JavaScript plugins - all with "Try it Yourself" examples: We have made some Bootstrap Templates you can play around with. They are completely free to use: Browse Themes Browse Basic Templates This tutorial follows Bootstrap 3, which was released in 2013. However, we also cover newer versions; Bootstrap 4 (released 2018) and Bootstrap 5 (released 2021). Bootstrap 5 is the newest version of Bootstrap; with new components, faster stylesheets, more responsiveness etc. It supports the latest, stable releases of all major browsers and platforms. However, Internet Explorer 11 and down is not supported. The main differences between Bootstrap 5 and Bootstrap 3 & 4, is that Bootstrap 5 has switched to JavaScript instead of jQuery. Note: Bootstrap 3 and Bootstrap 4 is still supported by the team for critical bugfixes and documentation changes, and it is perfectly safe to continue to use them. However, new features will NOT be added to them. W3.CSS is an excellent alternative to Bootstrap. W3.CSS is smaller, faster, and easier to use. If you want to learn W3.CSS, go to our W3.CSS Tutorial. We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 116, "s": 0, "text": "Bootstrap is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites." }, { "code": null, "e": 166, "s": 116, "text": "Bootstrap is completely free to download and use!" }, { "code": null, "e": 231, "s": 166, "text": "This Bootstrap tutorial contains hundreds of Bootstrap examples." }, { "code": null, "e": 320, "s": 231, "text": "With our online editor, you can edit the code, and click on a button to view the result." }, { "code": null, "e": 379, "s": 320, "text": "Click on the \"Try it Yourself\" button to see how it works." }, { "code": null, "e": 458, "s": 379, "text": "Add the correct class name to transform the list below into a pagination menu." }, { "code": null, "e": 624, "s": 458, "text": "<ul class=\"\">\n <li><a href=\"#\">1</a></li>\n <li><a href=\"#\">2</a></li>\n <li><a href=\"#\">3</a></li>\n <li><a href=\"#\">4</a></li>\n <li><a href=\"#\">5</a></li>\n</ul>\n" }, { "code": null, "e": 643, "s": 624, "text": "Start the Exercise" }, { "code": null, "e": 684, "s": 643, "text": "Test your Bootstrap skills at W3Schools!" }, { "code": null, "e": 706, "s": 684, "text": "Start Bootstrap Quiz!" }, { "code": null, "e": 859, "s": 706, "text": "At W3Schools you will find a complete Bootstrap reference of all CSS classes, \nComponents, and JavaScript plugins - all with \"Try it Yourself\" examples:" }, { "code": null, "e": 956, "s": 859, "text": "We have made some Bootstrap Templates you can play around with. They are completely free to use:" }, { "code": null, "e": 970, "s": 956, "text": "Browse Themes" }, { "code": null, "e": 993, "s": 970, "text": "Browse Basic Templates" }, { "code": null, "e": 1156, "s": 993, "text": "This tutorial follows Bootstrap 3, which was released in 2013. However, we also cover newer versions; Bootstrap 4 (released 2018) and Bootstrap 5 (released 2021)." }, { "code": null, "e": 1406, "s": 1156, "text": "Bootstrap 5 is the newest version of Bootstrap; \nwith new components, faster stylesheets, more responsiveness etc. It supports the latest, stable releases of all major browsers and \nplatforms. However, Internet Explorer 11 and down is not supported." }, { "code": null, "e": 1535, "s": 1406, "text": "The main differences between Bootstrap 5 and Bootstrap 3 & 4, is that \nBootstrap 5 has switched to JavaScript instead of jQuery." }, { "code": null, "e": 1750, "s": 1535, "text": "Note: Bootstrap 3 and Bootstrap 4 is still supported by the team for critical bugfixes and documentation changes, \nand it is perfectly safe to continue to use them. However, new features will NOT be added to \nthem." }, { "code": null, "e": 1799, "s": 1750, "text": "W3.CSS is an excellent alternative to Bootstrap." }, { "code": null, "e": 1845, "s": 1799, "text": "W3.CSS is smaller, faster, and easier to use." }, { "code": null, "e": 1902, "s": 1845, "text": "If you want to learn W3.CSS, go to our W3.CSS \nTutorial." }, { "code": null, "e": 1935, "s": 1902, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1977, "s": 1935, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2084, "s": 1977, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 2103, "s": 2084, "text": "help@w3schools.com" } ]
continue - Unix, Linux Command
continue - To resume the next iteration of an enclosing for, while, until, or select loop. continue [n] Create a Utility Class to use continue. #continuesample for myloop in 1 2 3 4 5 do echo -n "$myloop" if [ "$myloop" -eq 3 ] then continue # Skip rest of this particular loop iteration. fi done Run the utility $ chmod a+x continuesample $ ./continuesample 1245 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10668, "s": 10577, "text": "continue - To resume the next iteration of an enclosing for, while, until, or select loop." }, { "code": null, "e": 10681, "s": 10668, "text": "continue [n]" }, { "code": null, "e": 10721, "s": 10681, "text": "Create a Utility Class to use continue." }, { "code": null, "e": 10891, "s": 10721, "text": "#continuesample\nfor myloop in 1 2 3 4 5 \ndo \n echo -n \"$myloop\"\n if [ \"$myloop\" -eq 3 ] \n then \n continue # Skip rest of this particular loop iteration.\n fi\ndone\n" }, { "code": null, "e": 10907, "s": 10891, "text": "Run the utility" }, { "code": null, "e": 10959, "s": 10907, "text": "$ chmod a+x continuesample\n$ ./continuesample\n1245\n" }, { "code": null, "e": 10994, "s": 10959, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 11022, "s": 10994, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11056, "s": 11022, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11073, "s": 11056, "text": " Frahaan Hussain" }, { "code": null, "e": 11106, "s": 11073, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 11117, "s": 11106, "text": " Pradeep D" }, { "code": null, "e": 11152, "s": 11117, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 11168, "s": 11152, "text": " Musab Zayadneh" }, { "code": null, "e": 11201, "s": 11168, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 11213, "s": 11201, "text": " GUHARAJANM" }, { "code": null, "e": 11245, "s": 11213, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 11253, "s": 11245, "text": " Uplatz" }, { "code": null, "e": 11260, "s": 11253, "text": " Print" }, { "code": null, "e": 11271, "s": 11260, "text": " Add Notes" } ]
Valid Parentheses in C++
Suppose we have an expression. The expression has some parentheses; we have to check the parentheses are balanced or not. The order of the parentheses are (), {} and []. Suppose there are two strings. “()[(){()}]” this is valid, but “{[}]” is invalid. The task is simple; we will use the stack to do this. We should follow these steps to get the solution − Traverse through the expression until it has exhaustedif the current character is opening bracket like (, { or [, then push into stackif the current character is closing bracket like ), } or ], then pop from stack, and check whether the popped bracket is corresponding starting bracket of the current character, then it is fine, otherwise, that is not balanced. Traverse through the expression until it has exhausted if the current character is opening bracket like (, { or [, then push into stack if the current character is opening bracket like (, { or [, then push into stack if the current character is closing bracket like ), } or ], then pop from stack, and check whether the popped bracket is corresponding starting bracket of the current character, then it is fine, otherwise, that is not balanced. if the current character is closing bracket like ), } or ], then pop from stack, and check whether the popped bracket is corresponding starting bracket of the current character, then it is fine, otherwise, that is not balanced. After the string is exhausted, if there are some starting bracket left into the stack, then the string is not balanced. After the string is exhausted, if there are some starting bracket left into the stack, then the string is not balanced. Live Demo #include <iostream> #include <stack> using namespace std; bool isBalancedExp(string exp) { stack<char> stk; char x; for (int i=0; i<exp.length(); i++) { if (exp[i]=='('||exp[i]=='['||exp[i]=='{') { stk.push(exp[i]); continue; } if (stk.empty()) return false; switch (exp[i]) { case ')': x = stk.top(); stk.pop(); if (x=='{' || x=='[') return false; break; case '}': x = stk.top(); stk.pop(); if (x=='(' || x=='[') return false; break; case ']': x = stk.top(); stk.pop(); if (x =='(' || x == '{') return false; break; } } return (stk.empty()); } int main() { string expresion = "()[(){()}]"; if (isBalancedExp(expresion)) cout << "This is Balanced Expression"; else cout << "This is Not Balanced Expression"; } "()[(){()}]" This is Balanced Expression
[ { "code": null, "e": 1314, "s": 1062, "text": "Suppose we have an expression. The expression has some parentheses; we have to check the parentheses are balanced or not. The order of the parentheses are (), {} and []. Suppose there are two strings. “()[(){()}]” this is valid, but “{[}]” is invalid." }, { "code": null, "e": 1419, "s": 1314, "text": "The task is simple; we will use the stack to do this. We should follow these steps to get the solution −" }, { "code": null, "e": 1781, "s": 1419, "text": "Traverse through the expression until it has exhaustedif the current character is opening bracket like (, { or [, then push into stackif the current character is closing bracket like ), } or ], then pop from stack, and check whether the popped bracket is corresponding starting bracket of the current character, then it is fine, otherwise, that is not balanced." }, { "code": null, "e": 1836, "s": 1781, "text": "Traverse through the expression until it has exhausted" }, { "code": null, "e": 1917, "s": 1836, "text": "if the current character is opening bracket like (, { or [, then push into stack" }, { "code": null, "e": 1998, "s": 1917, "text": "if the current character is opening bracket like (, { or [, then push into stack" }, { "code": null, "e": 2226, "s": 1998, "text": "if the current character is closing bracket like ), } or ], then pop from stack, and check whether the popped bracket is corresponding starting bracket of the current character, then it is fine, otherwise, that is not balanced." }, { "code": null, "e": 2454, "s": 2226, "text": "if the current character is closing bracket like ), } or ], then pop from stack, and check whether the popped bracket is corresponding starting bracket of the current character, then it is fine, otherwise, that is not balanced." }, { "code": null, "e": 2574, "s": 2454, "text": "After the string is exhausted, if there are some starting bracket left into the stack, then the string is not balanced." }, { "code": null, "e": 2694, "s": 2574, "text": "After the string is exhausted, if there are some starting bracket left into the stack, then the string is not balanced." }, { "code": null, "e": 2705, "s": 2694, "text": " Live Demo" }, { "code": null, "e": 3670, "s": 2705, "text": "#include <iostream>\n#include <stack>\nusing namespace std;\nbool isBalancedExp(string exp) {\n stack<char> stk;\n char x;\n for (int i=0; i<exp.length(); i++) {\n if (exp[i]=='('||exp[i]=='['||exp[i]=='{') {\n stk.push(exp[i]);\n continue;\n }\n if (stk.empty())\n return false;\n switch (exp[i]) {\n case ')':\n x = stk.top();\n stk.pop();\n if (x=='{' || x=='[')\n return false;\n break;\n case '}':\n x = stk.top();\n stk.pop();\n if (x=='(' || x=='[')\n return false;\n break;\n case ']':\n x = stk.top();\n stk.pop();\n if (x =='(' || x == '{')\n return false;\n break;\n }\n }\n return (stk.empty());\n}\nint main() {\n string expresion = \"()[(){()}]\";\n if (isBalancedExp(expresion))\n cout << \"This is Balanced Expression\";\n else\n cout << \"This is Not Balanced Expression\";\n}" }, { "code": null, "e": 3683, "s": 3670, "text": "\"()[(){()}]\"" }, { "code": null, "e": 3711, "s": 3683, "text": "This is Balanced Expression" } ]
How to convert ISO 8601 string to Date/time object in Android?
This example demonstrates how do I convert ISO 8601 string to date/time object 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:gravity="center" tools:context=".MainActivity"> <TextView android:padding="20sp" android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textSize="12sp" android:textStyle="bold"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class MainActivity extends AppCompatActivity { TextView textView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); String dtStart = "2019-08-15T09:27:37Z"; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); try { Date date = format.parse(dtStart); textView.setText("ISO 1801 date/time: " + date); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 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 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": 1153, "s": 1062, "text": "This example demonstrates how do I convert ISO 8601 string to date/time object in android." }, { "code": null, "e": 1282, "s": 1153, "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": 1347, "s": 1282, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1936, "s": 1347, "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:gravity=\"center\"\n tools:context=\".MainActivity\">\n <TextView\n android:padding=\"20sp\"\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:textSize=\"12sp\"\n android:textStyle=\"bold\"/>\n</RelativeLayout>" }, { "code": null, "e": 1993, "s": 1936, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2834, "s": 1993, "text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.TextView;\nimport java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.textView);\n String dtStart = \"2019-08-15T09:27:37Z\";\n SimpleDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss'Z'\");\n try {\n Date date = format.parse(dtStart);\n textView.setText(\"ISO 1801 date/time: \" + date);\n } catch (ParseException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 2889, "s": 2834, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3562, "s": 2889, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 3909, "s": 3562, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" } ]
Containership in C++ - GeeksforGeeks
09 Oct, 2019 We can create an object of one class into another and that object will be a member of the class. This type of relationship between classes is known as containership or has_a relationship as one class contain the object of another class. And the class which contains the object and members of another class in this kind of relationship is called a container class.The object that is part of another object is called contained object, whereas object that contains another object as its part or attribute is called container object. Difference between containership and inheritance Containership-> When features of existing class are wanted inside your new class, but, not its interfacefor eg->1)computer system has a hard disk2)car has an Engine, chassis, steering wheels. Inheritance-> When you want to force the new type to be the same type as the base class.for eg->1)computer system is an electronic device2)Car is a vehicle Employees can be of Different types as can be seen above. It can be a developer, an HR manager, a sales executive, and so on. Each one of them belongs to Different problem domain but the basic Characteristics of an employee are common to all. Syntax for Containership: // Class that is to be contained class first { . . }; // Container class class second { // creating object of first first f; . . }; Below examples explain the Containership in C++ in a better way. Example 1: // CPP program to illustrate// concept of Containership #include <iostream>using namespace std; class first {public: void showf() { cout << "Hello from first class\n"; }}; // Container classclass second { // creating object of first first f; public: // constructor second() { // calling function of first class f.showf(); }}; int main(){ // creating object of second second s;} Hello from first class Explanation:In the class second we have an object of class first. This is another type of inheritance we are witnessing. This type of inheritance is known as has_a relationship as we say that class second has an object of first class first as its member. From the object f we call the function of class first. Example 2: #include <iostream>using namespace std; class first {public: first() { cout << "Hello from first class\n"; }}; // Container classclass second { // creating object of first first f; public: // constructor second() { cout << "Hello from second class\n"; }}; int main(){ // creating object of second second s;} Hello from first class Hello from second class Explanation:In this program we have not inherited class first into class second but as we are having an object of class first as a member of class second. So when default constructor of class second is called, due to presence of object f of first class in second, default constructor of class first is called first and then default constructor of class second is called . Example 3: #include <iostream>using namespace std; class first {private: int num; public: void showf() { cout << "Hello from first class\n"; cout << "num = " << num << endl; } int& getnum() { return num; }}; // Container classclass second { // creating object of first first f; public: // constructor second() { f.getnum() = 20; f.showf(); }}; int main(){ // creating object of second second s;} Hello from first class num = 20 Explanation:With the help of containership we can only use public member/function of the class but not protected or private. In the first class we have returned the reference with the help of getnum. Then we show it by a call to showf. Example 4 #include<iostream>using namespace std; class cDate{ int mDay,mMonth,mYear;public: cDate() { mDay = 10; mMonth = 11; mYear = 1999; } cDate(int d,int m ,int y) { mDay = d; mMonth = m; mYear = y; } void display() { cout << "day" << mDay << endl; cout <<"Month" << mMonth << endl; cout << "Year" << mYear << endl; }};// Container classclass cEmployee {protected: int mId; int mBasicSal; // Contained Object cDate mBdate; public: cEmployee() { mId = 1; mBasicSal = 10000; mBdate = cDate(); } cEmployee(int, int, int, int, int); void display();}; cEmployee :: cEmployee(int i, int sal, int d, int m, int y){ mId = i; mBasicSal = sal; mBdate = cDate(d,m,y);}void cEmployee::display(){ cout << "Id : " << mId << endl; cout << "Salary :" <<mBasicSal << endl; mBdate.display();} int main(){ // Default constructor call cEmployee e1; e1.display(); // Parameterized constructor called cEmployee e2(2,20000,11,11,1999); e2.display(); return 0;} output Id : 1 Salary :10000 day 10 Month 11 Year 1999 Id : 2 Salary :20000 day 11 Month 11 Year 1999 omkarjadhav880 C++-Class and Object C++-Inheritance cpp-containers-library C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) Convert string to char array in C++ List in C++ Standard Template Library (STL) Iterators in C++ STL std::string class in C++ Inline Functions in C++
[ { "code": null, "e": 24124, "s": 24096, "text": "\n09 Oct, 2019" }, { "code": null, "e": 24654, "s": 24124, "text": "We can create an object of one class into another and that object will be a member of the class. This type of relationship between classes is known as containership or has_a relationship as one class contain the object of another class. And the class which contains the object and members of another class in this kind of relationship is called a container class.The object that is part of another object is called contained object, whereas object that contains another object as its part or attribute is called container object." }, { "code": null, "e": 24703, "s": 24654, "text": "Difference between containership and inheritance" }, { "code": null, "e": 24895, "s": 24703, "text": "Containership-> When features of existing class are wanted inside your new class, but, not its interfacefor eg->1)computer system has a hard disk2)car has an Engine, chassis, steering wheels." }, { "code": null, "e": 25051, "s": 24895, "text": "Inheritance-> When you want to force the new type to be the same type as the base class.for eg->1)computer system is an electronic device2)Car is a vehicle" }, { "code": null, "e": 25294, "s": 25051, "text": "Employees can be of Different types as can be seen above. It can be a developer, an HR manager, a sales executive, and so on. Each one of them belongs to Different problem domain but the basic Characteristics of an employee are common to all." }, { "code": null, "e": 25320, "s": 25294, "text": "Syntax for Containership:" }, { "code": null, "e": 25479, "s": 25320, "text": "// Class that is to be contained\nclass first {\n .\n .\n};\n\n// Container class\nclass second {\n\n // creating object of first\n first f;\n .\n .\n};\n" }, { "code": null, "e": 25544, "s": 25479, "text": "Below examples explain the Containership in C++ in a better way." }, { "code": null, "e": 25555, "s": 25544, "text": "Example 1:" }, { "code": "// CPP program to illustrate// concept of Containership #include <iostream>using namespace std; class first {public: void showf() { cout << \"Hello from first class\\n\"; }}; // Container classclass second { // creating object of first first f; public: // constructor second() { // calling function of first class f.showf(); }}; int main(){ // creating object of second second s;}", "e": 25992, "s": 25555, "text": null }, { "code": null, "e": 26016, "s": 25992, "text": "Hello from first class\n" }, { "code": null, "e": 26326, "s": 26016, "text": "Explanation:In the class second we have an object of class first. This is another type of inheritance we are witnessing. This type of inheritance is known as has_a relationship as we say that class second has an object of first class first as its member. From the object f we call the function of class first." }, { "code": null, "e": 26337, "s": 26326, "text": "Example 2:" }, { "code": "#include <iostream>using namespace std; class first {public: first() { cout << \"Hello from first class\\n\"; }}; // Container classclass second { // creating object of first first f; public: // constructor second() { cout << \"Hello from second class\\n\"; }}; int main(){ // creating object of second second s;}", "e": 26696, "s": 26337, "text": null }, { "code": null, "e": 26744, "s": 26696, "text": "Hello from first class\nHello from second class\n" }, { "code": null, "e": 27116, "s": 26744, "text": "Explanation:In this program we have not inherited class first into class second but as we are having an object of class first as a member of class second. So when default constructor of class second is called, due to presence of object f of first class in second, default constructor of class first is called first and then default constructor of class second is called ." }, { "code": null, "e": 27127, "s": 27116, "text": "Example 3:" }, { "code": "#include <iostream>using namespace std; class first {private: int num; public: void showf() { cout << \"Hello from first class\\n\"; cout << \"num = \" << num << endl; } int& getnum() { return num; }}; // Container classclass second { // creating object of first first f; public: // constructor second() { f.getnum() = 20; f.showf(); }}; int main(){ // creating object of second second s;}", "e": 27599, "s": 27127, "text": null }, { "code": null, "e": 27632, "s": 27599, "text": "Hello from first class\nnum = 20\n" }, { "code": null, "e": 27868, "s": 27632, "text": "Explanation:With the help of containership we can only use public member/function of the class but not protected or private. In the first class we have returned the reference with the help of getnum. Then we show it by a call to showf." }, { "code": null, "e": 27878, "s": 27868, "text": "Example 4" }, { "code": "#include<iostream>using namespace std; class cDate{ int mDay,mMonth,mYear;public: cDate() { mDay = 10; mMonth = 11; mYear = 1999; } cDate(int d,int m ,int y) { mDay = d; mMonth = m; mYear = y; } void display() { cout << \"day\" << mDay << endl; cout <<\"Month\" << mMonth << endl; cout << \"Year\" << mYear << endl; }};// Container classclass cEmployee {protected: int mId; int mBasicSal; // Contained Object cDate mBdate; public: cEmployee() { mId = 1; mBasicSal = 10000; mBdate = cDate(); } cEmployee(int, int, int, int, int); void display();}; cEmployee :: cEmployee(int i, int sal, int d, int m, int y){ mId = i; mBasicSal = sal; mBdate = cDate(d,m,y);}void cEmployee::display(){ cout << \"Id : \" << mId << endl; cout << \"Salary :\" <<mBasicSal << endl; mBdate.display();} int main(){ // Default constructor call cEmployee e1; e1.display(); // Parameterized constructor called cEmployee e2(2,20000,11,11,1999); e2.display(); return 0;}", "e": 29020, "s": 27878, "text": null }, { "code": null, "e": 29122, "s": 29020, "text": "output\nId : 1\nSalary :10000\nday 10\nMonth 11\nYear 1999\nId : 2\nSalary :20000\nday 11\nMonth 11\nYear 1999\n" }, { "code": null, "e": 29137, "s": 29122, "text": "omkarjadhav880" }, { "code": null, "e": 29158, "s": 29137, "text": "C++-Class and Object" }, { "code": null, "e": 29174, "s": 29158, "text": "C++-Inheritance" }, { "code": null, "e": 29197, "s": 29174, "text": "cpp-containers-library" }, { "code": null, "e": 29201, "s": 29197, "text": "C++" }, { "code": null, "e": 29205, "s": 29201, "text": "CPP" }, { "code": null, "e": 29303, "s": 29205, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29331, "s": 29303, "text": "Operator Overloading in C++" }, { "code": null, "e": 29351, "s": 29331, "text": "Polymorphism in C++" }, { "code": null, "e": 29375, "s": 29351, "text": "Sorting a vector in C++" }, { "code": null, "e": 29408, "s": 29375, "text": "Friend class and function in C++" }, { "code": null, "e": 29452, "s": 29408, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 29488, "s": 29452, "text": "Convert string to char array in C++" }, { "code": null, "e": 29532, "s": 29488, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 29553, "s": 29532, "text": "Iterators in C++ STL" }, { "code": null, "e": 29578, "s": 29553, "text": "std::string class in C++" } ]
How to Align Column DIVs as Left-Center-Right with CSS Flex
To align items of a flex container along its main axis by distributing space around it, we use the justify-content property of CSS. The syntax of CSS justify-content property is as follows − Selector { display: flex; justify-content: /*value*/ } The following examples illustrate CSS justify-content property. Live Demo <!DOCTYPE html> <html> <head> <style> #root { margin: 5%; display: flex; justify-content: space-between; } #one { float:left; box-shadow: inset 0 0 34px #b798e1; } #two { box-shadow: inset 0 0 34px #236fa0; } #three { box-shadow: inset 0 0 34px #43946a; } .element { padding: 7%; border-radius: 15%; } </style> </head> <body> <div id="root"> <div class="element" id="one">1</div> <div class="element" id="two">2</div> <div class="element" id="three">3</div> </div> </body> </html> This gives the following output Live Demo <!DOCTYPE html> <html> <head> <style> #root { margin: 5%; padding: 2%; display: flex; justify-content: space-evenly; box-shadow: inset 0 10px 40px magenta; font-weight: bold; } div > div { padding: 2%; border-radius: 15%; } div:nth-of-type(even) { box-shadow: inset 2px 2px 20px orange; } div > div:nth-of-type(odd) { box-shadow: inset 2px 2px 20px lightblue; } </style> </head> <body> <div id="root"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> </div> </body> </html> This gives the following output
[ { "code": null, "e": 1194, "s": 1062, "text": "To align items of a flex container along its main axis by distributing space around it, we use the justify-content property of CSS." }, { "code": null, "e": 1253, "s": 1194, "text": "The syntax of CSS justify-content property is as follows −" }, { "code": null, "e": 1314, "s": 1253, "text": "Selector {\n display: flex;\n justify-content: /*value*/\n}" }, { "code": null, "e": 1378, "s": 1314, "text": "The following examples illustrate CSS justify-content property." }, { "code": null, "e": 1389, "s": 1378, "text": " Live Demo" }, { "code": null, "e": 2131, "s": 1389, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n #root {\n margin: 5%;\n display: flex;\n justify-content: space-between;\n }\n #one {\n float:left;\n box-shadow: inset 0 0 34px #b798e1;\n }\n #two {\n box-shadow: inset 0 0 34px #236fa0;\n }\n #three {\n box-shadow: inset 0 0 34px #43946a;\n }\n .element {\n padding: 7%;\n border-radius: 15%;\n }\n </style>\n </head>\n <body>\n <div id=\"root\">\n <div class=\"element\" id=\"one\">1</div>\n <div class=\"element\" id=\"two\">2</div>\n <div class=\"element\" id=\"three\">3</div>\n </div>\n </body>\n</html>" }, { "code": null, "e": 2163, "s": 2131, "text": "This gives the following output" }, { "code": null, "e": 2174, "s": 2163, "text": " Live Demo" }, { "code": null, "e": 2959, "s": 2174, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n #root {\n margin: 5%;\n padding: 2%;\n display: flex;\n justify-content: space-evenly;\n box-shadow: inset 0 10px 40px magenta;\n font-weight: bold;\n }\n div > div {\n padding: 2%;\n border-radius: 15%;\n }\n div:nth-of-type(even) {\n box-shadow: inset 2px 2px 20px orange;\n }\n div > div:nth-of-type(odd) {\n box-shadow: inset 2px 2px 20px lightblue;\n }\n </style>\n </head>\n <body>\n <div id=\"root\">\n <div>1</div>\n <div>2</div>\n <div>3</div>\n <div>4</div>\n <div>5</div>\n <div>6</div>\n </div>\n </body>\n</html>" }, { "code": null, "e": 2991, "s": 2959, "text": "This gives the following output" } ]
SWING - Quick Guide
Swing API is a set of extensible GUI Components to ease the developer's life to create JAVA based Front End/GUI Applications. It is build on top of AWT API and acts as a replacement of AWT API, since it has almost every control corresponding to AWT controls. Swing component follows a Model-View-Controller architecture to fulfill the following criterias. A single API is to be sufficient to support multiple look and feel. A single API is to be sufficient to support multiple look and feel. API is to be model driven so that the highest level API is not required to have data. API is to be model driven so that the highest level API is not required to have data. API is to use the Java Bean model so that Builder Tools and IDE can provide better services to the developers for use. API is to use the Java Bean model so that Builder Tools and IDE can provide better services to the developers for use. Swing API architecture follows loosely based MVC architecture in the following manner. Model represents component's data. Model represents component's data. View represents visual representation of the component's data. View represents visual representation of the component's data. Controller takes the input from the user on the view and reflects the changes in Component's data. Controller takes the input from the user on the view and reflects the changes in Component's data. Swing component has Model as a seperate element, while the View and Controller part are clubbed in the User Interface elements. Because of which, Swing has a pluggable look-and-feel architecture. Swing component has Model as a seperate element, while the View and Controller part are clubbed in the User Interface elements. Because of which, Swing has a pluggable look-and-feel architecture. Light Weight − Swing components are independent of native Operating System's API as Swing API controls are rendered mostly using pure JAVA code instead of underlying operating system calls. Light Weight − Swing components are independent of native Operating System's API as Swing API controls are rendered mostly using pure JAVA code instead of underlying operating system calls. Rich Controls − Swing provides a rich set of advanced controls like Tree, TabbedPane, slider, colorpicker, and table controls. Rich Controls − Swing provides a rich set of advanced controls like Tree, TabbedPane, slider, colorpicker, and table controls. Highly Customizable − Swing controls can be customized in a very easy way as visual apperance is independent of internal representation. Highly Customizable − Swing controls can be customized in a very easy way as visual apperance is independent of internal representation. Pluggable look-and-feel − SWING based GUI Application look and feel can be changed at run-time, based on available values. Pluggable look-and-feel − SWING based GUI Application look and feel can be changed at run-time, based on available values. This section guides you on how to download and set up Java on your machine. Please use the following steps to set up the environment. Java SE is freely available from the link Download Java. Hence, you can download a version based on your operating system. Follow the instructions to download Java and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set the environment variables to point to the correct installation directories. Assuming you have installed Java in c:\Program Files\java\jdk directory − Step 1 − Right-click on 'My Computer' and select 'Properties'. Step 2 − Click the 'Environment variables' button under the 'Advanced' tab. Step 3 − Alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'. Assuming you have installed Java in c:\Program Files\java\jdk directory − Step 1 − Edit the 'C:\autoexec.bat' file and add the following line at the end: 'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'. Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your Shell documentation if you have trouble doing this. Example, if you use bash as your shell, then you would add the following line to the end '.bashrc: export PATH=/path/to/java:$PATH'. To write your Java programs, you will need a text editor. There are even more sophisticated IDE available in the market. But for now, you can consider one of the following − Notepad − On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad. Notepad − On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad. Netbeans − Netbeans is a Java IDE that is open source and free, which can be downloaded from https://www.netbeans.org/index.html. Netbeans − Netbeans is a Java IDE that is open source and free, which can be downloaded from https://www.netbeans.org/index.html. Eclipse − Eclipse is also a Java IDE developed by the Eclipse open source community and can be downloaded from https://www.eclipse.org/. Eclipse − Eclipse is also a Java IDE developed by the Eclipse open source community and can be downloaded from https://www.eclipse.org/. Every user interface considers the following three main aspects − UI Elements − These are the core visual elements the user eventually sees and interacts with. GWT provides a huge list of widely used and common elements varying from basic to complex, which we will cover in this tutorial. UI Elements − These are the core visual elements the user eventually sees and interacts with. GWT provides a huge list of widely used and common elements varying from basic to complex, which we will cover in this tutorial. Layouts − They define how UI elements should be organized on the screen and provide a final look and feel to the GUI (Graphical User Interface). This part will be covered in the Layout chapter. Layouts − They define how UI elements should be organized on the screen and provide a final look and feel to the GUI (Graphical User Interface). This part will be covered in the Layout chapter. Behavior − These are the events which occur when the user interacts with UI elements. This part will be covered in the Event Handling chapter. Behavior − These are the events which occur when the user interacts with UI elements. This part will be covered in the Event Handling chapter. Every SWING controls inherits properties from the following Component class hiearchy. A Component is the abstract base class for the non menu user-interface controls of SWING. Component represents an object with graphical representation A Container is a component that can contain other SWING components A JComponent is a base class for all SWING UI components. In order to use a SWING component that inherits from JComponent, the component must be in a containment hierarchy whose root is a top-level SWING container Following is the list of commonly used controls while designing GUI using SWING. A JLabel object is a component for placing text in a container. This class creates a labeled button. A JColorChooser provides a pane of controls designed to allow a user to manipulate and select a color. A JCheckBox is a graphical component that can be in either an on (true) or off (false) state. The JRadioButton class is a graphical component that can be in either an on (true) or off (false) state. in a group. A JList component presents the user with a scrolling list of text items. A JComboBox component presents the user with a to show up menu of choices. A JTextField object is a text component that allows for the editing of a single line of text. A JPasswordField object is a text component specialized for password entry. A JTextArea object is a text component that allows editing of a multiple lines of text. A ImageIcon control is an implementation of the Icon interface that paints Icons from Images A Scrollbar control represents a scroll bar component in order to enable the user to select from range of values. JOptionPane provides set of standard dialog boxes that prompt users for a value or informs them of something. A JFileChooser control represents a dialog window from which the user can select a file. As the task progresses towards completion, the progress bar displays the task's percentage of completion. A JSlider lets the user graphically select a value by sliding a knob within a bounded interval. A JSpinner is a single line input field that lets the user select a number or an object value from an ordered sequence. In this chapter, you will learn about Events, its types, and also learn how to handle an event. Example is provided at the end of the chapter for better understanding. Change in the state of an object is known as Event, i.e., event describes the change in the state of the source. Events are generated as a result of user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from the list, and scrolling the page are the activities that causes an event to occur. The events can be broadly classified into two categories − Foreground Events − These events require direct interaction of the user. They are generated as consequences of a person interacting with the graphical components in the Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page, etc. Foreground Events − These events require direct interaction of the user. They are generated as consequences of a person interacting with the graphical components in the Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page, etc. Background Events − These events require the interaction of the end user. Operating system interrupts, hardware or software failure, timer expiration, and operation completion are some examples of background events. Background Events − These events require the interaction of the end user. Operating system interrupts, hardware or software failure, timer expiration, and operation completion are some examples of background events. Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism has a code which is known as an event handler, that is executed when an event occurs. Java uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events. The Delegation Event Model has the following key participants. Source − The source is an object on which the event occurs. Source is responsible for providing information of the occurred event to it's handler. Java provide us with classes for the source object. Source − The source is an object on which the event occurs. Source is responsible for providing information of the occurred event to it's handler. Java provide us with classes for the source object. Listener − It is also known as event handler. The listener is responsible for generating a response to an event. From the point of view of Java implementation, the listener is also an object. The listener waits till it receives an event. Once the event is received, the listener processes the event and then returns. Listener − It is also known as event handler. The listener is responsible for generating a response to an event. From the point of view of Java implementation, the listener is also an object. The listener waits till it receives an event. Once the event is received, the listener processes the event and then returns. The benefit of this approach is that the user interface logic is completely separated from the logic that generates the event. The user interface element is able to delegate the processing of an event to a separate piece of code. In this model, the listener needs to be registered with the source object so that the listener can receive the event notification. This is an efficient way of handling the event because the event notifications are sent only to those listeners who want to receive them. Step 1 − The user clicks the button and the event is generated. Step 2 − The object of concerned event class is created automatically and information about the source and the event get populated within the same object. Step 3 − Event object is forwarded to the method of the registered listener class. Step 4 − The method is gets executed and returns. In order to design a listener class, you have to develop some listener interfaces. These Listener interfaces forecast some public abstract callback methods, which must be implemented by the listener class. In order to design a listener class, you have to develop some listener interfaces. These Listener interfaces forecast some public abstract callback methods, which must be implemented by the listener class. If you do not implement any of the predefined interfaces, then your class cannot act as a listener class for a source object. If you do not implement any of the predefined interfaces, then your class cannot act as a listener class for a source object. These are the methods that are provided by API provider and are defined by the application programmer and invoked by the application developer. Here the callback methods represent an event method. In response to an event, java jre will fire callback method. All such callback methods are provided in listener interfaces. If a component wants some listener to listen ot its events, the source must register itself to the listener. Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui > SwingControlDemo.java package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SwingControlDemo { private JFrame mainFrame; private JLabel headerLabel; private JLabel statusLabel; private JPanel controlPanel; public SwingControlDemo(){ prepareGUI(); } public static void main(String[] args){ SwingControlDemo swingControlDemo = new SwingControlDemo(); swingControlDemo.showEventDemo(); } private void prepareGUI(){ mainFrame = new JFrame("Java SWING Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); headerLabel = new JLabel("",JLabel.CENTER ); statusLabel = new JLabel("",JLabel.CENTER); statusLabel.setSize(350,100); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showEventDemo(){ headerLabel.setText("Control in action: Button"); JButton okButton = new JButton("OK"); JButton submitButton = new JButton("Submit"); JButton cancelButton = new JButton("Cancel"); okButton.setActionCommand("OK"); submitButton.setActionCommand("Submit"); cancelButton.setActionCommand("Cancel"); okButton.addActionListener(new ButtonClickListener()); submitButton.addActionListener(new ButtonClickListener()); cancelButton.addActionListener(new ButtonClickListener()); controlPanel.add(okButton); controlPanel.add(submitButton); controlPanel.add(cancelButton); mainFrame.setVisible(true); } private class ButtonClickListener implements ActionListener{ public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if( command.equals( "OK" )) { statusLabel.setText("Ok Button clicked."); } else if( command.equals( "Submit" ) ) { statusLabel.setText("Submit Button clicked."); } else { statusLabel.setText("Cancel Button clicked."); } } } } Compile the program using the command prompt. Go to D:/ > SWING and type the following command. D:\AWT>javac com\tutorialspoint\gui\SwingControlDemo.java If no error occurs, it means the compilation is successful. Run the program using the following command. D:\AWT>java com.tutorialspoint.gui.SwingControlDemo Verify the following output. Event classes represent the event. Java provides various Event classes, however, only those which are more frequently used will be discussed. It is the root class from which all event state objects shall be derived. All Events are constructed with a reference to the object, the source, that is logically deemed to be the object upon which the Event in question initially occurred upon. This class is defined in java.util package. Following is the declaration for java.util.EventObject class − public class EventObject extends Object implements Serializable Following are the fields for java.util.EventObject class − protected Object source − The object on which the Event initially occurred. EventObject(Object source) Constructs a prototypical Event. Object getSource() The object on which the Event initially occurred. String toString() Returns a String representation of this EventObject. This class inherits methods from the following class − java.lang.Object Following is the list of commonly used Event classes. It is the root event class for all SWING events. This class and its subclasses supercede the original java.awt.Event class. The ActionEvent is generated when the button is clicked or the item of a list is double-clicked. The InputEvent class is the root event class for all component-level input events. On entering the character the Key event is generated. This event indicates a mouse action occurred in a component. The object of this class represents the change in the state of a window. The object of this class represents the adjustment event emitted by Adjustable objects. The object of this class represents the change in the state of a window. The object of this class represents the change in the state of a window. The object of this class represents the change in the state of a window. The object of this class represents the change in the state of a window. Event listeners represent the interfaces responsible to handle events. Java provides various Event listener classes, however, only those which are more frequently used will be discussed. Every method of an event listener method has a single argument as an object which is the subclass of EventObject class. For example, mouse event listener methods will accept instance of MouseEvent, where MouseEvent derives from EventObject. It is a marker interface which every listener interface has to extend. This class is defined in java.util package. Following is the declaration for java.util.EventListener interface − public interface EventListener Following is the list of commonly used event listeners. This interface is used for receiving the action events. This interface is used for receiving the component events. This interface is used for receiving the item events. This interface is used for receiving the key events. This interface is used for receiving the mouse events. This interface is used for receiving the window events. This interface is used for receiving the adjustment events. This interface is used for receiving the container events. This interface is used for receiving the mouse motion events. This interface is used for receiving the focus events. Adapters are abstract classes for receiving various events. The methods in these classes are empty. These classes exist as convenience for creating listener objects. Following is the list of commonly used adapters while listening GUI events in SWING. An abstract adapter class for receiving focus events. An abstract adapter class for receiving key events. An abstract adapter class for receiving mouse events. An abstract adapter class for receiving mouse motion events. An abstract adapter class for receiving window events. Layout refers to the arrangement of components within the container. In another way, it could be said that layout is placing the components at a particular position within the container. The task of laying out the controls is done automatically by the Layout Manager. The layout manager automatically positions all the components within the container. Even if you do not use the layout manager, the components are still positioned by the default layout manager. It is possible to lay out the controls by hand, however, it becomes very difficult because of the following two reasons. It is very tedious to handle a large number of controls within the container. It is very tedious to handle a large number of controls within the container. Usually, the width and height information of a component is not given when we need to arrange them. Usually, the width and height information of a component is not given when we need to arrange them. Java provides various layout managers to position the controls. Properties like size, shape, and arrangement varies from one layout manager to the other. When the size of the applet or the application window changes, the size, shape, and arrangement of the components also changes in response, i.e. the layout managers adapt to the dimensions of the appletviewer or the application window. The layout manager is associated with every Container object. Each layout manager is an object of the class that implements the LayoutManager interface. Following are the interfaces defining the functionalities of Layout Managers. The LayoutManager interface declares those methods which need to be implemented by the class, whose object will act as a layout manager. The LayoutManager2 is the sub-interface of the LayoutManager. This interface is for those classes that know how to layout containers based on layout constraint object. Following is the list of commonly used controls while designing GUI using AWT. The borderlayout arranges the components to fit in the five regions: east, west, north, south, and center. The CardLayout object treats each component in the container as a card. Only one card is visible at a time. The FlowLayout is the default layout. It layout the components in a directional flow. The GridLayout manages the components in the form of a rectangular grid. This is the most flexible layout manager class. The object of GridBagLayout aligns the component vertically, horizontally, or along their baseline without requiring the components of the same size. The GroupLayout hierarchically groups the components in order to position them in a Container. A SpringLayout positions the children of its associated container according to a set of constraints. As we know that every top-level window has a menu bar associated with it. This menu bar consists of various menu choices available to the end user. Further, each choice contains a list of options, which is called drop-down menus. Menu and MenuItem controls are subclass of MenuComponent class. The JMenuBar object is associated with the top-level window. The items in the menu must belong to the JMenuItem or any of its subclass. The JMenu object is a pull-down menu component which is displayed from the menu bar. JCheckboxMenuItem is the subclass of JMenuItem. JRadioButtonMenuItem is the subclass of JMenuItem. JPopupMenu can be dynamically popped up at a specified position within a component. Containers are an integral part of SWING GUI components. A container provides a space where a component can be located. A Container in AWT is a component itself and it provides the capability to add a component to itself. Following are certain noticable points to be considered. Sub classes of Container are called as Container. For example, JPanel, JFrame and JWindow. Sub classes of Container are called as Container. For example, JPanel, JFrame and JWindow. Container can add only a Component to itself. Container can add only a Component to itself. A default layout is present in each container which can be overridden using setLayout method. A default layout is present in each container which can be overridden using setLayout method. Following is the list of commonly used containers while designed GUI using SWING. JPanel is the simplest container. It provides space in which any other component can be placed, including other panels. A JFrame is a top-level window with a title and a border. A JWindow object is a top-level window with no borders and no menubar. 30 Lectures 3.5 hours Pranjal Srivastava 13 Lectures 1 hours Pranjal Srivastava 25 Lectures 4.5 hours Emenwa Global, Ejike IfeanyiChukwu 14 Lectures 1.5 hours Travis Rose 14 Lectures 1 hours Travis Rose Print Add Notes Bookmark this page
[ { "code": null, "e": 2119, "s": 1763, "text": "Swing API is a set of extensible GUI Components to ease the developer's life to create JAVA based Front End/GUI Applications. It is build on top of AWT API and acts as a replacement of AWT API, since it has almost every control corresponding to AWT controls. Swing component follows a Model-View-Controller architecture to fulfill the following criterias." }, { "code": null, "e": 2187, "s": 2119, "text": "A single API is to be sufficient to support multiple look and feel." }, { "code": null, "e": 2255, "s": 2187, "text": "A single API is to be sufficient to support multiple look and feel." }, { "code": null, "e": 2341, "s": 2255, "text": "API is to be model driven so that the highest level API is not required to have data." }, { "code": null, "e": 2427, "s": 2341, "text": "API is to be model driven so that the highest level API is not required to have data." }, { "code": null, "e": 2546, "s": 2427, "text": "API is to use the Java Bean model so that Builder Tools and IDE can provide better services to the developers for use." }, { "code": null, "e": 2665, "s": 2546, "text": "API is to use the Java Bean model so that Builder Tools and IDE can provide better services to the developers for use." }, { "code": null, "e": 2752, "s": 2665, "text": "Swing API architecture follows loosely based MVC architecture in the following manner." }, { "code": null, "e": 2787, "s": 2752, "text": "Model represents component's data." }, { "code": null, "e": 2822, "s": 2787, "text": "Model represents component's data." }, { "code": null, "e": 2885, "s": 2822, "text": "View represents visual representation of the component's data." }, { "code": null, "e": 2948, "s": 2885, "text": "View represents visual representation of the component's data." }, { "code": null, "e": 3047, "s": 2948, "text": "Controller takes the input from the user on the view and reflects the changes in Component's data." }, { "code": null, "e": 3146, "s": 3047, "text": "Controller takes the input from the user on the view and reflects the changes in Component's data." }, { "code": null, "e": 3342, "s": 3146, "text": "Swing component has Model as a seperate element, while the View and Controller part are clubbed in the User Interface elements. Because of which, Swing has a pluggable look-and-feel architecture." }, { "code": null, "e": 3538, "s": 3342, "text": "Swing component has Model as a seperate element, while the View and Controller part are clubbed in the User Interface elements. Because of which, Swing has a pluggable look-and-feel architecture." }, { "code": null, "e": 3728, "s": 3538, "text": "Light Weight − Swing components are independent of native Operating System's API as Swing API controls are rendered mostly using pure JAVA code instead of underlying operating system calls." }, { "code": null, "e": 3918, "s": 3728, "text": "Light Weight − Swing components are independent of native Operating System's API as Swing API controls are rendered mostly using pure JAVA code instead of underlying operating system calls." }, { "code": null, "e": 4045, "s": 3918, "text": "Rich Controls − Swing provides a rich set of advanced controls like Tree, TabbedPane, slider, colorpicker, and table controls." }, { "code": null, "e": 4172, "s": 4045, "text": "Rich Controls − Swing provides a rich set of advanced controls like Tree, TabbedPane, slider, colorpicker, and table controls." }, { "code": null, "e": 4309, "s": 4172, "text": "Highly Customizable − Swing controls can be customized in a very easy way as visual apperance is independent of internal representation." }, { "code": null, "e": 4446, "s": 4309, "text": "Highly Customizable − Swing controls can be customized in a very easy way as visual apperance is independent of internal representation." }, { "code": null, "e": 4569, "s": 4446, "text": "Pluggable look-and-feel − SWING based GUI Application look and feel can be changed at run-time, based on available values." }, { "code": null, "e": 4692, "s": 4569, "text": "Pluggable look-and-feel − SWING based GUI Application look and feel can be changed at run-time, based on available values." }, { "code": null, "e": 4826, "s": 4692, "text": "This section guides you on how to download and set up Java on your machine. Please use the following steps to set up the environment." }, { "code": null, "e": 4949, "s": 4826, "text": "Java SE is freely available from the link Download Java. Hence, you can download a version based on your operating system." }, { "code": null, "e": 5184, "s": 4949, "text": "Follow the instructions to download Java and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set the environment variables to point to the correct installation directories." }, { "code": null, "e": 5258, "s": 5184, "text": "Assuming you have installed Java in c:\\Program Files\\java\\jdk directory −" }, { "code": null, "e": 5321, "s": 5258, "text": "Step 1 − Right-click on 'My Computer' and select 'Properties'." }, { "code": null, "e": 5397, "s": 5321, "text": "Step 2 − Click the 'Environment variables' button under the 'Advanced' tab." }, { "code": null, "e": 5637, "s": 5397, "text": "Step 3 − Alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\\WINDOWS\\SYSTEM32', then change your path to read 'C:\\WINDOWS\\SYSTEM32;c:\\Program Files\\java\\jdk\\bin'." }, { "code": null, "e": 5711, "s": 5637, "text": "Assuming you have installed Java in c:\\Program Files\\java\\jdk directory −" }, { "code": null, "e": 5840, "s": 5711, "text": "Step 1 − Edit the 'C:\\autoexec.bat' file and add the following line at the end: 'SET PATH=%PATH%;C:\\Program Files\\java\\jdk\\bin'." }, { "code": null, "e": 6003, "s": 5840, "text": "Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your Shell documentation if you have trouble doing this." }, { "code": null, "e": 6136, "s": 6003, "text": "Example, if you use bash as your shell, then you would add the following line to the end '.bashrc: export PATH=/path/to/java:$PATH'." }, { "code": null, "e": 6310, "s": 6136, "text": "To write your Java programs, you will need a text editor. There are even more sophisticated IDE available in the market. But for now, you can consider one of the following −" }, { "code": null, "e": 6430, "s": 6310, "text": "Notepad − On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad." }, { "code": null, "e": 6550, "s": 6430, "text": "Notepad − On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad." }, { "code": null, "e": 6680, "s": 6550, "text": "Netbeans − Netbeans is a Java IDE that is open source and free, which can be downloaded from https://www.netbeans.org/index.html." }, { "code": null, "e": 6810, "s": 6680, "text": "Netbeans − Netbeans is a Java IDE that is open source and free, which can be downloaded from https://www.netbeans.org/index.html." }, { "code": null, "e": 6947, "s": 6810, "text": "Eclipse − Eclipse is also a Java IDE developed by the Eclipse open source community and can be downloaded from https://www.eclipse.org/." }, { "code": null, "e": 7084, "s": 6947, "text": "Eclipse − Eclipse is also a Java IDE developed by the Eclipse open source community and can be downloaded from https://www.eclipse.org/." }, { "code": null, "e": 7150, "s": 7084, "text": "Every user interface considers the following three main aspects −" }, { "code": null, "e": 7373, "s": 7150, "text": "UI Elements − These are the core visual elements the user eventually sees and interacts with. GWT provides a huge list of widely used and common elements varying from basic to complex, which we will cover in this tutorial." }, { "code": null, "e": 7596, "s": 7373, "text": "UI Elements − These are the core visual elements the user eventually sees and interacts with. GWT provides a huge list of widely used and common elements varying from basic to complex, which we will cover in this tutorial." }, { "code": null, "e": 7790, "s": 7596, "text": "Layouts − They define how UI elements should be organized on the screen and provide a final look and feel to the GUI (Graphical User Interface). This part will be covered in the Layout chapter." }, { "code": null, "e": 7984, "s": 7790, "text": "Layouts − They define how UI elements should be organized on the screen and provide a final look and feel to the GUI (Graphical User Interface). This part will be covered in the Layout chapter." }, { "code": null, "e": 8127, "s": 7984, "text": "Behavior − These are the events which occur when the user interacts with UI elements. This part will be covered in the Event Handling chapter." }, { "code": null, "e": 8270, "s": 8127, "text": "Behavior − These are the events which occur when the user interacts with UI elements. This part will be covered in the Event Handling chapter." }, { "code": null, "e": 8356, "s": 8270, "text": "Every SWING controls inherits properties from the following Component class hiearchy." }, { "code": null, "e": 8507, "s": 8356, "text": "A Component is the abstract base class for the non menu user-interface controls of SWING. Component represents an object with graphical representation" }, { "code": null, "e": 8574, "s": 8507, "text": "A Container is a component that can contain other SWING components" }, { "code": null, "e": 8788, "s": 8574, "text": "A JComponent is a base class for all SWING UI components. In order to use a SWING component that inherits from JComponent, the component must be in a containment hierarchy whose root is a top-level SWING container" }, { "code": null, "e": 8869, "s": 8788, "text": "Following is the list of commonly used controls while designing GUI using SWING." }, { "code": null, "e": 8933, "s": 8869, "text": "A JLabel object is a component for placing text in a container." }, { "code": null, "e": 8970, "s": 8933, "text": "This class creates a labeled button." }, { "code": null, "e": 9073, "s": 8970, "text": "A JColorChooser provides a pane of controls designed to allow a user to manipulate and select a color." }, { "code": null, "e": 9167, "s": 9073, "text": "A JCheckBox is a graphical component that can be in either an on (true) or off (false) state." }, { "code": null, "e": 9284, "s": 9167, "text": "The JRadioButton class is a graphical component that can be in either an on (true) or off (false) state. in a group." }, { "code": null, "e": 9357, "s": 9284, "text": "A JList component presents the user with a scrolling list of text items." }, { "code": null, "e": 9432, "s": 9357, "text": "A JComboBox component presents the user with a to show up menu of choices." }, { "code": null, "e": 9526, "s": 9432, "text": "A JTextField object is a text component that allows for the editing of a single line of text." }, { "code": null, "e": 9602, "s": 9526, "text": "A JPasswordField object is a text component specialized for password entry." }, { "code": null, "e": 9690, "s": 9602, "text": "A JTextArea object is a text component that allows editing of a multiple lines of text." }, { "code": null, "e": 9783, "s": 9690, "text": "A ImageIcon control is an implementation of the Icon interface that paints Icons from Images" }, { "code": null, "e": 9897, "s": 9783, "text": "A Scrollbar control represents a scroll bar component in order to enable the user to select from range of values." }, { "code": null, "e": 10007, "s": 9897, "text": "JOptionPane provides set of standard dialog boxes that prompt users for a value or informs them of something." }, { "code": null, "e": 10096, "s": 10007, "text": "A JFileChooser control represents a dialog window from which the user can select a file." }, { "code": null, "e": 10202, "s": 10096, "text": "As the task progresses towards completion, the progress bar displays the task's percentage of completion." }, { "code": null, "e": 10298, "s": 10202, "text": "A JSlider lets the user graphically select a value by sliding a knob within a bounded interval." }, { "code": null, "e": 10418, "s": 10298, "text": "A JSpinner is a single line input field that lets the user select a number or an object value from an ordered sequence." }, { "code": null, "e": 10586, "s": 10418, "text": "In this chapter, you will learn about Events, its types, and also learn how to handle an event. Example is provided at the end of the chapter for better understanding." }, { "code": null, "e": 10996, "s": 10586, "text": "Change in the state of an object is known as Event, i.e., event describes the change in the state of the source. Events are generated as a result of user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from the list, and scrolling the page are the activities that causes an event to occur." }, { "code": null, "e": 11055, "s": 10996, "text": "The events can be broadly classified into two categories −" }, { "code": null, "e": 11396, "s": 11055, "text": "Foreground Events − These events require direct interaction of the user. They are generated as consequences of a person interacting with the graphical components in the Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page, etc." }, { "code": null, "e": 11737, "s": 11396, "text": "Foreground Events − These events require direct interaction of the user. They are generated as consequences of a person interacting with the graphical components in the Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page, etc." }, { "code": null, "e": 11953, "s": 11737, "text": "Background Events − These events require the interaction of the end user. Operating system interrupts, hardware or software failure, timer expiration, and operation completion are some examples of background events." }, { "code": null, "e": 12169, "s": 11953, "text": "Background Events − These events require the interaction of the end user. Operating system interrupts, hardware or software failure, timer expiration, and operation completion are some examples of background events." }, { "code": null, "e": 12377, "s": 12169, "text": "Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism has a code which is known as an event handler, that is executed when an event occurs." }, { "code": null, "e": 12513, "s": 12377, "text": "Java uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events." }, { "code": null, "e": 12576, "s": 12513, "text": "The Delegation Event Model has the following key participants." }, { "code": null, "e": 12775, "s": 12576, "text": "Source − The source is an object on which the event occurs. Source is responsible for providing information of the occurred event to it's handler. Java provide us with classes for the source object." }, { "code": null, "e": 12974, "s": 12775, "text": "Source − The source is an object on which the event occurs. Source is responsible for providing information of the occurred event to it's handler. Java provide us with classes for the source object." }, { "code": null, "e": 13291, "s": 12974, "text": "Listener − It is also known as event handler. The listener is responsible for generating a response to an event. From the point of view of Java implementation, the listener is also an object. The listener waits till it receives an event. Once the event is received, the listener processes the event and then returns." }, { "code": null, "e": 13608, "s": 13291, "text": "Listener − It is also known as event handler. The listener is responsible for generating a response to an event. From the point of view of Java implementation, the listener is also an object. The listener waits till it receives an event. Once the event is received, the listener processes the event and then returns." }, { "code": null, "e": 13838, "s": 13608, "text": "The benefit of this approach is that the user interface logic is completely separated from the logic that generates the event. The user interface element is able to delegate the processing of an event to a separate piece of code." }, { "code": null, "e": 14107, "s": 13838, "text": "In this model, the listener needs to be registered with the source object so that the listener can receive the event notification. This is an efficient way of handling the event because the event notifications are sent only to those listeners who want to receive them." }, { "code": null, "e": 14171, "s": 14107, "text": "Step 1 − The user clicks the button and the event is generated." }, { "code": null, "e": 14326, "s": 14171, "text": "Step 2 − The object of concerned event class is created automatically and information about the source and the event get populated within the same object." }, { "code": null, "e": 14409, "s": 14326, "text": "Step 3 − Event object is forwarded to the method of the registered listener class." }, { "code": null, "e": 14459, "s": 14409, "text": "Step 4 − The method is gets executed and returns." }, { "code": null, "e": 14665, "s": 14459, "text": "In order to design a listener class, you have to develop some listener interfaces. These Listener interfaces forecast some public abstract callback methods, which must be implemented by the listener class." }, { "code": null, "e": 14871, "s": 14665, "text": "In order to design a listener class, you have to develop some listener interfaces. These Listener interfaces forecast some public abstract callback methods, which must be implemented by the listener class." }, { "code": null, "e": 14997, "s": 14871, "text": "If you do not implement any of the predefined interfaces, then your class cannot act as a listener class for a source object." }, { "code": null, "e": 15123, "s": 14997, "text": "If you do not implement any of the predefined interfaces, then your class cannot act as a listener class for a source object." }, { "code": null, "e": 15444, "s": 15123, "text": "These are the methods that are provided by API provider and are defined by the application programmer and invoked by the application developer. Here the callback methods represent an event method. In response to an event, java jre will fire callback method. All such callback methods are provided in listener interfaces." }, { "code": null, "e": 15553, "s": 15444, "text": "If a component wants some listener to listen ot its events, the source must register itself to the listener." }, { "code": null, "e": 15669, "s": 15553, "text": "Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >" }, { "code": null, "e": 15691, "s": 15669, "text": "SwingControlDemo.java" }, { "code": null, "e": 18108, "s": 15691, "text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\n\npublic class SwingControlDemo {\n private JFrame mainFrame;\n private JLabel headerLabel;\n private JLabel statusLabel;\n private JPanel controlPanel;\n\n public SwingControlDemo(){\n prepareGUI();\n }\n public static void main(String[] args){\n SwingControlDemo swingControlDemo = new SwingControlDemo(); \n swingControlDemo.showEventDemo(); \n }\n private void prepareGUI(){\n mainFrame = new JFrame(\"Java SWING Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n\n headerLabel = new JLabel(\"\",JLabel.CENTER );\n statusLabel = new JLabel(\"\",JLabel.CENTER); \n statusLabel.setSize(350,100);\n \n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n controlPanel = new JPanel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n private void showEventDemo(){\n headerLabel.setText(\"Control in action: Button\"); \n\n JButton okButton = new JButton(\"OK\");\n JButton submitButton = new JButton(\"Submit\");\n JButton cancelButton = new JButton(\"Cancel\");\n\n okButton.setActionCommand(\"OK\");\n submitButton.setActionCommand(\"Submit\");\n cancelButton.setActionCommand(\"Cancel\");\n\n okButton.addActionListener(new ButtonClickListener()); \n submitButton.addActionListener(new ButtonClickListener()); \n cancelButton.addActionListener(new ButtonClickListener()); \n\n controlPanel.add(okButton);\n controlPanel.add(submitButton);\n controlPanel.add(cancelButton); \n\n mainFrame.setVisible(true); \n }\n private class ButtonClickListener implements ActionListener{\n public void actionPerformed(ActionEvent e) {\n String command = e.getActionCommand(); \n \n if( command.equals( \"OK\" )) {\n statusLabel.setText(\"Ok Button clicked.\");\n } else if( command.equals( \"Submit\" ) ) {\n statusLabel.setText(\"Submit Button clicked.\"); \n } else {\n statusLabel.setText(\"Cancel Button clicked.\");\n } \t\n }\t\t\n }\n}" }, { "code": null, "e": 18204, "s": 18108, "text": "Compile the program using the command prompt. Go to D:/ > SWING and type the following command." }, { "code": null, "e": 18263, "s": 18204, "text": "D:\\AWT>javac com\\tutorialspoint\\gui\\SwingControlDemo.java\n" }, { "code": null, "e": 18368, "s": 18263, "text": "If no error occurs, it means the compilation is successful. Run the program using the following command." }, { "code": null, "e": 18421, "s": 18368, "text": "D:\\AWT>java com.tutorialspoint.gui.SwingControlDemo\n" }, { "code": null, "e": 18450, "s": 18421, "text": "Verify the following output." }, { "code": null, "e": 18592, "s": 18450, "text": "Event classes represent the event. Java provides various Event classes, however, only those which are more frequently used will be discussed." }, { "code": null, "e": 18881, "s": 18592, "text": "It is the root class from which all event state objects shall be derived. All Events are constructed with a reference to the object, the source, that is logically deemed to be the object upon which the Event in question initially occurred upon. This class is defined in java.util package." }, { "code": null, "e": 18944, "s": 18881, "text": "Following is the declaration for java.util.EventObject class −" }, { "code": null, "e": 19018, "s": 18944, "text": "public class EventObject\n extends Object\n implements Serializable\n" }, { "code": null, "e": 19077, "s": 19018, "text": "Following are the fields for java.util.EventObject class −" }, { "code": null, "e": 19153, "s": 19077, "text": "protected Object source − The object on which the Event initially occurred." }, { "code": null, "e": 19180, "s": 19153, "text": "EventObject(Object source)" }, { "code": null, "e": 19213, "s": 19180, "text": "Constructs a prototypical Event." }, { "code": null, "e": 19232, "s": 19213, "text": "Object getSource()" }, { "code": null, "e": 19282, "s": 19232, "text": "The object on which the Event initially occurred." }, { "code": null, "e": 19300, "s": 19282, "text": "String toString()" }, { "code": null, "e": 19353, "s": 19300, "text": "Returns a String representation of this EventObject." }, { "code": null, "e": 19408, "s": 19353, "text": "This class inherits methods from the following class −" }, { "code": null, "e": 19425, "s": 19408, "text": "java.lang.Object" }, { "code": null, "e": 19479, "s": 19425, "text": "Following is the list of commonly used Event classes." }, { "code": null, "e": 19603, "s": 19479, "text": "It is the root event class for all SWING events. This class and its subclasses supercede the original java.awt.Event class." }, { "code": null, "e": 19700, "s": 19603, "text": "The ActionEvent is generated when the button is clicked or the item of a list is double-clicked." }, { "code": null, "e": 19783, "s": 19700, "text": "The InputEvent class is the root event class for all component-level input events." }, { "code": null, "e": 19837, "s": 19783, "text": "On entering the character the Key event is generated." }, { "code": null, "e": 19898, "s": 19837, "text": "This event indicates a mouse action occurred in a component." }, { "code": null, "e": 19971, "s": 19898, "text": "The object of this class represents the change in the state of a window." }, { "code": null, "e": 20059, "s": 19971, "text": "The object of this class represents the adjustment event emitted by Adjustable objects." }, { "code": null, "e": 20132, "s": 20059, "text": "The object of this class represents the change in the state of a window." }, { "code": null, "e": 20205, "s": 20132, "text": "The object of this class represents the change in the state of a window." }, { "code": null, "e": 20278, "s": 20205, "text": "The object of this class represents the change in the state of a window." }, { "code": null, "e": 20351, "s": 20278, "text": "The object of this class represents the change in the state of a window." }, { "code": null, "e": 20779, "s": 20351, "text": "Event listeners represent the interfaces responsible to handle events. Java provides various Event listener classes, however, only those which are more frequently used will be discussed. Every method of an event listener method has a single argument as an object which is the subclass of EventObject class. For example, mouse event listener methods will accept instance of MouseEvent, where MouseEvent derives from EventObject." }, { "code": null, "e": 20894, "s": 20779, "text": "It is a marker interface which every listener interface has to extend. This class is defined in java.util package." }, { "code": null, "e": 20963, "s": 20894, "text": "Following is the declaration for java.util.EventListener interface −" }, { "code": null, "e": 20995, "s": 20963, "text": "public interface EventListener\n" }, { "code": null, "e": 21051, "s": 20995, "text": "Following is the list of commonly used event listeners." }, { "code": null, "e": 21107, "s": 21051, "text": "This interface is used for receiving the action events." }, { "code": null, "e": 21166, "s": 21107, "text": "This interface is used for receiving the component events." }, { "code": null, "e": 21220, "s": 21166, "text": "This interface is used for receiving the item events." }, { "code": null, "e": 21273, "s": 21220, "text": "This interface is used for receiving the key events." }, { "code": null, "e": 21328, "s": 21273, "text": "This interface is used for receiving the mouse events." }, { "code": null, "e": 21384, "s": 21328, "text": "This interface is used for receiving the window events." }, { "code": null, "e": 21444, "s": 21384, "text": "This interface is used for receiving the adjustment events." }, { "code": null, "e": 21503, "s": 21444, "text": "This interface is used for receiving the container events." }, { "code": null, "e": 21565, "s": 21503, "text": "This interface is used for receiving the mouse motion events." }, { "code": null, "e": 21620, "s": 21565, "text": "This interface is used for receiving the focus events." }, { "code": null, "e": 21786, "s": 21620, "text": "Adapters are abstract classes for receiving various events. The methods in these classes are empty. These classes exist as convenience for creating listener objects." }, { "code": null, "e": 21871, "s": 21786, "text": "Following is the list of commonly used adapters while listening GUI events in SWING." }, { "code": null, "e": 21925, "s": 21871, "text": "An abstract adapter class for receiving focus events." }, { "code": null, "e": 21977, "s": 21925, "text": "An abstract adapter class for receiving key events." }, { "code": null, "e": 22031, "s": 21977, "text": "An abstract adapter class for receiving mouse events." }, { "code": null, "e": 22092, "s": 22031, "text": "An abstract adapter class for receiving mouse motion events." }, { "code": null, "e": 22147, "s": 22092, "text": "An abstract adapter class for receiving window events." }, { "code": null, "e": 22415, "s": 22147, "text": "Layout refers to the arrangement of components within the container. In another way, it could be said that layout is placing the components at a particular position within the container. The task of laying out the controls is done automatically by the Layout Manager." }, { "code": null, "e": 22731, "s": 22415, "text": "The layout manager automatically positions all the components within the container. Even if you do not use the layout manager, the components are still positioned by the default layout manager. It is possible to lay out the controls by hand, however, it becomes very difficult because of the following two reasons." }, { "code": null, "e": 22809, "s": 22731, "text": "It is very tedious to handle a large number of controls within the container." }, { "code": null, "e": 22887, "s": 22809, "text": "It is very tedious to handle a large number of controls within the container." }, { "code": null, "e": 22987, "s": 22887, "text": "Usually, the width and height information of a component is not given when we need to arrange them." }, { "code": null, "e": 23087, "s": 22987, "text": "Usually, the width and height information of a component is not given when we need to arrange them." }, { "code": null, "e": 23477, "s": 23087, "text": "Java provides various layout managers to position the controls. Properties like size, shape, and arrangement varies from one layout manager to the other. When the size of the applet or the application window changes, the size, shape, and arrangement of the components also changes in response, i.e. the layout managers adapt to the dimensions of the appletviewer or the application window." }, { "code": null, "e": 23630, "s": 23477, "text": "The layout manager is associated with every Container object. Each layout manager is an object of the class that implements the LayoutManager interface." }, { "code": null, "e": 23708, "s": 23630, "text": "Following are the interfaces defining the functionalities of Layout Managers." }, { "code": null, "e": 23845, "s": 23708, "text": "The LayoutManager interface declares those methods which need to be implemented by the class, whose object will act as a layout manager." }, { "code": null, "e": 24013, "s": 23845, "text": "The LayoutManager2 is the sub-interface of the LayoutManager. This interface is for those classes that know how to layout containers based on layout constraint object." }, { "code": null, "e": 24092, "s": 24013, "text": "Following is the list of commonly used controls while designing GUI using AWT." }, { "code": null, "e": 24199, "s": 24092, "text": "The borderlayout arranges the components to fit in the five regions: east, west, north, south, and center." }, { "code": null, "e": 24307, "s": 24199, "text": "The CardLayout object treats each component in the container as a card. Only one card is visible at a time." }, { "code": null, "e": 24393, "s": 24307, "text": "The FlowLayout is the default layout. It layout the components in a directional flow." }, { "code": null, "e": 24466, "s": 24393, "text": "The GridLayout manages the components in the form of a rectangular grid." }, { "code": null, "e": 24664, "s": 24466, "text": "This is the most flexible layout manager class. The object of GridBagLayout aligns the component vertically, horizontally, or along their baseline without requiring the components of the same size." }, { "code": null, "e": 24759, "s": 24664, "text": "The GroupLayout hierarchically groups the components in order to position them in a Container." }, { "code": null, "e": 24860, "s": 24759, "text": "A SpringLayout positions the children of its associated container according to a set of constraints." }, { "code": null, "e": 25154, "s": 24860, "text": "As we know that every top-level window has a menu bar associated with it. This menu bar consists of various menu choices available to the end user. Further, each choice contains a list of options, which is called drop-down menus. Menu and MenuItem controls are subclass of MenuComponent class." }, { "code": null, "e": 25215, "s": 25154, "text": "The JMenuBar object is associated with the top-level window." }, { "code": null, "e": 25290, "s": 25215, "text": "The items in the menu must belong to the JMenuItem or any of its subclass." }, { "code": null, "e": 25375, "s": 25290, "text": "The JMenu object is a pull-down menu component which is displayed from the menu bar." }, { "code": null, "e": 25423, "s": 25375, "text": "JCheckboxMenuItem is the subclass of JMenuItem." }, { "code": null, "e": 25474, "s": 25423, "text": "JRadioButtonMenuItem is the subclass of JMenuItem." }, { "code": null, "e": 25558, "s": 25474, "text": "JPopupMenu can be dynamically popped up at a specified position within a component." }, { "code": null, "e": 25837, "s": 25558, "text": "Containers are an integral part of SWING GUI components. A container provides a space where a component can be located. A Container in AWT is a component itself and it provides the capability to add a component to itself. Following are certain noticable points to be considered." }, { "code": null, "e": 25928, "s": 25837, "text": "Sub classes of Container are called as Container. For example, JPanel, JFrame and JWindow." }, { "code": null, "e": 26019, "s": 25928, "text": "Sub classes of Container are called as Container. For example, JPanel, JFrame and JWindow." }, { "code": null, "e": 26065, "s": 26019, "text": "Container can add only a Component to itself." }, { "code": null, "e": 26111, "s": 26065, "text": "Container can add only a Component to itself." }, { "code": null, "e": 26205, "s": 26111, "text": "A default layout is present in each container which can be overridden using setLayout method." }, { "code": null, "e": 26299, "s": 26205, "text": "A default layout is present in each container which can be overridden using setLayout method." }, { "code": null, "e": 26381, "s": 26299, "text": "Following is the list of commonly used containers while designed GUI using SWING." }, { "code": null, "e": 26501, "s": 26381, "text": "JPanel is the simplest container. It provides space in which any other component can be placed, including other panels." }, { "code": null, "e": 26559, "s": 26501, "text": "A JFrame is a top-level window with a title and a border." }, { "code": null, "e": 26630, "s": 26559, "text": "A JWindow object is a top-level window with no borders and no menubar." }, { "code": null, "e": 26665, "s": 26630, "text": "\n 30 Lectures \n 3.5 hours \n" }, { "code": null, "e": 26685, "s": 26665, "text": " Pranjal Srivastava" }, { "code": null, "e": 26718, "s": 26685, "text": "\n 13 Lectures \n 1 hours \n" }, { "code": null, "e": 26738, "s": 26718, "text": " Pranjal Srivastava" }, { "code": null, "e": 26773, "s": 26738, "text": "\n 25 Lectures \n 4.5 hours \n" }, { "code": null, "e": 26809, "s": 26773, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 26844, "s": 26809, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 26857, "s": 26844, "text": " Travis Rose" }, { "code": null, "e": 26890, "s": 26857, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 26903, "s": 26890, "text": " Travis Rose" }, { "code": null, "e": 26910, "s": 26903, "text": " Print" }, { "code": null, "e": 26921, "s": 26910, "text": " Add Notes" } ]
Find Duplicates of array using bit array in C++
We have an array of n numbers, where n is maximum 32,000. Now the given array may have duplicate entries and we do not know what n is. Now the question is arisen that with only4 Kilobytes of memory available, how would display or print all duplicates elements in the array? arr[] = {2, 6, 2, 11, 13, 11} 2 11 2 and 11 appear more than once in given array. arr[] = {60, 50, 60} 60 Now we have 4 Kilobytes of memory which indicates we can address up to 8 * 4 * 210 bits.It should be noted that 32 * 210 bits is larger than 32000. So we can generate a bit with32000 bits, where each bit represents one integer. Again it should be noted that if we require generating a bit with more than 32000 bits then we can generate easily more and more than 32000; implementing this bit vector, we can be able to iterate through the array, flagging each element v by setting bit v to 1. In this case, when we traverse a duplicate element, we print it. Live Demo // C++ program to print all Duplicates in array #include <bits/stdc++.h> using namespace std; // Shows a class to represent an array of bits using // array of integers class BitArray{ int *arr1; public: BitArray() {} // Constructor BitArray(int n1){ // Used to divide by 32. To store n bits, we require // n/32 + 1 integers (Assuming int is stored // using 32 bits) arr1 = new int[(n1 >> 5) + 1]; } // Now get value of a bit at given position bool get(int pos1){ // Used to divide by 32 to find position of // integer. int index1 = (pos1 >> 5); // Now determine bit number in arr[index] int bitNo1 = (pos1 & 0x1F); // Determine value of given bit number in // arr1[index1] return (arr1[index1] & (1 << bitNo1)) != 0; } // Used to set a bit at given position void set(int pos1){ // Determine index of bit position int index1 = (pos1 >> 5); // Used to set bit number in arr1[index1] int bitNo1 = (pos1 & 0x1F); arr1[index1] |= (1 << bitNo1); } //Shows main function to print all Duplicates void checkDuplicates1(int arr1[], int n1){ // Used to create a bit with 32000 bits BitArray ba1 = BitArray(320000); // Used to traverse array elements for (int i = 0; i < n1; i++){ // Shows index in bit array int num1 = arr1[i]; // Now if num is already present in bit array if (ba1.get(num1)) cout << num1 << " "; // Otherwise or else insert num else ba1.set(num1); } } }; // Driver code int main(){ int arr1[] = {2, 6, 2, 11, 13, 11}; int n1 = sizeof(arr1) / sizeof(arr1[0]); BitArray obj1 = BitArray(); obj1.checkDuplicates1(arr1, n1); return 0; } 2 11
[ { "code": null, "e": 1336, "s": 1062, "text": "We have an array of n numbers, where n is maximum 32,000. Now the given array may have duplicate entries and we do not know what n is. Now the question is arisen that with only4 Kilobytes of memory available, how would display or print all duplicates elements in the array?" }, { "code": null, "e": 1366, "s": 1336, "text": "arr[] = {2, 6, 2, 11, 13, 11}" }, { "code": null, "e": 1418, "s": 1366, "text": "2 11\n2 and 11 appear more than once in given array." }, { "code": null, "e": 1439, "s": 1418, "text": "arr[] = {60, 50, 60}" }, { "code": null, "e": 1442, "s": 1439, "text": "60" }, { "code": null, "e": 1670, "s": 1442, "text": "Now we have 4 Kilobytes of memory which indicates we can address up to 8 * 4 * 210 bits.It should be noted that 32 * 210 bits is larger than 32000. So we can generate a bit with32000 bits, where each bit represents one integer." }, { "code": null, "e": 1998, "s": 1670, "text": "Again it should be noted that if we require generating a bit with more than 32000 bits then we can\ngenerate easily more and more than 32000; implementing this bit vector, we can be able to iterate through the array, flagging each element v by setting bit v to 1. In this case, when we traverse a duplicate element, we print it." }, { "code": null, "e": 2009, "s": 1998, "text": " Live Demo" }, { "code": null, "e": 3818, "s": 2009, "text": "// C++ program to print all Duplicates in array\n#include <bits/stdc++.h>\nusing namespace std;\n// Shows a class to represent an array of bits using\n// array of integers\nclass BitArray{\n int *arr1;\n public:\n BitArray() {}\n // Constructor\n BitArray(int n1){\n // Used to divide by 32. To store n bits, we require\n // n/32 + 1 integers (Assuming int is stored\n // using 32 bits)\n arr1 = new int[(n1 >> 5) + 1];\n }\n // Now get value of a bit at given position\n bool get(int pos1){\n // Used to divide by 32 to find position of\n // integer.\n int index1 = (pos1 >> 5);\n // Now determine bit number in arr[index]\n int bitNo1 = (pos1 & 0x1F);\n // Determine value of given bit number in\n // arr1[index1]\n return (arr1[index1] & (1 << bitNo1)) != 0;\n }\n // Used to set a bit at given position\n void set(int pos1){\n // Determine index of bit position\n int index1 = (pos1 >> 5);\n // Used to set bit number in arr1[index1]\n int bitNo1 = (pos1 & 0x1F);\n arr1[index1] |= (1 << bitNo1);\n }\n //Shows main function to print all Duplicates\n void checkDuplicates1(int arr1[], int n1){\n // Used to create a bit with 32000 bits\n BitArray ba1 = BitArray(320000);\n // Used to traverse array elements\n for (int i = 0; i < n1; i++){\n // Shows index in bit array\n int num1 = arr1[i];\n // Now if num is already present in bit array\n if (ba1.get(num1))\n cout << num1 << \" \";\n // Otherwise or else insert num\n else\n ba1.set(num1);\n }\n }\n};\n// Driver code\nint main(){\n int arr1[] = {2, 6, 2, 11, 13, 11};\n int n1 = sizeof(arr1) / sizeof(arr1[0]);\n BitArray obj1 = BitArray();\n obj1.checkDuplicates1(arr1, n1);\n return 0;\n}" }, { "code": null, "e": 3823, "s": 3818, "text": "2 11" } ]
Multiple Statements in Python
The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code block. Here is a sample snip using the semicolon − import sys; x = 'foo'; sys.stdout.write(x + '\n') A group of individual statements, which make a single code block are called suites in Python. Compound or complex statements, such as if, while, def, and class require a header line and a suite. Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by one or more lines which make up the suite. For example − if expression : suite elif expression : suite else : suite
[ { "code": null, "e": 1226, "s": 1062, "text": "The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code block. Here is a sample snip using the semicolon −" }, { "code": null, "e": 1276, "s": 1226, "text": "import sys; x = 'foo'; sys.stdout.write(x + '\\n')" }, { "code": null, "e": 1471, "s": 1276, "text": "A group of individual statements, which make a single code block are called suites in Python. Compound or complex statements, such as if, while, def, and class require a header line and a suite." }, { "code": null, "e": 1633, "s": 1471, "text": "Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by one or more lines which make up the suite. For example −" }, { "code": null, "e": 1701, "s": 1633, "text": "if expression :\n suite\nelif expression :\n suite\nelse :\n suite" } ]
How to compare two lists in Python?
The list in python is a collection of similar items. We may at times need to compare data items in the two lists to perform certain operations. We will discuss certain methods to compare two lists in python. The list.sort() method sorts the two lists and the == operator compares the two lists item by item which means they have equal data items at equal positions. This checks if the list contains equal data item values but it does not take into account the order of elements in the list. This means that the list [1,2,3] will be equal to the list [2,1,3] according to this method of comparison. Live Demo def compareList(l1,l2): l1.sort() l2.sort() if(l1==l2): return "Equal" else: return "Non equal" l1=[1,2,3] l2=[2,1,3] print("First comparison",compareList(l1,l2)) l3=[1,2,3] l4=[1,2,4] print("Second comparison",compareList(l3,l4)) First comparison Equal Second comparison Non equal This method tests for the equality of the lists by comparing frequency of each element in first list with the second list. This method also does not take into account the order of the elements of the list. Live Demo import collections def compareList(l1,l2): if(collections.Counter(l1)==collections.Counter(l2)): return "Equal" else: return "Non equal" l1=[1,2,3] l2=[2,1,3] print("First comparison",compareList(l1,l2)) l3=[1,2,3] l4=[1,2,4] print("Second comparison",compareList(l3,l4)) First comparison Non equal Second comparison Equal This method first compares each element of the two lists and store those as summation of 1, which is then compared with the length of the other list. For this method, we have to first check if the lengths of both the lists are equal before performing this computation. This method also checks for the order of the elements. This means that the list [1,2,3] is not equal to the list [2,1,3]. Live Demo def compareList(l1,l2): if(len(l1)==len(l2) and len(l1)==sum([1 for i,j in zip(l1,l2) if i==j])): return "Equal" else: return "Non equal" l1=[1,2,3] l2=[2,1,3] print("First comparison",compareList(l1,l2)) l3=[1,2,3] l4=[1,2,3] print("Second comparison",compareList(l3,l4)) First comparison Non equal Second comparison Equal As in the above example, for the first comparison, the data items in both the lists are equal but the order of the elements is different. Therefore, the first comparison returns not equal. This is a modification of the first method. In this method, the lists are compared without sorting and thus, this method takes into account the order of the data items in the lists. Live Demo def compareList(l1,l2): if(l1==l2): return "Equal" else: return "Non equal" l1=[1,2,3] l2=[2,1,3] print("First comparison",compareList(l1,l2)) l3=[1,2,3] l4=[1,2,3] print("Second comparison",compareList(l3,l4)) First comparison Non equal Second comparison Equal These are some of the methods to compare lists in python, both taking into account the order of the data items as well as without taking into account the order of data items.
[ { "code": null, "e": 1270, "s": 1062, "text": "The list in python is a collection of similar items. We may at times need to compare data items in the two lists to perform certain operations. We will discuss certain methods to compare two lists in python." }, { "code": null, "e": 1660, "s": 1270, "text": "The list.sort() method sorts the two lists and the == operator compares the two lists item by item which means they have equal data items at equal positions. This checks if the list contains equal data item values but it does not take into account the order of elements in the list. This means that the list [1,2,3] will be equal to the list [2,1,3] according to this method of comparison." }, { "code": null, "e": 1671, "s": 1660, "text": " Live Demo" }, { "code": null, "e": 1926, "s": 1671, "text": "def compareList(l1,l2):\n l1.sort()\n l2.sort()\n if(l1==l2):\n return \"Equal\"\n else:\n return \"Non equal\"\nl1=[1,2,3]\nl2=[2,1,3]\nprint(\"First comparison\",compareList(l1,l2))\nl3=[1,2,3]\nl4=[1,2,4]\nprint(\"Second comparison\",compareList(l3,l4))" }, { "code": null, "e": 1977, "s": 1926, "text": "First comparison Equal\nSecond comparison Non equal" }, { "code": null, "e": 2183, "s": 1977, "text": "This method tests for the equality of the lists by comparing frequency of each element in first list with the second list. This method also does not take into account the order of the elements of the list." }, { "code": null, "e": 2194, "s": 2183, "text": " Live Demo" }, { "code": null, "e": 2484, "s": 2194, "text": "import collections\ndef compareList(l1,l2):\n if(collections.Counter(l1)==collections.Counter(l2)):\n return \"Equal\"\n else:\n return \"Non equal\"\nl1=[1,2,3]\nl2=[2,1,3]\nprint(\"First comparison\",compareList(l1,l2))\nl3=[1,2,3]\nl4=[1,2,4]\nprint(\"Second comparison\",compareList(l3,l4))" }, { "code": null, "e": 2535, "s": 2484, "text": "First comparison Non equal\nSecond comparison Equal" }, { "code": null, "e": 2804, "s": 2535, "text": "This method first compares each element of the two lists and store those as summation of 1, which is then compared with the length of the other list. For this method, we have to first check if the lengths of both the lists are equal before performing this computation." }, { "code": null, "e": 2926, "s": 2804, "text": "This method also checks for the order of the elements. This means that the list [1,2,3] is not equal to the list [2,1,3]." }, { "code": null, "e": 2937, "s": 2926, "text": " Live Demo" }, { "code": null, "e": 3228, "s": 2937, "text": "def compareList(l1,l2):\n if(len(l1)==len(l2) and len(l1)==sum([1 for i,j in zip(l1,l2) if i==j])):\n return \"Equal\"\n else:\n return \"Non equal\"\nl1=[1,2,3]\nl2=[2,1,3]\nprint(\"First comparison\",compareList(l1,l2))\nl3=[1,2,3]\nl4=[1,2,3]\nprint(\"Second comparison\",compareList(l3,l4))" }, { "code": null, "e": 3279, "s": 3228, "text": "First comparison Non equal\nSecond comparison Equal" }, { "code": null, "e": 3468, "s": 3279, "text": "As in the above example, for the first comparison, the data items in both the lists are equal but the order of the elements is different. Therefore, the first comparison returns not equal." }, { "code": null, "e": 3650, "s": 3468, "text": "This is a modification of the first method. In this method, the lists are compared without sorting and thus, this method takes into account the order of the data items in the lists." }, { "code": null, "e": 3661, "s": 3650, "text": " Live Demo" }, { "code": null, "e": 3890, "s": 3661, "text": "def compareList(l1,l2):\n if(l1==l2):\n return \"Equal\"\n else:\n return \"Non equal\"\nl1=[1,2,3]\nl2=[2,1,3]\nprint(\"First comparison\",compareList(l1,l2))\nl3=[1,2,3]\nl4=[1,2,3]\nprint(\"Second comparison\",compareList(l3,l4))" }, { "code": null, "e": 3941, "s": 3890, "text": "First comparison Non equal\nSecond comparison Equal" }, { "code": null, "e": 4116, "s": 3941, "text": "These are some of the methods to compare lists in python, both taking into account the order of the data items as well as without taking into account the order of data items." } ]
Bayesian Linear Regression in Python: Using Machine Learning to Predict Student Grades Part 2 | by Will Koehrsen | Towards Data Science
In Part One of this Bayesian Machine Learning project, we outlined our problem, performed a full exploratory data analysis, selected our features, and established benchmarks. Here we will implement Bayesian Linear Regression in Python to build a model. After we have trained our model, we will interpret the model parameters and use the model to make predictions. The entire code for this project is available as a Jupyter Notebook on GitHub and I encourage anyone to check it out! As a reminder, we are working on a supervised, regression machine learning problem. Using a dataset of student grades, we want to build a model that can predict a final student’s score from personal and academic characteristics of the student. The final dataset after feature selection is: We have 6 features (explanatory variables) that we use to predict the target (response variable), in this case the grade. There are 474 students in the training set and 159 in the test set. To get a sense of the variable distributions (and because I really enjoy this plot) here is a Pairs plot of the variables showing scatter plots, histograms, density plots, and correlation coefficients. For details about this plot and the meaning of all the variables check out part one and the notebook. Now, let’s move on to implementing Bayesian Linear Regression in Python. Let’s briefly recap Frequentist and Bayesian linear regression. The Frequentist view of linear regression assumes data is generated from the following model: Where the response, y, is generated from the model parameters, β, times the input matrix, X, plus error due to random sampling noise or latent variables. In the ordinary least squares (OLS) method, the model parameters, β, are calculated by finding the parameters which minimize the sum of squared errors on the training data. The output from OLS is single point estimates for the “best” model parameters given the training data. These parameters can then be used to make predictions for new data points. In contrast, Bayesian Linear Regression assumes the responses are sampled from a probability distribution such as the normal (Gaussian) distribution: The mean of the Gaussian is the product of the parameters, β and the inputs, X, and the standard deviation is σ. In Bayesian Models, not only is the response assumed to be sampled from a distribution, but so are the parameters. The objective is to determine the posterior probability distribution for the model parameters given the inputs, X, and outputs, y: The posterior is equal to the likelihood of the data times the prior for the model parameters divided by a normalization constant. If we have some domain knowledge, we can use it to assign priors for the model parameters, or we can use non-informative priors: distributions with large standard deviations that do not assume anything about the variable. Using a non-informative prior means we “let the data speak.” A common prior choice is to use a normal distribution for β and a half-cauchy distribution for σ. In practice, calculating the exact posterior distribution is computationally intractable for continuous values and so we turn to sampling methods such as Markov Chain Monte Carlo (MCMC) to draw samples from the posterior in order to approximate the posterior. Monte Carlo refers to the general technique of drawing random samples, and Markov Chain means the next sample drawn is based only on the previous sample value. The concept is that as we draw more samples, the approximation of the posterior will eventually converge on the true posterior distribution for the model parameters. The end result of Bayesian Linear Modeling is not a single estimate for the model parameters, but a distribution that we can use to make inferences about new observations. This distribution allows us to demonstrate our uncertainty in the model and is one of the benefits of Bayesian Modeling methods. As the number of data points increases, the uncertainty should decrease, showing a higher level of certainty in our estimates. The best library for probabilistic programming and Bayesian Inference in Python is currently PyMC3. It includes numerous utilities for constructing Bayesian Models and using MCMC methods to infer the model parameters. We will be using the Generalized Linear Models (GLM) module of PyMC3, in particular, the GLM.from_formula function which makes constructing Bayesian Linear Models extremely simple. There are only two steps we need to do to perform Bayesian Linear Regression with this module: Build a formula relating the features to the target and decide on a prior distribution for the data likelihoodSample from the parameter posterior distribution using MCMC Build a formula relating the features to the target and decide on a prior distribution for the data likelihood Sample from the parameter posterior distribution using MCMC Instead of having to define probability distributions for each of the model parameters separately, we pass in an R-style formula relating the features (input) to the target (output). Here is the formula relating the grade to the student characteristics: Grade ~ failures + higher_edu + mother_edu + studytime + father_edu + absences In this syntax, ~, is read as “is a function of”. We are telling the model that Grade is a linear combination of the six features on the right side of the tilde. The model is built in a context using the with statement. In the call to GLM.from_formula we pass the formula, the data, and the data likelihood family (this actually is optional and defaults to a normal distribution). The function parses the formula, adds random variables for each feature (along with the standard deviation), adds the likelihood for the data, and initializes the parameters to a reasonable starting estimate. By default, the model parameters priors are modeled as a normal distribution. Once the GLM model is built, we sample from the posterior using a MCMC algorithm. If we do not specify which method, PyMC3 will automatically choose the best for us. In the code below, I let PyMC3 choose the sampler and specify the number of samples, 2000, the number of chains, 2, and the number of tuning steps, 500. In this case, PyMC3 chose the No-U-Turn Sampler and intialized the sampler with jitter+adapt_diag. To be honest, I don’t really know the full details of what these mean, but I assume someone much smarter than myself implemented them correctly. Sometimes just knowing how to use the tool is more important than understanding every detail of the implementation! The sampler runs for a few minutes and our results are stored in normal_trace. This contains all the samples for every one of the model parameters (except the tuning samples which are discarded). The trace is essentially our model because it contains all the information we need to perform inference. To get an idea of what Bayesian Linear Regression does, we can examine the trace using built-in functions in PyMC3. A traceplot shows the posterior distribution for the model parameters on the left and the progression of the samples drawn in the trace for the variable on the right. The two colors represent the two difference chains sampled. pm.traceplot(normal_trace) Here we can see that our model parameters are not point estimates but distributions. The mean of each distribution can be taken as the most likely estimate, but we also use the entire range of values to show we are uncertain about the true values. Another way to look at the posterior distributions is as histograms: pm.plot_posterior(normal_trace) Here we can see the mean, which we can use as most likely estimate, and also the entire distribution. 95% HPD stands for the 95% Highest Posterior Density and is a credible interval for our parameters. A credible interval is the Bayesian equivalent of a confidence interval in Frequentist statistics (although with different interpretations). We can also see a summary of all the model parameters: pm.df_summary(normal_trace) We can interpret these weights in much the same way as those of OLS linear regression. For example in the model: Previous class failures and absences have a negative weight Higher Education plans and studying time have a positive weight The mother’s and father’s education have a positive weight (although the mother’s is much more positive) The standard deviation column and hpd limits give us a sense of how confident we are in the model parameters. For example, the father_edu feature has a 95% hpd that goes from -0.22 to 0.27 meaning that we are not entirely sure if the effect in the model is either negative or positive! There is also a large standard deviation (the sd row) for the data likelihood, indicating large uncertainty in the targets. Overall, we see considerable uncertainty in the model because we are dealing with a small number of samples. With only several hundred students, we do not have enough data to pin down the model parameters precisely. In order to see the effect of a single variable on the grade, we can change the value of this variable while holding the others constant and look at how the estimated grades change. To do this, we use the plot_posterior_predictive function and assume that all variables except for the one of interest (the query variable) are at the median value. We generate a range of values for the query variable and the function estimates the grade across this range by drawing model parameters from the posterior distribution. Here’s the code: The results show the estimated grade versus the range of the query variable for 100 samples from the posterior: Each line (there are 100 in each plot) is drawn by picking one set of model parameters from the posterior trace and evaluating the predicted grade across a range of the query variable. The distribution of the lines shows uncertainty in the model parameters: the more spread out the lines, the less sure the model is about the effect of that variable. For one variable, the father’s education, our model is not even sure if the effect of increasing the variable is positive or negative! If we were using this model to make decisions, we might want to think twice about deploying it without first gathering more data to form more certain estimates. With only several hundred students, there is considerable uncertainty in the model parameters. For example, we should not make claims such as “the father’s level of education positively impacts the grade” because the results show there is little certainly about this conclusion. If we were using Frequentist methods and saw only a point estimate, we might make faulty decisions because of the limited amount of data. In cases where we have a limited dataset, Bayesian models are a great choice for showing our uncertainty in the model. When it comes to predicting, the Bayesian model can be used to estimate distributions. We remember that the model for Bayesian Linear Regression is: Where β is the coefficient matrix (model parameters), X is the data matrix, and σ is the standard deviation. If we want to make a prediction for a new data point, we can find a normal distribution of estimated outputs by multiplying the model parameters by our data point to find the mean and using the standard deviation from the model parameters. In this case, we will take the mean of each model parameter from the trace to serve as the best estimate of the parameter. If we take the mean of the parameters in the trace, then the distribution for a prediction becomes: Grade ~ N(9.20 * Intercept - 1.32 * failures + 1.85 * higher_edu + 0.26 * mother_edu + 0.58 * studytime + 0.03 * father_edu - 0.07 * absences, 2.28^2) For a new data point, we substitute in the value of the variables and construct the probability density function for the grade. As an example, here is an observation from the test set along with the probability density function (see the Notebook for the code to build this distribution): Test Observation:failures = 0, higher_edu = 1, mother_edu = 2, studytime = 1,father_edu = 2, absences = 8 True Grade = 12Average Estimate = 11.67635% Estimate = 7.7618 95% Estimate = 15.5931 For this data point, the mean estimate lines up well with the actual grade, but there is also a wide estimated interval. If we had more students, the uncertainty in the estimates should be lower. We can also make predictions for any new point that is not in the test set: New Observation:absences = 1, failures = 0, father_edu = 1higher_edu = 1, mother_edu = 4, studytime = 3 Average Estimate = 13.80095% Estimate = 10.0696 95% Estimate = 17.4629 In the first part of this series, we calculated benchmarks for a number of standard machine learning models as well as a naive baseline. To calculate the MAE and RMSE metrics, we need to make a single point estimate for all the data points in the test set. We can make a “most likely” prediction using the means value from the estimated distributed. The resulting metrics, along with those of the benchmarks, are shown below: Bayesian Linear Regression achieves nearly the same performance as the best standard models! However, the main benefits of Bayesian Linear Modeling are not in the accuracy, but in the interpretability and the quantification of our uncertainty. Any model is only an estimate of the real world, and here we have seen how little confidence we should have in models trained on limited data. For anyone looking to get started with Bayesian Modeling, I recommend checking out the notebook. In this project, I only explored half of the student data (I used math scores and the other half contains Portuguese class scores) so feel free to carry out the same analysis on the other half. In addition, we can change the distribution for the data likelihood—for example to a Student’s T distribution — and see how that changes the model. As with most machine learning, there is a considerable amount that can be learned just by experimenting with different settings and often no single right answer! In this series of articles, we walked through the complete machine learning process used to solve a data science problem. We started with exploratory data analysis, moved to establishing a baseline, tried out several different models, implemented our model of choice, interpreted the results, and used the model to make new predictions. While the model implementation details may change, this general structure will serve you well for most data science projects. Moreover, hopefully this project has given you an idea of the unique capabilities of Bayesian Machine Learning and has added another tool to your skillset. Learning new skills is the most exciting aspect of data science and now you have one more to deploy to solve your data problems. As always, I welcome feedback and constructive criticism. I can be reached on Twitter @koehrsen_will.
[ { "code": null, "e": 654, "s": 172, "text": "In Part One of this Bayesian Machine Learning project, we outlined our problem, performed a full exploratory data analysis, selected our features, and established benchmarks. Here we will implement Bayesian Linear Regression in Python to build a model. After we have trained our model, we will interpret the model parameters and use the model to make predictions. The entire code for this project is available as a Jupyter Notebook on GitHub and I encourage anyone to check it out!" }, { "code": null, "e": 944, "s": 654, "text": "As a reminder, we are working on a supervised, regression machine learning problem. Using a dataset of student grades, we want to build a model that can predict a final student’s score from personal and academic characteristics of the student. The final dataset after feature selection is:" }, { "code": null, "e": 1336, "s": 944, "text": "We have 6 features (explanatory variables) that we use to predict the target (response variable), in this case the grade. There are 474 students in the training set and 159 in the test set. To get a sense of the variable distributions (and because I really enjoy this plot) here is a Pairs plot of the variables showing scatter plots, histograms, density plots, and correlation coefficients." }, { "code": null, "e": 1511, "s": 1336, "text": "For details about this plot and the meaning of all the variables check out part one and the notebook. Now, let’s move on to implementing Bayesian Linear Regression in Python." }, { "code": null, "e": 1669, "s": 1511, "text": "Let’s briefly recap Frequentist and Bayesian linear regression. The Frequentist view of linear regression assumes data is generated from the following model:" }, { "code": null, "e": 2174, "s": 1669, "text": "Where the response, y, is generated from the model parameters, β, times the input matrix, X, plus error due to random sampling noise or latent variables. In the ordinary least squares (OLS) method, the model parameters, β, are calculated by finding the parameters which minimize the sum of squared errors on the training data. The output from OLS is single point estimates for the “best” model parameters given the training data. These parameters can then be used to make predictions for new data points." }, { "code": null, "e": 2324, "s": 2174, "text": "In contrast, Bayesian Linear Regression assumes the responses are sampled from a probability distribution such as the normal (Gaussian) distribution:" }, { "code": null, "e": 2683, "s": 2324, "text": "The mean of the Gaussian is the product of the parameters, β and the inputs, X, and the standard deviation is σ. In Bayesian Models, not only is the response assumed to be sampled from a distribution, but so are the parameters. The objective is to determine the posterior probability distribution for the model parameters given the inputs, X, and outputs, y:" }, { "code": null, "e": 3195, "s": 2683, "text": "The posterior is equal to the likelihood of the data times the prior for the model parameters divided by a normalization constant. If we have some domain knowledge, we can use it to assign priors for the model parameters, or we can use non-informative priors: distributions with large standard deviations that do not assume anything about the variable. Using a non-informative prior means we “let the data speak.” A common prior choice is to use a normal distribution for β and a half-cauchy distribution for σ." }, { "code": null, "e": 3781, "s": 3195, "text": "In practice, calculating the exact posterior distribution is computationally intractable for continuous values and so we turn to sampling methods such as Markov Chain Monte Carlo (MCMC) to draw samples from the posterior in order to approximate the posterior. Monte Carlo refers to the general technique of drawing random samples, and Markov Chain means the next sample drawn is based only on the previous sample value. The concept is that as we draw more samples, the approximation of the posterior will eventually converge on the true posterior distribution for the model parameters." }, { "code": null, "e": 4209, "s": 3781, "text": "The end result of Bayesian Linear Modeling is not a single estimate for the model parameters, but a distribution that we can use to make inferences about new observations. This distribution allows us to demonstrate our uncertainty in the model and is one of the benefits of Bayesian Modeling methods. As the number of data points increases, the uncertainty should decrease, showing a higher level of certainty in our estimates." }, { "code": null, "e": 4608, "s": 4209, "text": "The best library for probabilistic programming and Bayesian Inference in Python is currently PyMC3. It includes numerous utilities for constructing Bayesian Models and using MCMC methods to infer the model parameters. We will be using the Generalized Linear Models (GLM) module of PyMC3, in particular, the GLM.from_formula function which makes constructing Bayesian Linear Models extremely simple." }, { "code": null, "e": 4703, "s": 4608, "text": "There are only two steps we need to do to perform Bayesian Linear Regression with this module:" }, { "code": null, "e": 4873, "s": 4703, "text": "Build a formula relating the features to the target and decide on a prior distribution for the data likelihoodSample from the parameter posterior distribution using MCMC" }, { "code": null, "e": 4984, "s": 4873, "text": "Build a formula relating the features to the target and decide on a prior distribution for the data likelihood" }, { "code": null, "e": 5044, "s": 4984, "text": "Sample from the parameter posterior distribution using MCMC" }, { "code": null, "e": 5298, "s": 5044, "text": "Instead of having to define probability distributions for each of the model parameters separately, we pass in an R-style formula relating the features (input) to the target (output). Here is the formula relating the grade to the student characteristics:" }, { "code": null, "e": 5377, "s": 5298, "text": "Grade ~ failures + higher_edu + mother_edu + studytime + father_edu + absences" }, { "code": null, "e": 5539, "s": 5377, "text": "In this syntax, ~, is read as “is a function of”. We are telling the model that Grade is a linear combination of the six features on the right side of the tilde." }, { "code": null, "e": 6045, "s": 5539, "text": "The model is built in a context using the with statement. In the call to GLM.from_formula we pass the formula, the data, and the data likelihood family (this actually is optional and defaults to a normal distribution). The function parses the formula, adds random variables for each feature (along with the standard deviation), adds the likelihood for the data, and initializes the parameters to a reasonable starting estimate. By default, the model parameters priors are modeled as a normal distribution." }, { "code": null, "e": 6364, "s": 6045, "text": "Once the GLM model is built, we sample from the posterior using a MCMC algorithm. If we do not specify which method, PyMC3 will automatically choose the best for us. In the code below, I let PyMC3 choose the sampler and specify the number of samples, 2000, the number of chains, 2, and the number of tuning steps, 500." }, { "code": null, "e": 6724, "s": 6364, "text": "In this case, PyMC3 chose the No-U-Turn Sampler and intialized the sampler with jitter+adapt_diag. To be honest, I don’t really know the full details of what these mean, but I assume someone much smarter than myself implemented them correctly. Sometimes just knowing how to use the tool is more important than understanding every detail of the implementation!" }, { "code": null, "e": 7141, "s": 6724, "text": "The sampler runs for a few minutes and our results are stored in normal_trace. This contains all the samples for every one of the model parameters (except the tuning samples which are discarded). The trace is essentially our model because it contains all the information we need to perform inference. To get an idea of what Bayesian Linear Regression does, we can examine the trace using built-in functions in PyMC3." }, { "code": null, "e": 7368, "s": 7141, "text": "A traceplot shows the posterior distribution for the model parameters on the left and the progression of the samples drawn in the trace for the variable on the right. The two colors represent the two difference chains sampled." }, { "code": null, "e": 7395, "s": 7368, "text": "pm.traceplot(normal_trace)" }, { "code": null, "e": 7643, "s": 7395, "text": "Here we can see that our model parameters are not point estimates but distributions. The mean of each distribution can be taken as the most likely estimate, but we also use the entire range of values to show we are uncertain about the true values." }, { "code": null, "e": 7712, "s": 7643, "text": "Another way to look at the posterior distributions is as histograms:" }, { "code": null, "e": 7744, "s": 7712, "text": "pm.plot_posterior(normal_trace)" }, { "code": null, "e": 8087, "s": 7744, "text": "Here we can see the mean, which we can use as most likely estimate, and also the entire distribution. 95% HPD stands for the 95% Highest Posterior Density and is a credible interval for our parameters. A credible interval is the Bayesian equivalent of a confidence interval in Frequentist statistics (although with different interpretations)." }, { "code": null, "e": 8142, "s": 8087, "text": "We can also see a summary of all the model parameters:" }, { "code": null, "e": 8170, "s": 8142, "text": "pm.df_summary(normal_trace)" }, { "code": null, "e": 8283, "s": 8170, "text": "We can interpret these weights in much the same way as those of OLS linear regression. For example in the model:" }, { "code": null, "e": 8343, "s": 8283, "text": "Previous class failures and absences have a negative weight" }, { "code": null, "e": 8407, "s": 8343, "text": "Higher Education plans and studying time have a positive weight" }, { "code": null, "e": 8512, "s": 8407, "text": "The mother’s and father’s education have a positive weight (although the mother’s is much more positive)" }, { "code": null, "e": 9138, "s": 8512, "text": "The standard deviation column and hpd limits give us a sense of how confident we are in the model parameters. For example, the father_edu feature has a 95% hpd that goes from -0.22 to 0.27 meaning that we are not entirely sure if the effect in the model is either negative or positive! There is also a large standard deviation (the sd row) for the data likelihood, indicating large uncertainty in the targets. Overall, we see considerable uncertainty in the model because we are dealing with a small number of samples. With only several hundred students, we do not have enough data to pin down the model parameters precisely." }, { "code": null, "e": 9671, "s": 9138, "text": "In order to see the effect of a single variable on the grade, we can change the value of this variable while holding the others constant and look at how the estimated grades change. To do this, we use the plot_posterior_predictive function and assume that all variables except for the one of interest (the query variable) are at the median value. We generate a range of values for the query variable and the function estimates the grade across this range by drawing model parameters from the posterior distribution. Here’s the code:" }, { "code": null, "e": 9783, "s": 9671, "text": "The results show the estimated grade versus the range of the query variable for 100 samples from the posterior:" }, { "code": null, "e": 10134, "s": 9783, "text": "Each line (there are 100 in each plot) is drawn by picking one set of model parameters from the posterior trace and evaluating the predicted grade across a range of the query variable. The distribution of the lines shows uncertainty in the model parameters: the more spread out the lines, the less sure the model is about the effect of that variable." }, { "code": null, "e": 10269, "s": 10134, "text": "For one variable, the father’s education, our model is not even sure if the effect of increasing the variable is positive or negative!" }, { "code": null, "e": 10709, "s": 10269, "text": "If we were using this model to make decisions, we might want to think twice about deploying it without first gathering more data to form more certain estimates. With only several hundred students, there is considerable uncertainty in the model parameters. For example, we should not make claims such as “the father’s level of education positively impacts the grade” because the results show there is little certainly about this conclusion." }, { "code": null, "e": 10966, "s": 10709, "text": "If we were using Frequentist methods and saw only a point estimate, we might make faulty decisions because of the limited amount of data. In cases where we have a limited dataset, Bayesian models are a great choice for showing our uncertainty in the model." }, { "code": null, "e": 11115, "s": 10966, "text": "When it comes to predicting, the Bayesian model can be used to estimate distributions. We remember that the model for Bayesian Linear Regression is:" }, { "code": null, "e": 11464, "s": 11115, "text": "Where β is the coefficient matrix (model parameters), X is the data matrix, and σ is the standard deviation. If we want to make a prediction for a new data point, we can find a normal distribution of estimated outputs by multiplying the model parameters by our data point to find the mean and using the standard deviation from the model parameters." }, { "code": null, "e": 11687, "s": 11464, "text": "In this case, we will take the mean of each model parameter from the trace to serve as the best estimate of the parameter. If we take the mean of the parameters in the trace, then the distribution for a prediction becomes:" }, { "code": null, "e": 11839, "s": 11687, "text": "Grade ~ N(9.20 * Intercept - 1.32 * failures + 1.85 * higher_edu + 0.26 * mother_edu + 0.58 * studytime + 0.03 * father_edu - 0.07 * absences, 2.28^2)" }, { "code": null, "e": 12127, "s": 11839, "text": "For a new data point, we substitute in the value of the variables and construct the probability density function for the grade. As an example, here is an observation from the test set along with the probability density function (see the Notebook for the code to build this distribution):" }, { "code": null, "e": 12233, "s": 12127, "text": "Test Observation:failures = 0, higher_edu = 1, mother_edu = 2, studytime = 1,father_edu = 2, absences = 8" }, { "code": null, "e": 12321, "s": 12233, "text": "True Grade = 12Average Estimate = 11.67635% Estimate = 7.7618 95% Estimate = 15.5931" }, { "code": null, "e": 12517, "s": 12321, "text": "For this data point, the mean estimate lines up well with the actual grade, but there is also a wide estimated interval. If we had more students, the uncertainty in the estimates should be lower." }, { "code": null, "e": 12593, "s": 12517, "text": "We can also make predictions for any new point that is not in the test set:" }, { "code": null, "e": 12697, "s": 12593, "text": "New Observation:absences = 1, failures = 0, father_edu = 1higher_edu = 1, mother_edu = 4, studytime = 3" }, { "code": null, "e": 12771, "s": 12697, "text": "Average Estimate = 13.80095% Estimate = 10.0696 95% Estimate = 17.4629" }, { "code": null, "e": 13197, "s": 12771, "text": "In the first part of this series, we calculated benchmarks for a number of standard machine learning models as well as a naive baseline. To calculate the MAE and RMSE metrics, we need to make a single point estimate for all the data points in the test set. We can make a “most likely” prediction using the means value from the estimated distributed. The resulting metrics, along with those of the benchmarks, are shown below:" }, { "code": null, "e": 13584, "s": 13197, "text": "Bayesian Linear Regression achieves nearly the same performance as the best standard models! However, the main benefits of Bayesian Linear Modeling are not in the accuracy, but in the interpretability and the quantification of our uncertainty. Any model is only an estimate of the real world, and here we have seen how little confidence we should have in models trained on limited data." }, { "code": null, "e": 14185, "s": 13584, "text": "For anyone looking to get started with Bayesian Modeling, I recommend checking out the notebook. In this project, I only explored half of the student data (I used math scores and the other half contains Portuguese class scores) so feel free to carry out the same analysis on the other half. In addition, we can change the distribution for the data likelihood—for example to a Student’s T distribution — and see how that changes the model. As with most machine learning, there is a considerable amount that can be learned just by experimenting with different settings and often no single right answer!" }, { "code": null, "e": 14933, "s": 14185, "text": "In this series of articles, we walked through the complete machine learning process used to solve a data science problem. We started with exploratory data analysis, moved to establishing a baseline, tried out several different models, implemented our model of choice, interpreted the results, and used the model to make new predictions. While the model implementation details may change, this general structure will serve you well for most data science projects. Moreover, hopefully this project has given you an idea of the unique capabilities of Bayesian Machine Learning and has added another tool to your skillset. Learning new skills is the most exciting aspect of data science and now you have one more to deploy to solve your data problems." } ]
How to get the child element of a parent using JavaScript?
Following is the code for getting the child element of a parent using JavaScript − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .child1, .child2, .child3 { display: none; margin: 10px; width: 70px; height: 70px; } .child1 { background-color: red; } .child2 { background-color: pink; } .child3 { background-color: blue; } </style> </head> <body> <h1>Get the child element of a parent using JavaScript</h1> <div class="parent1"> <div class="child1">Child 1</div> <div class="child2">Child 2</div> <div class="child3">Child 3</div> </div> <br /> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to see the parent1 child elements</h3> <script> let BtnEle = document.querySelector(".Btn"); let parentEle = document.querySelector(".parent1"); BtnEle.addEventListener("click", (event) => { Array.from(parentEle.children).forEach((item) => { item.style.display = "inline-block"; }); }); </script> </body> </html> On clicking the ‘CLICK HERE’ button −
[ { "code": null, "e": 1145, "s": 1062, "text": "Following is the code for getting the child element of a parent using JavaScript −" }, { "code": null, "e": 1156, "s": 1145, "text": " Live Demo" }, { "code": null, "e": 2312, "s": 1156, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .child1,\n .child2,\n .child3 {\n display: none;\n margin: 10px;\n width: 70px;\n height: 70px;\n }\n .child1 {\n background-color: red;\n }\n .child2 {\n background-color: pink;\n }\n .child3 {\n background-color: blue;\n }\n</style>\n</head>\n<body>\n<h1>Get the child element of a parent using JavaScript</h1>\n<div class=\"parent1\">\n<div class=\"child1\">Child 1</div>\n<div class=\"child2\">Child 2</div>\n<div class=\"child3\">Child 3</div>\n</div>\n<br />\n<button class=\"Btn\">CLICK HERE</button>\n<h3>Click on the above button to see the parent1 child elements</h3>\n<script>\n let BtnEle = document.querySelector(\".Btn\");\n let parentEle = document.querySelector(\".parent1\");\n BtnEle.addEventListener(\"click\", (event) => {\n Array.from(parentEle.children).forEach((item) => {\n item.style.display = \"inline-block\";\n });\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2350, "s": 2312, "text": "On clicking the ‘CLICK HERE’ button −" } ]
Implement Your First Ever Lane Detection In Any Car Racing Game | Towards Data Science
Lane detection and control has become a common feature in many vehicles today. Additionally it is a basic starting point for anyone going in the direction of Autonomous Driving. But for most people who are not working on autonomous driving or computer vision, starting with it might appear much more of a daunting task than it actually is. There is a lot of technical research involved in doing actual lane detection. In this case, we see a practical perspective so that anyone interested can try it out without much hassle. The detailed links to the theory are still there in the relevant sections for the curious ones: those of you who do not get satiated with just practical applications and like to get their teeth to sink deeper into the subject matter. Here is everything you need to start: Asphalt 8 Airborne: If you are a Windows 10 user, you can download it free from the Windows Store: https://www.microsoft.com/en-us/p/asphalt-8-airborne/9wzdncrfj12h?activetab=pivot:overviewtabPython 3.7: You could install the latest version of Anaconda, most of the required packages will be already bundled and ready to use. Here is the link to download the latest version: https://www.anaconda.com/products/individualOpenCV: It is a library mainly aimed at real time computer vision. You can find the documentation about how to install and use it here: https://www.learnopencv.com/install-opencv3-on-windows/ Asphalt 8 Airborne: If you are a Windows 10 user, you can download it free from the Windows Store: https://www.microsoft.com/en-us/p/asphalt-8-airborne/9wzdncrfj12h?activetab=pivot:overviewtab Python 3.7: You could install the latest version of Anaconda, most of the required packages will be already bundled and ready to use. Here is the link to download the latest version: https://www.anaconda.com/products/individual OpenCV: It is a library mainly aimed at real time computer vision. You can find the documentation about how to install and use it here: https://www.learnopencv.com/install-opencv3-on-windows/ Now that we have all we need, let’s cut to the chase! Step 1: Find a way to access the game screen This one is easy enough. I did a quick google search to check out python codes that can be used to access the screen. Here is a really great tutorial, from which I used the basic code and adapted it for this case: holypython.com If we run the code directly, you would see a similar result as seen below in a random game level. You will notice that the colors are a bit different, and the screen rate results in some lag (which is OK for our purpose). Let’s correct the color part with some help from the OpenCV documentation. There is a argument in cv2 that makes the screen recording look like the actual color (or at least as far as my vision allows) which is COLOR_BGR2RGB, that is what I used for the correction here. Also, the time function is used to get the screen rate, which comes to around 10 fps, not bad at all! The modified code looks as follows: # import librariesfrom PIL import ImageGrabimport cv2import numpy as npimport time# for timinglast_time = time.time()# screen capture loopwhile True: screen = np.array(ImageGrab.grab(bbox=(0,40,800,700))) print(f'the screen rate is {(1/(time.time()-last_time))}') last_time = time.time() cv2.imshow('Python Window', cv2.cvtColor(screen, \ cv2.COLOR_BGR2RGB)) if cv2.waitKey(25) & 0xFF == ord('q'): cv2.destroyAllWindows() break For the above code to correctly capture screen, I have minimized the game window to the top left corner of my primary monitor, with the dimensions as 800 x 700. You could adjust it appropriately in your code (by changing bbox in the ImageGrab above), especially if you are using multiple monitors. Once you run this, you get the screen capture as follows: This method of screen capture is extremely handy, particularly when we need to generate images for machine learning use cases. Now that we can capture the game window, we can move on to the next step. Step 2: Image processing for edge detection Since lane detection is basically an edge identification from image, you would have to process the image to actually get the main outlines. One of the most popular method used in computational vision processing is the Canny algorithm for edge detection. It basically extracts and retains the useful structural information from images, all the while drastically reducing its size. Open CV has a neat little implementation of the Canny edge detection. This reduces the complexity of the image much further and we get the edges of the image in the screen with pretty much a three line code. Let’s create a small function for processing the image using the Canny implementation in cv2. You can experiment with various values of thresholds by looking into the documentation, the code looks like this: # canny image processing for detecting edgesdef edgeprocessed(image): gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) edgeprocessed_img = cv2.Canny(gray_image, \ threshold1 = 200, threshold2 = 300) return edgeprocessed_img We have to run the processed image again in the image capture loop, so it makes more sense to define this loop as a function to take into consideration the processing as the input. I will get a bit ahead of myself here and modify it to general function taking the inputs as list, which will make more sense further down in the analysis. def screen_capture(processing = None): # takes in a list for type of processing # [processing_function, masking_function] last_time = time.time() while True: screen = np.array(ImageGrab.grab(bbox=(0,40,800,700))) count = 0 if processing is not None: for i in processing: count += 1 processed_screen = processing[0](screen) if count > 1: masked_screen = processing[1] \ (processed_screen,[vertices]) screen_1 = masked_screen else: screen_1 = processed_screen else: screen_1 = screen cv2.imshow('Python Window 2', screen_1) cv2.imshow('Python Window', cv2.cvtColor(screen, \ cv2.COLOR_BGR2RGB)) print(f'the screen rate is {(1/(time.time()-last_time))}') last_time = time.time() if cv2.waitKey(25) & 0xFF == ord('q'): cv2.destroyAllWindows() break Makes it much better to use the function now. You will see why I structured the function this way in the next section. Till then, let us check out the result with the edge processing. screen_capture([edgeprocessed]) This is what you will see: We pretty much get the edges of the objects from the game screen. This is how it looks like when I tried it in a test track in the game: As you notice, there is still too much unwanted information in the image. The trees, rocks, electricity lines, basically everything above the horizon of the road. Not to mention the overlay controls display from the game itself. If we want to focus on the lanes, we have to find a way to somehow filter out or mask the rest of the image lines. Step 3: Masking additional information from the image For this, let’s define a masking function. What we need is to define a polygon shape that masks all the information from the image, except the region that lets us focus on the lanes. This is a very basic method used, in this case I defined the vertices of the exact region I need with a bit of trial and error, as seen in the image below: The required region function uses a masked frame and a polygon with vertices. The intersection of the masked and the polygon gives us only the required section of the image. The function and the vertices (defined above) are as you see here: def required_region(image, vertices): mask = np.zeros_like(image) # black image cv2.fillPoly(mask, vertices, 255) # fill within vertices masked = cv2.bitwise_and(image, mask) # intersection return maskedvertices = np.array([[120,500],[120,400],[150,330],[650,330], \ [680,400],[680,500],[260,500],[260,450], \ [325,370],[475,370],[540,450][540,500]], \ np.int32) Now, we can run the screen capture function with these inputs as well. screen_capture([edgeprocessed, required_region]) And, the result is as follows: As you notice now, I have opaqued out all the unnecessary information except for the lanes. For a rudimentary level code, I’d say that this is pretty neat! But we are not quite there yet. Step 4: Finding lines with Hough Lines Finding the actual geometric lines, we need to do some kind of transformation on the edge processed image. In this case, I used the Hough Transform implementation in Open CV. For this to work properly, the image has to be blurred a bit before giving as the input for Hough transform. I used the Gaussian Blur from Open CV for this case. Additionally, there is a need to draw the detected lines on the image frames. So I defined one more function overlay the detected lines on the frames. The modified overlay line and the edge processing codes are: def overlay_lines(image, lines): for line in lines: coordinates = line[0] cv2.line(image,(coordinates[0],coordinates[1]), \ (coordinates[2],coordinates[3]),[255,255,255],3)def edgeprocessed(image): gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) edgeprocessed_img = cv2.Canny(gray_image, threshold1 = 200,\ threshold2 = 300) edgeprocessed_img = cv2.GaussianBlur(edgeprocessed_img,(5,5),0) lines = cv2.HoughLinesP(edgeprocessed_img, 1, np.pi/180, \ 180, np.array([]), 100, 5) overlay_lines(edgeprocessed_img, lines) return edgeprocessed_img As you can see, that is not bad at all, and with just a few lines of code! We are almost there. Step 5: Get Lanes There are a variety of lines detected in the previous step. We have to find a way to merge them in some way so that we can get the actual lanes. This is a bit more complex and I checked out several resources online to see if there is a simpler way that it could be done. I found a great draw lanes function in the Github project here which I used here directly (code not added below as it is too long, but you can refer my project notebook in Github, linked at the end). All that was needed to be done then was to modify the edge processing function as follows: def edgeprocessed(image): original_image = image gray_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY) edgeprocessed_img = cv2.Canny(gray_image, threshold1 = 200, \ threshold2 = 300) edgeprocessed_img = cv2.GaussianBlur(edgeprocessed_img,(5,5),0) edgeprocessed_img = required_region(edgeprocessed_img, \ [vertices]) lines = cv2.HoughLinesP(edgeprocessed_img, 1, np.pi/180, 180, \ np.array([]), 100, 5) #overlay_lines(edgeprocessed_img, lines) m1 = 0 m2 = 0 try: l1, l2, m1, m2 = draw_lines(original_image,lines) cv2.line(original_image, (l1[0], l1[1]), \ (l1[2], l1[3]), [0,255,0], 30) cv2.line(original_image, (l2[0], l2[1]), \ (l2[2], l2[3]), [0,255,0], 30) except Exception as e: pass try: for coords in lines: coords = coords[0] try: cv2.line(edgeprocessed_img, (coords[0], coords[1]), (coords[2], coords[3]), [255,0,0], 2) except Exception as e: print(str(e)) except Exception as e: passreturn edgeprocessed_img,original_image, m1, m2 And accordingly a few tweaks in the capture function: def screen_capture(processing = None): # takes in a list for type of processing # [processing_function, masking_function] last_time = time.time() while True: screen = np.array(ImageGrab.grab(bbox=(0,40,800,700))) count = 0 if processing is not None: for i in processing: count += 1 processed_screen ,original_image, m1, m2 = \ processing[0](screen) if count > 1: masked_screen = processing[1] \ (processed_screen,[vertices]) screen_1 = masked_screen else: screen_1 = processed_screen else: screen_1 = screen cv2.imshow('Python Window 2', screen_1) cv2.imshow('Python Window', cv2.cvtColor(screen, \ cv2.COLOR_BGR2RGB)) print(f'the screen rate is {(1/(time.time()-last_time))}') last_time = time.time() if cv2.waitKey(25) & 0xFF == ord('q'): cv2.destroyAllWindows() break And voila! screen_capture([edgeprocessed]) As you see, there are still more tweaks and fine tuning that can be done. But it is an awesome application as an introductory learning project! The fun part is, the entire thing works live! You can play the game and detect lanes simultaneously as you keep the code running. This gives us a host of possibilities, like saving images for ML, game controls etc. which I will explore in future posts. That’s it, folks! I hope you managed to implement lane detection in these 5 simple steps. The Jupyter notebook can be found in this link. Feel free use and adapt the code and let me know if you have any interesting tweaks, results or ideas. Happy learning!
[ { "code": null, "e": 512, "s": 172, "text": "Lane detection and control has become a common feature in many vehicles today. Additionally it is a basic starting point for anyone going in the direction of Autonomous Driving. But for most people who are not working on autonomous driving or computer vision, starting with it might appear much more of a daunting task than it actually is." }, { "code": null, "e": 931, "s": 512, "text": "There is a lot of technical research involved in doing actual lane detection. In this case, we see a practical perspective so that anyone interested can try it out without much hassle. The detailed links to the theory are still there in the relevant sections for the curious ones: those of you who do not get satiated with just practical applications and like to get their teeth to sink deeper into the subject matter." }, { "code": null, "e": 969, "s": 931, "text": "Here is everything you need to start:" }, { "code": null, "e": 1580, "s": 969, "text": "Asphalt 8 Airborne: If you are a Windows 10 user, you can download it free from the Windows Store: https://www.microsoft.com/en-us/p/asphalt-8-airborne/9wzdncrfj12h?activetab=pivot:overviewtabPython 3.7: You could install the latest version of Anaconda, most of the required packages will be already bundled and ready to use. Here is the link to download the latest version: https://www.anaconda.com/products/individualOpenCV: It is a library mainly aimed at real time computer vision. You can find the documentation about how to install and use it here: https://www.learnopencv.com/install-opencv3-on-windows/" }, { "code": null, "e": 1773, "s": 1580, "text": "Asphalt 8 Airborne: If you are a Windows 10 user, you can download it free from the Windows Store: https://www.microsoft.com/en-us/p/asphalt-8-airborne/9wzdncrfj12h?activetab=pivot:overviewtab" }, { "code": null, "e": 2001, "s": 1773, "text": "Python 3.7: You could install the latest version of Anaconda, most of the required packages will be already bundled and ready to use. Here is the link to download the latest version: https://www.anaconda.com/products/individual" }, { "code": null, "e": 2193, "s": 2001, "text": "OpenCV: It is a library mainly aimed at real time computer vision. You can find the documentation about how to install and use it here: https://www.learnopencv.com/install-opencv3-on-windows/" }, { "code": null, "e": 2247, "s": 2193, "text": "Now that we have all we need, let’s cut to the chase!" }, { "code": null, "e": 2292, "s": 2247, "text": "Step 1: Find a way to access the game screen" }, { "code": null, "e": 2506, "s": 2292, "text": "This one is easy enough. I did a quick google search to check out python codes that can be used to access the screen. Here is a really great tutorial, from which I used the basic code and adapted it for this case:" }, { "code": null, "e": 2521, "s": 2506, "text": "holypython.com" }, { "code": null, "e": 2743, "s": 2521, "text": "If we run the code directly, you would see a similar result as seen below in a random game level. You will notice that the colors are a bit different, and the screen rate results in some lag (which is OK for our purpose)." }, { "code": null, "e": 3152, "s": 2743, "text": "Let’s correct the color part with some help from the OpenCV documentation. There is a argument in cv2 that makes the screen recording look like the actual color (or at least as far as my vision allows) which is COLOR_BGR2RGB, that is what I used for the correction here. Also, the time function is used to get the screen rate, which comes to around 10 fps, not bad at all! The modified code looks as follows:" }, { "code": null, "e": 3635, "s": 3152, "text": "# import librariesfrom PIL import ImageGrabimport cv2import numpy as npimport time# for timinglast_time = time.time()# screen capture loopwhile True: screen = np.array(ImageGrab.grab(bbox=(0,40,800,700))) print(f'the screen rate is {(1/(time.time()-last_time))}') last_time = time.time() cv2.imshow('Python Window', cv2.cvtColor(screen, \\ cv2.COLOR_BGR2RGB)) if cv2.waitKey(25) & 0xFF == ord('q'): cv2.destroyAllWindows() break" }, { "code": null, "e": 3933, "s": 3635, "text": "For the above code to correctly capture screen, I have minimized the game window to the top left corner of my primary monitor, with the dimensions as 800 x 700. You could adjust it appropriately in your code (by changing bbox in the ImageGrab above), especially if you are using multiple monitors." }, { "code": null, "e": 3991, "s": 3933, "text": "Once you run this, you get the screen capture as follows:" }, { "code": null, "e": 4118, "s": 3991, "text": "This method of screen capture is extremely handy, particularly when we need to generate images for machine learning use cases." }, { "code": null, "e": 4192, "s": 4118, "text": "Now that we can capture the game window, we can move on to the next step." }, { "code": null, "e": 4236, "s": 4192, "text": "Step 2: Image processing for edge detection" }, { "code": null, "e": 4616, "s": 4236, "text": "Since lane detection is basically an edge identification from image, you would have to process the image to actually get the main outlines. One of the most popular method used in computational vision processing is the Canny algorithm for edge detection. It basically extracts and retains the useful structural information from images, all the while drastically reducing its size." }, { "code": null, "e": 4824, "s": 4616, "text": "Open CV has a neat little implementation of the Canny edge detection. This reduces the complexity of the image much further and we get the edges of the image in the screen with pretty much a three line code." }, { "code": null, "e": 5032, "s": 4824, "text": "Let’s create a small function for processing the image using the Canny implementation in cv2. You can experiment with various values of thresholds by looking into the documentation, the code looks like this:" }, { "code": null, "e": 5310, "s": 5032, "text": "# canny image processing for detecting edgesdef edgeprocessed(image): gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) edgeprocessed_img = cv2.Canny(gray_image, \\ threshold1 = 200, threshold2 = 300) return edgeprocessed_img" }, { "code": null, "e": 5647, "s": 5310, "text": "We have to run the processed image again in the image capture loop, so it makes more sense to define this loop as a function to take into consideration the processing as the input. I will get a bit ahead of myself here and modify it to general function taking the inputs as list, which will make more sense further down in the analysis." }, { "code": null, "e": 6860, "s": 5647, "text": "def screen_capture(processing = None): # takes in a list for type of processing # [processing_function, masking_function] last_time = time.time() while True: screen = np.array(ImageGrab.grab(bbox=(0,40,800,700))) count = 0 if processing is not None: for i in processing: count += 1 processed_screen = processing[0](screen) if count > 1: masked_screen = processing[1] \\ (processed_screen,[vertices]) screen_1 = masked_screen else: screen_1 = processed_screen else: screen_1 = screen cv2.imshow('Python Window 2', screen_1) cv2.imshow('Python Window', cv2.cvtColor(screen, \\ cv2.COLOR_BGR2RGB)) print(f'the screen rate is {(1/(time.time()-last_time))}') last_time = time.time() if cv2.waitKey(25) & 0xFF == ord('q'): cv2.destroyAllWindows() break" }, { "code": null, "e": 7044, "s": 6860, "text": "Makes it much better to use the function now. You will see why I structured the function this way in the next section. Till then, let us check out the result with the edge processing." }, { "code": null, "e": 7076, "s": 7044, "text": "screen_capture([edgeprocessed])" }, { "code": null, "e": 7103, "s": 7076, "text": "This is what you will see:" }, { "code": null, "e": 7240, "s": 7103, "text": "We pretty much get the edges of the objects from the game screen. This is how it looks like when I tried it in a test track in the game:" }, { "code": null, "e": 7584, "s": 7240, "text": "As you notice, there is still too much unwanted information in the image. The trees, rocks, electricity lines, basically everything above the horizon of the road. Not to mention the overlay controls display from the game itself. If we want to focus on the lanes, we have to find a way to somehow filter out or mask the rest of the image lines." }, { "code": null, "e": 7638, "s": 7584, "text": "Step 3: Masking additional information from the image" }, { "code": null, "e": 7977, "s": 7638, "text": "For this, let’s define a masking function. What we need is to define a polygon shape that masks all the information from the image, except the region that lets us focus on the lanes. This is a very basic method used, in this case I defined the vertices of the exact region I need with a bit of trial and error, as seen in the image below:" }, { "code": null, "e": 8218, "s": 7977, "text": "The required region function uses a masked frame and a polygon with vertices. The intersection of the masked and the polygon gives us only the required section of the image. The function and the vertices (defined above) are as you see here:" }, { "code": null, "e": 8671, "s": 8218, "text": "def required_region(image, vertices): mask = np.zeros_like(image) # black image cv2.fillPoly(mask, vertices, 255) # fill within vertices masked = cv2.bitwise_and(image, mask) # intersection return maskedvertices = np.array([[120,500],[120,400],[150,330],[650,330], \\ [680,400],[680,500],[260,500],[260,450], \\ [325,370],[475,370],[540,450][540,500]], \\ np.int32)" }, { "code": null, "e": 8742, "s": 8671, "text": "Now, we can run the screen capture function with these inputs as well." }, { "code": null, "e": 8791, "s": 8742, "text": "screen_capture([edgeprocessed, required_region])" }, { "code": null, "e": 8822, "s": 8791, "text": "And, the result is as follows:" }, { "code": null, "e": 8978, "s": 8822, "text": "As you notice now, I have opaqued out all the unnecessary information except for the lanes. For a rudimentary level code, I’d say that this is pretty neat!" }, { "code": null, "e": 9010, "s": 8978, "text": "But we are not quite there yet." }, { "code": null, "e": 9049, "s": 9010, "text": "Step 4: Finding lines with Hough Lines" }, { "code": null, "e": 9386, "s": 9049, "text": "Finding the actual geometric lines, we need to do some kind of transformation on the edge processed image. In this case, I used the Hough Transform implementation in Open CV. For this to work properly, the image has to be blurred a bit before giving as the input for Hough transform. I used the Gaussian Blur from Open CV for this case." }, { "code": null, "e": 9537, "s": 9386, "text": "Additionally, there is a need to draw the detected lines on the image frames. So I defined one more function overlay the detected lines on the frames." }, { "code": null, "e": 9598, "s": 9537, "text": "The modified overlay line and the edge processing codes are:" }, { "code": null, "e": 10289, "s": 9598, "text": "def overlay_lines(image, lines): for line in lines: coordinates = line[0] cv2.line(image,(coordinates[0],coordinates[1]), \\ (coordinates[2],coordinates[3]),[255,255,255],3)def edgeprocessed(image): gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) edgeprocessed_img = cv2.Canny(gray_image, threshold1 = 200,\\ threshold2 = 300) edgeprocessed_img = cv2.GaussianBlur(edgeprocessed_img,(5,5),0) lines = cv2.HoughLinesP(edgeprocessed_img, 1, np.pi/180, \\ 180, np.array([]), 100, 5) overlay_lines(edgeprocessed_img, lines) return edgeprocessed_img" }, { "code": null, "e": 10385, "s": 10289, "text": "As you can see, that is not bad at all, and with just a few lines of code! We are almost there." }, { "code": null, "e": 10403, "s": 10385, "text": "Step 5: Get Lanes" }, { "code": null, "e": 10965, "s": 10403, "text": "There are a variety of lines detected in the previous step. We have to find a way to merge them in some way so that we can get the actual lanes. This is a bit more complex and I checked out several resources online to see if there is a simpler way that it could be done. I found a great draw lanes function in the Github project here which I used here directly (code not added below as it is too long, but you can refer my project notebook in Github, linked at the end). All that was needed to be done then was to modify the edge processing function as follows:" }, { "code": null, "e": 12310, "s": 10965, "text": "def edgeprocessed(image): original_image = image gray_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY) edgeprocessed_img = cv2.Canny(gray_image, threshold1 = 200, \\ threshold2 = 300) edgeprocessed_img = cv2.GaussianBlur(edgeprocessed_img,(5,5),0) edgeprocessed_img = required_region(edgeprocessed_img, \\ [vertices]) lines = cv2.HoughLinesP(edgeprocessed_img, 1, np.pi/180, 180, \\ np.array([]), 100, 5) #overlay_lines(edgeprocessed_img, lines) m1 = 0 m2 = 0 try: l1, l2, m1, m2 = draw_lines(original_image,lines) cv2.line(original_image, (l1[0], l1[1]), \\ (l1[2], l1[3]), [0,255,0], 30) cv2.line(original_image, (l2[0], l2[1]), \\ (l2[2], l2[3]), [0,255,0], 30) except Exception as e: pass try: for coords in lines: coords = coords[0] try: cv2.line(edgeprocessed_img, (coords[0], coords[1]), (coords[2], coords[3]), [255,0,0], 2) except Exception as e: print(str(e)) except Exception as e: passreturn edgeprocessed_img,original_image, m1, m2" }, { "code": null, "e": 12364, "s": 12310, "text": "And accordingly a few tweaks in the capture function:" }, { "code": null, "e": 13645, "s": 12364, "text": "def screen_capture(processing = None): # takes in a list for type of processing # [processing_function, masking_function] last_time = time.time() while True: screen = np.array(ImageGrab.grab(bbox=(0,40,800,700))) count = 0 if processing is not None: for i in processing: count += 1 processed_screen ,original_image, m1, m2 = \\ processing[0](screen) if count > 1: masked_screen = processing[1] \\ (processed_screen,[vertices]) screen_1 = masked_screen else: screen_1 = processed_screen else: screen_1 = screen cv2.imshow('Python Window 2', screen_1) cv2.imshow('Python Window', cv2.cvtColor(screen, \\ cv2.COLOR_BGR2RGB)) print(f'the screen rate is {(1/(time.time()-last_time))}') last_time = time.time() if cv2.waitKey(25) & 0xFF == ord('q'): cv2.destroyAllWindows() break" }, { "code": null, "e": 13656, "s": 13645, "text": "And voila!" }, { "code": null, "e": 13688, "s": 13656, "text": "screen_capture([edgeprocessed])" }, { "code": null, "e": 13832, "s": 13688, "text": "As you see, there are still more tweaks and fine tuning that can be done. But it is an awesome application as an introductory learning project!" }, { "code": null, "e": 14085, "s": 13832, "text": "The fun part is, the entire thing works live! You can play the game and detect lanes simultaneously as you keep the code running. This gives us a host of possibilities, like saving images for ML, game controls etc. which I will explore in future posts." }, { "code": null, "e": 14223, "s": 14085, "text": "That’s it, folks! I hope you managed to implement lane detection in these 5 simple steps. The Jupyter notebook can be found in this link." } ]
[Learning Note] Single Shot MultiBox Detector with Pytorch — Part 1 | by Ceshine Lee | Towards Data Science
Recently I’m trying to pick up Pytorch as well as some object detection deep learning algorithms. So to kill two birds with one stone, I decided to read the Single Shot MultiBox Detector paper along with one of the Pytorch implementation written by Max deGroot. Admittedly, I have some trouble understanding some ideas in the paper. After reading the implementation and scratching my head for a while, I think I figured out at least some parts of them. So the following is my notes on some confusing concept after my first and second pass of reading. Firstly, Single Shot MultiBox Detector (SSD) uses VGG-16 structure pre-trained on the ILSVRC CLS-LOC dataset, and add some extra convolution layers. The relevant code is located at ssd.py: base = { '300': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'C', 512, 512, 512, 'M', 512, 512, 512], '512': [],}extras = { '300': [256, 'S', 512, 128, 'S', 256, 128, 256, 128, 256], '512': [],} ‘M’ means max pooling with kernel size 2 and stride 2. ‘C’ means the same max pooling but with ceil_mode=True, which does not appear in the original structure. My understanding is thatceil_mode=True deals with cases where input height or width is not divisible by 2, so there will be some cell coming from 1x2, 2x1, 1x1 max pooling in the output. Not sure why it’s there, but shouldn’t make much difference. ‘S’ means a stride=2 and padding=1 convolution layer, the number of filters comes next in the list (for example, the first ‘S’ has 512 filters). def vgg(cfg, i, batch_norm=False): layers = [] in_channels = i for v in cfg: if v == 'M': layers += [nn.MaxPool2d(kernel_size=2, stride=2)] elif v == 'C': layers += [nn.MaxPool2d( kernel_size=2, stride=2, ceil_mode=True)] else: conv2d = nn.Conv2d( in_channels, v, kernel_size=3, padding=1) if batch_norm: layers += [ conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)] else: layers += [conv2d, nn.ReLU(inplace=True)] in_channels = v pool5 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1) conv6 = nn.Conv2d( 512, 1024, kernel_size=3, padding=6, dilation=6) conv7 = nn.Conv2d(1024, 1024, kernel_size=1) layers += [pool5, conv6, nn.ReLU(inplace=True), conv7, nn.ReLU(inplace=True)] return layers Note it adds a conv6 (1024 3x3 convolution filters with dilation=6 and padding=6) and a conv7 (1024 1x1 convolution filters) layer to the original VGG structure. def add_extras(cfg, i, batch_norm=False): # Extra layers added to VGG for feature scaling layers = [] in_channels = i flag = False for k, v in enumerate(cfg): if in_channels != 'S': if v == 'S': layers += [ nn.Conv2d(in_channels, cfg[k + 1], kernel_size=(1, 3)[flag], stride=2, padding=1)] else: layers += [ nn.Conv2d( in_channels, v, kernel_size=(1, 3)[flag])] flag = not flag in_channels = v return layer The construction of extra layers use a rotating 3x3 and 1x1 kernel size with optional ‘S’ flag indicated stride=2 and padding=1 as we already mentioned. We’ve covered the network structure. Now it’s time to move on to actually predict/detect the class and location of the objects. A key concept of SSD is taking intermediate layers in the neural network as feature map. It then run 3x3 convolution filters on the feature map to classify and predict the offset to the default boxes (prior boxes in Python code). Each position has 4 or 6 corresponding default boxes. Naturally, default boxes in the lower layers are smaller because lower layers captures more fine details of the input images. For each default box we predict: the probability of it belong to a certain classthe x and y offsets to the center of the default boxthe width and height scales to the width and height of the default box the probability of it belong to a certain class the x and y offsets to the center of the default box the width and height scales to the width and height of the default box The default box setup in ssd.py: mbox = { # number of boxes per feature map location '300': [4, 6, 6, 6, 4, 4], '512': [],}def multibox(vgg, extra_layers, cfg, num_classes): loc_layers = [] conf_layers = [] vgg_source = [24, -2] for k, v in enumerate(vgg_source): loc_layers += [ nn.Conv2d(vgg[v].out_channels, cfg[k] * 4, kernel_size=3, padding=1)] conf_layers += [ nn.Conv2d(vgg[v].out_channels, cfg[k] * num_classes, kernel_size=3, padding=1)] for k, v in enumerate(extra_layers[1::2], 2): loc_layers += [ nn.Conv2d(v.out_channels, cfg[k] * 4, kernel_size=3, padding=1)] conf_layers += [ nn.Conv2d(v.out_channels, cfg[k] * num_classes, kernel_size=3, padding=1)] return vgg, extra_layers, (loc_layers, conf_layers)def build_ssd(phase, size=300, num_classes=21): if phase != "test" and phase != "train": print("Error: Phase not recognized") return if size != 300: print("Error: Sorry only SSD300 is supported currently!") return return SSD( phase, *multibox(vgg(base[str(size)], 3), add_extras(extras[str(size)], 1024), mbox[str(size)], num_classes), num_classes ) SSD use two layers from the VGG model — Conv4_3 and Conv7/FC7, which correspond to layer index 24 and -2 (that is, before relu activation). This way of getting layers is a bit shaky. If we decided to use use batch_norm=True in VGG construction, the multibox construction would get the wrong layer. The same should go with extra layers as well, but in fact batch_norm=True has not even been implemented yet in add_extras() . For extra layers, we use the second layer as feature map in every two layers. One weird part is that because final layer Conv11_2 has shape (256, 1, 1), so 3x3 convolution isn’t really necessary. I guess it just for the simplicity of code structure. Note we should have num_class + 4 (x, y, w, h) outputs per default box. Try to verify the number of default boxes in SSD300 (the one implemented). Conv4_3: 38 * 38 * 4 = 5776Conv7: 19 * 19 * 6 = 2166Conv8_2: 10 * 10 * 6 = 600Conv9_2: 5 * 5 * 6 = 150Conv10_2: 3 * 3 * 4 = 36Conv11_2: 4 Conv4_3: 38 * 38 * 4 = 5776 Conv7: 19 * 19 * 6 = 2166 Conv8_2: 10 * 10 * 6 = 600 Conv9_2: 5 * 5 * 6 = 150 Conv10_2: 3 * 3 * 4 = 36 Conv11_2: 4 Total: 5776+ 2166 + 600 + 150 + 36 + 4 = 8732 Note that this calculation includes default boxes from padded cells, which will always be zeros, thereby essentially useless boxes. Additional exercise: calculate the number of valid default boxes in SSD300. We still haven’t discuss how to map those default boxes back to actual locations in the input images, how do we pick correct default boxes that matches the ground truth, and how to construct loss function to train the network. They will be addressed in the next post. (2017/07/28 Update: Here are the links to the second part and the third part of the series.) (2018/07/12 Update: Someone asked me an interesting question privately. With that person’s permission, the Q&A is reposted here: Q: I tried to read both paper VGG-16 and SSD and everywhere it is mentioned that SSD used VGG-16 architecture but SSD architecture image from original paper starts from size (38 X 38 X 512) but only size available in VGG-16 architecture is (224x224x64),(112x112x128),(56x56x256) and so on but nowhere its (38x38x512). A: Note the (official) input image size of VGG16 is 224, and the one of SSD is 300. For 224, the feature map evolve as (224, 224, 64), (112, 112, 128), (56, 56, 256) and (28, 28, 512) as you said. But if you put (300, 300, 3) image input into the VGG16 architecture. The feature map evolution becomes (300, 300, 64), (150, 150, 128), (75, 75, 256), (38, 38, 512).)
[ { "code": null, "e": 434, "s": 172, "text": "Recently I’m trying to pick up Pytorch as well as some object detection deep learning algorithms. So to kill two birds with one stone, I decided to read the Single Shot MultiBox Detector paper along with one of the Pytorch implementation written by Max deGroot." }, { "code": null, "e": 723, "s": 434, "text": "Admittedly, I have some trouble understanding some ideas in the paper. After reading the implementation and scratching my head for a while, I think I figured out at least some parts of them. So the following is my notes on some confusing concept after my first and second pass of reading." }, { "code": null, "e": 912, "s": 723, "text": "Firstly, Single Shot MultiBox Detector (SSD) uses VGG-16 structure pre-trained on the ILSVRC CLS-LOC dataset, and add some extra convolution layers. The relevant code is located at ssd.py:" }, { "code": null, "e": 1130, "s": 912, "text": "base = { '300': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'C', 512, 512, 512, 'M', 512, 512, 512], '512': [],}extras = { '300': [256, 'S', 512, 128, 'S', 256, 128, 256, 128, 256], '512': [],}" }, { "code": null, "e": 1538, "s": 1130, "text": "‘M’ means max pooling with kernel size 2 and stride 2. ‘C’ means the same max pooling but with ceil_mode=True, which does not appear in the original structure. My understanding is thatceil_mode=True deals with cases where input height or width is not divisible by 2, so there will be some cell coming from 1x2, 2x1, 1x1 max pooling in the output. Not sure why it’s there, but shouldn’t make much difference." }, { "code": null, "e": 1683, "s": 1538, "text": "‘S’ means a stride=2 and padding=1 convolution layer, the number of filters comes next in the list (for example, the first ‘S’ has 512 filters)." }, { "code": null, "e": 2629, "s": 1683, "text": "def vgg(cfg, i, batch_norm=False): layers = [] in_channels = i for v in cfg: if v == 'M': layers += [nn.MaxPool2d(kernel_size=2, stride=2)] elif v == 'C': layers += [nn.MaxPool2d( kernel_size=2, stride=2, ceil_mode=True)] else: conv2d = nn.Conv2d( in_channels, v, kernel_size=3, padding=1) if batch_norm: layers += [ conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)] else: layers += [conv2d, nn.ReLU(inplace=True)] in_channels = v pool5 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1) conv6 = nn.Conv2d( 512, 1024, kernel_size=3, padding=6, dilation=6) conv7 = nn.Conv2d(1024, 1024, kernel_size=1) layers += [pool5, conv6, nn.ReLU(inplace=True), conv7, nn.ReLU(inplace=True)] return layers" }, { "code": null, "e": 2791, "s": 2629, "text": "Note it adds a conv6 (1024 3x3 convolution filters with dilation=6 and padding=6) and a conv7 (1024 1x1 convolution filters) layer to the original VGG structure." }, { "code": null, "e": 3396, "s": 2791, "text": "def add_extras(cfg, i, batch_norm=False): # Extra layers added to VGG for feature scaling layers = [] in_channels = i flag = False for k, v in enumerate(cfg): if in_channels != 'S': if v == 'S': layers += [ nn.Conv2d(in_channels, cfg[k + 1], kernel_size=(1, 3)[flag], stride=2, padding=1)] else: layers += [ nn.Conv2d( in_channels, v, kernel_size=(1, 3)[flag])] flag = not flag in_channels = v return layer" }, { "code": null, "e": 3549, "s": 3396, "text": "The construction of extra layers use a rotating 3x3 and 1x1 kernel size with optional ‘S’ flag indicated stride=2 and padding=1 as we already mentioned." }, { "code": null, "e": 3677, "s": 3549, "text": "We’ve covered the network structure. Now it’s time to move on to actually predict/detect the class and location of the objects." }, { "code": null, "e": 4087, "s": 3677, "text": "A key concept of SSD is taking intermediate layers in the neural network as feature map. It then run 3x3 convolution filters on the feature map to classify and predict the offset to the default boxes (prior boxes in Python code). Each position has 4 or 6 corresponding default boxes. Naturally, default boxes in the lower layers are smaller because lower layers captures more fine details of the input images." }, { "code": null, "e": 4120, "s": 4087, "text": "For each default box we predict:" }, { "code": null, "e": 4290, "s": 4120, "text": "the probability of it belong to a certain classthe x and y offsets to the center of the default boxthe width and height scales to the width and height of the default box" }, { "code": null, "e": 4338, "s": 4290, "text": "the probability of it belong to a certain class" }, { "code": null, "e": 4391, "s": 4338, "text": "the x and y offsets to the center of the default box" }, { "code": null, "e": 4462, "s": 4391, "text": "the width and height scales to the width and height of the default box" }, { "code": null, "e": 4495, "s": 4462, "text": "The default box setup in ssd.py:" }, { "code": null, "e": 5846, "s": 4495, "text": "mbox = { # number of boxes per feature map location '300': [4, 6, 6, 6, 4, 4], '512': [],}def multibox(vgg, extra_layers, cfg, num_classes): loc_layers = [] conf_layers = [] vgg_source = [24, -2] for k, v in enumerate(vgg_source): loc_layers += [ nn.Conv2d(vgg[v].out_channels, cfg[k] * 4, kernel_size=3, padding=1)] conf_layers += [ nn.Conv2d(vgg[v].out_channels, cfg[k] * num_classes, kernel_size=3, padding=1)] for k, v in enumerate(extra_layers[1::2], 2): loc_layers += [ nn.Conv2d(v.out_channels, cfg[k] * 4, kernel_size=3, padding=1)] conf_layers += [ nn.Conv2d(v.out_channels, cfg[k] * num_classes, kernel_size=3, padding=1)] return vgg, extra_layers, (loc_layers, conf_layers)def build_ssd(phase, size=300, num_classes=21): if phase != \"test\" and phase != \"train\": print(\"Error: Phase not recognized\") return if size != 300: print(\"Error: Sorry only SSD300 is supported currently!\") return return SSD( phase, *multibox(vgg(base[str(size)], 3), add_extras(extras[str(size)], 1024), mbox[str(size)], num_classes), num_classes )" }, { "code": null, "e": 6270, "s": 5846, "text": "SSD use two layers from the VGG model — Conv4_3 and Conv7/FC7, which correspond to layer index 24 and -2 (that is, before relu activation). This way of getting layers is a bit shaky. If we decided to use use batch_norm=True in VGG construction, the multibox construction would get the wrong layer. The same should go with extra layers as well, but in fact batch_norm=True has not even been implemented yet in add_extras() ." }, { "code": null, "e": 6520, "s": 6270, "text": "For extra layers, we use the second layer as feature map in every two layers. One weird part is that because final layer Conv11_2 has shape (256, 1, 1), so 3x3 convolution isn’t really necessary. I guess it just for the simplicity of code structure." }, { "code": null, "e": 6592, "s": 6520, "text": "Note we should have num_class + 4 (x, y, w, h) outputs per default box." }, { "code": null, "e": 6667, "s": 6592, "text": "Try to verify the number of default boxes in SSD300 (the one implemented)." }, { "code": null, "e": 6805, "s": 6667, "text": "Conv4_3: 38 * 38 * 4 = 5776Conv7: 19 * 19 * 6 = 2166Conv8_2: 10 * 10 * 6 = 600Conv9_2: 5 * 5 * 6 = 150Conv10_2: 3 * 3 * 4 = 36Conv11_2: 4" }, { "code": null, "e": 6833, "s": 6805, "text": "Conv4_3: 38 * 38 * 4 = 5776" }, { "code": null, "e": 6859, "s": 6833, "text": "Conv7: 19 * 19 * 6 = 2166" }, { "code": null, "e": 6886, "s": 6859, "text": "Conv8_2: 10 * 10 * 6 = 600" }, { "code": null, "e": 6911, "s": 6886, "text": "Conv9_2: 5 * 5 * 6 = 150" }, { "code": null, "e": 6936, "s": 6911, "text": "Conv10_2: 3 * 3 * 4 = 36" }, { "code": null, "e": 6948, "s": 6936, "text": "Conv11_2: 4" }, { "code": null, "e": 6994, "s": 6948, "text": "Total: 5776+ 2166 + 600 + 150 + 36 + 4 = 8732" }, { "code": null, "e": 7126, "s": 6994, "text": "Note that this calculation includes default boxes from padded cells, which will always be zeros, thereby essentially useless boxes." }, { "code": null, "e": 7202, "s": 7126, "text": "Additional exercise: calculate the number of valid default boxes in SSD300." }, { "code": null, "e": 7470, "s": 7202, "text": "We still haven’t discuss how to map those default boxes back to actual locations in the input images, how do we pick correct default boxes that matches the ground truth, and how to construct loss function to train the network. They will be addressed in the next post." }, { "code": null, "e": 7563, "s": 7470, "text": "(2017/07/28 Update: Here are the links to the second part and the third part of the series.)" }, { "code": null, "e": 7692, "s": 7563, "text": "(2018/07/12 Update: Someone asked me an interesting question privately. With that person’s permission, the Q&A is reposted here:" }, { "code": null, "e": 8010, "s": 7692, "text": "Q: I tried to read both paper VGG-16 and SSD and everywhere it is mentioned that SSD used VGG-16 architecture but SSD architecture image from original paper starts from size (38 X 38 X 512) but only size available in VGG-16 architecture is (224x224x64),(112x112x128),(56x56x256) and so on but nowhere its (38x38x512)." } ]
Java.io.SequenceInputStream in Java - GeeksforGeeks
06 Jan, 2017 The SequenceInputStream class allows you to concatenate multiple InputStreams. It reads data of streams one by one. It starts out with an ordered collection of input streams and reads from the first one until end of file is reached, whereupon it reads from the second one, and so on, until end of file is reached on the last of the contained input streams. Constructor and Description SequenceInputStream(Enumeration e) : Initializes a newly created SequenceInputStream , which must be an Enumeration that produces objects whose type is InputStream. SequenceInputStream(InputStream s1, InputStream s2) : Initializes a newly created SequenceInputStream by remembering the two arguments, which will be read in order, first s1 and then s2. Important Methods: read :Reads the next byte of data from this input stream.Syntax: public int read() throws IOException Returns: the next byte of data, or -1 if the end of the stream is reached. Throws: IOException - if an I/O error occurs. Syntax: public int read() throws IOException Returns: the next byte of data, or -1 if the end of the stream is reached. Throws: IOException - if an I/O error occurs. read(byte[] b, int off, int len) : Reads up to len bytes of data from this input stream into an array ofSyntax: public int read(byte[] b, int off, int len) throws IOException Overrides: read in class InputStream Parameters: b - the buffer into which the data is read. off - the start offset in array b at which the data is written. len - the maximum number of bytes read. Returns: int the number of bytes read. Throws: NullPointerException - If b is null. IndexOutOfBoundsException - If off is negative, len is negative, or len is greater than b.length - off IOException - if an I/O error occurs. Syntax: public int read(byte[] b, int off, int len) throws IOException Overrides: read in class InputStream Parameters: b - the buffer into which the data is read. off - the start offset in array b at which the data is written. len - the maximum number of bytes read. Returns: int the number of bytes read. Throws: NullPointerException - If b is null. IndexOutOfBoundsException - If off is negative, len is negative, or len is greater than b.length - off IOException - if an I/O error occurs. available : Returns an estimate of the number of bytes that can be read (or skipped over) from the current underlying input stream without blocking by the next invocation of a method for the current underlying input stream.Syntax : public int available() throws IOException Overrides: available in class InputStream Returns:an estimate of the number of bytes that can be read (or skipped over) from the current underlying input stream without blocking or 0 if this input stream has been closed by invoking its close() method Throws: IOException - if an I/O error occurs. Syntax : public int available() throws IOException Overrides: available in class InputStream Returns:an estimate of the number of bytes that can be read (or skipped over) from the current underlying input stream without blocking or 0 if this input stream has been closed by invoking its close() method Throws: IOException - if an I/O error occurs. close:Closes this input stream and releases any system resources associated with the stream.Syntax : public void close() throws IOException Overrides: close in class InputStream Throws: IOException - if an I/O error occurs. Syntax : public void close() throws IOException Overrides: close in class InputStream Throws: IOException - if an I/O error occurs. The following is an example of SequenceInputStream class that implements some of the important methods.Program: //Java program to demonstrate SequenceInputStreamimport java.io.*;import java.util.*; class SequenceISDemp{ public static void main(String args[])throws IOException { //creating the FileInputStream objects for all the following files FileInputStream fin=new FileInputStream("file1.txt"); FileInputStream fin2=new FileInputStream("file2.txt"); FileInputStream fin3=new FileInputStream("file3.txt"); //adding fileinputstream obj to a vector object Vector v = new Vector(); v.add(fin); v.add(fin2); v.add(fin3); //creating enumeration object by calling the elements method Enumeration enumeration = v.elements(); //passing the enumeration object in the constructor SequenceInputStream sin = new SequenceInputStream(enumeration); // determine how many bytes are available in the first stream System.out.println("" + sin.available()); // Estimating the number of bytes that can be read // from the current underlying input stream System.out.println( sin.available()); int i = 0; while((i = sin.read())! = -1) { System.out.print((char)i); } sin.close(); fin.close(); fin2.close(); fin3.close(); }} Output: 19 This is first file This is second file This is third file Note: This program will not run on online IDE as there are no files associated with it. This article is contributed by Nishant Sharma. 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. Java-I/O Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Initialize an ArrayList in Java Overriding in Java Multidimensional Arrays in Java LinkedList in Java ArrayList in Java PriorityQueue in Java Queue Interface In Java Stack Class in Java Initializing a List in Java Collections.sort() in Java with Examples
[ { "code": null, "e": 23939, "s": 23911, "text": "\n06 Jan, 2017" }, { "code": null, "e": 24296, "s": 23939, "text": "The SequenceInputStream class allows you to concatenate multiple InputStreams. It reads data of streams one by one. It starts out with an ordered collection of input streams and reads from the first one until end of file is reached, whereupon it reads from the second one, and so on, until end of file is reached on the last of the contained input streams." }, { "code": null, "e": 24324, "s": 24296, "text": "Constructor and Description" }, { "code": null, "e": 24489, "s": 24324, "text": "SequenceInputStream(Enumeration e) : Initializes a newly created SequenceInputStream , which must be an Enumeration that produces objects whose type is InputStream." }, { "code": null, "e": 24676, "s": 24489, "text": "SequenceInputStream(InputStream s1, InputStream s2) : Initializes a newly created SequenceInputStream by remembering the two arguments, which will be read in order, first s1 and then s2." }, { "code": null, "e": 24695, "s": 24676, "text": "Important Methods:" }, { "code": null, "e": 24929, "s": 24695, "text": "read :Reads the next byte of data from this input stream.Syntax:\npublic int read()\n throws IOException \nReturns: the next byte of data, or -1 if the end of the stream is reached.\nThrows: IOException - if an I/O error occurs.\n" }, { "code": null, "e": 25106, "s": 24929, "text": "Syntax:\npublic int read()\n throws IOException \nReturns: the next byte of data, or -1 if the end of the stream is reached.\nThrows: IOException - if an I/O error occurs.\n" }, { "code": null, "e": 25727, "s": 25106, "text": "read(byte[] b, int off, int len) : Reads up to len bytes of data from this input stream into an array ofSyntax:\npublic int read(byte[] b,\n int off,\n int len)\n throws IOException\nOverrides: read in class InputStream\nParameters:\nb - the buffer into which the data is read.\noff - the start offset in array b at which the data is written.\nlen - the maximum number of bytes read.\nReturns: int the number of bytes read.\nThrows:\nNullPointerException - If b is null.\nIndexOutOfBoundsException - If off is negative, len is negative, \nor len is greater than b.length - off\nIOException - if an I/O error occurs." }, { "code": null, "e": 26244, "s": 25727, "text": "Syntax:\npublic int read(byte[] b,\n int off,\n int len)\n throws IOException\nOverrides: read in class InputStream\nParameters:\nb - the buffer into which the data is read.\noff - the start offset in array b at which the data is written.\nlen - the maximum number of bytes read.\nReturns: int the number of bytes read.\nThrows:\nNullPointerException - If b is null.\nIndexOutOfBoundsException - If off is negative, len is negative, \nor len is greater than b.length - off\nIOException - if an I/O error occurs." }, { "code": null, "e": 26831, "s": 26244, "text": "available : Returns an estimate of the number of bytes that can be read (or skipped over) from the current underlying input stream without blocking by the next invocation of a method for the current underlying input stream.Syntax :\npublic int available()\n throws IOException \nOverrides: available in class InputStream\nReturns:an estimate of the number of bytes that can be read (or skipped over) \nfrom the current underlying input stream without blocking or 0 if this input stream\nhas been closed by invoking its close() method\nThrows:\nIOException - if an I/O error occurs." }, { "code": null, "e": 27195, "s": 26831, "text": "Syntax :\npublic int available()\n throws IOException \nOverrides: available in class InputStream\nReturns:an estimate of the number of bytes that can be read (or skipped over) \nfrom the current underlying input stream without blocking or 0 if this input stream\nhas been closed by invoking its close() method\nThrows:\nIOException - if an I/O error occurs." }, { "code": null, "e": 27430, "s": 27195, "text": "close:Closes this input stream and releases any system resources associated with the stream.Syntax :\npublic void close()\n throws IOException\nOverrides: close in class InputStream\nThrows:\nIOException - if an I/O error occurs." }, { "code": null, "e": 27573, "s": 27430, "text": "Syntax :\npublic void close()\n throws IOException\nOverrides: close in class InputStream\nThrows:\nIOException - if an I/O error occurs." }, { "code": null, "e": 27685, "s": 27573, "text": "The following is an example of SequenceInputStream class that implements some of the important methods.Program:" }, { "code": "//Java program to demonstrate SequenceInputStreamimport java.io.*;import java.util.*; class SequenceISDemp{ public static void main(String args[])throws IOException { //creating the FileInputStream objects for all the following files FileInputStream fin=new FileInputStream(\"file1.txt\"); FileInputStream fin2=new FileInputStream(\"file2.txt\"); FileInputStream fin3=new FileInputStream(\"file3.txt\"); //adding fileinputstream obj to a vector object Vector v = new Vector(); v.add(fin); v.add(fin2); v.add(fin3); //creating enumeration object by calling the elements method Enumeration enumeration = v.elements(); //passing the enumeration object in the constructor SequenceInputStream sin = new SequenceInputStream(enumeration); // determine how many bytes are available in the first stream System.out.println(\"\" + sin.available()); // Estimating the number of bytes that can be read // from the current underlying input stream System.out.println( sin.available()); int i = 0; while((i = sin.read())! = -1) { System.out.print((char)i); } sin.close(); fin.close(); fin2.close(); fin3.close(); }}", "e": 29038, "s": 27685, "text": null }, { "code": null, "e": 29046, "s": 29038, "text": "Output:" }, { "code": null, "e": 29108, "s": 29046, "text": "19\nThis is first file This is second file This is third file\n" }, { "code": null, "e": 29196, "s": 29108, "text": "Note: This program will not run on online IDE as there are no files associated with it." }, { "code": null, "e": 29498, "s": 29196, "text": "This article is contributed by Nishant Sharma. 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": 29623, "s": 29498, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 29632, "s": 29623, "text": "Java-I/O" }, { "code": null, "e": 29637, "s": 29632, "text": "Java" }, { "code": null, "e": 29642, "s": 29637, "text": "Java" }, { "code": null, "e": 29740, "s": 29642, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29749, "s": 29740, "text": "Comments" }, { "code": null, "e": 29762, "s": 29749, "text": "Old Comments" }, { "code": null, "e": 29794, "s": 29762, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29813, "s": 29794, "text": "Overriding in Java" }, { "code": null, "e": 29845, "s": 29813, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 29864, "s": 29845, "text": "LinkedList in Java" }, { "code": null, "e": 29882, "s": 29864, "text": "ArrayList in Java" }, { "code": null, "e": 29904, "s": 29882, "text": "PriorityQueue in Java" }, { "code": null, "e": 29928, "s": 29904, "text": "Queue Interface In Java" }, { "code": null, "e": 29948, "s": 29928, "text": "Stack Class in Java" }, { "code": null, "e": 29976, "s": 29948, "text": "Initializing a List in Java" } ]
Hierarchical data in Pandas - GeeksforGeeks
11 Dec, 2020 In pandas, we can arrange data within the data frame from the existing data frame. For example, we are having the same name with different features, instead of writing the name all time, we can write only once. We can create hierarchical data from the existing data frame using pandas. Example: See the student subject details. Here we can see name of student is always repeating. With this, we need memory to store multiple name. We can reduce this by using data hierarchy. Example: Python3 # import pandas module for data frameimport pandas as pd # Create dataframe for student data in different collegessubjectsdata = {'Name': ['sravan', 'sravan', 'sravan', 'sravan', 'sravan', 'sravan', 'sravan', 'sravan', 'Ojaswi', 'Ojaswi', 'Ojaswi', 'Ojaswi', 'Ojaswi', 'Ojaswi', 'Ojaswi', 'Ojaswi', 'Rohith', 'Rohith', 'Rohith', 'Rohith', 'Rohith', 'Rohith', 'Rohith', 'Rohith'], 'college': ['VFSTRU', 'VFSTRU', 'VFSTRU', 'VFSTRU', 'VFSTRU', 'VFSTRU', 'VFSTRU', 'VFSTRU', 'VIT', 'VIT', 'VIT', 'VIT', 'VIT', 'VIT', 'VIT', 'VIT', 'IIT-Bhu', 'IIT-Bhu', 'IIT-Bhu', 'IIT-Bhu', 'IIT-Bhu', 'IIT-Bhu', 'IIT-Bhu', 'IIT-Bhu'], 'subject': ['java', 'dbms', 'dms', 'coa', 'python', 'dld', 'android', 'iot', 'java', 'dbms', 'dms', 'coa', 'python', 'dld', 'android', 'iot', 'java', 'dbms', 'dms', 'coa', 'python', 'dld', 'android', 'iot'] } # Convert into data framedf = pd.DataFrame(subjectsdata) # print the data(student records)print(df) Output: Python3 # Set the hierarchical indexdf = df.set_index(['Name', 'college'], drop=False) # print data framedf Output: The next step is to remove the name. Python3 # setting indexdf = df.set_index(['Name', 'college']) # print data framedf Output: Now get college as the index using swap level. Python3 # Swap the levels in the indexdf.swaplevel('Name', 'college') Output: Now give a summary of the results Python3 # Summarize the results by collegedf.sum(level='college') Output: Python-pandas Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Python OOPs Concepts Python | Get unique values from a list Check if element exists in list in Python Python Classes and Objects Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Pandas dataframe.groupby() Create a directory in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n11 Dec, 2020" }, { "code": null, "e": 24498, "s": 24212, "text": "In pandas, we can arrange data within the data frame from the existing data frame. For example, we are having the same name with different features, instead of writing the name all time, we can write only once. We can create hierarchical data from the existing data frame using pandas." }, { "code": null, "e": 24507, "s": 24498, "text": "Example:" }, { "code": null, "e": 24593, "s": 24507, "text": "See the student subject details. Here we can see name of student is always repeating." }, { "code": null, "e": 24687, "s": 24593, "text": "With this, we need memory to store multiple name. We can reduce this by using data hierarchy." }, { "code": null, "e": 24696, "s": 24687, "text": "Example:" }, { "code": null, "e": 24704, "s": 24696, "text": "Python3" }, { "code": "# import pandas module for data frameimport pandas as pd # Create dataframe for student data in different collegessubjectsdata = {'Name': ['sravan', 'sravan', 'sravan', 'sravan', 'sravan', 'sravan', 'sravan', 'sravan', 'Ojaswi', 'Ojaswi', 'Ojaswi', 'Ojaswi', 'Ojaswi', 'Ojaswi', 'Ojaswi', 'Ojaswi', 'Rohith', 'Rohith', 'Rohith', 'Rohith', 'Rohith', 'Rohith', 'Rohith', 'Rohith'], 'college': ['VFSTRU', 'VFSTRU', 'VFSTRU', 'VFSTRU', 'VFSTRU', 'VFSTRU', 'VFSTRU', 'VFSTRU', 'VIT', 'VIT', 'VIT', 'VIT', 'VIT', 'VIT', 'VIT', 'VIT', 'IIT-Bhu', 'IIT-Bhu', 'IIT-Bhu', 'IIT-Bhu', 'IIT-Bhu', 'IIT-Bhu', 'IIT-Bhu', 'IIT-Bhu'], 'subject': ['java', 'dbms', 'dms', 'coa', 'python', 'dld', 'android', 'iot', 'java', 'dbms', 'dms', 'coa', 'python', 'dld', 'android', 'iot', 'java', 'dbms', 'dms', 'coa', 'python', 'dld', 'android', 'iot'] } # Convert into data framedf = pd.DataFrame(subjectsdata) # print the data(student records)print(df)", "e": 26082, "s": 24704, "text": null }, { "code": null, "e": 26090, "s": 26082, "text": "Output:" }, { "code": null, "e": 26098, "s": 26090, "text": "Python3" }, { "code": "# Set the hierarchical indexdf = df.set_index(['Name', 'college'], drop=False) # print data framedf", "e": 26199, "s": 26098, "text": null }, { "code": null, "e": 26207, "s": 26199, "text": "Output:" }, { "code": null, "e": 26244, "s": 26207, "text": "The next step is to remove the name." }, { "code": null, "e": 26252, "s": 26244, "text": "Python3" }, { "code": "# setting indexdf = df.set_index(['Name', 'college']) # print data framedf", "e": 26328, "s": 26252, "text": null }, { "code": null, "e": 26336, "s": 26328, "text": "Output:" }, { "code": null, "e": 26383, "s": 26336, "text": "Now get college as the index using swap level." }, { "code": null, "e": 26391, "s": 26383, "text": "Python3" }, { "code": "# Swap the levels in the indexdf.swaplevel('Name', 'college')", "e": 26453, "s": 26391, "text": null }, { "code": null, "e": 26461, "s": 26453, "text": "Output:" }, { "code": null, "e": 26495, "s": 26461, "text": "Now give a summary of the results" }, { "code": null, "e": 26503, "s": 26495, "text": "Python3" }, { "code": "# Summarize the results by collegedf.sum(level='college')", "e": 26561, "s": 26503, "text": null }, { "code": null, "e": 26569, "s": 26561, "text": "Output:" }, { "code": null, "e": 26583, "s": 26569, "text": "Python-pandas" }, { "code": null, "e": 26607, "s": 26583, "text": "Technical Scripter 2020" }, { "code": null, "e": 26614, "s": 26607, "text": "Python" }, { "code": null, "e": 26633, "s": 26614, "text": "Technical Scripter" }, { "code": null, "e": 26731, "s": 26633, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26740, "s": 26731, "text": "Comments" }, { "code": null, "e": 26753, "s": 26740, "text": "Old Comments" }, { "code": null, "e": 26785, "s": 26753, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26841, "s": 26785, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26862, "s": 26841, "text": "Python OOPs Concepts" }, { "code": null, "e": 26901, "s": 26862, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26943, "s": 26901, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26970, "s": 26943, "text": "Python Classes and Objects" }, { "code": null, "e": 27001, "s": 26970, "text": "Python | os.path.join() method" }, { "code": null, "e": 27043, "s": 27001, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27079, "s": 27043, "text": "Python | Pandas dataframe.groupby()" } ]
HTML5 - Web RTC
Web RTC introduced by World Wide Web Consortium (W3C). That supports browser-tobrowser applications for voice calling, video chat, and P2P file sharing. If you want to try out? web RTC available for Chrome, Opera, and Firefox. A good place to start is the simple video chat application at here. Web RTC implements three API's as shown below − MediaStream − get access to the user's camera and microphone. MediaStream − get access to the user's camera and microphone. RTCPeerConnection − get access to audio or video calling facility. RTCPeerConnection − get access to audio or video calling facility. RTCDataChannel − get access to peer-to-peer communication. RTCDataChannel − get access to peer-to-peer communication. The MediaStream represents synchronized streams of media, For an example, Click on HTML5 Video player in HTML5 demo section or else click here. The above example contains stream.getAudioTracks() and stream.VideoTracks(). If there is no audio tracks, it returns an empty array and it will check video stream,if webcam connected, stream.getVideoTracks() returns an array of one MediaStreamTrack representing the stream from the webcam. A simple example is chat applications, a chat application gets stream from web camera, rear camera, microphone. function gotStream(stream) { window.AudioContext = window.AudioContext || window.webkitAudioContext; var audioContext = new AudioContext(); // Create an AudioNode from the stream var mediaStreamSource = audioContext.createMediaStreamSource(stream); // Connect it to destination to hear yourself // or any other node for processing! mediaStreamSource.connect(audioContext.destination); } navigator.getUserMedia({audio:true}, gotStream); It's also possible in Chrome browser with mediaStreamSource and it requires HTTPS. This feature is not yet available in opera. Sample demo is available at here Web RTC required peer-to-peer communication between browsers. This mechanism required signaling, network information, session control and media information. Web developers can choose different mechanism to communicate between the browsers such as SIP or XMPP or any two way communications. A sample example of XHR is here. var signalingChannel = createSignalingChannel(); var pc; var configuration = ...; // run start(true) to initiate a call function start(isCaller) { pc = new RTCPeerConnection(configuration); // send any ice candidates to the other peer pc.onicecandidate = function (evt) { signalingChannel.send(JSON.stringify({ "candidate": evt.candidate })); }; // once remote stream arrives, show it in the remote video element pc.onaddstream = function (evt) { remoteView.src = URL.createObjectURL(evt.stream); }; // get the local stream, show it in the local video element and send it navigator.getUserMedia({ "audio": true, "video": true }, function (stream) { selfView.src = URL.createObjectURL(stream); pc.addStream(stream); if (isCaller) pc.createOffer(gotDescription); else pc.createAnswer(pc.remoteDescription, gotDescription); function gotDescription(desc) { pc.setLocalDescription(desc); signalingChannel.send(JSON.stringify({ "sdp": desc })); } }); } signalingChannel.onmessage = function (evt) { if (!pc) start(false); var signal = JSON.parse(evt.data); if (signal.sdp) pc.setRemoteDescription(new RTCSessionDescription(signal.sdp)); else pc.addIceCandidate(new RTCIceCandidate(signal.candidate)); }; 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2761, "s": 2608, "text": "Web RTC introduced by World Wide Web Consortium (W3C). That supports browser-tobrowser applications for voice calling, video chat, and P2P file sharing." }, { "code": null, "e": 2951, "s": 2761, "text": "If you want to try out? web RTC available for Chrome, Opera, and Firefox. A good place to start is the simple video chat application at here. Web RTC implements three API's as shown below −" }, { "code": null, "e": 3013, "s": 2951, "text": "MediaStream − get access to the user's camera and microphone." }, { "code": null, "e": 3075, "s": 3013, "text": "MediaStream − get access to the user's camera and microphone." }, { "code": null, "e": 3142, "s": 3075, "text": "RTCPeerConnection − get access to audio or video calling facility." }, { "code": null, "e": 3209, "s": 3142, "text": "RTCPeerConnection − get access to audio or video calling facility." }, { "code": null, "e": 3268, "s": 3209, "text": "RTCDataChannel − get access to peer-to-peer communication." }, { "code": null, "e": 3327, "s": 3268, "text": "RTCDataChannel − get access to peer-to-peer communication." }, { "code": null, "e": 3471, "s": 3327, "text": "The MediaStream represents synchronized streams of media, For an example, Click on HTML5 Video player in HTML5 demo section or else click here." }, { "code": null, "e": 3873, "s": 3471, "text": "The above example contains stream.getAudioTracks() and stream.VideoTracks(). If there is no audio tracks, it returns an empty array and it will check video stream,if webcam connected, stream.getVideoTracks() returns an array of one MediaStreamTrack representing the stream from the webcam. A simple example is chat applications, a chat application gets stream from web camera, rear camera, microphone." }, { "code": null, "e": 4338, "s": 3873, "text": "function gotStream(stream) {\n window.AudioContext = window.AudioContext || window.webkitAudioContext;\n var audioContext = new AudioContext();\n \n // Create an AudioNode from the stream\n var mediaStreamSource = audioContext.createMediaStreamSource(stream);\n \n // Connect it to destination to hear yourself\n // or any other node for processing!\n mediaStreamSource.connect(audioContext.destination);\n}\nnavigator.getUserMedia({audio:true}, gotStream);" }, { "code": null, "e": 4498, "s": 4338, "text": "It's also possible in Chrome browser with mediaStreamSource and it requires HTTPS. This feature is not yet available in opera. Sample demo is available at here" }, { "code": null, "e": 4822, "s": 4498, "text": "Web RTC required peer-to-peer communication between browsers. This mechanism required signaling, network information, session control and media information. Web developers can choose different mechanism to communicate between the browsers such as SIP or XMPP or any two way communications. A sample example of XHR is here. " }, { "code": null, "e": 6264, "s": 4822, "text": "var signalingChannel = createSignalingChannel();\nvar pc;\nvar configuration = ...;\n\n// run start(true) to initiate a call\nfunction start(isCaller) {\n pc = new RTCPeerConnection(configuration);\n \n // send any ice candidates to the other peer\n pc.onicecandidate = function (evt) {\n signalingChannel.send(JSON.stringify({ \"candidate\": evt.candidate }));\n };\n \n // once remote stream arrives, show it in the remote video element\n pc.onaddstream = function (evt) {\n remoteView.src = URL.createObjectURL(evt.stream);\n };\n \n // get the local stream, show it in the local video element and send it\n navigator.getUserMedia({ \"audio\": true, \"video\": true }, function (stream) {\n selfView.src = URL.createObjectURL(stream);\n pc.addStream(stream);\n \n if (isCaller)\n pc.createOffer(gotDescription);\n \n else\n pc.createAnswer(pc.remoteDescription, gotDescription);\n \n function gotDescription(desc) {\n pc.setLocalDescription(desc);\n signalingChannel.send(JSON.stringify({ \"sdp\": desc }));\n }\n });\n }\n \n signalingChannel.onmessage = function (evt) {\n if (!pc)\n start(false);\n var signal = JSON.parse(evt.data);\n \n if (signal.sdp)\n pc.setRemoteDescription(new RTCSessionDescription(signal.sdp));\n \n else\n pc.addIceCandidate(new RTCIceCandidate(signal.candidate));\n};" }, { "code": null, "e": 6297, "s": 6264, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 6311, "s": 6297, "text": " Anadi Sharma" }, { "code": null, "e": 6346, "s": 6311, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6360, "s": 6346, "text": " Anadi Sharma" }, { "code": null, "e": 6395, "s": 6360, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6412, "s": 6395, "text": " Frahaan Hussain" }, { "code": null, "e": 6447, "s": 6412, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6478, "s": 6447, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 6511, "s": 6478, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 6542, "s": 6511, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 6577, "s": 6542, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6608, "s": 6577, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 6615, "s": 6608, "text": " Print" }, { "code": null, "e": 6626, "s": 6615, "text": " Add Notes" } ]
Visual Servoing for Robotics. Robotics — path planning using only... | by Emmanouil Markodimitrakis | Towards Data Science
The purpose of this project is to implement an end to end visual servoing project using a fish-eye camera and a Turtlubot3 with ROS. Visual servoing means, that the robot will implement autonomous driving using only one sensor, the camera! The first objective is to move the robot from the current position to the target position. To specify those positions and their poses, we use two Aruco markers.The second task for the robot is to avoid obstacles that are specified using red color, we implemented this task using A-star path finding algorithm.Finally, when the robot is at the target position we have to do “parking”, that means that the target’s position pose should be the same as the robot’s pose. The first objective is to move the robot from the current position to the target position. To specify those positions and their poses, we use two Aruco markers. The second task for the robot is to avoid obstacles that are specified using red color, we implemented this task using A-star path finding algorithm. Finally, when the robot is at the target position we have to do “parking”, that means that the target’s position pose should be the same as the robot’s pose. Following on this report, we will analyze the mathematical theoretical background and the code implementation we implemented. The Robot Operating System (ROS) is an open source middleware which contains a set of libraries, software and tools that are used to facilitate the development of robotic applications. There is a plethora of features, from sensor drivers to state-of-the-art algorithms. As middleware, it contains characteristics of both software and hardware, hence, it is able to perform various actions like hardware abstraction and low level control.Until now, a different version of ROS exists with some crucial differences, so for compatibility reasons we are using the Melodic release. For the project, the mobile robot used is a Turtlebot3 Burger. The Turtlebot3 is a compact, modular and programmable mobile robot. It uses ROS, and it is able to create multiple application for training research and development. Camera calibration is an integral part of this project. For this phase, the project uses the camera_calibration package, which allows easy calibration of monocular cameras using a checkerboard calibration target. The packages use OpenCV library which contains the camera calibration method. Intrinsic calibrationAs we aforementioned, it uses the camera_calibration package. This package allows easy calibration of monocular or stereo cameras. The checkerboard was the tool in order to fix the Radial Distortion of the acquired image. Radial or Barrel Distortion can be presented as: In the same manner, tangential distortion occurs because the imaging-taking lens is not aligned perfectly parallel to the imaging plane. So, some images look nearer than expected. The amount of tangential distortion can be presented as below: According to the equation above, we can find the five parameters, known as distortion coefficients Furthermore, intrinsic parameters allow a mapping between camera coordinates and pixel coordinates in the image frame. They include information like local length (fx, fy), and optical center (Cx, Cy). These parameters can be expressed in camera matrix: The next step is to receive image frames by subscribing to the ROS topic “/camera/image_raw” and convert it to NumPy array. Then we need to crop the image according to our needs, by specifying the window that we need to work on. Afterwards, we undistort the received image using the camera matrix and the distortion coefficients received on the previous step. Using the OpenCV library, we can detect two Aruco markers that are placed on the top of the robot, one marker for the current and one for the target position. We only have to call the function `cv2.detectMarkers` from which we receive the corners of each marker, and we can move on to the pose estimation. Next step is to estimate the current and target poses, simple by calling the function cv2.estimatePoseSingleMarkers in the pose estimation module. From which we receive two vectors for each marker, one translational vector [x, y, z] and one rotational vector `[x, y, z]`. Using the ROS publisher, we sent those vectors to the robot controller, who is responsible to translate those matrices in a way that the robot should be able to move. This is implemented with the ROS publisher Where the current_position is the ROS topic that the controller will subscribe to fetch the custom message Pose_estimation_vectors that we created, in order to send those vectors. The structure of this message is the following: geometry_msgs/Vector3 rotationalgeometry_msgs/Vector3 translational Here is the image with both of the poses: The homogeneous transformation is encoded by the extrinsic parameters R and t and represents the change of basis from world coordinate system w to the camera coordinate system c. Thus, given the representation of the point P in world coordinates, Pw, we obtain P’s representation in the camera coordinate system, Pc, by: This homogeneous transformation is composed out of R, a 3-by-3 rotation matrix, and t, a 3-by-1 translation vector: Combining the projective transformation and the homogeneous transformation, we obtain the projective transformation that maps 3D points in world coordinates into 2D points in the image plane and in normalized camera coordinates: The controller module has to convert the rotational vector into rotational matrix using the Rodrigues transformation with the OpenCV function: rotational_matrix, _ = cv2.Rodrigues(np.array([data.rotational.x, data.rotational.y, data.rotational.z], dtype=np.float32)) Then we stack the rotational matrix horizontally with the transformational vector and append at the end the row [0, 0, 0, 1] in order to receive the homogeneous matrix. The homogeneous matrices, we obtain from the previous step, describe the position of each position in respect with the camera’s frame. We need to combine them in order to receive the position from one position in respect to the other position. To do that, we multiply the inverse of the current homogeneous matrix with the target homogeneous matrix to receive the combined homogeneous matrix (t): t = np.matmul(np.linalg.inv(self.curr_homogeneous_matrix), self.target_homogeneous_matrix) Following, we need to calculate the angle (alpha) and the distance (rho) that the robot should move: We get the dx, dy from the matrix above: dx = t[0][3]dy = t[1][3] Then we calculate the arctan using dx, dy: self.alpha = math.atan2(dy, dx) And finally we get the distance to target (rho) by applying the Euclidean distance: self.rho = math.sqrt(math.pow(dy, 2) + math.pow(dx, 2)) Now we fix the beta angle by publishing to the ROS topic `cmd_vel` only angular velocity, and when the angle is correct according to the target angle we publish again to the same topic only linear velocity until the distance to target is near to zero. We use a proportional controller, so the velocities that are given to the robot are multiplied by two constants, one for angular and one for linear velocity. The obstacle detection module is using the input image and slice it into boxes of size equal to the robot size. This way, we have an array with all the possible moves that the robot can achieve. To distinguish the obstacles, that mean if there is an obstacle -a red box- in the image, the robot should not be able to move there. Then we iterate for every box of the image and convert the box to HSV. Next, we mask the image if the box contains any pixels in the range of red color, and apply the bitwise mask to the output. If the box contains red pixels, we assume that it is an obstacle. The output of this step is a one directional array with length equals to the number of the boxes, which contains zero’s (when there is no obstacle) and one’s (where there is an obstacle). Using the obstacles map array of the previous step, we implement the Path planning module to receive the shortest path the robot should move to go into the target faster. This is a graph based algorithm which is using an heuristic method for better performance. The core of this is f = g + h, where: F is the total cost G is the distance between the current node and the start node. H is the heuristic — estimated distance from the current node to the end node. Read the following article for more informations. Shortest path contains some middlepoints that the robot should move to find the target position faster without any collision with the obstacles. Here, we face a problem because we only have the indexes of those middlepoints. So, we decided to convert those indexes to pixels according to our boxed frame. Using their corners we calculate their poses the same way we calculate the pose for the aruco markers with the function: cv2.aruco.estimatePoseSingleMarkers. Then, we itterate throught the obstacles map and draw on the image each middle point of the shortest path we calculated in the previous steps. This is the final map, where blue zeros specify that there is a valid movement for the robot, light blue X specify there is an obstacle, orange circles specify the shortest path, bold white S and G specify the starting and goal point of the path respectively. Our controller receives the current pose vectors each time the on_receive_image callback is executed. It calculates the homogeneous matrix as explaind earlier and save it as class variable self.current_homogeneous_matrix. For each middle point the controller receives the same vectors and update the list target_position_path class variable. When this list has no values the robot is not moving, as it doesn't know where to go. When it receive some values it calculate the homogeneous matrix for this specific middlepoint and save it as the class variable self.target_homogeneous_matrix. The robot is able to move now on every midlepoint specified in the target_position_path list by fixing the angle and then moving to the middlepoint. When the robot is approaching the middlepoint and the distance error is small we get the next element (midlepoint) of the list and continue moving until the list is empty! On the controller move_robot there are two loops for the implementation of the previous steps (fix angle, move forward). For the purposes of parking we need to add another loop that will be executed only when the robot is on the target position, and the objective of this loop is to fix the final angle in respect with the specified target pose. The additinal code we need is simple: rotational_matrix = np.array([ [t[0][0], t[0][1], t[0][2]], [t[1][0], t[1][1], t[1][2]], [t[2][0], t[2][1], t[2][2]], ]) r = R.from_matrix(rotational_matrix)self.beta = r.as_euler('XYZ', degrees=False)[2] We convert the rotational matrix to Euler angles, we receive a vector [x,y,z] and get the third value because we only need the z angle, which we save as the class variable beta. Finally, we publish the desired angular velocity and the robot fix the beta angle! Execute Roscore: roscore Launch the camera roslaunch ueye_cam rgb8.launch Remote monitor and control, for more details click here: ssh ubuntu@192.168.0.200 On the turtlebot run, for more details click here: roslaunch turtlebot3_bringup turtlebot3_robot.launch On the remote computer launch our implementation: roslaunch visual_servoing visual_servoing.launch GitHub link for the project My LinkedIn Account
[ { "code": null, "e": 411, "s": 171, "text": "The purpose of this project is to implement an end to end visual servoing project using a fish-eye camera and a Turtlubot3 with ROS. Visual servoing means, that the robot will implement autonomous driving using only one sensor, the camera!" }, { "code": null, "e": 878, "s": 411, "text": "The first objective is to move the robot from the current position to the target position. To specify those positions and their poses, we use two Aruco markers.The second task for the robot is to avoid obstacles that are specified using red color, we implemented this task using A-star path finding algorithm.Finally, when the robot is at the target position we have to do “parking”, that means that the target’s position pose should be the same as the robot’s pose." }, { "code": null, "e": 1039, "s": 878, "text": "The first objective is to move the robot from the current position to the target position. To specify those positions and their poses, we use two Aruco markers." }, { "code": null, "e": 1189, "s": 1039, "text": "The second task for the robot is to avoid obstacles that are specified using red color, we implemented this task using A-star path finding algorithm." }, { "code": null, "e": 1347, "s": 1189, "text": "Finally, when the robot is at the target position we have to do “parking”, that means that the target’s position pose should be the same as the robot’s pose." }, { "code": null, "e": 1473, "s": 1347, "text": "Following on this report, we will analyze the mathematical theoretical background and the code implementation we implemented." }, { "code": null, "e": 2049, "s": 1473, "text": "The Robot Operating System (ROS) is an open source middleware which contains a set of libraries, software and tools that are used to facilitate the development of robotic applications. There is a plethora of features, from sensor drivers to state-of-the-art algorithms. As middleware, it contains characteristics of both software and hardware, hence, it is able to perform various actions like hardware abstraction and low level control.Until now, a different version of ROS exists with some crucial differences, so for compatibility reasons we are using the Melodic release." }, { "code": null, "e": 2278, "s": 2049, "text": "For the project, the mobile robot used is a Turtlebot3 Burger. The Turtlebot3 is a compact, modular and programmable mobile robot. It uses ROS, and it is able to create multiple application for training research and development." }, { "code": null, "e": 2569, "s": 2278, "text": "Camera calibration is an integral part of this project. For this phase, the project uses the camera_calibration package, which allows easy calibration of monocular cameras using a checkerboard calibration target. The packages use OpenCV library which contains the camera calibration method." }, { "code": null, "e": 2861, "s": 2569, "text": "Intrinsic calibrationAs we aforementioned, it uses the camera_calibration package. This package allows easy calibration of monocular or stereo cameras. The checkerboard was the tool in order to fix the Radial Distortion of the acquired image. Radial or Barrel Distortion can be presented as:" }, { "code": null, "e": 3104, "s": 2861, "text": "In the same manner, tangential distortion occurs because the imaging-taking lens is not aligned perfectly parallel to the imaging plane. So, some images look nearer than expected. The amount of tangential distortion can be presented as below:" }, { "code": null, "e": 3203, "s": 3104, "text": "According to the equation above, we can find the five parameters, known as distortion coefficients" }, { "code": null, "e": 3404, "s": 3203, "text": "Furthermore, intrinsic parameters allow a mapping between camera coordinates and pixel coordinates in the image frame. They include information like local length (fx, fy), and optical center (Cx, Cy)." }, { "code": null, "e": 3456, "s": 3404, "text": "These parameters can be expressed in camera matrix:" }, { "code": null, "e": 3816, "s": 3456, "text": "The next step is to receive image frames by subscribing to the ROS topic “/camera/image_raw” and convert it to NumPy array. Then we need to crop the image according to our needs, by specifying the window that we need to work on. Afterwards, we undistort the received image using the camera matrix and the distortion coefficients received on the previous step." }, { "code": null, "e": 4122, "s": 3816, "text": "Using the OpenCV library, we can detect two Aruco markers that are placed on the top of the robot, one marker for the current and one for the target position. We only have to call the function `cv2.detectMarkers` from which we receive the corners of each marker, and we can move on to the pose estimation." }, { "code": null, "e": 4604, "s": 4122, "text": "Next step is to estimate the current and target poses, simple by calling the function cv2.estimatePoseSingleMarkers in the pose estimation module. From which we receive two vectors for each marker, one translational vector [x, y, z] and one rotational vector `[x, y, z]`. Using the ROS publisher, we sent those vectors to the robot controller, who is responsible to translate those matrices in a way that the robot should be able to move. This is implemented with the ROS publisher" }, { "code": null, "e": 4784, "s": 4604, "text": "Where the current_position is the ROS topic that the controller will subscribe to fetch the custom message Pose_estimation_vectors that we created, in order to send those vectors." }, { "code": null, "e": 4900, "s": 4784, "text": "The structure of this message is the following: geometry_msgs/Vector3 rotationalgeometry_msgs/Vector3 translational" }, { "code": null, "e": 4942, "s": 4900, "text": "Here is the image with both of the poses:" }, { "code": null, "e": 5263, "s": 4942, "text": "The homogeneous transformation is encoded by the extrinsic parameters R and t and represents the change of basis from world coordinate system w to the camera coordinate system c. Thus, given the representation of the point P in world coordinates, Pw, we obtain P’s representation in the camera coordinate system, Pc, by:" }, { "code": null, "e": 5379, "s": 5263, "text": "This homogeneous transformation is composed out of R, a 3-by-3 rotation matrix, and t, a 3-by-1 translation vector:" }, { "code": null, "e": 5608, "s": 5379, "text": "Combining the projective transformation and the homogeneous transformation, we obtain the projective transformation that maps 3D points in world coordinates into 2D points in the image plane and in normalized camera coordinates:" }, { "code": null, "e": 5751, "s": 5608, "text": "The controller module has to convert the rotational vector into rotational matrix using the Rodrigues transformation with the OpenCV function:" }, { "code": null, "e": 5875, "s": 5751, "text": "rotational_matrix, _ = cv2.Rodrigues(np.array([data.rotational.x, data.rotational.y, data.rotational.z], dtype=np.float32))" }, { "code": null, "e": 6044, "s": 5875, "text": "Then we stack the rotational matrix horizontally with the transformational vector and append at the end the row [0, 0, 0, 1] in order to receive the homogeneous matrix." }, { "code": null, "e": 6441, "s": 6044, "text": "The homogeneous matrices, we obtain from the previous step, describe the position of each position in respect with the camera’s frame. We need to combine them in order to receive the position from one position in respect to the other position. To do that, we multiply the inverse of the current homogeneous matrix with the target homogeneous matrix to receive the combined homogeneous matrix (t):" }, { "code": null, "e": 6532, "s": 6441, "text": "t = np.matmul(np.linalg.inv(self.curr_homogeneous_matrix), self.target_homogeneous_matrix)" }, { "code": null, "e": 6633, "s": 6532, "text": "Following, we need to calculate the angle (alpha) and the distance (rho) that the robot should move:" }, { "code": null, "e": 6674, "s": 6633, "text": "We get the dx, dy from the matrix above:" }, { "code": null, "e": 6699, "s": 6674, "text": "dx = t[0][3]dy = t[1][3]" }, { "code": null, "e": 6742, "s": 6699, "text": "Then we calculate the arctan using dx, dy:" }, { "code": null, "e": 6774, "s": 6742, "text": "self.alpha = math.atan2(dy, dx)" }, { "code": null, "e": 6858, "s": 6774, "text": "And finally we get the distance to target (rho) by applying the Euclidean distance:" }, { "code": null, "e": 6914, "s": 6858, "text": "self.rho = math.sqrt(math.pow(dy, 2) + math.pow(dx, 2))" }, { "code": null, "e": 7324, "s": 6914, "text": "Now we fix the beta angle by publishing to the ROS topic `cmd_vel` only angular velocity, and when the angle is correct according to the target angle we publish again to the same topic only linear velocity until the distance to target is near to zero. We use a proportional controller, so the velocities that are given to the robot are multiplied by two constants, one for angular and one for linear velocity." }, { "code": null, "e": 7653, "s": 7324, "text": "The obstacle detection module is using the input image and slice it into boxes of size equal to the robot size. This way, we have an array with all the possible moves that the robot can achieve. To distinguish the obstacles, that mean if there is an obstacle -a red box- in the image, the robot should not be able to move there." }, { "code": null, "e": 7914, "s": 7653, "text": "Then we iterate for every box of the image and convert the box to HSV. Next, we mask the image if the box contains any pixels in the range of red color, and apply the bitwise mask to the output. If the box contains red pixels, we assume that it is an obstacle." }, { "code": null, "e": 8102, "s": 7914, "text": "The output of this step is a one directional array with length equals to the number of the boxes, which contains zero’s (when there is no obstacle) and one’s (where there is an obstacle)." }, { "code": null, "e": 8273, "s": 8102, "text": "Using the obstacles map array of the previous step, we implement the Path planning module to receive the shortest path the robot should move to go into the target faster." }, { "code": null, "e": 8402, "s": 8273, "text": "This is a graph based algorithm which is using an heuristic method for better performance. The core of this is f = g + h, where:" }, { "code": null, "e": 8422, "s": 8402, "text": "F is the total cost" }, { "code": null, "e": 8485, "s": 8422, "text": "G is the distance between the current node and the start node." }, { "code": null, "e": 8564, "s": 8485, "text": "H is the heuristic — estimated distance from the current node to the end node." }, { "code": null, "e": 8614, "s": 8564, "text": "Read the following article for more informations." }, { "code": null, "e": 8759, "s": 8614, "text": "Shortest path contains some middlepoints that the robot should move to find the target position faster without any collision with the obstacles." }, { "code": null, "e": 9077, "s": 8759, "text": "Here, we face a problem because we only have the indexes of those middlepoints. So, we decided to convert those indexes to pixels according to our boxed frame. Using their corners we calculate their poses the same way we calculate the pose for the aruco markers with the function: cv2.aruco.estimatePoseSingleMarkers." }, { "code": null, "e": 9220, "s": 9077, "text": "Then, we itterate throught the obstacles map and draw on the image each middle point of the shortest path we calculated in the previous steps." }, { "code": null, "e": 9480, "s": 9220, "text": "This is the final map, where blue zeros specify that there is a valid movement for the robot, light blue X specify there is an obstacle, orange circles specify the shortest path, bold white S and G specify the starting and goal point of the path respectively." }, { "code": null, "e": 9702, "s": 9480, "text": "Our controller receives the current pose vectors each time the on_receive_image callback is executed. It calculates the homogeneous matrix as explaind earlier and save it as class variable self.current_homogeneous_matrix." }, { "code": null, "e": 10068, "s": 9702, "text": "For each middle point the controller receives the same vectors and update the list target_position_path class variable. When this list has no values the robot is not moving, as it doesn't know where to go. When it receive some values it calculate the homogeneous matrix for this specific middlepoint and save it as the class variable self.target_homogeneous_matrix." }, { "code": null, "e": 10389, "s": 10068, "text": "The robot is able to move now on every midlepoint specified in the target_position_path list by fixing the angle and then moving to the middlepoint. When the robot is approaching the middlepoint and the distance error is small we get the next element (midlepoint) of the list and continue moving until the list is empty!" }, { "code": null, "e": 10735, "s": 10389, "text": "On the controller move_robot there are two loops for the implementation of the previous steps (fix angle, move forward). For the purposes of parking we need to add another loop that will be executed only when the robot is on the target position, and the objective of this loop is to fix the final angle in respect with the specified target pose." }, { "code": null, "e": 10773, "s": 10735, "text": "The additinal code we need is simple:" }, { "code": null, "e": 11033, "s": 10773, "text": "rotational_matrix = np.array([ [t[0][0], t[0][1], t[0][2]], [t[1][0], t[1][1], t[1][2]], [t[2][0], t[2][1], t[2][2]], ]) r = R.from_matrix(rotational_matrix)self.beta = r.as_euler('XYZ', degrees=False)[2]" }, { "code": null, "e": 11211, "s": 11033, "text": "We convert the rotational matrix to Euler angles, we receive a vector [x,y,z] and get the third value because we only need the z angle, which we save as the class variable beta." }, { "code": null, "e": 11294, "s": 11211, "text": "Finally, we publish the desired angular velocity and the robot fix the beta angle!" }, { "code": null, "e": 11311, "s": 11294, "text": "Execute Roscore:" }, { "code": null, "e": 11319, "s": 11311, "text": "roscore" }, { "code": null, "e": 11337, "s": 11319, "text": "Launch the camera" }, { "code": null, "e": 11368, "s": 11337, "text": "roslaunch ueye_cam rgb8.launch" }, { "code": null, "e": 11425, "s": 11368, "text": "Remote monitor and control, for more details click here:" }, { "code": null, "e": 11450, "s": 11425, "text": "ssh ubuntu@192.168.0.200" }, { "code": null, "e": 11501, "s": 11450, "text": "On the turtlebot run, for more details click here:" }, { "code": null, "e": 11554, "s": 11501, "text": "roslaunch turtlebot3_bringup turtlebot3_robot.launch" }, { "code": null, "e": 11604, "s": 11554, "text": "On the remote computer launch our implementation:" }, { "code": null, "e": 11653, "s": 11604, "text": "roslaunch visual_servoing visual_servoing.launch" }, { "code": null, "e": 11681, "s": 11653, "text": "GitHub link for the project" } ]
jQuery | Keydown() with Examples - GeeksforGeeks
13 Feb, 2019 The keydown() is an inbuilt method in jQuery which is used to trigger the keydown event whenever User presses a key on the keyboard. If the key is kept pressed, the event is sent every time the operating system repeats the key. So, Using keydown() method we can detect if any key is on its way down.Syntax: $(selector).keydown(function) Here selector is the selected element.Parameter: It accepts an optional parameter as a function which gives the idea whether any key is pressed or not.Return values: It returns whether any key is pressed or not or which key is pressed.jQuery code to show the working of keydown() Method:Code #1:Below code is used to check if a key is on its way down. <title>Jquery | Keydown() </title> $(document).keydown(function(event) { alert('You pressed down a key'); }); <h1>Try pressing any key from the keyboard </h1> Output:After pressing run button- After pressing any key- Code #2:Below code is used to check which specific key is pressed down from the keyboard and the event.keyCode and event.which will return a UNICODE value of the pressed key, Both are browser specific. <title>Jquery | Keydown() </title> $(document).keydown(function(event) { var key = (event.keyCode ? event.keyCode : event.which); if (key >= '65' && key = '96' && key = '48' && key = '112' && key <= '123') alert('You pressed FUNCTION key - ' + (key - 111)); else if (key == '144') alert('You pressed NUMLOCK key'); else if (key == '145') alert('You pressed SCROLL LOCK key'); else alert('You pressed SPECIAL CHARACTER key'); }); <br><br> <h1>Try pressing any key from the keyboard </h1> Output:After pressing run button- After pressing any key- jQuery-Events JavaScript JQuery Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Convert a string to an integer in JavaScript Form validation using HTML and JavaScript Difference Between PUT and PATCH Request JQuery | Set the value of an input text field Form validation using jQuery How to Dynamically Add/Remove Table Rows using jQuery ? How to change the background color after clicking the button in JavaScript ? How to change selected value of a drop-down list using jQuery?
[ { "code": null, "e": 25151, "s": 25123, "text": "\n13 Feb, 2019" }, { "code": null, "e": 25458, "s": 25151, "text": "The keydown() is an inbuilt method in jQuery which is used to trigger the keydown event whenever User presses a key on the keyboard. If the key is kept pressed, the event is sent every time the operating system repeats the key. So, Using keydown() method we can detect if any key is on its way down.Syntax:" }, { "code": null, "e": 25490, "s": 25458, "text": "$(selector).keydown(function) \n" }, { "code": null, "e": 25842, "s": 25490, "text": "Here selector is the selected element.Parameter: It accepts an optional parameter as a function which gives the idea whether any key is pressed or not.Return values: It returns whether any key is pressed or not or which key is pressed.jQuery code to show the working of keydown() Method:Code #1:Below code is used to check if a key is on its way down." }, { "code": "<title>Jquery | Keydown() </title> $(document).keydown(function(event) { alert('You pressed down a key'); }); <h1>Try pressing any key from the keyboard </h1> ", "e": 26038, "s": 25842, "text": null }, { "code": null, "e": 26072, "s": 26038, "text": "Output:After pressing run button-" }, { "code": null, "e": 26096, "s": 26072, "text": "After pressing any key-" }, { "code": null, "e": 26298, "s": 26096, "text": "Code #2:Below code is used to check which specific key is pressed down from the keyboard and the event.keyCode and event.which will return a UNICODE value of the pressed key, Both are browser specific." }, { "code": "<title>Jquery | Keydown() </title> $(document).keydown(function(event) { var key = (event.keyCode ? event.keyCode : event.which); if (key >= '65' && key = '96' && key = '48' && key = '112' && key <= '123') alert('You pressed FUNCTION key - ' + (key - 111)); else if (key == '144') alert('You pressed NUMLOCK key'); else if (key == '145') alert('You pressed SCROLL LOCK key'); else alert('You pressed SPECIAL CHARACTER key'); }); <br><br> <h1>Try pressing any key from the keyboard </h1> ", "e": 26862, "s": 26298, "text": null }, { "code": null, "e": 26896, "s": 26862, "text": "Output:After pressing run button-" }, { "code": null, "e": 26920, "s": 26896, "text": "After pressing any key-" }, { "code": null, "e": 26934, "s": 26920, "text": "jQuery-Events" }, { "code": null, "e": 26945, "s": 26934, "text": "JavaScript" }, { "code": null, "e": 26952, "s": 26945, "text": "JQuery" }, { "code": null, "e": 27050, "s": 26952, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27059, "s": 27050, "text": "Comments" }, { "code": null, "e": 27072, "s": 27059, "text": "Old Comments" }, { "code": null, "e": 27133, "s": 27072, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27205, "s": 27133, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27250, "s": 27205, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27292, "s": 27250, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 27333, "s": 27292, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27379, "s": 27333, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 27408, "s": 27379, "text": "Form validation using jQuery" }, { "code": null, "e": 27464, "s": 27408, "text": "How to Dynamically Add/Remove Table Rows using jQuery ?" }, { "code": null, "e": 27541, "s": 27464, "text": "How to change the background color after clicking the button in JavaScript ?" } ]
numpy.index() in Python
28 Nov, 2018 numpy.core.defchararray.index(arr, substring, start=0, end=None): Finds the lowest index of the sub-string in the specified range But if substring is not found, it raises ValueError. Parameters:arr : array-like or string to be searched.substring : substring to search for.start, end : [int, optional] Range to search in. Returns : An integer array with the lowest index of found sub-string, raises ValueError if substring is not found. Code #1: # Python Program illustrating # numpy.char.index() method import numpy as np arr = ['this is geeks for geek'] print ("arr : ", arr) print ("\nindex of 'geeks' : ", np.char.index(arr, 'geeks')) Output: arr : ['this is geeks for geek'] index of 'geeks' : [8] Code #2: # Python Program illustrating # numpy.char.index() method import numpy as np arr = ['this is geeks for geek'] print ("\nindex of 'geeks' : ", np.char.index(arr, 'geeks', start = 2))print ("\nindex of 'geeks' : ", np.char.index(arr, 'geeks', start = 10))print ("\nindex of 'geek' : ", np.char.index(arr, 'geek', start = 10)) Output: index of 'geeks' : [8] ValueError: substring not found index of 'geek' : [18] Python numpy-String Operation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Nov, 2018" }, { "code": null, "e": 211, "s": 28, "text": "numpy.core.defchararray.index(arr, substring, start=0, end=None): Finds the lowest index of the sub-string in the specified range But if substring is not found, it raises ValueError." }, { "code": null, "e": 349, "s": 211, "text": "Parameters:arr : array-like or string to be searched.substring : substring to search for.start, end : [int, optional] Range to search in." }, { "code": null, "e": 464, "s": 349, "text": "Returns : An integer array with the lowest index of found sub-string, raises ValueError if substring is not found." }, { "code": null, "e": 473, "s": 464, "text": "Code #1:" }, { "code": "# Python Program illustrating # numpy.char.index() method import numpy as np arr = ['this is geeks for geek'] print (\"arr : \", arr) print (\"\\nindex of 'geeks' : \", np.char.index(arr, 'geeks'))", "e": 670, "s": 473, "text": null }, { "code": null, "e": 678, "s": 670, "text": "Output:" }, { "code": null, "e": 737, "s": 678, "text": "arr : ['this is geeks for geek']\n\nindex of 'geeks' : [8]\n" }, { "code": null, "e": 747, "s": 737, "text": " Code #2:" }, { "code": "# Python Program illustrating # numpy.char.index() method import numpy as np arr = ['this is geeks for geek'] print (\"\\nindex of 'geeks' : \", np.char.index(arr, 'geeks', start = 2))print (\"\\nindex of 'geeks' : \", np.char.index(arr, 'geeks', start = 10))print (\"\\nindex of 'geek' : \", np.char.index(arr, 'geek', start = 10))", "e": 1074, "s": 747, "text": null }, { "code": null, "e": 1082, "s": 1074, "text": "Output:" }, { "code": null, "e": 1161, "s": 1082, "text": "index of 'geeks' : [8]\nValueError: substring not found\nindex of 'geek' : [18]\n" }, { "code": null, "e": 1191, "s": 1161, "text": "Python numpy-String Operation" }, { "code": null, "e": 1204, "s": 1191, "text": "Python-numpy" }, { "code": null, "e": 1211, "s": 1204, "text": "Python" } ]
Sort Correlation Matrix in Python
26 Dec, 2020 Prerequisites: correlation matrix A correlation matrix investigates the dependence between multiple variables at the same time. It shows symmetric tabular data where each row and column represent a variable, and the corresponding value is the correlation coefficient denoting the strength of a relationship between these two variables. There are many types of correlation coefficients (Pearson’s coefficient, Kendall’s coefficient, Spearman’s coefficient, etc.) which are computed by different methods of correlation analysis. The variables with correlation coefficient values closer to 1 show a strong positive correlation, the values closer to -1 show a strong negative correlation, and the values closer to 0 show weak or no correlation. In data analysis, a correlation matrix is highly useful for summarizing and spotting relations in large amounts of data. It is also a common metric for exploratory data analysis and feature selection in machine learning. Interpreting a correlation matrix can become difficult with large data. Sometimes sorting the correlation values helps to see the degree of dependence of various variable pairs easily. In this article, we will see how to sort a correlation matrix in Python. Import module Load data Create a correlation matrix using the above data Sort the data. Display sorted data We will use the Iris data set from Python’s Seaborn package. The data set contains 3 classes of a type of iris flower having 50 instances of their attributes each. Note that a correlation matrix ignores any non-numeric column in the data. So, first change any non-numeric data that you want to include in your correlation matrix to numeric data using label encoding. Now, to sort the correlation matrix, first we have to convert the matrix to one-dimensional series. The unstack() function is used to do so. The series will have multiple index. For sorting sort_values() function is used. The sort_values() function sorts a data frame in Ascending or Descending order of passed Column. Syntax: DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’) Parameters: by: Single/List of column names to sort Data Frame by. axis: 0 or ‘index’ for rows and 1 or ‘columns’ for Column ascending: Boolean value which sorts Data frame in ascending order if True inplace: Boolean value. Makes the changes in passed data frame itself if True. kind: String which can have three inputs(‘quicksort’, ‘mergesort’ or ‘heapsort’) of algorithm used to sort data frame. na_position: Takes two string input ‘last’ or ‘first’ to set position of Null values. Default is ‘last’. Return type: Returns a sorted Data Frame with Same dimensions as of the function caller Data Frame. Dataframe in use: Example 1: Python3 # Import required librariesimport pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as pltfrom sklearn.preprocessing import LabelEncoder # Load datasetdf = sns.load_dataset('iris') # Convert categorical values to numericlabel_encoder = LabelEncoder()df['species'] = label_encoder.fit_transform(df['species']) # Create correlation matrixcorr_mat = df.corr(method='pearson') # Convert correlation matrix to 1-D Series and sortsorted_mat = corr_mat.unstack().sort_values() print(sorted_mat) Output: Example 2: Sort correlation matrix without duplicates In order to remove duplicate and self-correlation values, get the upper or lower triangular values of the matrix before converting the correlation matrix to one-dimensional series. For this purpose triu() function is used which returns an upper triangular matrix with the shape of the correlation matrix (Value 1 for elements above the main diagonal and 0 for others). The method astype() converts the matrix values to boolean. This is where the function can select arrays based on another conditional array so the result we get is a matrix with upper triangular values of the correlation matrix and the remaining values are null. Then the correlation matrix is converted to the one-dimensional array to be sorted as done in the example above. Implementation is given below: Python3 # Import required librariesimport pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as pltfrom sklearn.preprocessing import LabelEncoder # Load datasetdf = sns.load_dataset('iris') # Convert categorical values to numericlabel_encoder = LabelEncoder()df['species'] = label_encoder.fit_transform(df['species']) # Create correlation matrixcorr_mat = df.corr(method='pearson') # Retain upper triangular values of correlation matrix and# make Lower triangular values Nullupper_corr_mat = corr_mat.where( np.triu(np.ones(corr_mat.shape), k=1).astype(np.bool)) # Convert to 1-D series and drop Null valuesunique_corr_pairs = upper_corr_mat.unstack().dropna() # Sort correlation pairssorted_mat = unique_corr_pairs.sort_values()print(sorted_mat) Output: Picked Python-numpy Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Dec, 2020" }, { "code": null, "e": 62, "s": 28, "text": "Prerequisites: correlation matrix" }, { "code": null, "e": 770, "s": 62, "text": "A correlation matrix investigates the dependence between multiple variables at the same time. It shows symmetric tabular data where each row and column represent a variable, and the corresponding value is the correlation coefficient denoting the strength of a relationship between these two variables. There are many types of correlation coefficients (Pearson’s coefficient, Kendall’s coefficient, Spearman’s coefficient, etc.) which are computed by different methods of correlation analysis. The variables with correlation coefficient values closer to 1 show a strong positive correlation, the values closer to -1 show a strong negative correlation, and the values closer to 0 show weak or no correlation. " }, { "code": null, "e": 991, "s": 770, "text": "In data analysis, a correlation matrix is highly useful for summarizing and spotting relations in large amounts of data. It is also a common metric for exploratory data analysis and feature selection in machine learning." }, { "code": null, "e": 1249, "s": 991, "text": "Interpreting a correlation matrix can become difficult with large data. Sometimes sorting the correlation values helps to see the degree of dependence of various variable pairs easily. In this article, we will see how to sort a correlation matrix in Python." }, { "code": null, "e": 1263, "s": 1249, "text": "Import module" }, { "code": null, "e": 1273, "s": 1263, "text": "Load data" }, { "code": null, "e": 1322, "s": 1273, "text": "Create a correlation matrix using the above data" }, { "code": null, "e": 1337, "s": 1322, "text": "Sort the data." }, { "code": null, "e": 1357, "s": 1337, "text": "Display sorted data" }, { "code": null, "e": 1724, "s": 1357, "text": "We will use the Iris data set from Python’s Seaborn package. The data set contains 3 classes of a type of iris flower having 50 instances of their attributes each. Note that a correlation matrix ignores any non-numeric column in the data. So, first change any non-numeric data that you want to include in your correlation matrix to numeric data using label encoding." }, { "code": null, "e": 1903, "s": 1724, "text": "Now, to sort the correlation matrix, first we have to convert the matrix to one-dimensional series. The unstack() function is used to do so. The series will have multiple index. " }, { "code": null, "e": 2045, "s": 1903, "text": "For sorting sort_values() function is used. The sort_values() function sorts a data frame in Ascending or Descending order of passed Column. " }, { "code": null, "e": 2156, "s": 2045, "text": "Syntax: DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’)" }, { "code": null, "e": 2168, "s": 2156, "text": "Parameters:" }, { "code": null, "e": 2223, "s": 2168, "text": "by: Single/List of column names to sort Data Frame by." }, { "code": null, "e": 2281, "s": 2223, "text": "axis: 0 or ‘index’ for rows and 1 or ‘columns’ for Column" }, { "code": null, "e": 2356, "s": 2281, "text": "ascending: Boolean value which sorts Data frame in ascending order if True" }, { "code": null, "e": 2435, "s": 2356, "text": "inplace: Boolean value. Makes the changes in passed data frame itself if True." }, { "code": null, "e": 2554, "s": 2435, "text": "kind: String which can have three inputs(‘quicksort’, ‘mergesort’ or ‘heapsort’) of algorithm used to sort data frame." }, { "code": null, "e": 2659, "s": 2554, "text": "na_position: Takes two string input ‘last’ or ‘first’ to set position of Null values. Default is ‘last’." }, { "code": null, "e": 2759, "s": 2659, "text": "Return type: Returns a sorted Data Frame with Same dimensions as of the function caller Data Frame." }, { "code": null, "e": 2777, "s": 2759, "text": "Dataframe in use:" }, { "code": null, "e": 2788, "s": 2777, "text": "Example 1:" }, { "code": null, "e": 2796, "s": 2788, "text": "Python3" }, { "code": "# Import required librariesimport pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as pltfrom sklearn.preprocessing import LabelEncoder # Load datasetdf = sns.load_dataset('iris') # Convert categorical values to numericlabel_encoder = LabelEncoder()df['species'] = label_encoder.fit_transform(df['species']) # Create correlation matrixcorr_mat = df.corr(method='pearson') # Convert correlation matrix to 1-D Series and sortsorted_mat = corr_mat.unstack().sort_values() print(sorted_mat)", "e": 3315, "s": 2796, "text": null }, { "code": null, "e": 3323, "s": 3315, "text": "Output:" }, { "code": null, "e": 3377, "s": 3323, "text": "Example 2: Sort correlation matrix without duplicates" }, { "code": null, "e": 4009, "s": 3377, "text": "In order to remove duplicate and self-correlation values, get the upper or lower triangular values of the matrix before converting the correlation matrix to one-dimensional series. For this purpose triu() function is used which returns an upper triangular matrix with the shape of the correlation matrix (Value 1 for elements above the main diagonal and 0 for others). The method astype() converts the matrix values to boolean. This is where the function can select arrays based on another conditional array so the result we get is a matrix with upper triangular values of the correlation matrix and the remaining values are null. " }, { "code": null, "e": 4153, "s": 4009, "text": "Then the correlation matrix is converted to the one-dimensional array to be sorted as done in the example above. Implementation is given below:" }, { "code": null, "e": 4161, "s": 4153, "text": "Python3" }, { "code": "# Import required librariesimport pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as pltfrom sklearn.preprocessing import LabelEncoder # Load datasetdf = sns.load_dataset('iris') # Convert categorical values to numericlabel_encoder = LabelEncoder()df['species'] = label_encoder.fit_transform(df['species']) # Create correlation matrixcorr_mat = df.corr(method='pearson') # Retain upper triangular values of correlation matrix and# make Lower triangular values Nullupper_corr_mat = corr_mat.where( np.triu(np.ones(corr_mat.shape), k=1).astype(np.bool)) # Convert to 1-D series and drop Null valuesunique_corr_pairs = upper_corr_mat.unstack().dropna() # Sort correlation pairssorted_mat = unique_corr_pairs.sort_values()print(sorted_mat)", "e": 4934, "s": 4161, "text": null }, { "code": null, "e": 4942, "s": 4934, "text": "Output:" }, { "code": null, "e": 4949, "s": 4942, "text": "Picked" }, { "code": null, "e": 4962, "s": 4949, "text": "Python-numpy" }, { "code": null, "e": 4976, "s": 4962, "text": "Python-pandas" }, { "code": null, "e": 4983, "s": 4976, "text": "Python" } ]
Print a given matrix in zigzag form
11 Jul, 2022 Given a 2D array, print it in zigzag form. Examples : Input : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Output : 1 2 3 4 5 10 9 8 7 6 11 12 13 14 15 20 19 18 17 16 Input : 10 24 32 50 6 17 99 10 11 Output : 10 24 32 17 6 50 99 10 11 CPP Java Python3 C# PHP // C++ program to print// matrix in zig-zag form#include <iostream>using namespace std;const int MAX = 100; // Method to print matrix in zig-zag form void printZigZag(int row, int col, int a[][MAX]) { int evenRow = 0; //starts from the first row int oddRow = 1; //starts from the next row while (evenRow<row) { for (int i=0;i<col;i++) { // evenRow will be printed // in the same direction cout<<a[evenRow][i] << " "; } // Skipping next row so as // to get the next evenRow evenRow = evenRow + 2; if(oddRow < row) { for (int i=col-1; i>=0; i--) { // oddRow will be printed in // the opposite direction cout<<a[oddRow][i] << " "; } } // Skipping next row so as // to get the next oddRow oddRow = oddRow + 2; } } // Driver functionint main() { int r = 3, c = 5; int mat[][MAX] = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}}; printZigZag(r , c , mat); return 0;} // Java program to print matrix in zig-zag formpublic class GFG{ // Method to print matrix in zig-zag form static void printZigZag(int row, int col, int a[][]) { int evenRow = 0; // starts from the first row int oddRow = 1; // starts from the next row while (evenRow < row) { for (int i = 0; i < col; i++) { // evenRow will be printed in the same direction System.out.print(a[evenRow][i] + " "); } // Skipping next row so as to get the next evenRow evenRow = evenRow + 2; if(oddRow < row) { for (int i = col - 1; i >= 0; i--) { // oddRow will be printed in the opposite direction System.out.print(a[oddRow][i] + " "); } } // Skipping next row so as to get the next oddRow oddRow = oddRow + 2; } } public static void main(String[] args) { int r = 3, c = 5; int mat[][] = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}}; printZigZag(r , c , mat); }} # Python 3 program to print# matrix in zig-zag form # Method to print matrix# in zig-zag formdef printZigZag(row, col, a): evenRow = 0 # starts from the first row oddRow = 1 # starts from the next row while evenRow < row: for i in range(col): # evenRow will be printed # in the same direction print(str(a[evenRow][i] ), end = " ") # Skipping next row so as # to get the next evenRow evenRow = evenRow + 2 if oddRow < row: for i in range(col - 1, -1, -1): # oddRow will be printed in # the opposite direction print(str(a[oddRow][i]), end = " ") # Skipping next row so as # to get the next oddRow oddRow = oddRow + 2 # Driver Coder = 3c = 5 mat = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]; printZigZag(r , c , mat) # This code is contributed# by ChitraNayal // C# program to print matrix in zig-zag formusing System; public class GFG { // Method to print matrix in zig-zag form static void printZigZag(int row, int col, int[, ] a) { // starts from the first row int evenRow = 0; // starts from the next row int oddRow = 1; while (evenRow < row) { for (int i = 0; i < col; i++) { // evenRow will be printed in // the same direction Console.Write(a[evenRow, i] + " "); } // Skipping next row so as to get the // next evenRow evenRow = evenRow + 2; if(oddRow < row) { for (int i = col - 1; i >= 0; i--) { // oddRow will be printed in the // opposite direction Console.Write(a[oddRow, i] + " "); } } // Skipping next row so as to get // the next oddRow oddRow = oddRow + 2; } } public static void Main() { int r = 3, c = 5; int[, ] mat = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 } }; printZigZag(r, c, mat); }} // This code is contributed by vt_m. <?php// PHP program to print// matrix in zig-zag form // Method to print matrix// in zig-zag formfunction printZigZag($row, $col, $a) { //starts from the first row $evenRow = 0; //starts from the next row $oddRow = 1; while ($evenRow < $row) { for ( $i = 0; $i < $col; $i++) { // evenRow will be printed // in the same direction echo $a[$evenRow][$i], " "; } // Skipping next row so as // to get the next evenRow $evenRow = $evenRow + 2; if($oddRow < $row) { for ($i = $col - 1; $i >= 0; $i--) { // oddRow will be printed in // the opposite direction echo $a[$oddRow][$i], " "; } } // Skipping next row so as // to get the next oddRow $oddRow = $oddRow + 2; } } // Driver Code$r = 3; $c = 5;$mat = array(array(1, 2, 3, 4, 5), array(6, 7, 8, 9, 10), array(11, 12, 13, 14, 15)); printZigZag($r , $c , $mat); // This code is contributed by m_kit.?> 1 2 3 4 5 10 9 8 7 6 11 12 13 14 15 Time Complexity: Time complexity of the above solution is O(row*column). Space Complexity: O(row*column) for 2-d array Related Articles: Diagonal traversal of Matrix Print matrix in antispiral form Print matrix in spiral form This article is contributed by Kamal Rawal. 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. jit_t ukasp RohanPrajapati _shinchancode technophpfij pattern-printing Matrix pattern-printing Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Jul, 2022" }, { "code": null, "e": 107, "s": 52, "text": "Given a 2D array, print it in zigzag form. Examples : " }, { "code": null, "e": 417, "s": 107, "text": "Input : \n 1 2 3 4 5\n 6 7 8 9 10\n 11 12 13 14 15\n 16 17 18 19 20\nOutput :\n1 2 3 4 5 10 9 8 7 6 11 12 13 14 15 20 19 18 17 16 \n\n\nInput :\n 10 24 32 \n 50 6 17 \n 99 10 11 \n \nOutput :\n10 24 32 17 6 50 99 10 11" }, { "code": null, "e": 423, "s": 419, "text": "CPP" }, { "code": null, "e": 428, "s": 423, "text": "Java" }, { "code": null, "e": 436, "s": 428, "text": "Python3" }, { "code": null, "e": 439, "s": 436, "text": "C#" }, { "code": null, "e": 443, "s": 439, "text": "PHP" }, { "code": "// C++ program to print// matrix in zig-zag form#include <iostream>using namespace std;const int MAX = 100; // Method to print matrix in zig-zag form void printZigZag(int row, int col, int a[][MAX]) { int evenRow = 0; //starts from the first row int oddRow = 1; //starts from the next row while (evenRow<row) { for (int i=0;i<col;i++) { // evenRow will be printed // in the same direction cout<<a[evenRow][i] << \" \"; } // Skipping next row so as // to get the next evenRow evenRow = evenRow + 2; if(oddRow < row) { for (int i=col-1; i>=0; i--) { // oddRow will be printed in // the opposite direction cout<<a[oddRow][i] << \" \"; } } // Skipping next row so as // to get the next oddRow oddRow = oddRow + 2; } } // Driver functionint main() { int r = 3, c = 5; int mat[][MAX] = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}}; printZigZag(r , c , mat); return 0;}", "e": 1773, "s": 443, "text": null }, { "code": "// Java program to print matrix in zig-zag formpublic class GFG{ // Method to print matrix in zig-zag form static void printZigZag(int row, int col, int a[][]) { int evenRow = 0; // starts from the first row int oddRow = 1; // starts from the next row while (evenRow < row) { for (int i = 0; i < col; i++) { // evenRow will be printed in the same direction System.out.print(a[evenRow][i] + \" \"); } // Skipping next row so as to get the next evenRow evenRow = evenRow + 2; if(oddRow < row) { for (int i = col - 1; i >= 0; i--) { // oddRow will be printed in the opposite direction System.out.print(a[oddRow][i] + \" \"); } } // Skipping next row so as to get the next oddRow oddRow = oddRow + 2; } } public static void main(String[] args) { int r = 3, c = 5; int mat[][] = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}}; printZigZag(r , c , mat); }}", "e": 3016, "s": 1773, "text": null }, { "code": "# Python 3 program to print# matrix in zig-zag form # Method to print matrix# in zig-zag formdef printZigZag(row, col, a): evenRow = 0 # starts from the first row oddRow = 1 # starts from the next row while evenRow < row: for i in range(col): # evenRow will be printed # in the same direction print(str(a[evenRow][i] ), end = \" \") # Skipping next row so as # to get the next evenRow evenRow = evenRow + 2 if oddRow < row: for i in range(col - 1, -1, -1): # oddRow will be printed in # the opposite direction print(str(a[oddRow][i]), end = \" \") # Skipping next row so as # to get the next oddRow oddRow = oddRow + 2 # Driver Coder = 3c = 5 mat = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]; printZigZag(r , c , mat) # This code is contributed# by ChitraNayal", "e": 4119, "s": 3016, "text": null }, { "code": "// C# program to print matrix in zig-zag formusing System; public class GFG { // Method to print matrix in zig-zag form static void printZigZag(int row, int col, int[, ] a) { // starts from the first row int evenRow = 0; // starts from the next row int oddRow = 1; while (evenRow < row) { for (int i = 0; i < col; i++) { // evenRow will be printed in // the same direction Console.Write(a[evenRow, i] + \" \"); } // Skipping next row so as to get the // next evenRow evenRow = evenRow + 2; if(oddRow < row) { for (int i = col - 1; i >= 0; i--) { // oddRow will be printed in the // opposite direction Console.Write(a[oddRow, i] + \" \"); } } // Skipping next row so as to get // the next oddRow oddRow = oddRow + 2; } } public static void Main() { int r = 3, c = 5; int[, ] mat = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 } }; printZigZag(r, c, mat); }} // This code is contributed by vt_m.", "e": 5548, "s": 4119, "text": null }, { "code": "<?php// PHP program to print// matrix in zig-zag form // Method to print matrix// in zig-zag formfunction printZigZag($row, $col, $a) { //starts from the first row $evenRow = 0; //starts from the next row $oddRow = 1; while ($evenRow < $row) { for ( $i = 0; $i < $col; $i++) { // evenRow will be printed // in the same direction echo $a[$evenRow][$i], \" \"; } // Skipping next row so as // to get the next evenRow $evenRow = $evenRow + 2; if($oddRow < $row) { for ($i = $col - 1; $i >= 0; $i--) { // oddRow will be printed in // the opposite direction echo $a[$oddRow][$i], \" \"; } } // Skipping next row so as // to get the next oddRow $oddRow = $oddRow + 2; } } // Driver Code$r = 3; $c = 5;$mat = array(array(1, 2, 3, 4, 5), array(6, 7, 8, 9, 10), array(11, 12, 13, 14, 15)); printZigZag($r , $c , $mat); // This code is contributed by m_kit.?>", "e": 6807, "s": 5548, "text": null }, { "code": null, "e": 6844, "s": 6807, "text": "1 2 3 4 5 10 9 8 7 6 11 12 13 14 15 " }, { "code": null, "e": 6918, "s": 6844, "text": "Time Complexity: Time complexity of the above solution is O(row*column). " }, { "code": null, "e": 6964, "s": 6918, "text": "Space Complexity: O(row*column) for 2-d array" }, { "code": null, "e": 6982, "s": 6964, "text": "Related Articles:" }, { "code": null, "e": 7011, "s": 6982, "text": "Diagonal traversal of Matrix" }, { "code": null, "e": 7043, "s": 7011, "text": "Print matrix in antispiral form" }, { "code": null, "e": 7071, "s": 7043, "text": "Print matrix in spiral form" }, { "code": null, "e": 7491, "s": 7071, "text": "This article is contributed by Kamal Rawal. 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": 7497, "s": 7491, "text": "jit_t" }, { "code": null, "e": 7503, "s": 7497, "text": "ukasp" }, { "code": null, "e": 7518, "s": 7503, "text": "RohanPrajapati" }, { "code": null, "e": 7532, "s": 7518, "text": "_shinchancode" }, { "code": null, "e": 7545, "s": 7532, "text": "technophpfij" }, { "code": null, "e": 7562, "s": 7545, "text": "pattern-printing" }, { "code": null, "e": 7569, "s": 7562, "text": "Matrix" }, { "code": null, "e": 7586, "s": 7569, "text": "pattern-printing" }, { "code": null, "e": 7593, "s": 7586, "text": "Matrix" } ]
Pairwise Swap Nodes of a given Linked List
15 Jul, 2022 Given a singly linked list, write a function to swap elements pairwise. Input : 1->2->3->4->5->6->NULL Output : 2->1->4->3->6->5->NULL Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Input : 1->2->3->4->5->NULL Output : 2->1->4->3->5->NULL Input : 1->NULL Output : 1->NULL For example, if the linked list is 1->2->3->4->5 then the function should change it to 2->1->4->3->5, and if the linked list is then the function should change it to. METHOD 1 (Iterative) Start from the head node and traverse the list. While traversing swap data of each node with its next node’s data. Below is the implementation of the above approach: C++ C Java Python C# Javascript // C++ program to pairwise swap elements// in a given linked list#include <bits/stdc++.h>using namespace std; /* A linked list node */class Node {public: int data; Node* next;}; /* Function to pairwise swap elementsof a linked list */void pairWiseSwap(Node* head){ Node* temp = head; /* Traverse further only if there are at-least two nodes left */ while (temp != NULL && temp->next != NULL) { /* Swap data of node with its next node's data */ swap(temp->data, temp->next->data); /* Move temp by 2 for the next pair */ temp = temp->next->next; }} /* Function to add a node at the beginning of Linked List */void push(Node** head_ref, int new_data){ /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(Node* node){ while (node != NULL) { cout << node->data << " "; node = node->next; }} // Driver Codeint main(){ Node* start = NULL; /* The constructed linked list is: 1->2->3->4->5 */ push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); cout << "Linked list " << "before calling pairWiseSwap()\n"; printList(start); pairWiseSwap(start); cout << "\nLinked list " << "after calling pairWiseSwap()\n"; printList(start); return 0;} // This code is contributed// by rathbhupendra /* C program to pairwise swap elements in a given linked list */#include <stdio.h>#include <stdlib.h> /* A linked list node */struct Node { int data; struct Node* next;}; /*Function to swap two integers at addresses a and b */void swap(int* a, int* b); /* Function to pairwise swap elements of a linked list */void pairWiseSwap(struct Node* head){ struct Node* temp = head; /* Traverse further only if there are at-least two nodes left */ while (temp != NULL && temp->next != NULL) { /* Swap data of node with its next node's data */ swap(&temp->data, &temp->next->data); /* Move temp by 2 for the next pair */ temp = temp->next->next; }} /* UTILITY FUNCTIONS *//* Function to swap two integers */void swap(int* a, int* b){ int temp; temp = *a; *a = *b; *b = temp;} /* Function to add a node at the beginning of Linked List */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} /* Driver program to test above function */int main(){ struct Node* start = NULL; /* The constructed linked list is: 1->2->3->4->5 */ push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); printf("Linked list before calling pairWiseSwap()\n"); printList(start); pairWiseSwap(start); printf("\nLinked list after calling pairWiseSwap()\n"); printList(start); return 0;} // Java program to pairwise swap elements of a linked listclass LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } void pairWiseSwap() { Node temp = head; /* Traverse only till there are atleast 2 nodes left */ while (temp != null && temp.next != null) { /* Swap the data */ int k = temp.data; temp.data = temp.next.data; temp.next.data = k; temp = temp.next.next; } } /* Utility functions */ /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist = new LinkedList(); /* Created Linked List 1->2->3->4->5 */ llist.push(5); llist.push(4); llist.push(3); llist.push(2); llist.push(1); System.out.println("Linked List before calling pairWiseSwap() "); llist.printList(); llist.pairWiseSwap(); System.out.println("Linked List after calling pairWiseSwap() "); llist.printList(); }}/* This code is contributed by Rajat Mishra */ # Python program to swap the elements of linked list pairwise # Node class class Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to pairwise swap elements of a linked list def pairwiseSwap(self): temp = self.head # There are no nodes in linked list if temp is None: return # Traverse furthethr only if there are at least two # left while(temp and temp.next): # If both nodes are same, # no need to swap data if(temp.data != temp.next.data): # Swap data of node with its next node's data temp.data, temp.next.data = temp.next.data, temp.data # Move temp by 2 to the next pair temp = temp.next.next # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print the linked LinkedList def printList(self): temp = self.head while(temp): print temp.data, temp = temp.next # Driver programllist = LinkedList()llist.push(5)llist.push(4)llist.push(3)llist.push(2)llist.push(1) print "Linked list before calling pairWiseSwap() "llist.printList() llist.pairwiseSwap() print "\nLinked list after calling pairWiseSwap()"llist.printList() # This code is contributed by Nikhil Kumar Singh(nickzuck_007) // C# program to pairwise swap elements of a linked listusing System;class LinkedList { Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } void pairWiseSwap() { Node temp = head; /* Traverse only till there are atleast 2 nodes left */ while (temp != null && temp.next != null) { /* Swap the data */ int k = temp.data; temp.data = temp.next.data; temp.next.data = k; temp = temp.next.next; } } /* Utility functions */ /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; } Console.WriteLine(); } /* Driver program to test above functions */ public static void Main(String[] args) { LinkedList llist = new LinkedList(); /* Created Linked List 1->2->3->4->5 */ llist.push(5); llist.push(4); llist.push(3); llist.push(2); llist.push(1); Console.WriteLine("Linked List before calling pairWiseSwap() "); llist.printList(); llist.pairWiseSwap(); Console.WriteLine("Linked List after calling pairWiseSwap() "); llist.printList(); }}// This code is contributed by Arnab Kundu <script> // JavaScript program to pairwise swap // elements of a linked listvar head; // head of list /* Linked list Node */ class Node { constructor(val) { this.data = val; this.next = null; } } function pairWiseSwap() {var temp = head; /* Traverse only till there are atleast 2 nodes left */ while (temp != null && temp.next != null) { /* Swap the data */ var k = temp.data; temp.data = temp.next.data; temp.next.data = k; temp = temp.next.next; } } /* Utility functions */ /* Inserts a new Node at front of the list. */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ function printList() {var temp = head; while (temp != null) { document.write(temp.data + " "); temp = temp.next; } document.write("<br/>"); } /* Driver program to test above functions */ /* Created Linked List 1->2->3->4->5 */ push(5); push(4); push(3); push(2); push(1); document.write( "Linked List before calling pairWiseSwap() <br/>" ); printList(); pairWiseSwap(); document.write( "Linked List after calling pairWiseSwap()<br/> " ); printList(); // This code is contributed by todaysgaurav </script> Linked list before calling pairWiseSwap() 1 2 3 4 5 Linked list after calling pairWiseSwap() 2 1 4 3 5 Time complexity: O(N) As we traverse the linked list only once. Auxiliary Space: O(1) As constant extra space is used. METHOD 2 (Recursive) If there are 2 or more than 2 nodes in Linked List then swap the first two nodes and recursively call for the rest of the list. Below image is a dry run of the above approach: Below is the implementation of the above approach: C++ C Java Python3 C# Javascript /* Recursive function to pairwise swap elements of a linked list */void pairWiseSwap(node* head){ /* There must be at-least two nodes in the list */ if (head != NULL && head->next != NULL) { /* Swap the node's data with data of next node */ swap(head->data, head->next->data); /* Call pairWiseSwap() for rest of the list */ pairWiseSwap(head->next->next); }} // The code is contributed by Gautam goel (gautamgoel962) /* Recursive function to pairwise swap elements of a linked list */void pairWiseSwap(struct node* head){ /* There must be at-least two nodes in the list */ if (head != NULL && head->next != NULL) { /* Swap the node's data with data of next node */ swap(head->data, head->next->data); /* Call pairWiseSwap() for rest of the list */ pairWiseSwap(head->next->next); }} /* Recursive function to pairwise swap elements of a linked list */static void pairWiseSwap(node head){ /* There must be at-least two nodes in the list */ if (head != null && head.next != null) { /* Swap the node's data with data of next node */ swap(head.data, head.next.data); /* Call pairWiseSwap() for rest of the list */ pairWiseSwap(head.next.next); }} // This code contributed by aashish1995 # Recursive function to pairwise swap elements of a linked list def pairWiseSwap(head): # There must be at-least two nodes in the list if (head != None and head.next != None): # Swap the node's data with data of next node swap(head.data, head.next.data); # Call pairWiseSwap() for rest of the list pairWiseSwap(head.next.next); # This code is contributed by _saurabh_jaiswal /* Recursive function to pairwise swap elements of a linked list */static void pairWiseSwap(node head){ /* There must be at-least two nodes in the list */ if (head != null && head.next != null) { /* Swap the node's data with data of next node */ swap(head.data, head.next.data); /* Call pairWiseSwap() for rest of the list */ pairWiseSwap(head.next.next); }} // This code contributed by aashish1995 <script>/* Recursive function to pairwise swap elements of a linked list */ function pairWiseSwap(head){ /* There must be at-least two nodes in the list */ if (head != null && head.next != null) { /* Swap the node's data with data of next node */ swap(head.data, head.next.data); /* Call pairWiseSwap() for rest of the list */ pairWiseSwap(head.next.next); }} // This code is contributed by avanitrachhadiya2155 </script> Time complexity: O(n) Auxiliary Space: O(1) As it is a tail recursive function, function call stack would not be build and thus no extra space will be used. The solution provided here swaps data of nodes. If the data contains many fields (for example a linked list of Student Objects), the swap operation will be costly. See the below article for a better solution that works well for all kind of linked lists Pairwise Swap Nodes by Changing Links Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem. andrew1234 Akanksha_Rai rathbhupendra nidhi_biet desaiparth2000 aashish1995 todaysgaurav shindesharad71 avanitrachhadiya2155 menonkartikeya _saurabh_jaiswal anikakapoor simranarora5sos khushboogoyal499 gautamgoel962 abhijeet19403 hardikkoriintern Amazon Microsoft Moonfrog Labs Linked List Moonfrog Labs Amazon Microsoft Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Jul, 2022" }, { "code": null, "e": 125, "s": 52, "text": "Given a singly linked list, write a function to swap elements pairwise. " }, { "code": null, "e": 188, "s": 125, "text": "Input : 1->2->3->4->5->6->NULL Output : 2->1->4->3->6->5->NULL" }, { "code": null, "e": 197, "s": 188, "text": "Chapters" }, { "code": null, "e": 224, "s": 197, "text": "descriptions off, selected" }, { "code": null, "e": 274, "s": 224, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 297, "s": 274, "text": "captions off, selected" }, { "code": null, "e": 305, "s": 297, "text": "English" }, { "code": null, "e": 329, "s": 305, "text": "This is a modal window." }, { "code": null, "e": 398, "s": 329, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 420, "s": 398, "text": "End of dialog window." }, { "code": null, "e": 477, "s": 420, "text": "Input : 1->2->3->4->5->NULL Output : 2->1->4->3->5->NULL" }, { "code": null, "e": 511, "s": 477, "text": "Input : 1->NULL Output : 1->NULL " }, { "code": null, "e": 680, "s": 511, "text": "For example, if the linked list is 1->2->3->4->5 then the function should change it to 2->1->4->3->5, and if the linked list is then the function should change it to. " }, { "code": null, "e": 702, "s": 680, "text": "METHOD 1 (Iterative) " }, { "code": null, "e": 818, "s": 702, "text": "Start from the head node and traverse the list. While traversing swap data of each node with its next node’s data. " }, { "code": null, "e": 870, "s": 818, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 874, "s": 870, "text": "C++" }, { "code": null, "e": 876, "s": 874, "text": "C" }, { "code": null, "e": 881, "s": 876, "text": "Java" }, { "code": null, "e": 888, "s": 881, "text": "Python" }, { "code": null, "e": 891, "s": 888, "text": "C#" }, { "code": null, "e": 902, "s": 891, "text": "Javascript" }, { "code": "// C++ program to pairwise swap elements// in a given linked list#include <bits/stdc++.h>using namespace std; /* A linked list node */class Node {public: int data; Node* next;}; /* Function to pairwise swap elementsof a linked list */void pairWiseSwap(Node* head){ Node* temp = head; /* Traverse further only if there are at-least two nodes left */ while (temp != NULL && temp->next != NULL) { /* Swap data of node with its next node's data */ swap(temp->data, temp->next->data); /* Move temp by 2 for the next pair */ temp = temp->next->next; }} /* Function to add a node at the beginning of Linked List */void push(Node** head_ref, int new_data){ /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(Node* node){ while (node != NULL) { cout << node->data << \" \"; node = node->next; }} // Driver Codeint main(){ Node* start = NULL; /* The constructed linked list is: 1->2->3->4->5 */ push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); cout << \"Linked list \" << \"before calling pairWiseSwap()\\n\"; printList(start); pairWiseSwap(start); cout << \"\\nLinked list \" << \"after calling pairWiseSwap()\\n\"; printList(start); return 0;} // This code is contributed// by rathbhupendra", "e": 2577, "s": 902, "text": null }, { "code": "/* C program to pairwise swap elements in a given linked list */#include <stdio.h>#include <stdlib.h> /* A linked list node */struct Node { int data; struct Node* next;}; /*Function to swap two integers at addresses a and b */void swap(int* a, int* b); /* Function to pairwise swap elements of a linked list */void pairWiseSwap(struct Node* head){ struct Node* temp = head; /* Traverse further only if there are at-least two nodes left */ while (temp != NULL && temp->next != NULL) { /* Swap data of node with its next node's data */ swap(&temp->data, &temp->next->data); /* Move temp by 2 for the next pair */ temp = temp->next->next; }} /* UTILITY FUNCTIONS *//* Function to swap two integers */void swap(int* a, int* b){ int temp; temp = *a; *a = *b; *b = temp;} /* Function to add a node at the beginning of Linked List */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} /* Driver program to test above function */int main(){ struct Node* start = NULL; /* The constructed linked list is: 1->2->3->4->5 */ push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); printf(\"Linked list before calling pairWiseSwap()\\n\"); printList(start); pairWiseSwap(start); printf(\"\\nLinked list after calling pairWiseSwap()\\n\"); printList(start); return 0;}", "e": 4458, "s": 2577, "text": null }, { "code": "// Java program to pairwise swap elements of a linked listclass LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } void pairWiseSwap() { Node temp = head; /* Traverse only till there are atleast 2 nodes left */ while (temp != null && temp.next != null) { /* Swap the data */ int k = temp.data; temp.data = temp.next.data; temp.next.data = k; temp = temp.next.next; } } /* Utility functions */ /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data + \" \"); temp = temp.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist = new LinkedList(); /* Created Linked List 1->2->3->4->5 */ llist.push(5); llist.push(4); llist.push(3); llist.push(2); llist.push(1); System.out.println(\"Linked List before calling pairWiseSwap() \"); llist.printList(); llist.pairWiseSwap(); System.out.println(\"Linked List after calling pairWiseSwap() \"); llist.printList(); }}/* This code is contributed by Rajat Mishra */", "e": 6299, "s": 4458, "text": null }, { "code": "# Python program to swap the elements of linked list pairwise # Node class class Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to pairwise swap elements of a linked list def pairwiseSwap(self): temp = self.head # There are no nodes in linked list if temp is None: return # Traverse furthethr only if there are at least two # left while(temp and temp.next): # If both nodes are same, # no need to swap data if(temp.data != temp.next.data): # Swap data of node with its next node's data temp.data, temp.next.data = temp.next.data, temp.data # Move temp by 2 to the next pair temp = temp.next.next # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print the linked LinkedList def printList(self): temp = self.head while(temp): print temp.data, temp = temp.next # Driver programllist = LinkedList()llist.push(5)llist.push(4)llist.push(3)llist.push(2)llist.push(1) print \"Linked list before calling pairWiseSwap() \"llist.printList() llist.pairwiseSwap() print \"\\nLinked list after calling pairWiseSwap()\"llist.printList() # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 7939, "s": 6299, "text": null }, { "code": "// C# program to pairwise swap elements of a linked listusing System;class LinkedList { Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } void pairWiseSwap() { Node temp = head; /* Traverse only till there are atleast 2 nodes left */ while (temp != null && temp.next != null) { /* Swap the data */ int k = temp.data; temp.data = temp.next.data; temp.next.data = k; temp = temp.next.next; } } /* Utility functions */ /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data + \" \"); temp = temp.next; } Console.WriteLine(); } /* Driver program to test above functions */ public static void Main(String[] args) { LinkedList llist = new LinkedList(); /* Created Linked List 1->2->3->4->5 */ llist.push(5); llist.push(4); llist.push(3); llist.push(2); llist.push(1); Console.WriteLine(\"Linked List before calling pairWiseSwap() \"); llist.printList(); llist.pairWiseSwap(); Console.WriteLine(\"Linked List after calling pairWiseSwap() \"); llist.printList(); }}// This code is contributed by Arnab Kundu", "e": 9808, "s": 7939, "text": null }, { "code": "<script> // JavaScript program to pairwise swap // elements of a linked listvar head; // head of list /* Linked list Node */ class Node { constructor(val) { this.data = val; this.next = null; } } function pairWiseSwap() {var temp = head; /* Traverse only till there are atleast 2 nodes left */ while (temp != null && temp.next != null) { /* Swap the data */ var k = temp.data; temp.data = temp.next.data; temp.next.data = k; temp = temp.next.next; } } /* Utility functions */ /* Inserts a new Node at front of the list. */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ function printList() {var temp = head; while (temp != null) { document.write(temp.data + \" \"); temp = temp.next; } document.write(\"<br/>\"); } /* Driver program to test above functions */ /* Created Linked List 1->2->3->4->5 */ push(5); push(4); push(3); push(2); push(1); document.write( \"Linked List before calling pairWiseSwap() <br/>\" ); printList(); pairWiseSwap(); document.write( \"Linked List after calling pairWiseSwap()<br/> \" ); printList(); // This code is contributed by todaysgaurav </script>", "e": 11503, "s": 9808, "text": null }, { "code": null, "e": 11608, "s": 11503, "text": "Linked list before calling pairWiseSwap()\n1 2 3 4 5 \nLinked list after calling pairWiseSwap()\n2 1 4 3 5 " }, { "code": null, "e": 11630, "s": 11608, "text": "Time complexity: O(N)" }, { "code": null, "e": 11672, "s": 11630, "text": "As we traverse the linked list only once." }, { "code": null, "e": 11694, "s": 11672, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 11727, "s": 11694, "text": "As constant extra space is used." }, { "code": null, "e": 11876, "s": 11727, "text": "METHOD 2 (Recursive) If there are 2 or more than 2 nodes in Linked List then swap the first two nodes and recursively call for the rest of the list." }, { "code": null, "e": 11925, "s": 11876, "text": "Below image is a dry run of the above approach: " }, { "code": null, "e": 11976, "s": 11925, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 11980, "s": 11976, "text": "C++" }, { "code": null, "e": 11982, "s": 11980, "text": "C" }, { "code": null, "e": 11987, "s": 11982, "text": "Java" }, { "code": null, "e": 11995, "s": 11987, "text": "Python3" }, { "code": null, "e": 11998, "s": 11995, "text": "C#" }, { "code": null, "e": 12009, "s": 11998, "text": "Javascript" }, { "code": "/* Recursive function to pairwise swap elements of a linked list */void pairWiseSwap(node* head){ /* There must be at-least two nodes in the list */ if (head != NULL && head->next != NULL) { /* Swap the node's data with data of next node */ swap(head->data, head->next->data); /* Call pairWiseSwap() for rest of the list */ pairWiseSwap(head->next->next); }} // The code is contributed by Gautam goel (gautamgoel962)", "e": 12470, "s": 12009, "text": null }, { "code": "/* Recursive function to pairwise swap elements of a linked list */void pairWiseSwap(struct node* head){ /* There must be at-least two nodes in the list */ if (head != NULL && head->next != NULL) { /* Swap the node's data with data of next node */ swap(head->data, head->next->data); /* Call pairWiseSwap() for rest of the list */ pairWiseSwap(head->next->next); }}", "e": 12879, "s": 12470, "text": null }, { "code": "/* Recursive function to pairwise swap elements of a linked list */static void pairWiseSwap(node head){ /* There must be at-least two nodes in the list */ if (head != null && head.next != null) { /* Swap the node's data with data of next node */ swap(head.data, head.next.data); /* Call pairWiseSwap() for rest of the list */ pairWiseSwap(head.next.next); }} // This code contributed by aashish1995 ", "e": 13323, "s": 12879, "text": null }, { "code": "# Recursive function to pairwise swap elements of a linked list def pairWiseSwap(head): # There must be at-least two nodes in the list if (head != None and head.next != None): # Swap the node's data with data of next node swap(head.data, head.next.data); # Call pairWiseSwap() for rest of the list pairWiseSwap(head.next.next); # This code is contributed by _saurabh_jaiswal", "e": 13744, "s": 13323, "text": null }, { "code": "/* Recursive function to pairwise swap elements of a linked list */static void pairWiseSwap(node head){ /* There must be at-least two nodes in the list */ if (head != null && head.next != null) { /* Swap the node's data with data of next node */ swap(head.data, head.next.data); /* Call pairWiseSwap() for rest of the list */ pairWiseSwap(head.next.next); }} // This code contributed by aashish1995", "e": 14189, "s": 13744, "text": null }, { "code": "<script>/* Recursive function to pairwise swap elements of a linked list */ function pairWiseSwap(head){ /* There must be at-least two nodes in the list */ if (head != null && head.next != null) { /* Swap the node's data with data of next node */ swap(head.data, head.next.data); /* Call pairWiseSwap() for rest of the list */ pairWiseSwap(head.next.next); }} // This code is contributed by avanitrachhadiya2155 </script>", "e": 14665, "s": 14189, "text": null }, { "code": null, "e": 14687, "s": 14665, "text": "Time complexity: O(n)" }, { "code": null, "e": 14709, "s": 14687, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 14822, "s": 14709, "text": "As it is a tail recursive function, function call stack would not be build and thus no extra space will be used." }, { "code": null, "e": 15075, "s": 14822, "text": "The solution provided here swaps data of nodes. If the data contains many fields (for example a linked list of Student Objects), the swap operation will be costly. See the below article for a better solution that works well for all kind of linked lists" }, { "code": null, "e": 15113, "s": 15075, "text": "Pairwise Swap Nodes by Changing Links" }, { "code": null, "e": 15230, "s": 15113, "text": "Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem." }, { "code": null, "e": 15241, "s": 15230, "text": "andrew1234" }, { "code": null, "e": 15254, "s": 15241, "text": "Akanksha_Rai" }, { "code": null, "e": 15268, "s": 15254, "text": "rathbhupendra" }, { "code": null, "e": 15279, "s": 15268, "text": "nidhi_biet" }, { "code": null, "e": 15294, "s": 15279, "text": "desaiparth2000" }, { "code": null, "e": 15306, "s": 15294, "text": "aashish1995" }, { "code": null, "e": 15319, "s": 15306, "text": "todaysgaurav" }, { "code": null, "e": 15334, "s": 15319, "text": "shindesharad71" }, { "code": null, "e": 15355, "s": 15334, "text": "avanitrachhadiya2155" }, { "code": null, "e": 15370, "s": 15355, "text": "menonkartikeya" }, { "code": null, "e": 15387, "s": 15370, "text": "_saurabh_jaiswal" }, { "code": null, "e": 15399, "s": 15387, "text": "anikakapoor" }, { "code": null, "e": 15415, "s": 15399, "text": "simranarora5sos" }, { "code": null, "e": 15432, "s": 15415, "text": "khushboogoyal499" }, { "code": null, "e": 15446, "s": 15432, "text": "gautamgoel962" }, { "code": null, "e": 15460, "s": 15446, "text": "abhijeet19403" }, { "code": null, "e": 15477, "s": 15460, "text": "hardikkoriintern" }, { "code": null, "e": 15484, "s": 15477, "text": "Amazon" }, { "code": null, "e": 15494, "s": 15484, "text": "Microsoft" }, { "code": null, "e": 15508, "s": 15494, "text": "Moonfrog Labs" }, { "code": null, "e": 15520, "s": 15508, "text": "Linked List" }, { "code": null, "e": 15534, "s": 15520, "text": "Moonfrog Labs" }, { "code": null, "e": 15541, "s": 15534, "text": "Amazon" }, { "code": null, "e": 15551, "s": 15541, "text": "Microsoft" }, { "code": null, "e": 15563, "s": 15551, "text": "Linked List" } ]
How to validate Visa Card number using Regular Expression
15 Feb, 2021 Given a string str, the task is to check whether the given string is valid Visa Card number or not by using Regular Expression. The valid Visa Card number must satisfy the following conditions: It should be 13 or 16 digits long, new cards have 16 digits and old cards have 13 digits.It should be starts with 4.If the cards have 13 digits the next twelve digits should be any number between 0-9.If the cards have 16 digits the next fifteen digits should be any number between 0-9.It should not contains any alphabets and special characters. It should be 13 or 16 digits long, new cards have 16 digits and old cards have 13 digits. It should be starts with 4. If the cards have 13 digits the next twelve digits should be any number between 0-9. If the cards have 16 digits the next fifteen digits should be any number between 0-9. It should not contains any alphabets and special characters. Examples: Input: str = “4155279860457”; Output: true Explanation: The given string satisfies all the above mentioned conditions. Therefore it is a valid Visa Card number. Input: str = “4155279”; Output: false. Explanation: The given string has 7 digits. Therefore it is not a valid Visa Card number. Input: str = “6155279860457”; Output: false. Explanation: The given string doesn’t starts with 4. Therefore it is not a valid Visa Card number. Approach: The idea is to use Regular Expression to solve this problem. The following steps can be followed to compute the answer. Get the String.Create a regular expression to check valid Visa Card number as mentioned below: Get the String. Create a regular expression to check valid Visa Card number as mentioned below: regex = "^4[0-9]{12}(?:[0-9]{3})?$"; Where: ^ represents the starting of the string.4 represents the string should be starts with 4.[0-9]{12} represents the next twelve digits should be any between 0-9.( represents the starting of the group.? represents the 0 or 1 time.[0-9]{3} represents the next three digits should be any between 0-9.) represents the ending of the group.? represents the 0 or 1 time.$ represents the ending of the string.Match the given string with the Regular Expression. In Java, this can be done by using Pattern.matcher().In C++, this can be done by using regex_match().Return true if the string matches with the given regular expression, else return false. Where: ^ represents the starting of the string.4 represents the string should be starts with 4.[0-9]{12} represents the next twelve digits should be any between 0-9.( represents the starting of the group.? represents the 0 or 1 time.[0-9]{3} represents the next three digits should be any between 0-9.) represents the ending of the group.? represents the 0 or 1 time.$ represents the ending of the string. ^ represents the starting of the string. 4 represents the string should be starts with 4. [0-9]{12} represents the next twelve digits should be any between 0-9. ( represents the starting of the group. ? represents the 0 or 1 time. [0-9]{3} represents the next three digits should be any between 0-9. ) represents the ending of the group. ? represents the 0 or 1 time. $ represents the ending of the string. Match the given string with the Regular Expression. In Java, this can be done by using Pattern.matcher().In C++, this can be done by using regex_match(). Return true if the string matches with the given regular expression, else return false. Below is the implementation of the above approach: C++ Java Python3 // C++ program to validate// Visa Card number// using Regular Expression#include <iostream>#include <regex>using namespace std; // Function to validate Visa Card numberbool isValidVisaCardNo(string str){ // Regex to check valid Visa Card number const regex pattern("^4[0-9]{12}(?:[0-9]{3})?$"); // If the Visa Card number // is empty return false if (str.empty()) { return false; } // Return true if the Visa Card number // matched the ReGex if(regex_match(str, pattern)) { return true; } else { return false; }} // Driver Codeint main(){ // Test Case 1: string str1 = "4155279860457"; cout << isValidVisaCardNo(str1) << endl; // Test Case 2: string str2 = "4155279860457201"; cout << isValidVisaCardNo(str2) << endl; // Test Case 3: string str3 = "4155279"; cout << isValidVisaCardNo(str3) << endl; // Test Case 4: string str4 = "6155279860457"; cout << isValidVisaCardNo(str4) << endl; // Test Case 5: string str5 = "415a27##60457"; cout << isValidVisaCardNo(str5) << endl; return 0;} // This code is contributed by yuvraj_chandra // Java program to validate// Visa Card number// using regular expressionimport java.util.regex.*;class GFG { // Function to validate // Visa Card number. // using regular expression. public static boolean isValidVisaCardNo(String str) { // Regex to check valid. // Visa Card number String regex = "^4[0-9]{12}(?:[0-9]{3})?$"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the string is empty // return false if (str == null) { return false; } // Find match between given string // and regular expression // using Pattern.matcher() Matcher m = p.matcher(str); // Return if the string // matched the ReGex return m.matches(); } // Driver code public static void main(String args[]) { // Test Case 1: String str1 = "4155279860457"; System.out.println( isValidVisaCardNo(str1)); // Test Case 2: String str2 = "4155279860457201"; System.out.println( isValidVisaCardNo(str2)); // Test Case 3: String str3 = "4155279"; System.out.println( isValidVisaCardNo(str3)); // Test Case 4: String str4 = "6155279860457"; System.out.println( isValidVisaCardNo(str4)); // Test Case 5: String str5 = "415a27##60457"; System.out.println( isValidVisaCardNo(str5)); }} # Python3 program to validate Visa# Card number using regular expressionimport re # Function to validate Visa Card# number using regular expression.def isValidVisaCardNo(string): # Regex to check valid Visa # Card number regex = "^4[0-9]{12}(?:[0-9]{3})?$"; # Compile the ReGex p = re.compile(regex); # If the string is empty # return false if (string == ''): return False; # Pattern class contains matcher() # method to find matching between # given string and regular expression. m = re.match(p, string); # Return True if the string # matched the ReGex else False if m is None: return False else: return True # Driver codeif __name__ == "__main__": # Test Case 1 str1 = "4155279860457"; print(isValidVisaCardNo(str1)); # Test Case 2 str2 = "4155279860457201"; print(isValidVisaCardNo(str2)); # Test Case 3 str3 = "4155279"; print(isValidVisaCardNo(str3)); # Test Case 4 str4 = "6155279860457"; print(isValidVisaCardNo(str4)); # Test Case 5 str5 = "415a27##60457"; print(isValidVisaCardNo(str5)); # This code is contributed by AnkitRai01 true true false false false ankthon yuvraj_chandra CPP-regex java-regular-expression regular-expression Pattern Searching Strings Strings Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Feb, 2021" }, { "code": null, "e": 250, "s": 54, "text": "Given a string str, the task is to check whether the given string is valid Visa Card number or not by using Regular Expression. The valid Visa Card number must satisfy the following conditions: " }, { "code": null, "e": 596, "s": 250, "text": "It should be 13 or 16 digits long, new cards have 16 digits and old cards have 13 digits.It should be starts with 4.If the cards have 13 digits the next twelve digits should be any number between 0-9.If the cards have 16 digits the next fifteen digits should be any number between 0-9.It should not contains any alphabets and special characters." }, { "code": null, "e": 686, "s": 596, "text": "It should be 13 or 16 digits long, new cards have 16 digits and old cards have 13 digits." }, { "code": null, "e": 714, "s": 686, "text": "It should be starts with 4." }, { "code": null, "e": 799, "s": 714, "text": "If the cards have 13 digits the next twelve digits should be any number between 0-9." }, { "code": null, "e": 885, "s": 799, "text": "If the cards have 16 digits the next fifteen digits should be any number between 0-9." }, { "code": null, "e": 946, "s": 885, "text": "It should not contains any alphabets and special characters." }, { "code": null, "e": 958, "s": 946, "text": "Examples: " }, { "code": null, "e": 1394, "s": 958, "text": "Input: str = “4155279860457”; Output: true Explanation: The given string satisfies all the above mentioned conditions. Therefore it is a valid Visa Card number. Input: str = “4155279”; Output: false. Explanation: The given string has 7 digits. Therefore it is not a valid Visa Card number. Input: str = “6155279860457”; Output: false. Explanation: The given string doesn’t starts with 4. Therefore it is not a valid Visa Card number. " }, { "code": null, "e": 1528, "s": 1396, "text": "Approach: The idea is to use Regular Expression to solve this problem. The following steps can be followed to compute the answer. " }, { "code": null, "e": 1625, "s": 1528, "text": "Get the String.Create a regular expression to check valid Visa Card number as mentioned below: " }, { "code": null, "e": 1641, "s": 1625, "text": "Get the String." }, { "code": null, "e": 1723, "s": 1641, "text": "Create a regular expression to check valid Visa Card number as mentioned below: " }, { "code": null, "e": 1760, "s": 1723, "text": "regex = \"^4[0-9]{12}(?:[0-9]{3})?$\";" }, { "code": null, "e": 2406, "s": 1760, "text": "Where: ^ represents the starting of the string.4 represents the string should be starts with 4.[0-9]{12} represents the next twelve digits should be any between 0-9.( represents the starting of the group.? represents the 0 or 1 time.[0-9]{3} represents the next three digits should be any between 0-9.) represents the ending of the group.? represents the 0 or 1 time.$ represents the ending of the string.Match the given string with the Regular Expression. In Java, this can be done by using Pattern.matcher().In C++, this can be done by using regex_match().Return true if the string matches with the given regular expression, else return false." }, { "code": null, "e": 2812, "s": 2406, "text": "Where: ^ represents the starting of the string.4 represents the string should be starts with 4.[0-9]{12} represents the next twelve digits should be any between 0-9.( represents the starting of the group.? represents the 0 or 1 time.[0-9]{3} represents the next three digits should be any between 0-9.) represents the ending of the group.? represents the 0 or 1 time.$ represents the ending of the string." }, { "code": null, "e": 2853, "s": 2812, "text": "^ represents the starting of the string." }, { "code": null, "e": 2902, "s": 2853, "text": "4 represents the string should be starts with 4." }, { "code": null, "e": 2973, "s": 2902, "text": "[0-9]{12} represents the next twelve digits should be any between 0-9." }, { "code": null, "e": 3013, "s": 2973, "text": "( represents the starting of the group." }, { "code": null, "e": 3043, "s": 3013, "text": "? represents the 0 or 1 time." }, { "code": null, "e": 3112, "s": 3043, "text": "[0-9]{3} represents the next three digits should be any between 0-9." }, { "code": null, "e": 3150, "s": 3112, "text": ") represents the ending of the group." }, { "code": null, "e": 3180, "s": 3150, "text": "? represents the 0 or 1 time." }, { "code": null, "e": 3219, "s": 3180, "text": "$ represents the ending of the string." }, { "code": null, "e": 3373, "s": 3219, "text": "Match the given string with the Regular Expression. In Java, this can be done by using Pattern.matcher().In C++, this can be done by using regex_match()." }, { "code": null, "e": 3461, "s": 3373, "text": "Return true if the string matches with the given regular expression, else return false." }, { "code": null, "e": 3514, "s": 3461, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 3518, "s": 3514, "text": "C++" }, { "code": null, "e": 3523, "s": 3518, "text": "Java" }, { "code": null, "e": 3531, "s": 3523, "text": "Python3" }, { "code": "// C++ program to validate// Visa Card number// using Regular Expression#include <iostream>#include <regex>using namespace std; // Function to validate Visa Card numberbool isValidVisaCardNo(string str){ // Regex to check valid Visa Card number const regex pattern(\"^4[0-9]{12}(?:[0-9]{3})?$\"); // If the Visa Card number // is empty return false if (str.empty()) { return false; } // Return true if the Visa Card number // matched the ReGex if(regex_match(str, pattern)) { return true; } else { return false; }} // Driver Codeint main(){ // Test Case 1: string str1 = \"4155279860457\"; cout << isValidVisaCardNo(str1) << endl; // Test Case 2: string str2 = \"4155279860457201\"; cout << isValidVisaCardNo(str2) << endl; // Test Case 3: string str3 = \"4155279\"; cout << isValidVisaCardNo(str3) << endl; // Test Case 4: string str4 = \"6155279860457\"; cout << isValidVisaCardNo(str4) << endl; // Test Case 5: string str5 = \"415a27##60457\"; cout << isValidVisaCardNo(str5) << endl; return 0;} // This code is contributed by yuvraj_chandra", "e": 4616, "s": 3531, "text": null }, { "code": "// Java program to validate// Visa Card number// using regular expressionimport java.util.regex.*;class GFG { // Function to validate // Visa Card number. // using regular expression. public static boolean isValidVisaCardNo(String str) { // Regex to check valid. // Visa Card number String regex = \"^4[0-9]{12}(?:[0-9]{3})?$\"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the string is empty // return false if (str == null) { return false; } // Find match between given string // and regular expression // using Pattern.matcher() Matcher m = p.matcher(str); // Return if the string // matched the ReGex return m.matches(); } // Driver code public static void main(String args[]) { // Test Case 1: String str1 = \"4155279860457\"; System.out.println( isValidVisaCardNo(str1)); // Test Case 2: String str2 = \"4155279860457201\"; System.out.println( isValidVisaCardNo(str2)); // Test Case 3: String str3 = \"4155279\"; System.out.println( isValidVisaCardNo(str3)); // Test Case 4: String str4 = \"6155279860457\"; System.out.println( isValidVisaCardNo(str4)); // Test Case 5: String str5 = \"415a27##60457\"; System.out.println( isValidVisaCardNo(str5)); }}", "e": 6109, "s": 4616, "text": null }, { "code": "# Python3 program to validate Visa# Card number using regular expressionimport re # Function to validate Visa Card# number using regular expression.def isValidVisaCardNo(string): # Regex to check valid Visa # Card number regex = \"^4[0-9]{12}(?:[0-9]{3})?$\"; # Compile the ReGex p = re.compile(regex); # If the string is empty # return false if (string == ''): return False; # Pattern class contains matcher() # method to find matching between # given string and regular expression. m = re.match(p, string); # Return True if the string # matched the ReGex else False if m is None: return False else: return True # Driver codeif __name__ == \"__main__\": # Test Case 1 str1 = \"4155279860457\"; print(isValidVisaCardNo(str1)); # Test Case 2 str2 = \"4155279860457201\"; print(isValidVisaCardNo(str2)); # Test Case 3 str3 = \"4155279\"; print(isValidVisaCardNo(str3)); # Test Case 4 str4 = \"6155279860457\"; print(isValidVisaCardNo(str4)); # Test Case 5 str5 = \"415a27##60457\"; print(isValidVisaCardNo(str5)); # This code is contributed by AnkitRai01", "e": 7316, "s": 6109, "text": null }, { "code": null, "e": 7344, "s": 7316, "text": "true\ntrue\nfalse\nfalse\nfalse" }, { "code": null, "e": 7354, "s": 7346, "text": "ankthon" }, { "code": null, "e": 7369, "s": 7354, "text": "yuvraj_chandra" }, { "code": null, "e": 7379, "s": 7369, "text": "CPP-regex" }, { "code": null, "e": 7403, "s": 7379, "text": "java-regular-expression" }, { "code": null, "e": 7422, "s": 7403, "text": "regular-expression" }, { "code": null, "e": 7440, "s": 7422, "text": "Pattern Searching" }, { "code": null, "e": 7448, "s": 7440, "text": "Strings" }, { "code": null, "e": 7456, "s": 7448, "text": "Strings" }, { "code": null, "e": 7474, "s": 7456, "text": "Pattern Searching" } ]
What is Application Service Provider (ASP) ?
22 Jun, 2021 Application Service Provider :It is a third-party unit which provides access to software applications and other services to individuals, multiple customers or organizations to meet their requirements through Internet. Multiple users and organizations access the service over the network based on pay per use or temporary contacts. On behalf of the customers, it deploys and manages application software, system hardware and networking at a centralized facility manner. It is also a very promising technology which gives cost-effective, competitive information technology. ASP in current market :Starting from small to medium and medium to large organizations, every organization are using ASP depending on their requirement and service choice. ASP acts as an important alternative to use required software for most of the small and medium businesses who run their organizations with low and limited budgeted IT infrastructure. But many large organizations also face budget outsourcing problem due to this ASP cost of charge There are several types of application service providers available, i.e. Specialist, Vertical market, Enterprise, Local/Regional, volume. Many smaller organizations use applications on a pay as per use.Many large organizations commit to ongoing contracts. Many smaller organizations use applications on a pay as per use. Many large organizations commit to ongoing contracts. Types of Application Service Provider :Application Service Providers can be breaking down into five subcategories i.e. Enterprise Application Service Providers –They deliver high-end business applications.Local/Regional Application Service Providers –They supply wide variety of application services for smaller organization in a local area.Specialist Application Service Providers –They provide applications for a specific need, for human resources or Web services.Vertical Market Application Service Providers –They provide support to a specific industries like health care.Volume Business Application Service Providers –They provide supply of application services in volume to small/medium businesses. Enterprise Application Service Providers –They deliver high-end business applications. Local/Regional Application Service Providers –They supply wide variety of application services for smaller organization in a local area. Specialist Application Service Providers –They provide applications for a specific need, for human resources or Web services. Vertical Market Application Service Providers –They provide support to a specific industries like health care. Volume Business Application Service Providers –They provide supply of application services in volume to small/medium businesses. ASP advantages : Back end of the application is already up and running faster. Faster deployment is possible. Software usability and reliability. It can also track and push software upgrades, without interference customers. It can handle much of the work of IT workers. Customers also could shift costs from capital to operating expenditures for accounting reasons. ASP disadvantages : Security risk is a major concern for the organizations using virtual servers. Lack of integration in between customer software and ASP software. Sometimes, customer’s have to pay high cost for it. Lacks ability to customize the software applications. Poor network sometimes affect the service availability rate. Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2021" }, { "code": null, "e": 600, "s": 28, "text": "Application Service Provider :It is a third-party unit which provides access to software applications and other services to individuals, multiple customers or organizations to meet their requirements through Internet. Multiple users and organizations access the service over the network based on pay per use or temporary contacts. On behalf of the customers, it deploys and manages application software, system hardware and networking at a centralized facility manner. It is also a very promising technology which gives cost-effective, competitive information technology." }, { "code": null, "e": 1190, "s": 600, "text": "ASP in current market :Starting from small to medium and medium to large organizations, every organization are using ASP depending on their requirement and service choice. ASP acts as an important alternative to use required software for most of the small and medium businesses who run their organizations with low and limited budgeted IT infrastructure. But many large organizations also face budget outsourcing problem due to this ASP cost of charge There are several types of application service providers available, i.e. Specialist, Vertical market, Enterprise, Local/Regional, volume." }, { "code": null, "e": 1308, "s": 1190, "text": "Many smaller organizations use applications on a pay as per use.Many large organizations commit to ongoing contracts." }, { "code": null, "e": 1373, "s": 1308, "text": "Many smaller organizations use applications on a pay as per use." }, { "code": null, "e": 1427, "s": 1373, "text": "Many large organizations commit to ongoing contracts." }, { "code": null, "e": 1546, "s": 1427, "text": "Types of Application Service Provider :Application Service Providers can be breaking down into five subcategories i.e." }, { "code": null, "e": 2132, "s": 1546, "text": "Enterprise Application Service Providers –They deliver high-end business applications.Local/Regional Application Service Providers –They supply wide variety of application services for smaller organization in a local area.Specialist Application Service Providers –They provide applications for a specific need, for human resources or Web services.Vertical Market Application Service Providers –They provide support to a specific industries like health care.Volume Business Application Service Providers –They provide supply of application services in volume to small/medium businesses." }, { "code": null, "e": 2219, "s": 2132, "text": "Enterprise Application Service Providers –They deliver high-end business applications." }, { "code": null, "e": 2356, "s": 2219, "text": "Local/Regional Application Service Providers –They supply wide variety of application services for smaller organization in a local area." }, { "code": null, "e": 2482, "s": 2356, "text": "Specialist Application Service Providers –They provide applications for a specific need, for human resources or Web services." }, { "code": null, "e": 2593, "s": 2482, "text": "Vertical Market Application Service Providers –They provide support to a specific industries like health care." }, { "code": null, "e": 2722, "s": 2593, "text": "Volume Business Application Service Providers –They provide supply of application services in volume to small/medium businesses." }, { "code": null, "e": 2739, "s": 2722, "text": "ASP advantages :" }, { "code": null, "e": 2801, "s": 2739, "text": "Back end of the application is already up and running faster." }, { "code": null, "e": 2832, "s": 2801, "text": "Faster deployment is possible." }, { "code": null, "e": 2868, "s": 2832, "text": "Software usability and reliability." }, { "code": null, "e": 2946, "s": 2868, "text": "It can also track and push software upgrades, without interference customers." }, { "code": null, "e": 2992, "s": 2946, "text": "It can handle much of the work of IT workers." }, { "code": null, "e": 3088, "s": 2992, "text": "Customers also could shift costs from capital to operating expenditures for accounting reasons." }, { "code": null, "e": 3108, "s": 3088, "text": "ASP disadvantages :" }, { "code": null, "e": 3186, "s": 3108, "text": "Security risk is a major concern for the organizations using virtual servers." }, { "code": null, "e": 3253, "s": 3186, "text": "Lack of integration in between customer software and ASP software." }, { "code": null, "e": 3305, "s": 3253, "text": "Sometimes, customer’s have to pay high cost for it." }, { "code": null, "e": 3359, "s": 3305, "text": "Lacks ability to customize the software applications." }, { "code": null, "e": 3420, "s": 3359, "text": "Poor network sometimes affect the service availability rate." }, { "code": null, "e": 3443, "s": 3422, "text": "Software Engineering" } ]
Program for IP forwarding table lookup
22 Nov, 2021 In Unix operating system, there is a routing table that contains a certain number of tuples. These tuples are consist of network IP, subnet mask, gateway IP, and interface name. These details are used to forward a packet to the outside of its network to connect to the internet. So this article gives an idea of how the system takes the decision when a packet is needed to be forwarded. Examples: Input: 201.2.2.2 Output: 12.23.44.1 eth9 Here, there is no network IP entry in the routing table which starts with "201". In this case it will choose default path(0.0.0.0, 0.0.0.0, 12.23.44.1, eth9). Still, it will perform bitwise AND operation with each entry and then chooses default path's interface and gateway to send packet outside. Default path means interface to which system is directly connected. Input: 200.200.200.1 Output: 190.164.1.2 eth0 Here bitwise AND operation is performed with each entry of routing table and correspondent network's interface name and gateway IP is returned. How forwarding of the packet works?This can be understood easily with the help of a small example: Suppose there is a packet with IP address “20.129.0.1” and the routing table has the following entries: So when the packet goes to the kernel of the system to find the gateway and interface, it will first perform a bitwise AND operation with a subnet mask of each entry to find the Longest prefix match. The result of the bitwise AND operation is then compared with the network’s IP address. So it will return the correspondent IP address of the gateway and interface’s name through which the packet can go out. The binary representation of 20.129.0.1 is 00010100.10000001.00000000.00000001. It then performs a bitwise AND operation with a subnet mask for each and every entry of the routing table. In this table that entry number is 4( i.e. 20.128.0.0, 255.128.0.0, 12.1.1.1, eth1) which gives the longest prefix match for this packet. So packet will go out from the eth1 interface and choose the gateway 12.1.1.1 for forwarding. Below is the implementation of the above approach using the Linked List data structure. It takes 2 files as an input and returns output in another file mentioned above. File “input.txt” represents the IP address of a packet. File “routing.txt” contains routing table entries to which IP address is going to be matched. File “output.txt” contains outputs for each input. Program: C // C code to implement IP forwarding table lookup #include <arpa/inet.h>#include <netinet/in.h>#include <stdio.h>#include <stdlib.h>#include <string.h> #define M 15#define N 150 // Declaration of structure of linked list// to store ip address in each nodestruct node { char* data; struct node* next;} * head[15]; // This function fetch data from file// and store them into different arraysvoid storeData(FILE* fp, char buf[M][N], char net[M][N], char mask[M][N], char gateway[M][N], char port[M][N]){ char line[200]; int c, i = 0, j, k = 0, m = 0; // Read data from the file line by line // and each line is stored in array separately. while (fgets(line, sizeof(line), fp)) { j = 0; for (int l = 0; l < strlen(line); l++) { buf[i][j] = line[l]; j++; } i++; } // From each lines stored in buf, // network id, subnet mask, gateway // and port are extracted // and stored into individual arrays. for (i = 0; i < 15; i++) { k = 0; for (j = 0; buf[i][j] != ','; j++) { net[i][k] = buf[i][j]; k++; } m = j + 2; k = 0; for (j = m; buf[i][j] != ','; j++) { mask[i][k] = buf[i][j]; k++; } m = j + 2; k = 0; for (j = m; buf[i][j] != ','; j++) { gateway[i][k] = buf[i][j]; k++; } m = j + 2; k = 0; for (j = m; buf[i][j] != '\0'; j++) { port[i][k] = buf[i][j]; k++; } }} // Function to create routing table// using arrays created by storeData() function// using linked list data structurevoid insert(char net[M][N], char mask[M][N], char gateway[M][N], char port[M][N], char buf[M][N]){ char *temp1, *temp2, *temp3, *temp4; struct node* new; for (int i = 0; i < M; i++) { // Initialize head of each // linked list with NULL. head[i] = NULL; } for (int i = 0; i < M; i++) { for (int j = 0; j < 4; j++) { // If head is null // then first create new node // and store network id into it. if (head[i] == NULL) { new = (struct node*)malloc( sizeof(struct node)); new->data = net[i]; new->next = NULL; head[i] = new; } // If head is not null // and value of j is 1 then create new node // which is pointed by head and it // will contain subnet mask else if (j == 1) { new->next = (struct node*)malloc( sizeof(struct node)); new = new->next; new->data = mask[i]; new->next = NULL; } // If head is not null and value of j is 2 // then create new node // which is pointed by subnet mask // and it will contain gateway else if (j == 2) { new->next = (struct node*)malloc( sizeof(struct node)); new = new->next; new->data = gateway[i]; } // If head is not null and value of j is 3 // then create new node // which is pointed by gateway and // it will contain port else if (j == 3) { new->next = (struct node*)malloc( sizeof(struct node)); new = new->next; new->data = port[i]; } } } // Perform sorting on the basis // of longest prefix of subnet mask for (int i = 0; i < M; i++) { for (int j = i; j < M; j++) { // Longest prefix has been compared // by using inet_addr() system call // which gives decimal value of an ip address. if (inet_addr(head[i]->next->data) < inet_addr(head[j]->next->data)) { struct node* temp = head[i]; head[i] = head[j]; head[j] = temp; } } }} // This function will search for gateway ip// and port number in routing table// through which packet has been sent// to next node/destinationvoid search(FILE* fp1, FILE* fp2){ char str[100]; struct in_addr addr; unsigned int val; fprintf(fp2, "%c", ' '); // Read file 'input.txt' line by line // and perform bitwise AND between subnet mask // and input(destination) ip coming from file. while (fgets(str, sizeof(str), fp1)) { for (int i = 0; i < M; i++) { // Perform bitwise AND operation on result // (i.e. Decimal value of an ip address) // coming from inet_addr() system call val = inet_addr(str) & inet_addr(head[i]->next->data); addr.s_addr = val; char* str1 = inet_ntoa(addr); char* str2 = head[i]->data; int count = 0; // Compare the network id string with result // coming after performing AND operation // and if they are same then increment count. for (int i = 0; str1[i] != '\0'; i++) { if (str1[i] == str2[i]) { count++; } } // If count is same as the string length // of network id then find gateway ip // and port number of that respective network id // and write it into 'output.txt' file. if (count == strlen(str1)) { struct node* ptr = head[i]->next; struct node* temp = ptr->next; while (temp != NULL) { fprintf(fp2, "%s ", temp->data); temp = temp->next; } break; } } }} // Driver codeint main(int argc, char* argv[]){ FILE *fin, *fout, *fp; char buf[M][N] = { { 0 } }; char net[M][N] = { { 0 } }; char mask[M][N] = { { 0 } }; char gateway[M][N] = { { 0 } }; char port[M][N] = { { 0 } }; // if command line argument is less than 3 // then it will show standard error. if (argc < 3) { fprintf(stderr, "File name:%s\n", argv[0]); return 1; } // If 3 arguments are given then input // and routing.txt files will be opened in read mode // while output.txt file is opened in write mode. else { fin = fopen(argv[1], "r"); fout = fopen(argv[2], "w"); fp = fopen(argv[3], "r"); } // If any of the file is not present // then it will give an error. if (fp == NULL || fin == NULL || fout == NULL) { printf("Error"); return 0; } // This function will read the data // of a file 'routing.txt' line by line // and store them into one array named 'buf', // after that the coma separated values in buf // are stored into their respective array. storeData(fp, buf, net, mask, gateway, port); // It will create routing table using linked list insert(net, mask, gateway, port, buf); // It will take input from input.txt files // which contains only destination ip address // and search about the route through which // packet has been sent in network // and output is stored in to an output.txt file search(fin, fout); printf("Forwarding table has been implemented successfully"); printf("See the output in %s file\n", argv[2]); /*Closes all the files*/ fclose(fin); fclose(fp); fclose(fout); return 0;}// This code is written by Pooja Patel 23620uday2021 IP Addressing Algorithms C Programs Computer Networks Algorithms Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Nov, 2021" }, { "code": null, "e": 416, "s": 28, "text": "In Unix operating system, there is a routing table that contains a certain number of tuples. These tuples are consist of network IP, subnet mask, gateway IP, and interface name. These details are used to forward a packet to the outside of its network to connect to the internet. So this article gives an idea of how the system takes the decision when a packet is needed to be forwarded. " }, { "code": null, "e": 427, "s": 416, "text": "Examples: " }, { "code": null, "e": 1032, "s": 427, "text": "Input: 201.2.2.2\nOutput: 12.23.44.1 eth9\nHere, there is no network IP entry in the routing table\nwhich starts with \"201\". In this case it will \nchoose default path(0.0.0.0, 0.0.0.0, 12.23.44.1, eth9). \nStill, it will perform bitwise AND operation with \neach entry and then chooses default path's interface \nand gateway to send packet outside. Default path means \ninterface to which system is directly connected.\n\nInput: 200.200.200.1\nOutput: 190.164.1.2 eth0\nHere bitwise AND operation is performed \nwith each entry of routing table and correspondent \nnetwork's interface name and gateway IP is returned." }, { "code": null, "e": 1131, "s": 1032, "text": "How forwarding of the packet works?This can be understood easily with the help of a small example:" }, { "code": null, "e": 1235, "s": 1131, "text": "Suppose there is a packet with IP address “20.129.0.1” and the routing table has the following entries:" }, { "code": null, "e": 1436, "s": 1235, "text": "So when the packet goes to the kernel of the system to find the gateway and interface, it will first perform a bitwise AND operation with a subnet mask of each entry to find the Longest prefix match. " }, { "code": null, "e": 1645, "s": 1436, "text": "The result of the bitwise AND operation is then compared with the network’s IP address. So it will return the correspondent IP address of the gateway and interface’s name through which the packet can go out. " }, { "code": null, "e": 1833, "s": 1645, "text": "The binary representation of 20.129.0.1 is 00010100.10000001.00000000.00000001. It then performs a bitwise AND operation with a subnet mask for each and every entry of the routing table. " }, { "code": null, "e": 2065, "s": 1833, "text": "In this table that entry number is 4( i.e. 20.128.0.0, 255.128.0.0, 12.1.1.1, eth1) which gives the longest prefix match for this packet. So packet will go out from the eth1 interface and choose the gateway 12.1.1.1 for forwarding." }, { "code": null, "e": 2234, "s": 2065, "text": "Below is the implementation of the above approach using the Linked List data structure. It takes 2 files as an input and returns output in another file mentioned above." }, { "code": null, "e": 2290, "s": 2234, "text": "File “input.txt” represents the IP address of a packet." }, { "code": null, "e": 2384, "s": 2290, "text": "File “routing.txt” contains routing table entries to which IP address is going to be matched." }, { "code": null, "e": 2435, "s": 2384, "text": "File “output.txt” contains outputs for each input." }, { "code": null, "e": 2446, "s": 2435, "text": "Program: " }, { "code": null, "e": 2448, "s": 2446, "text": "C" }, { "code": "// C code to implement IP forwarding table lookup #include <arpa/inet.h>#include <netinet/in.h>#include <stdio.h>#include <stdlib.h>#include <string.h> #define M 15#define N 150 // Declaration of structure of linked list// to store ip address in each nodestruct node { char* data; struct node* next;} * head[15]; // This function fetch data from file// and store them into different arraysvoid storeData(FILE* fp, char buf[M][N], char net[M][N], char mask[M][N], char gateway[M][N], char port[M][N]){ char line[200]; int c, i = 0, j, k = 0, m = 0; // Read data from the file line by line // and each line is stored in array separately. while (fgets(line, sizeof(line), fp)) { j = 0; for (int l = 0; l < strlen(line); l++) { buf[i][j] = line[l]; j++; } i++; } // From each lines stored in buf, // network id, subnet mask, gateway // and port are extracted // and stored into individual arrays. for (i = 0; i < 15; i++) { k = 0; for (j = 0; buf[i][j] != ','; j++) { net[i][k] = buf[i][j]; k++; } m = j + 2; k = 0; for (j = m; buf[i][j] != ','; j++) { mask[i][k] = buf[i][j]; k++; } m = j + 2; k = 0; for (j = m; buf[i][j] != ','; j++) { gateway[i][k] = buf[i][j]; k++; } m = j + 2; k = 0; for (j = m; buf[i][j] != '\\0'; j++) { port[i][k] = buf[i][j]; k++; } }} // Function to create routing table// using arrays created by storeData() function// using linked list data structurevoid insert(char net[M][N], char mask[M][N], char gateway[M][N], char port[M][N], char buf[M][N]){ char *temp1, *temp2, *temp3, *temp4; struct node* new; for (int i = 0; i < M; i++) { // Initialize head of each // linked list with NULL. head[i] = NULL; } for (int i = 0; i < M; i++) { for (int j = 0; j < 4; j++) { // If head is null // then first create new node // and store network id into it. if (head[i] == NULL) { new = (struct node*)malloc( sizeof(struct node)); new->data = net[i]; new->next = NULL; head[i] = new; } // If head is not null // and value of j is 1 then create new node // which is pointed by head and it // will contain subnet mask else if (j == 1) { new->next = (struct node*)malloc( sizeof(struct node)); new = new->next; new->data = mask[i]; new->next = NULL; } // If head is not null and value of j is 2 // then create new node // which is pointed by subnet mask // and it will contain gateway else if (j == 2) { new->next = (struct node*)malloc( sizeof(struct node)); new = new->next; new->data = gateway[i]; } // If head is not null and value of j is 3 // then create new node // which is pointed by gateway and // it will contain port else if (j == 3) { new->next = (struct node*)malloc( sizeof(struct node)); new = new->next; new->data = port[i]; } } } // Perform sorting on the basis // of longest prefix of subnet mask for (int i = 0; i < M; i++) { for (int j = i; j < M; j++) { // Longest prefix has been compared // by using inet_addr() system call // which gives decimal value of an ip address. if (inet_addr(head[i]->next->data) < inet_addr(head[j]->next->data)) { struct node* temp = head[i]; head[i] = head[j]; head[j] = temp; } } }} // This function will search for gateway ip// and port number in routing table// through which packet has been sent// to next node/destinationvoid search(FILE* fp1, FILE* fp2){ char str[100]; struct in_addr addr; unsigned int val; fprintf(fp2, \"%c\", ' '); // Read file 'input.txt' line by line // and perform bitwise AND between subnet mask // and input(destination) ip coming from file. while (fgets(str, sizeof(str), fp1)) { for (int i = 0; i < M; i++) { // Perform bitwise AND operation on result // (i.e. Decimal value of an ip address) // coming from inet_addr() system call val = inet_addr(str) & inet_addr(head[i]->next->data); addr.s_addr = val; char* str1 = inet_ntoa(addr); char* str2 = head[i]->data; int count = 0; // Compare the network id string with result // coming after performing AND operation // and if they are same then increment count. for (int i = 0; str1[i] != '\\0'; i++) { if (str1[i] == str2[i]) { count++; } } // If count is same as the string length // of network id then find gateway ip // and port number of that respective network id // and write it into 'output.txt' file. if (count == strlen(str1)) { struct node* ptr = head[i]->next; struct node* temp = ptr->next; while (temp != NULL) { fprintf(fp2, \"%s \", temp->data); temp = temp->next; } break; } } }} // Driver codeint main(int argc, char* argv[]){ FILE *fin, *fout, *fp; char buf[M][N] = { { 0 } }; char net[M][N] = { { 0 } }; char mask[M][N] = { { 0 } }; char gateway[M][N] = { { 0 } }; char port[M][N] = { { 0 } }; // if command line argument is less than 3 // then it will show standard error. if (argc < 3) { fprintf(stderr, \"File name:%s\\n\", argv[0]); return 1; } // If 3 arguments are given then input // and routing.txt files will be opened in read mode // while output.txt file is opened in write mode. else { fin = fopen(argv[1], \"r\"); fout = fopen(argv[2], \"w\"); fp = fopen(argv[3], \"r\"); } // If any of the file is not present // then it will give an error. if (fp == NULL || fin == NULL || fout == NULL) { printf(\"Error\"); return 0; } // This function will read the data // of a file 'routing.txt' line by line // and store them into one array named 'buf', // after that the coma separated values in buf // are stored into their respective array. storeData(fp, buf, net, mask, gateway, port); // It will create routing table using linked list insert(net, mask, gateway, port, buf); // It will take input from input.txt files // which contains only destination ip address // and search about the route through which // packet has been sent in network // and output is stored in to an output.txt file search(fin, fout); printf(\"Forwarding table has been implemented successfully\"); printf(\"See the output in %s file\\n\", argv[2]); /*Closes all the files*/ fclose(fin); fclose(fp); fclose(fout); return 0;}// This code is written by Pooja Patel", "e": 10071, "s": 2448, "text": null }, { "code": null, "e": 10085, "s": 10071, "text": "23620uday2021" }, { "code": null, "e": 10099, "s": 10085, "text": "IP Addressing" }, { "code": null, "e": 10110, "s": 10099, "text": "Algorithms" }, { "code": null, "e": 10121, "s": 10110, "text": "C Programs" }, { "code": null, "e": 10139, "s": 10121, "text": "Computer Networks" }, { "code": null, "e": 10150, "s": 10139, "text": "Algorithms" }, { "code": null, "e": 10168, "s": 10150, "text": "Computer Networks" } ]
Conditional Inference Trees in R Programming
10 Jul, 2020 Conditional Inference Trees is a non-parametric class of decision trees and is also known as unbiased recursive partitioning. It is a recursive partitioning approach for continuous and multivariate response variables in a conditional inference framework. To perform this approach in R Programming, ctree() function is used and requires partykit package. In this article, let’s learn about conditional inference trees, syntax, and its implementation with the help of examples. Conditional Inference Trees is a different kind of decision tree that uses recursive partitioning of dependent variables based on the value of correlations. It avoids biasing just like other algorithms of classification and regression in machine learning. Thus, avoiding vulnerability to the errors making it more flexible for the problems in the data. Conditional inference trees use a significance test which is a permutation test that selects covariate to split and recurse the variable. The p-value is calculated in this test. The significance test is executed at each start of the algorithm. This algorithm is not good for data with missing values for learning.Algorithm: Test the global null hypothesis between random input and response variables and select the input variable with the highest p-value with response variable.Perform binary split on the selected input variable.Recursively perform step 1 and 2. Test the global null hypothesis between random input and response variables and select the input variable with the highest p-value with response variable. Perform binary split on the selected input variable. Recursively perform step 1 and 2. Conditional Inference Trees is a tree-based classification algorithm. It is similar to the decision trees as ctree() also performs recursively partitioning of data just like decision trees. The only procedure that makes conditional inference trees different from decision trees is that conditional inference trees use a significance test to select input variables rather than selecting the variable that maximizes the information measure. For example, the Gini coefficient is used in traditional decision trees to select the variable that maximizes the information measure. Syntax:ctree(formula, data) Parameters:formula: represents formula on the basis of which model is to be fitdata: represents dataframe containing the variables in the model Example 1: In this example, let’s use the regression approach of Condition Inference trees on the air quality dataset which is present in the R base package. After the execution, different levels of ozone will be determined based on different environmental conditions. This helps in learning the different behavior of ozone value in different environmental conditions. Step 1: Installing the required packages. # Install the required # Package for functioninstall.packages("partykit") Step 2: Loading the required package. # Load the librarylibrary(partykit) Step 3: Creating regression model of Condition inference tree. air <- subset(airquality, !is.na(Ozone))airConInfTree <- ctree(Ozone ~ ., data = air) Step 4: Print regression model. # Print modelprint(airConInfTree) Output: Model formula: Ozone ~ Solar.R + Wind + Temp + Month + Day Fitted party: [1] root | [2] Temp <= 82 | | [3] Wind 6.9 | | | [5] Temp 77: 31.143 (n = 21, err = 4620.6) | [7] Temp > 82 | | [8] Wind 10.3: 48.714 (n = 7, err = 1183.4) Number of inner nodes: 4 Number of terminal nodes: 5 Step 4: Plotting the graph. # Output to be present as PNG filepng(file = "conditionalRegression.png") # Plotting graphplot(airConInfTree) # Save the filedev.off() Output: Explanation:After executing, the above code produces a graph of conditional inference tree that shows the ozone value in the form of a box plot in each node in different environmental conditions. As in the above output image, Node 5 shows the minimum ozone value. Further, learning the behavior shows Temp6.9 shows the least ozone value in air quality. Example 2: In this example, let’s use the classification approach of Condition Inference trees on the iris dataset present in the R base package. After executing the code, different species of iris plants will be determined on the basis of petal length and width. Step 1: Installing the required packages. # Install the required # Package for functioninstall.packages("partykit") Step 2: Loading the required package. # Load the librarylibrary(partykit) Step 3: Creating classification model of Condition inference tree irisConInfTree <- ctree(Species ~ ., data = iris) Step 4: Print classification model # Print modelprint(irisConInfTree) Output: Model formula: Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width Fitted party: [1] root | [2] Petal.Length 1.9 | | [4] Petal.Width <= 1.7 | | | [5] Petal.Length 4.8: versicolor (n = 8, err = 50.0%) | | [7] Petal.Width > 1.7: virginica (n = 46, err = 2.2%) Number of inner nodes: 3 Number of terminal nodes: 4 Step 4: Plotting the graph # Output to be present as PNG filepng(file = "conditionalClassification.png",width = 1200, height = 400) # Plotting graphplot(irisConInfTree) # Save the filedev.off() Output:Explanation:After executing the above code, species of iris plants are classified based on petal length and width. As in above graph, setosa species have petal length <= 1.9. Picked R Machine-Learning R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n10 Jul, 2020" }, { "code": null, "e": 529, "s": 53, "text": "Conditional Inference Trees is a non-parametric class of decision trees and is also known as unbiased recursive partitioning. It is a recursive partitioning approach for continuous and multivariate response variables in a conditional inference framework. To perform this approach in R Programming, ctree() function is used and requires partykit package. In this article, let’s learn about conditional inference trees, syntax, and its implementation with the help of examples." }, { "code": null, "e": 1206, "s": 529, "text": "Conditional Inference Trees is a different kind of decision tree that uses recursive partitioning of dependent variables based on the value of correlations. It avoids biasing just like other algorithms of classification and regression in machine learning. Thus, avoiding vulnerability to the errors making it more flexible for the problems in the data. Conditional inference trees use a significance test which is a permutation test that selects covariate to split and recurse the variable. The p-value is calculated in this test. The significance test is executed at each start of the algorithm. This algorithm is not good for data with missing values for learning.Algorithm:" }, { "code": null, "e": 1446, "s": 1206, "text": "Test the global null hypothesis between random input and response variables and select the input variable with the highest p-value with response variable.Perform binary split on the selected input variable.Recursively perform step 1 and 2." }, { "code": null, "e": 1601, "s": 1446, "text": "Test the global null hypothesis between random input and response variables and select the input variable with the highest p-value with response variable." }, { "code": null, "e": 1654, "s": 1601, "text": "Perform binary split on the selected input variable." }, { "code": null, "e": 1688, "s": 1654, "text": "Recursively perform step 1 and 2." }, { "code": null, "e": 2262, "s": 1688, "text": "Conditional Inference Trees is a tree-based classification algorithm. It is similar to the decision trees as ctree() also performs recursively partitioning of data just like decision trees. The only procedure that makes conditional inference trees different from decision trees is that conditional inference trees use a significance test to select input variables rather than selecting the variable that maximizes the information measure. For example, the Gini coefficient is used in traditional decision trees to select the variable that maximizes the information measure." }, { "code": null, "e": 2290, "s": 2262, "text": "Syntax:ctree(formula, data)" }, { "code": null, "e": 2434, "s": 2290, "text": "Parameters:formula: represents formula on the basis of which model is to be fitdata: represents dataframe containing the variables in the model" }, { "code": null, "e": 2445, "s": 2434, "text": "Example 1:" }, { "code": null, "e": 2803, "s": 2445, "text": "In this example, let’s use the regression approach of Condition Inference trees on the air quality dataset which is present in the R base package. After the execution, different levels of ozone will be determined based on different environmental conditions. This helps in learning the different behavior of ozone value in different environmental conditions." }, { "code": null, "e": 2845, "s": 2803, "text": "Step 1: Installing the required packages." }, { "code": "# Install the required # Package for functioninstall.packages(\"partykit\")", "e": 2919, "s": 2845, "text": null }, { "code": null, "e": 2957, "s": 2919, "text": "Step 2: Loading the required package." }, { "code": "# Load the librarylibrary(partykit)", "e": 2993, "s": 2957, "text": null }, { "code": null, "e": 3056, "s": 2993, "text": "Step 3: Creating regression model of Condition inference tree." }, { "code": "air <- subset(airquality, !is.na(Ozone))airConInfTree <- ctree(Ozone ~ ., data = air)", "e": 3165, "s": 3056, "text": null }, { "code": null, "e": 3197, "s": 3165, "text": "Step 4: Print regression model." }, { "code": "# Print modelprint(airConInfTree)", "e": 3231, "s": 3197, "text": null }, { "code": null, "e": 3239, "s": 3231, "text": "Output:" }, { "code": null, "e": 3548, "s": 3239, "text": "Model formula:\nOzone ~ Solar.R + Wind + Temp + Month + Day\n\nFitted party:\n[1] root\n| [2] Temp <= 82\n| | [3] Wind 6.9\n| | | [5] Temp 77: 31.143 (n = 21, err = 4620.6)\n| [7] Temp > 82\n| | [8] Wind 10.3: 48.714 (n = 7, err = 1183.4)\n\nNumber of inner nodes: 4\nNumber of terminal nodes: 5\n" }, { "code": null, "e": 3576, "s": 3548, "text": "Step 4: Plotting the graph." }, { "code": "# Output to be present as PNG filepng(file = \"conditionalRegression.png\") # Plotting graphplot(airConInfTree) # Save the filedev.off()", "e": 3713, "s": 3576, "text": null }, { "code": null, "e": 3721, "s": 3713, "text": "Output:" }, { "code": null, "e": 4074, "s": 3721, "text": "Explanation:After executing, the above code produces a graph of conditional inference tree that shows the ozone value in the form of a box plot in each node in different environmental conditions. As in the above output image, Node 5 shows the minimum ozone value. Further, learning the behavior shows Temp6.9 shows the least ozone value in air quality." }, { "code": null, "e": 4085, "s": 4074, "text": "Example 2:" }, { "code": null, "e": 4338, "s": 4085, "text": "In this example, let’s use the classification approach of Condition Inference trees on the iris dataset present in the R base package. After executing the code, different species of iris plants will be determined on the basis of petal length and width." }, { "code": null, "e": 4380, "s": 4338, "text": "Step 1: Installing the required packages." }, { "code": "# Install the required # Package for functioninstall.packages(\"partykit\")", "e": 4454, "s": 4380, "text": null }, { "code": null, "e": 4492, "s": 4454, "text": "Step 2: Loading the required package." }, { "code": "# Load the librarylibrary(partykit)", "e": 4528, "s": 4492, "text": null }, { "code": null, "e": 4594, "s": 4528, "text": "Step 3: Creating classification model of Condition inference tree" }, { "code": "irisConInfTree <- ctree(Species ~ ., data = iris)", "e": 4668, "s": 4594, "text": null }, { "code": null, "e": 4703, "s": 4668, "text": "Step 4: Print classification model" }, { "code": "# Print modelprint(irisConInfTree)", "e": 4738, "s": 4703, "text": null }, { "code": null, "e": 4746, "s": 4738, "text": "Output:" }, { "code": null, "e": 5095, "s": 4746, "text": "Model formula:\nSpecies ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width\n\nFitted party:\n[1] root\n| [2] Petal.Length 1.9\n| | [4] Petal.Width <= 1.7\n| | | [5] Petal.Length 4.8: versicolor (n = 8, err = 50.0%)\n| | [7] Petal.Width > 1.7: virginica (n = 46, err = 2.2%)\n\nNumber of inner nodes: 3\nNumber of terminal nodes: 4\n" }, { "code": null, "e": 5122, "s": 5095, "text": "Step 4: Plotting the graph" }, { "code": "# Output to be present as PNG filepng(file = \"conditionalClassification.png\",width = 1200, height = 400) # Plotting graphplot(irisConInfTree) # Save the filedev.off()", "e": 5291, "s": 5122, "text": null }, { "code": null, "e": 5473, "s": 5291, "text": "Output:Explanation:After executing the above code, species of iris plants are classified based on petal length and width. As in above graph, setosa species have petal length <= 1.9." }, { "code": null, "e": 5480, "s": 5473, "text": "Picked" }, { "code": null, "e": 5499, "s": 5480, "text": "R Machine-Learning" }, { "code": null, "e": 5510, "s": 5499, "text": "R Language" } ]
Converting an image to ASCII image in Python
In this article we we want to convert a given images into a text bases image also called ASCII image. Below is the Python program which will take an input imagee and various functions to convert them into grayscale picture and then apply the ASCII characters to create different patterns insert the image. Finally the emails comes text based image this is a series of plane ASCII characters. from PIL import Image import os ASCII_CHARS = [ '#', '?', '%', '.', 'S', '+', '.', '*', ':', ',', '@'] def resize_image(image, new_width=25): (input__width, input__height) = image.size aspect_ratio = input__height/float(input__width) changed_height = int(aspect_ratio * new_width) changed_image = image.resize((new_width, changed_height)) return changed_image def make_grey(image): return image.convert('L') def pixel_to_ascii(image, range_width=25): pixels_in_image = list(image.getdata()) pixels_to_chars = [ASCII_CHARS[pixel_value//range_width] for pixel_value in pixels_in_image] return "".join(pixels_to_chars) def image_to_ascii(image, new_width=25): image = resize_image(image) image = make_grey(image) pixels_to_chars = pixel_to_ascii(image) len_pixels_to_chars = len(pixels_to_chars) image_ascii = [pixels_to_chars[index: index + new_width] for index in range(0, len_pixels_to_chars, new_width)] return "\n".join(image_ascii) def convert_image(image_filepath): # image = None try: image = Image.open(image_filepath) except Exception as e: print("Unable to open image file {image_filepath}.".format(image_filepath=image_filepath)) print(e) return image_ascii = image_to_ascii(image) f = open(os.path.splitext(image_filepath)[0]+'.txt','w') f.write(image_ascii) f.close() convert_image('D:\\button.jpg') Running the above code gives us the following result −
[ { "code": null, "e": 1164, "s": 1062, "text": "In this article we we want to convert a given images into a text bases image also called ASCII image." }, { "code": null, "e": 1454, "s": 1164, "text": "Below is the Python program which will take an input imagee and various functions to convert them into grayscale picture and then apply the ASCII characters to create different patterns insert the image. Finally the emails comes text based image this is a series of plane ASCII characters." }, { "code": null, "e": 2864, "s": 1454, "text": "from PIL import Image\nimport os\nASCII_CHARS = [ '#', '?', '%', '.', 'S', '+', '.', '*', ':', ',', '@']\ndef resize_image(image, new_width=25):\n (input__width, input__height) = image.size\n aspect_ratio = input__height/float(input__width)\n changed_height = int(aspect_ratio * new_width)\n changed_image = image.resize((new_width, changed_height))\n return changed_image\ndef make_grey(image):\n return image.convert('L')\ndef pixel_to_ascii(image, range_width=25):\n pixels_in_image = list(image.getdata())\n pixels_to_chars = [ASCII_CHARS[pixel_value//range_width] for pixel_value in\n pixels_in_image]\n return \"\".join(pixels_to_chars)\ndef image_to_ascii(image, new_width=25):\n image = resize_image(image)\n image = make_grey(image)\n pixels_to_chars = pixel_to_ascii(image)\n len_pixels_to_chars = len(pixels_to_chars)\n image_ascii = [pixels_to_chars[index: index + new_width] for index in\n range(0, len_pixels_to_chars, new_width)]\n return \"\\n\".join(image_ascii)\ndef convert_image(image_filepath):\n # image = None\n try:\n image = Image.open(image_filepath)\n except Exception as e:\n print(\"Unable to open image file {image_filepath}.\".format(image_filepath=image_filepath))\n print(e)\n return\n image_ascii = image_to_ascii(image)\n f = open(os.path.splitext(image_filepath)[0]+'.txt','w')\n f.write(image_ascii)\n f.close()\nconvert_image('D:\\\\button.jpg')" }, { "code": null, "e": 2919, "s": 2864, "text": "Running the above code gives us the following result −" } ]
C++ Program for QuickSort?
Quicksort is a sorting technique which uses comparisons to sort an unsorted list( array ). Quicksort is also known as partition exchange sort. It is not a stable sort, Because the relative order of equal sort items is not preserved. Quicksort can operate on an array, requiring small additional amounts of memory to perform the sorting. It is very similar to selection sort, except that it does not always choose worst-case partition. So, so we can take it as a better formed of selection Sort. QuickSort is one of the most efficient sorting algorithms and is based on the splitting of an array into smaller ones. The name comes from the fact that quicksort is capable of sorting a list of data elements significantly faster than any of the common sorting algorithms. And like Merge sort, Quick sort also falls into the category of divide and conquer approach of problem-solving methodology. Taking the analogical view in perspective, consider a situation where one had to sort the papers bearing the names of the students, by name. One might use the approach as follows −Select a splitting value, say L. The splitting value is also known as Pivot.Divide the stack of papers into two. A-L and M-Z. It is not necessary that the piles should be equal.Repeat the above two steps with the A-L pile, splitting it into its significant two halves. And M-Z pile, split into its halves. The process is repeated until the piles are small enough to be sorted easily.Ultimately, the smaller piles can be placed one on top of the other to produce a fully sorted and ordered set of papers. Taking the analogical view in perspective, consider a situation where one had to sort the papers bearing the names of the students, by name. One might use the approach as follows − Select a splitting value, say L. The splitting value is also known as Pivot. Select a splitting value, say L. The splitting value is also known as Pivot. Divide the stack of papers into two. A-L and M-Z. It is not necessary that the piles should be equal. Divide the stack of papers into two. A-L and M-Z. It is not necessary that the piles should be equal. Repeat the above two steps with the A-L pile, splitting it into its significant two halves. And M-Z pile, split into its halves. The process is repeated until the piles are small enough to be sorted easily. Repeat the above two steps with the A-L pile, splitting it into its significant two halves. And M-Z pile, split into its halves. The process is repeated until the piles are small enough to be sorted easily. Ultimately, the smaller piles can be placed one on top of the other to produce a fully sorted and ordered set of papers. Ultimately, the smaller piles can be placed one on top of the other to produce a fully sorted and ordered set of papers. The approach used here is recursion at each split to get to the single-element array. The approach used here is recursion at each split to get to the single-element array. At every split, the pile was divided and then the same approach was used for the smaller piles. At every split, the pile was divided and then the same approach was used for the smaller piles. Due to these features, quicksort is also called a partition exchange sort. Due to these features, quicksort is also called a partition exchange sort. Input: arr[] = {7,4,2,6,3,1,5} Output: 1 2 3 4 5 6 7 An example might come in handy to understand the concept. Consider the following array: 50, 23, 9, 18, 61, 32 Step 1− Decide any value to be the pivot from the list (generally the last value). Suppose for two values “Low” and “High” corresponding to the first index, and last index. In our case low is 0 and high is 5. Values at low and high are 50 and 32 and Value of pivot is 32. Hence, call for partitioning, rearranging the array in such a way that pivot (32) comes to its actual position. And to the left of the pivot, the array has all the elements less than it, and to the right greater than it. In the partition function, we start from the first element and compare it with the pivot. Since 50 is greater than 32, we don’t make any change and move on to the next element 23. Compare again with the pivot. Since 23 is less than 32, we swap 50 and 23. The array becomes 23, 50, 9, 18, 61, 32. We move on to the next element 9 which is again less than pivot (32) thus swapping it with 50 makes our array as 23, 9, 50, 18, 61, 32. Similarly, for the next element 18 which is less than 32, the array becomes 23, 9, 18, 50, 61, 32 Now 61 is greater than pivot (32), hence no changes. Lastly, we swap our pivot with 50 so that it comes to the correct position. Thus the pivot (32) comes at its actual position and all elements to its left are lesser, and all elements to the right are greater than itself. Step 2− Hence the array after the first step becomes 23, 9, 18, 32, 61, 50, taking 32 as the pivot. Step 3− Now the list is divided into two parts: 1. Sublist before pivot: 23, 9, 18 2. Sublist after pivot: 61, 50 Step 4− Repeat the steps for these sublists again. The final array thus becomes 9, 18, 23, 32, 50, 61. #include <stdio.h> void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } int Partition(int a[], int low, int high) { int pivot, index, i; index = low; pivot = high; for(i=low; i < high; i++) { if(a[i] < a[pivot]) { swap(&a[i], &a[index]); index++; } } swap(&a[pivot], &a[index]); return index; } int RandomPivotPartition(int a[], int low, int high) { int pvt, n, temp; n = rand(); pvt = low + n%(high-low+1); swap(&a[high], &a[pvt]); return Partition(a, low, high); } int QuickSort(int a[], int low, int high) { return 0; } int main() { int n, i; n=7; int arr[]={7,4,2,6,3,1,5}; int high = n-1; int low = 0 ; int pindex; if(low < high) { pindex = RandomPivotPartition(arr, low, high); QuickSort(arr, low, pindex-1); QuickSort(arr, pindex+1, high); } for (i = 0; i < n; i++) printf("%d ", arr[i]); return 0; }
[ { "code": null, "e": 1205, "s": 1062, "text": "Quicksort is a sorting technique which uses comparisons to sort an unsorted list( array ). Quicksort is also known as partition exchange sort." }, { "code": null, "e": 1557, "s": 1205, "text": "It is not a stable sort, Because the relative order of equal sort items is not preserved. Quicksort can operate on an array, requiring small additional amounts of memory to perform the sorting. It is very similar to selection sort, except that it does not always choose worst-case partition. So, so we can take it as a better formed of selection Sort." }, { "code": null, "e": 1954, "s": 1557, "text": "QuickSort is one of the most efficient sorting algorithms and is based on the splitting of an array into smaller ones. The name comes from the fact that quicksort is capable of sorting a list of data elements significantly faster than any of the common sorting algorithms. And like Merge sort, Quick sort also falls into the category of divide and conquer approach of problem-solving methodology." }, { "code": null, "e": 2638, "s": 1954, "text": "Taking the analogical view in perspective, consider a situation where one had to sort the papers bearing the names of the students, by name. One might use the approach as follows −Select a splitting value, say L. The splitting value is also known as Pivot.Divide the stack of papers into two. A-L and M-Z. It is not necessary that the piles should be equal.Repeat the above two steps with the A-L pile, splitting it into its significant two halves. And M-Z pile, split into its halves. The process is repeated until the piles are small enough to be sorted easily.Ultimately, the smaller piles can be placed one on top of the other to produce a fully sorted and ordered set of papers." }, { "code": null, "e": 2819, "s": 2638, "text": "Taking the analogical view in perspective, consider a situation where one had to sort the papers bearing the names of the students, by name. One might use the approach as follows −" }, { "code": null, "e": 2896, "s": 2819, "text": "Select a splitting value, say L. The splitting value is also known as Pivot." }, { "code": null, "e": 2973, "s": 2896, "text": "Select a splitting value, say L. The splitting value is also known as Pivot." }, { "code": null, "e": 3075, "s": 2973, "text": "Divide the stack of papers into two. A-L and M-Z. It is not necessary that the piles should be equal." }, { "code": null, "e": 3177, "s": 3075, "text": "Divide the stack of papers into two. A-L and M-Z. It is not necessary that the piles should be equal." }, { "code": null, "e": 3384, "s": 3177, "text": "Repeat the above two steps with the A-L pile, splitting it into its significant two halves. And M-Z pile, split into its halves. The process is repeated until the piles are small enough to be sorted easily." }, { "code": null, "e": 3591, "s": 3384, "text": "Repeat the above two steps with the A-L pile, splitting it into its significant two halves. And M-Z pile, split into its halves. The process is repeated until the piles are small enough to be sorted easily." }, { "code": null, "e": 3712, "s": 3591, "text": "Ultimately, the smaller piles can be placed one on top of the other to produce a fully sorted and ordered set of papers." }, { "code": null, "e": 3833, "s": 3712, "text": "Ultimately, the smaller piles can be placed one on top of the other to produce a fully sorted and ordered set of papers." }, { "code": null, "e": 3919, "s": 3833, "text": "The approach used here is recursion at each split to get to the single-element array." }, { "code": null, "e": 4005, "s": 3919, "text": "The approach used here is recursion at each split to get to the single-element array." }, { "code": null, "e": 4101, "s": 4005, "text": "At every split, the pile was divided and then the same approach was used for the smaller piles." }, { "code": null, "e": 4197, "s": 4101, "text": "At every split, the pile was divided and then the same approach was used for the smaller piles." }, { "code": null, "e": 4272, "s": 4197, "text": "Due to these features, quicksort is also called a partition exchange sort." }, { "code": null, "e": 4347, "s": 4272, "text": "Due to these features, quicksort is also called a partition exchange sort." }, { "code": null, "e": 4400, "s": 4347, "text": "Input: arr[] = {7,4,2,6,3,1,5}\nOutput: 1 2 3 4 5 6 7" }, { "code": null, "e": 4510, "s": 4400, "text": "An example might come in handy to understand the concept. Consider the following array: 50, 23, 9, 18, 61, 32" }, { "code": null, "e": 4683, "s": 4510, "text": "Step 1− Decide any value to be the pivot from the list (generally the last value). Suppose for two values “Low” and “High” corresponding to the first index, and last index." }, { "code": null, "e": 4719, "s": 4683, "text": "In our case low is 0 and high is 5." }, { "code": null, "e": 4782, "s": 4719, "text": "Values at low and high are 50 and 32 and Value of pivot is 32." }, { "code": null, "e": 5003, "s": 4782, "text": "Hence, call for partitioning, rearranging the array in such a way that pivot (32) comes to its actual position. And to the left of the pivot, the array has all the elements less than it, and to the right greater than it." }, { "code": null, "e": 5183, "s": 5003, "text": "In the partition function, we start from the first element and compare it with the pivot. Since 50 is greater than 32, we don’t make any change and move on to the next element 23." }, { "code": null, "e": 5299, "s": 5183, "text": "Compare again with the pivot. Since 23 is less than 32, we swap 50 and 23. The array becomes 23, 50, 9, 18, 61, 32." }, { "code": null, "e": 5412, "s": 5299, "text": "We move on to the next element 9 which is again less than pivot (32) thus swapping it with 50 makes our array as" }, { "code": null, "e": 5435, "s": 5412, "text": "23, 9, 50, 18, 61, 32." }, { "code": null, "e": 5511, "s": 5435, "text": "Similarly, for the next element 18 which is less than 32, the array becomes" }, { "code": null, "e": 5586, "s": 5511, "text": "23, 9, 18, 50, 61, 32 Now 61 is greater than pivot (32), hence no changes." }, { "code": null, "e": 5662, "s": 5586, "text": "Lastly, we swap our pivot with 50 so that it comes to the correct position." }, { "code": null, "e": 5807, "s": 5662, "text": "Thus the pivot (32) comes at its actual position and all elements to its left are lesser, and all elements to the right are greater than itself." }, { "code": null, "e": 5860, "s": 5807, "text": "Step 2− Hence the array after the first step becomes" }, { "code": null, "e": 5907, "s": 5860, "text": "23, 9, 18, 32, 61, 50, taking 32 as the pivot." }, { "code": null, "e": 5955, "s": 5907, "text": "Step 3− Now the list is divided into two parts:" }, { "code": null, "e": 5990, "s": 5955, "text": "1. Sublist before pivot: 23, 9, 18" }, { "code": null, "e": 6021, "s": 5990, "text": "2. Sublist after pivot: 61, 50" }, { "code": null, "e": 6072, "s": 6021, "text": "Step 4− Repeat the steps for these sublists again." }, { "code": null, "e": 6124, "s": 6072, "text": "The final array thus becomes 9, 18, 23, 32, 50, 61." }, { "code": null, "e": 7085, "s": 6124, "text": "#include <stdio.h>\nvoid swap(int *a, int *b) {\n int temp;\n temp = *a;\n *a = *b;\n *b = temp;\n}\nint Partition(int a[], int low, int high) {\n int pivot, index, i;\n index = low;\n pivot = high;\n for(i=low; i < high; i++) {\n if(a[i] < a[pivot]) {\n swap(&a[i], &a[index]);\n index++;\n }\n }\n swap(&a[pivot], &a[index]);\n return index;\n}\nint RandomPivotPartition(int a[], int low, int high) {\n int pvt, n, temp;\n n = rand();\n pvt = low + n%(high-low+1);\n swap(&a[high], &a[pvt]);\n return Partition(a, low, high);\n}\nint QuickSort(int a[], int low, int high) {\n return 0;\n}\nint main() {\n int n, i;\n n=7;\n int arr[]={7,4,2,6,3,1,5};\n int high = n-1;\n int low = 0 ;\n int pindex;\n if(low < high) {\n pindex = RandomPivotPartition(arr, low, high);\n QuickSort(arr, low, pindex-1);\n QuickSort(arr, pindex+1, high);\n }\n for (i = 0; i < n; i++)\n printf(\"%d \", arr[i]);\n return 0;\n}" } ]
Pandas GroupBy – Unstack
19 Jan, 2022 Pandas Unstack is a function that pivots the level of the indexed columns in a stacked dataframe. A stacked dataframe is usually a result of an aggregated groupby function in pandas. Stack() sets the columns to a new level of hierarchy whereas Unstack() pivots the indexed column. There are different ways to Unstack a pandas dataframe which would be discussed in the below methods. Groupby aggregation on a dataframe usually returns a stacked dataframe object, of multi-levels depending on the aggregation model. Python3 # import the python pandas packageimport pandas as pd# create a sample dataframedata = pd.DataFrame({"cars": ["bmw", "bmw", "benz", "benz"], "sale_q1 in Cr": [20, 22, 24, 26], 'sale_q2 in Cr': [11, 13, 15, 17]}, columns=["cars", "sale_q1 in Cr", 'sale_q2 in Cr'])print(data) # stack the data using stack() functionstacked_data = data.stack()print(stacked_data) # unstack the dataframe by first levelstack_level_1 = stacked_data.unstack(level=0)print(stack_level_1) # unstack the dataframe by second levelstack_level_2 = stacked_data.unstack(level=1)print(stack_level_2) Output: Code Explanation: Create a sample dataframe showing car sales in two quarters. Now, stack the dataframe using stack() function, this will stack the columns to row values. As we have two columns while unstacking it will be considered as two different levels. Now, use unstack function with level 0 and level 1 separately to stack the dataframe at two different levels. It depends on the use case to stack the first or second level. Whenever we use groupby function on pandas dataframe with more than one aggregation function per column, the output is usually a multi-indexed column where as the first index specifies the column name and the second column index specifies the aggregation function name. Python3 # import the python pandas packageimport pandas as pd # create a sample dataframedata = pd.DataFrame({"cars": ["bmw", "bmw", "benz", "benz"], "sale_q1 in Cr": [20, 22, 24, 26], 'sale_q2 in Cr': [11, 13, 15, 17]}, columns=["cars", "sale_q1 in Cr", 'sale_q2 in Cr'])print(data) # aggregate the car sales data by sum min# and max sales of two quarters as showngrouped_data = data.groupby('cars').agg( {"sale_q1 in Cr": [sum, max], "sale_q2 in Cr": [sum, min]})print(grouped_data) # general way of unstacking the grouped dataframegen_unstack = grouped_data.unstack()print(gen_unstack) # stacking the grouped dataframe at# different levels and unstacking# unstacking the stacked dataframe at level = 0unstack_level1 = grouped_data.stack(level=0).unstack()print(unstack_level1) # unstacking the stacked dataframe at level =1unstack_level2 = grouped_data.stack(level=1).unstack()print(unstack_level2) Output: Code Explanation: Create a sample dataframe showing car sales in two quarters. Use GroupBy function to group the car sales data by sum min and max sales of two quarters as shown As we have two columns while unstacking it will be considered as two different levels at two indexes. The first index will have the column name and the second index will have the name of the aggregated function. Now, perform a simple unstack operation on the grouped dataframe. This simple unstack will convert the columns as rows and vice versa as shown in the output Generally, to have more depth in insights generated by GroupBy function, it is normally stacked at different levels of the grouped dataframe. This grouped dataframe can be further investigated by unstacking at different levels using unstack() function. The practical implementation is given below. Python3 # import the python pandas packageimport pandas as pd# create a sample dataframedata = pd.DataFrame({"cars": ["bmw", "bmw", "benz", "benz"], "sale_q1 in Cr": [20, 22, 24, 26], 'sale_q2 in Cr': [11, 13, 15, 17]}, columns=["cars", "sale_q1 in Cr", 'sale_q2 in Cr'])print(data) # aggregate the car sales data by sum min and# max sales of two quarters as showngrouped_data = data.groupby('cars').agg( {"sale_q1 in Cr": [sum, max], "sale_q2 in Cr": [sum, min]})print(grouped_data) # stacking the grouped dataframe at# different levels and unstacking# unstacking the stacked dataframe at level = 0unstack_level1 = grouped_data.stack(level=0).unstack()print(unstack_level1) # unstacking the stacked dataframe at level =1unstack_level2 = grouped_data.stack(level=1).unstack()print(unstack_level2) Output: Code Explanation: Create a sample dataframe showing car sales in two quarters. Use GroupBy function to group the car sales data by sum min and max sales of two quarters as shown As we have two columns while unstacking it will be considered as two different levels at two indexes. The first index will have the column name and the second index will have the name of the aggregated function. Now, use stack() at level 0 of the grouped dataframe and unstack() the grouped dataframe. Then, use stack() at level 1 of the grouped dataframe and unstack() the grouped dataframe. It depends on the use case to unstack the dataframe at the first or second level. sagar0719kumar Picked Python pandas-groupby 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 ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Jan, 2022" }, { "code": null, "e": 436, "s": 52, "text": "Pandas Unstack is a function that pivots the level of the indexed columns in a stacked dataframe. A stacked dataframe is usually a result of an aggregated groupby function in pandas. Stack() sets the columns to a new level of hierarchy whereas Unstack() pivots the indexed column. There are different ways to Unstack a pandas dataframe which would be discussed in the below methods." }, { "code": null, "e": 567, "s": 436, "text": "Groupby aggregation on a dataframe usually returns a stacked dataframe object, of multi-levels depending on the aggregation model." }, { "code": null, "e": 575, "s": 567, "text": "Python3" }, { "code": "# import the python pandas packageimport pandas as pd# create a sample dataframedata = pd.DataFrame({\"cars\": [\"bmw\", \"bmw\", \"benz\", \"benz\"], \"sale_q1 in Cr\": [20, 22, 24, 26], 'sale_q2 in Cr': [11, 13, 15, 17]}, columns=[\"cars\", \"sale_q1 in Cr\", 'sale_q2 in Cr'])print(data) # stack the data using stack() functionstacked_data = data.stack()print(stacked_data) # unstack the dataframe by first levelstack_level_1 = stacked_data.unstack(level=0)print(stack_level_1) # unstack the dataframe by second levelstack_level_2 = stacked_data.unstack(level=1)print(stack_level_2)", "e": 1232, "s": 575, "text": null }, { "code": null, "e": 1240, "s": 1232, "text": "Output:" }, { "code": null, "e": 1258, "s": 1240, "text": "Code Explanation:" }, { "code": null, "e": 1319, "s": 1258, "text": "Create a sample dataframe showing car sales in two quarters." }, { "code": null, "e": 1411, "s": 1319, "text": "Now, stack the dataframe using stack() function, this will stack the columns to row values." }, { "code": null, "e": 1498, "s": 1411, "text": "As we have two columns while unstacking it will be considered as two different levels." }, { "code": null, "e": 1608, "s": 1498, "text": "Now, use unstack function with level 0 and level 1 separately to stack the dataframe at two different levels." }, { "code": null, "e": 1671, "s": 1608, "text": "It depends on the use case to stack the first or second level." }, { "code": null, "e": 1941, "s": 1671, "text": "Whenever we use groupby function on pandas dataframe with more than one aggregation function per column, the output is usually a multi-indexed column where as the first index specifies the column name and the second column index specifies the aggregation function name." }, { "code": null, "e": 1949, "s": 1941, "text": "Python3" }, { "code": "# import the python pandas packageimport pandas as pd # create a sample dataframedata = pd.DataFrame({\"cars\": [\"bmw\", \"bmw\", \"benz\", \"benz\"], \"sale_q1 in Cr\": [20, 22, 24, 26], 'sale_q2 in Cr': [11, 13, 15, 17]}, columns=[\"cars\", \"sale_q1 in Cr\", 'sale_q2 in Cr'])print(data) # aggregate the car sales data by sum min# and max sales of two quarters as showngrouped_data = data.groupby('cars').agg( {\"sale_q1 in Cr\": [sum, max], \"sale_q2 in Cr\": [sum, min]})print(grouped_data) # general way of unstacking the grouped dataframegen_unstack = grouped_data.unstack()print(gen_unstack) # stacking the grouped dataframe at# different levels and unstacking# unstacking the stacked dataframe at level = 0unstack_level1 = grouped_data.stack(level=0).unstack()print(unstack_level1) # unstacking the stacked dataframe at level =1unstack_level2 = grouped_data.stack(level=1).unstack()print(unstack_level2)", "e": 2937, "s": 1949, "text": null }, { "code": null, "e": 2945, "s": 2937, "text": "Output:" }, { "code": null, "e": 2963, "s": 2945, "text": "Code Explanation:" }, { "code": null, "e": 3024, "s": 2963, "text": "Create a sample dataframe showing car sales in two quarters." }, { "code": null, "e": 3123, "s": 3024, "text": "Use GroupBy function to group the car sales data by sum min and max sales of two quarters as shown" }, { "code": null, "e": 3335, "s": 3123, "text": "As we have two columns while unstacking it will be considered as two different levels at two indexes. The first index will have the column name and the second index will have the name of the aggregated function." }, { "code": null, "e": 3492, "s": 3335, "text": "Now, perform a simple unstack operation on the grouped dataframe. This simple unstack will convert the columns as rows and vice versa as shown in the output" }, { "code": null, "e": 3790, "s": 3492, "text": "Generally, to have more depth in insights generated by GroupBy function, it is normally stacked at different levels of the grouped dataframe. This grouped dataframe can be further investigated by unstacking at different levels using unstack() function. The practical implementation is given below." }, { "code": null, "e": 3798, "s": 3790, "text": "Python3" }, { "code": "# import the python pandas packageimport pandas as pd# create a sample dataframedata = pd.DataFrame({\"cars\": [\"bmw\", \"bmw\", \"benz\", \"benz\"], \"sale_q1 in Cr\": [20, 22, 24, 26], 'sale_q2 in Cr': [11, 13, 15, 17]}, columns=[\"cars\", \"sale_q1 in Cr\", 'sale_q2 in Cr'])print(data) # aggregate the car sales data by sum min and# max sales of two quarters as showngrouped_data = data.groupby('cars').agg( {\"sale_q1 in Cr\": [sum, max], \"sale_q2 in Cr\": [sum, min]})print(grouped_data) # stacking the grouped dataframe at# different levels and unstacking# unstacking the stacked dataframe at level = 0unstack_level1 = grouped_data.stack(level=0).unstack()print(unstack_level1) # unstacking the stacked dataframe at level =1unstack_level2 = grouped_data.stack(level=1).unstack()print(unstack_level2)", "e": 4677, "s": 3798, "text": null }, { "code": null, "e": 4685, "s": 4677, "text": "Output:" }, { "code": null, "e": 4703, "s": 4685, "text": "Code Explanation:" }, { "code": null, "e": 4764, "s": 4703, "text": "Create a sample dataframe showing car sales in two quarters." }, { "code": null, "e": 4863, "s": 4764, "text": "Use GroupBy function to group the car sales data by sum min and max sales of two quarters as shown" }, { "code": null, "e": 5075, "s": 4863, "text": "As we have two columns while unstacking it will be considered as two different levels at two indexes. The first index will have the column name and the second index will have the name of the aggregated function." }, { "code": null, "e": 5165, "s": 5075, "text": "Now, use stack() at level 0 of the grouped dataframe and unstack() the grouped dataframe." }, { "code": null, "e": 5256, "s": 5165, "text": "Then, use stack() at level 1 of the grouped dataframe and unstack() the grouped dataframe." }, { "code": null, "e": 5338, "s": 5256, "text": "It depends on the use case to unstack the dataframe at the first or second level." }, { "code": null, "e": 5353, "s": 5338, "text": "sagar0719kumar" }, { "code": null, "e": 5360, "s": 5353, "text": "Picked" }, { "code": null, "e": 5382, "s": 5360, "text": "Python pandas-groupby" }, { "code": null, "e": 5396, "s": 5382, "text": "Python-pandas" }, { "code": null, "e": 5403, "s": 5396, "text": "Python" }, { "code": null, "e": 5501, "s": 5403, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5533, "s": 5501, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5560, "s": 5533, "text": "Python Classes and Objects" }, { "code": null, "e": 5581, "s": 5560, "text": "Python OOPs Concepts" }, { "code": null, "e": 5604, "s": 5581, "text": "Introduction To PYTHON" }, { "code": null, "e": 5660, "s": 5604, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 5691, "s": 5660, "text": "Python | os.path.join() method" }, { "code": null, "e": 5733, "s": 5691, "text": "Check if element exists in list in Python" }, { "code": null, "e": 5775, "s": 5733, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 5814, "s": 5775, "text": "Python | Get unique values from a list" } ]
Minimum increment by k operations to make all elements equal
31 May, 2022 You are given an array of n-elements, you have to find the number of operations needed to make all elements of array equal. Where a single operation can increment an element by k. If it is not possible to make all elements equal print -1.Example : Input : arr[] = {4, 7, 19, 16}, k = 3 Output : 10 Input : arr[] = {4, 4, 4, 4}, k = 3 Output : 0 Input : arr[] = {4, 2, 6, 8}, k = 3 Output : -1 To solve this question we require to check whether all elements can became equal or not and that too only by incrementing k from elements value. For this we have to check that the difference of any two elements should always be divisible by k. If it is so, then all elements can become equal otherwise they can not became equal in any case by incrementing k from them. Also, the number of operations required can be calculated by finding value of (max – Ai)/k for all elements. where max is maximum element of array.Algorithm : // iterate for all elements for (int i=0; i<n; i++) { // check if element can make equal to max // or not if not then return -1 if ((max - arr[i]) % k != 0 ) return -1; // else update res for required operations else res += (max - arr[i]) / k ; } return res; C++ Java Python3 C# PHP Javascript // Program to make all array equal#include <bits/stdc++.h>using namespace std; // function for calculating min operationsint minOps(int arr[], int n, int k){ // max elements of array int max = *max_element(arr, arr + n); int res = 0; // iterate for all elements for (int i = 0; i < n; i++) { // check if element can make equal to // max or not if not then return -1 if ((max - arr[i]) % k != 0) return -1; // else update res for required operations else res += (max - arr[i]) / k; } // return result return res;} // driver programint main(){ int arr[] = { 21, 33, 9, 45, 63 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 6; cout << minOps(arr, n, k); return 0;} // Program to make all array equalimport java.io.*;import java.util.Arrays; class GFG { // function for calculating min operations static int minOps(int arr[], int n, int k) { // max elements of array Arrays.sort(arr); int max = arr[arr.length - 1]; int res = 0; // iterate for all elements for (int i = 0; i < n; i++) { // check if element can make equal to // max or not if not then return -1 if ((max - arr[i]) % k != 0) return -1; // else update res for required operations else res += (max - arr[i]) / k; } // return result return res; } // Driver program public static void main(String[] args) { int arr[] = { 21, 33, 9, 45, 63 }; int n = arr.length; int k = 6; System.out.println(minOps(arr, n, k)); }} // This code is contributed by vt_m # Python3 Program to make all array equal # function for calculating min operationsdef minOps(arr, n, k): # max elements of array max1 = max(arr) res = 0 # iterate for all elements for i in range(0, n): # check if element can make equal to # max or not if not then return -1 if ((max1 - arr[i]) % k != 0): return -1 # else update res for # required operations else: res += (max1 - arr[i]) / k # return result return int(res) # driver programarr = [21, 33, 9, 45, 63]n = len(arr)k = 6print(minOps(arr, n, k)) # This code is contributed by# Smitha Dinesh Semwal // C# program Minimum increment by// k operations to make all elements equal.using System; class GFG { // function for calculating min operations static int minOps(int[] arr, int n, int k) { // max elements of array Array.Sort(arr); int max = arr[arr.Length - 1]; int res = 0; // iterate for all elements for (int i = 0; i < n; i++) { // check if element can make // equal to max or not if not // then return -1 if ((max - arr[i]) % k != 0) return -1; // else update res for required // operations else res += (max - arr[i]) / k; } // return result return res; } // Driver program public static void Main() { int[] arr = { 21, 33, 9, 45, 63 }; int n = arr.Length; int k = 6; Console.Write(minOps(arr, n, k)); }} // This code is contributed by nitin mittal. <?php// Program to make all array equal // function for calculating// min operationsfunction minOps($arr, $n, $k){ // max elements of array $max = max($arr); $res = 0; // iterate for all elements for ($i = 0; $i < $n; $i++) { // check if element can // make equal to max or // not if not then return -1 if (($max - $arr[$i]) % $k != 0) return -1; // else update res for // required operations else $res += ($max - $arr[$i]) / $k; } // return result return $res;} // Driver Code$arr = array(21, 33, 9, 45, 63);$n = count($arr);$k = 6;print (minOps($arr, $n, $k)); // This code is contributed// by Manish Shaw(manishshaw1)?> <script> // Program to make all array equal // function for calculating min operationsfunction minOps(arr, n, k){ // max elements of array var max = arr[0]; for(var i=0; i<arr.length; i++) { if(arr[i]>max) max = arr[i]; } var res = 0; // iterate for all elements for (var i = 0; i < n; i++) { // check if element can make equal to // max or not if not then return -1 if ((max - arr[i]) % k != 0) return -1; // else update res for required operations else res += (max - arr[i]) / k; } // return result return res;} // driver programvar arr = [ 21, 33, 9, 45, 63 ];var n = arr.length;var k = 6;document.write( minOps(arr, n, k)); // This code is contributed by rutvik_56.</script> Output : 24 Time Complexity: O(n) Auxiliary Space: O(1) nitin mittal manishshaw1 niimisshhh_ rutvik_56 rishavnitro simmytarika5 Arrays Greedy Searching Arrays Searching Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Largest Sum Contiguous Subarray Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Write a program to print all permutations of a given string Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 52, "s": 24, "text": "\n31 May, 2022" }, { "code": null, "e": 302, "s": 52, "text": "You are given an array of n-elements, you have to find the number of operations needed to make all elements of array equal. Where a single operation can increment an element by k. If it is not possible to make all elements equal print -1.Example : " }, { "code": null, "e": 450, "s": 302, "text": "Input : arr[] = {4, 7, 19, 16}, k = 3\nOutput : 10\n\nInput : arr[] = {4, 4, 4, 4}, k = 3\nOutput : 0\n\nInput : arr[] = {4, 2, 6, 8}, k = 3\nOutput : -1" }, { "code": null, "e": 982, "s": 452, "text": "To solve this question we require to check whether all elements can became equal or not and that too only by incrementing k from elements value. For this we have to check that the difference of any two elements should always be divisible by k. If it is so, then all elements can become equal otherwise they can not became equal in any case by incrementing k from them. Also, the number of operations required can be calculated by finding value of (max – Ai)/k for all elements. where max is maximum element of array.Algorithm : " }, { "code": null, "e": 1280, "s": 982, "text": "// iterate for all elements\nfor (int i=0; i<n; i++)\n{\n // check if element can make equal to max\n // or not if not then return -1\n if ((max - arr[i]) % k != 0 )\n return -1;\n\n // else update res for required operations\n else\n res += (max - arr[i]) / k ;\n}\n\nreturn res;" }, { "code": null, "e": 1286, "s": 1282, "text": "C++" }, { "code": null, "e": 1291, "s": 1286, "text": "Java" }, { "code": null, "e": 1299, "s": 1291, "text": "Python3" }, { "code": null, "e": 1302, "s": 1299, "text": "C#" }, { "code": null, "e": 1306, "s": 1302, "text": "PHP" }, { "code": null, "e": 1317, "s": 1306, "text": "Javascript" }, { "code": "// Program to make all array equal#include <bits/stdc++.h>using namespace std; // function for calculating min operationsint minOps(int arr[], int n, int k){ // max elements of array int max = *max_element(arr, arr + n); int res = 0; // iterate for all elements for (int i = 0; i < n; i++) { // check if element can make equal to // max or not if not then return -1 if ((max - arr[i]) % k != 0) return -1; // else update res for required operations else res += (max - arr[i]) / k; } // return result return res;} // driver programint main(){ int arr[] = { 21, 33, 9, 45, 63 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 6; cout << minOps(arr, n, k); return 0;}", "e": 2081, "s": 1317, "text": null }, { "code": "// Program to make all array equalimport java.io.*;import java.util.Arrays; class GFG { // function for calculating min operations static int minOps(int arr[], int n, int k) { // max elements of array Arrays.sort(arr); int max = arr[arr.length - 1]; int res = 0; // iterate for all elements for (int i = 0; i < n; i++) { // check if element can make equal to // max or not if not then return -1 if ((max - arr[i]) % k != 0) return -1; // else update res for required operations else res += (max - arr[i]) / k; } // return result return res; } // Driver program public static void main(String[] args) { int arr[] = { 21, 33, 9, 45, 63 }; int n = arr.length; int k = 6; System.out.println(minOps(arr, n, k)); }} // This code is contributed by vt_m", "e": 3032, "s": 2081, "text": null }, { "code": "# Python3 Program to make all array equal # function for calculating min operationsdef minOps(arr, n, k): # max elements of array max1 = max(arr) res = 0 # iterate for all elements for i in range(0, n): # check if element can make equal to # max or not if not then return -1 if ((max1 - arr[i]) % k != 0): return -1 # else update res for # required operations else: res += (max1 - arr[i]) / k # return result return int(res) # driver programarr = [21, 33, 9, 45, 63]n = len(arr)k = 6print(minOps(arr, n, k)) # This code is contributed by# Smitha Dinesh Semwal", "e": 3686, "s": 3032, "text": null }, { "code": "// C# program Minimum increment by// k operations to make all elements equal.using System; class GFG { // function for calculating min operations static int minOps(int[] arr, int n, int k) { // max elements of array Array.Sort(arr); int max = arr[arr.Length - 1]; int res = 0; // iterate for all elements for (int i = 0; i < n; i++) { // check if element can make // equal to max or not if not // then return -1 if ((max - arr[i]) % k != 0) return -1; // else update res for required // operations else res += (max - arr[i]) / k; } // return result return res; } // Driver program public static void Main() { int[] arr = { 21, 33, 9, 45, 63 }; int n = arr.Length; int k = 6; Console.Write(minOps(arr, n, k)); }} // This code is contributed by nitin mittal.", "e": 4685, "s": 3686, "text": null }, { "code": "<?php// Program to make all array equal // function for calculating// min operationsfunction minOps($arr, $n, $k){ // max elements of array $max = max($arr); $res = 0; // iterate for all elements for ($i = 0; $i < $n; $i++) { // check if element can // make equal to max or // not if not then return -1 if (($max - $arr[$i]) % $k != 0) return -1; // else update res for // required operations else $res += ($max - $arr[$i]) / $k; } // return result return $res;} // Driver Code$arr = array(21, 33, 9, 45, 63);$n = count($arr);$k = 6;print (minOps($arr, $n, $k)); // This code is contributed// by Manish Shaw(manishshaw1)?>", "e": 5434, "s": 4685, "text": null }, { "code": "<script> // Program to make all array equal // function for calculating min operationsfunction minOps(arr, n, k){ // max elements of array var max = arr[0]; for(var i=0; i<arr.length; i++) { if(arr[i]>max) max = arr[i]; } var res = 0; // iterate for all elements for (var i = 0; i < n; i++) { // check if element can make equal to // max or not if not then return -1 if ((max - arr[i]) % k != 0) return -1; // else update res for required operations else res += (max - arr[i]) / k; } // return result return res;} // driver programvar arr = [ 21, 33, 9, 45, 63 ];var n = arr.length;var k = 6;document.write( minOps(arr, n, k)); // This code is contributed by rutvik_56.</script>", "e": 6230, "s": 5434, "text": null }, { "code": null, "e": 6241, "s": 6230, "text": "Output : " }, { "code": null, "e": 6244, "s": 6241, "text": "24" }, { "code": null, "e": 6266, "s": 6244, "text": "Time Complexity: O(n)" }, { "code": null, "e": 6289, "s": 6266, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 6302, "s": 6289, "text": "nitin mittal" }, { "code": null, "e": 6314, "s": 6302, "text": "manishshaw1" }, { "code": null, "e": 6326, "s": 6314, "text": "niimisshhh_" }, { "code": null, "e": 6336, "s": 6326, "text": "rutvik_56" }, { "code": null, "e": 6348, "s": 6336, "text": "rishavnitro" }, { "code": null, "e": 6361, "s": 6348, "text": "simmytarika5" }, { "code": null, "e": 6368, "s": 6361, "text": "Arrays" }, { "code": null, "e": 6375, "s": 6368, "text": "Greedy" }, { "code": null, "e": 6385, "s": 6375, "text": "Searching" }, { "code": null, "e": 6392, "s": 6385, "text": "Arrays" }, { "code": null, "e": 6402, "s": 6392, "text": "Searching" }, { "code": null, "e": 6409, "s": 6402, "text": "Greedy" }, { "code": null, "e": 6507, "s": 6409, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6522, "s": 6507, "text": "Arrays in Java" }, { "code": null, "e": 6568, "s": 6522, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 6636, "s": 6568, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 6680, "s": 6636, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 6712, "s": 6680, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 6763, "s": 6712, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 6814, "s": 6763, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 6874, "s": 6814, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 6932, "s": 6874, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" } ]
Maximum difference between node and its ancestor in Binary Tree
31 Mar, 2022 Given a binary tree, we need to find maximum value we can get by subtracting value of node B from value of node A, where A and B are two nodes of the binary tree and A is an ancestor of B. Expected time complexity is O(n). For example, consider below binary tree We can have various ancestor-node difference, some of which are given below : 8 – 3 = 5 3 – 7 = -4 8 – 1 = 7 10 – 13 = -3 . . . .But among all those differences maximum value is 7 obtained by subtracting 1 from 8, which we need to return as result. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. As we are given a binary tree, there is no relationship between node values so we need to traverse whole binary tree to get max difference and we can obtain the result in one traversal only by following below steps : If we are at leaf node then just return its value because it can’t be ancestor of any node. Then at each internal node we will try to get minimum value from left subtree and right subtree and calculate the difference between node value and this minimum value and according to that we will update the result. As we are calculating minimum value while returning in recurrence we will check all optimal possibilities (checking node value with minimum subtree value only) of differences and hence calculate the result in one traversal only. Below is the implementation of above idea. C++ Java Python3 C# Javascript // C++ program to find maximum difference between node// and its ancestor#include <bits/stdc++.h>using namespace std; /* A binary tree node has key, pointer to left child and a pointer to right child */struct Node{ int key; struct Node* left, *right;}; /* To create a newNode of tree and return pointer */struct Node* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);} /* Recursive function to calculate maximum ancestor-node difference in binary tree. It updates value at 'res' to store the result. The returned value of this function is minimum value in subtree rooted with 't' */int maxDiffUtil(Node* t, int *res){ /* Returning Maximum int value if node is not there (one child case) */ if (t == NULL) return INT_MAX; /* If leaf node then just return node's value */ if (t->left == NULL && t->right == NULL) return t->key; /* Recursively calling left and right subtree for minimum value */ int val = min(maxDiffUtil(t->left, res), maxDiffUtil(t->right, res)); /* Updating res if (node value - minimum value from subtree) is bigger than res */ *res = max(*res, t->key - val); /* Returning minimum value got so far */ return min(val, t->key);} /* This function mainly calls maxDiffUtil() */int maxDiff(Node *root){ // Initialising result with minimum int value int res = INT_MIN; maxDiffUtil(root, &res); return res;} /* Helper function to print inorder traversal of binary tree */void inorder(Node* root){ if (root) { inorder(root->left); printf("%d ", root->key); inorder(root->right); }} // Driver program to test above functionsint main(){ // Making above given diagram's binary tree Node* root; root = newNode(8); root->left = newNode(3); root->left->left = newNode(1); root->left->right = newNode(6); root->left->right->left = newNode(4); root->left->right->right = newNode(7); root->right = newNode(10); root->right->right = newNode(14); root->right->right->left = newNode(13); printf("Maximum difference between a node and" " its ancestor is : %d\n", maxDiff(root));} /* Java program to find maximum difference between node and its ancestor */ // A binary tree node has key, pointer to left// and right childclass Node{ int key; Node left, right; public Node(int key) { this.key = key; left = right = null; }} /* Class Res created to implement pass by reference of 'res' variable */class Res{ int r = Integer.MIN_VALUE;} public class BinaryTree{ Node root; /* Recursive function to calculate maximum ancestor-node difference in binary tree. It updates value at 'res' to store the result. The returned value of this function is minimum value in subtree rooted with 't' */ int maxDiffUtil(Node t, Res res) { /* Returning Maximum int value if node is not there (one child case) */ if (t == null) return Integer.MAX_VALUE; /* If leaf node then just return node's value */ if (t.left == null && t.right == null) return t.key; /* Recursively calling left and right subtree for minimum value */ int val = Math.min(maxDiffUtil(t.left, res), maxDiffUtil(t.right, res)); /* Updating res if (node value - minimum value from subtree) is bigger than res */ res.r = Math.max(res.r, t.key - val); /* Returning minimum value got so far */ return Math.min(val, t.key); } /* This function mainly calls maxDiffUtil() */ int maxDiff(Node root) { // Initialising result with minimum int value Res res = new Res(); maxDiffUtil(root, res); return res.r; } /* Helper function to print inorder traversal of binary tree */ void inorder(Node root) { if (root != null) { inorder(root.left); System.out.print(root.key + ""); inorder(root.right); } } // Driver program to test the above functions public static void main(String[] args) { BinaryTree tree = new BinaryTree(); // Making above given diagram's binary tree tree.root = new Node(8); tree.root.left = new Node(3); tree.root.left.left = new Node(1); tree.root.left.right = new Node(6); tree.root.left.right.left = new Node(4); tree.root.left.right.right = new Node(7); tree.root.right = new Node(10); tree.root.right.right = new Node(14); tree.root.right.right.left = new Node(13); System.out.println("Maximum difference between a node and" + " its ancestor is : " + tree.maxDiff(tree.root)); }} // This code has been contributed by Mayank Jaiswal(mayank_24) # Python3 program to find maximum difference# between node and its ancestor _MIN = -2147483648_MAX = 2147483648 # Helper function that allocates a new# node with the given data and None left# and right pointers. class newNode: # Constructor to create a new node def __init__(self, key): self.key = key self.left = None self.right = None """Recursive function to calculate maximumancestor-node difference in binary tree.It updates value at 'res' to store theresult. The returned value of this functionis minimum value in subtree rooted with 't' """def maxDiffUtil(t, res): """ Returning Maximum value if node is not there (one child case) """ if (t == None): return _MAX, res """ If leaf node then just return node's value """ if (t.left == None and t.right == None): return t.key, res """ Recursively calling left and right subtree for minimum value """ a, res = maxDiffUtil(t.left, res) b, res = maxDiffUtil(t.right, res) val = min(a, b) """ Updating res if (node value - minimum value from subtree) is bigger than res """ res = max(res, t.key - val) """ Returning minimum value got so far """ return min(val, t.key), res """ This function mainly calls maxDiffUtil() """def maxDiff(root): # Initialising result with minimum value res = _MIN x, res = maxDiffUtil(root, res) return res """ Helper function to print inordertraversal of binary tree """def inorder(root): if (root): inorder(root.left) prf("%d ", root.key) inorder(root.right) # Driver Codeif __name__ == '__main__': """ Let us create Binary Tree shown in above example """ root = newNode(8) root.left = newNode(3) root.left.left = newNode(1) root.left.right = newNode(6) root.left.right.left = newNode(4) root.left.right.right = newNode(7) root.right = newNode(10) root.right.right = newNode(14) root.right.right.left = newNode(13) print("Maximum difference between a node and", "its ancestor is :", maxDiff(root)) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) using System; /* C# program to find maximum difference between node and its ancestor */ // A binary tree node has key, pointer to left // and right child public class Node{ public int key; public Node left, right; public Node(int key) { this.key = key; left = right = null; }} /* Class Res created to implement pass by reference of 'res' variable */public class Res{ public int r = int.MinValue;} public class BinaryTree{ public Node root; /* Recursive function to calculate maximum ancestor-node difference in binary tree. It updates value at 'res' to store the result. The returned value of this function is minimum value in subtree rooted with 't' */ public virtual int maxDiffUtil(Node t, Res res) { /* Returning Maximum int value if node is not there (one child case) */ if (t == null) { return int.MaxValue; } /* If leaf node then just return node's value */ if (t.left == null && t.right == null) { return t.key; } /* Recursively calling left and right subtree for minimum value */ int val = Math.Min(maxDiffUtil(t.left, res), maxDiffUtil(t.right, res)); /* Updating res if (node value - minimum value from subtree) is bigger than res */ res.r = Math.Max(res.r, t.key - val); /* Returning minimum value got so far */ return Math.Min(val, t.key); } /* This function mainly calls maxDiffUtil() */ public virtual int maxDiff(Node root) { // Initialising result with minimum int value Res res = new Res(); maxDiffUtil(root, res); return res.r; } /* Helper function to print inorder traversal of binary tree */ public virtual void inorder(Node root) { if (root != null) { inorder(root.left); Console.Write(root.key + ""); inorder(root.right); } } // Driver program to test the above functions public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); // Making above given diagram's binary tree tree.root = new Node(8); tree.root.left = new Node(3); tree.root.left.left = new Node(1); tree.root.left.right = new Node(6); tree.root.left.right.left = new Node(4); tree.root.left.right.right = new Node(7); tree.root.right = new Node(10); tree.root.right.right = new Node(14); tree.root.right.right.left = new Node(13); Console.WriteLine("Maximum difference between a node and" + " its ancestor is : " + tree.maxDiff(tree.root)); }} // This code is contributed by Shrikant13 <script>/* javascript program to find maximum difference between node and its ancestor */ // A binary tree node has key, pointer to left// and right childclass Node { constructor(key) { this.key = key; this.left = this.right = null; }} /* * Class Res created to implement pass by reference of 'res' variable */class Res {constructor(){ this.r = Number.MIN_VALUE; }} var root; /* * Recursive function to calculate maximum ancestor-node difference in binary * tree. It updates value at 'res' to store the result. The returned value of * this function is minimum value in subtree rooted with 't' */ function maxDiffUtil( t, res) { /* * Returning Maximum var value if node is not there (one child case) */ if (t == null) return Number.MAX_VALUE; /* If leaf node then just return node's value */ if (t.left == null && t.right == null) return t.key; /* * Recursively calling left and right subtree for minimum value */ var val = Math.min(maxDiffUtil(t.left, res), maxDiffUtil(t.right, res)); /* * Updating res if (node value - minimum value from subtree) is bigger than res */ res.r = Math.max(res.r, t.key - val); /* Returning minimum value got so far */ return Math.min(val, t.key); } /* This function mainly calls maxDiffUtil() */ function maxDiff( root) { // Initialising result with minimum var value res = new Res(); maxDiffUtil(root, res); return res.r; } /* * Helper function to print inorder traversal of binary tree */ function inorder( root) { if (root !=null) { inorder(root.left); document.write(root.key + ""); inorder(root.right); } } // Driver program to test the above functions // Making above given diagram's binary tree root = new Node(8); root.left = new Node(3); root.left.left = new Node(1); root.left.right = new Node(6); root.left.right.left = new Node(4); root.left.right.right = new Node(7); root.right = new Node(10); root.right.right = new Node(14); root.right.right.left = new Node(13); document.write("Maximum difference between a node and" + " its ancestor is : " + maxDiff(root)); // This code contributed by umadevi9616</script> Output : Maximum difference between a node and its ancestor is : 7 Maximum difference between node and its ancestor in Binary Tree | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersMaximum difference between node and its ancestor in Binary Tree | GeeksforGeeksInfoShoppingTap 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 laterShareCopy linkWatch on0:000:000:00 / 2:59•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=d3ceg_7NcEY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> ?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above shrikanth13 SHUBHAMSINGH10 Akanksha_Rai umadevi9616 simranarora5sos simmytarika5 surinderdawra388 Amazon Tree Amazon Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n31 Mar, 2022" }, { "code": null, "e": 277, "s": 54, "text": "Given a binary tree, we need to find maximum value we can get by subtracting value of node B from value of node A, where A and B are two nodes of the binary tree and A is an ancestor of B. Expected time complexity is O(n)." }, { "code": null, "e": 318, "s": 277, "text": "For example, consider below binary tree " }, { "code": null, "e": 568, "s": 318, "text": "We can have various ancestor-node difference, some of which are given below : 8 – 3 = 5 3 – 7 = -4 8 – 1 = 7 10 – 13 = -3 . . . .But among all those differences maximum value is 7 obtained by subtracting 1 from 8, which we need to return as result. " }, { "code": null, "e": 577, "s": 568, "text": "Chapters" }, { "code": null, "e": 604, "s": 577, "text": "descriptions off, selected" }, { "code": null, "e": 654, "s": 604, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 677, "s": 654, "text": "captions off, selected" }, { "code": null, "e": 685, "s": 677, "text": "English" }, { "code": null, "e": 709, "s": 685, "text": "This is a modal window." }, { "code": null, "e": 778, "s": 709, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 800, "s": 778, "text": "End of dialog window." }, { "code": null, "e": 1326, "s": 800, "text": "As we are given a binary tree, there is no relationship between node values so we need to traverse whole binary tree to get max difference and we can obtain the result in one traversal only by following below steps : If we are at leaf node then just return its value because it can’t be ancestor of any node. Then at each internal node we will try to get minimum value from left subtree and right subtree and calculate the difference between node value and this minimum value and according to that we will update the result. " }, { "code": null, "e": 1555, "s": 1326, "text": "As we are calculating minimum value while returning in recurrence we will check all optimal possibilities (checking node value with minimum subtree value only) of differences and hence calculate the result in one traversal only." }, { "code": null, "e": 1600, "s": 1555, "text": "Below is the implementation of above idea. " }, { "code": null, "e": 1604, "s": 1600, "text": "C++" }, { "code": null, "e": 1609, "s": 1604, "text": "Java" }, { "code": null, "e": 1617, "s": 1609, "text": "Python3" }, { "code": null, "e": 1620, "s": 1617, "text": "C#" }, { "code": null, "e": 1631, "s": 1620, "text": "Javascript" }, { "code": "// C++ program to find maximum difference between node// and its ancestor#include <bits/stdc++.h>using namespace std; /* A binary tree node has key, pointer to left child and a pointer to right child */struct Node{ int key; struct Node* left, *right;}; /* To create a newNode of tree and return pointer */struct Node* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);} /* Recursive function to calculate maximum ancestor-node difference in binary tree. It updates value at 'res' to store the result. The returned value of this function is minimum value in subtree rooted with 't' */int maxDiffUtil(Node* t, int *res){ /* Returning Maximum int value if node is not there (one child case) */ if (t == NULL) return INT_MAX; /* If leaf node then just return node's value */ if (t->left == NULL && t->right == NULL) return t->key; /* Recursively calling left and right subtree for minimum value */ int val = min(maxDiffUtil(t->left, res), maxDiffUtil(t->right, res)); /* Updating res if (node value - minimum value from subtree) is bigger than res */ *res = max(*res, t->key - val); /* Returning minimum value got so far */ return min(val, t->key);} /* This function mainly calls maxDiffUtil() */int maxDiff(Node *root){ // Initialising result with minimum int value int res = INT_MIN; maxDiffUtil(root, &res); return res;} /* Helper function to print inorder traversal of binary tree */void inorder(Node* root){ if (root) { inorder(root->left); printf(\"%d \", root->key); inorder(root->right); }} // Driver program to test above functionsint main(){ // Making above given diagram's binary tree Node* root; root = newNode(8); root->left = newNode(3); root->left->left = newNode(1); root->left->right = newNode(6); root->left->right->left = newNode(4); root->left->right->right = newNode(7); root->right = newNode(10); root->right->right = newNode(14); root->right->right->left = newNode(13); printf(\"Maximum difference between a node and\" \" its ancestor is : %d\\n\", maxDiff(root));}", "e": 3875, "s": 1631, "text": null }, { "code": "/* Java program to find maximum difference between node and its ancestor */ // A binary tree node has key, pointer to left// and right childclass Node{ int key; Node left, right; public Node(int key) { this.key = key; left = right = null; }} /* Class Res created to implement pass by reference of 'res' variable */class Res{ int r = Integer.MIN_VALUE;} public class BinaryTree{ Node root; /* Recursive function to calculate maximum ancestor-node difference in binary tree. It updates value at 'res' to store the result. The returned value of this function is minimum value in subtree rooted with 't' */ int maxDiffUtil(Node t, Res res) { /* Returning Maximum int value if node is not there (one child case) */ if (t == null) return Integer.MAX_VALUE; /* If leaf node then just return node's value */ if (t.left == null && t.right == null) return t.key; /* Recursively calling left and right subtree for minimum value */ int val = Math.min(maxDiffUtil(t.left, res), maxDiffUtil(t.right, res)); /* Updating res if (node value - minimum value from subtree) is bigger than res */ res.r = Math.max(res.r, t.key - val); /* Returning minimum value got so far */ return Math.min(val, t.key); } /* This function mainly calls maxDiffUtil() */ int maxDiff(Node root) { // Initialising result with minimum int value Res res = new Res(); maxDiffUtil(root, res); return res.r; } /* Helper function to print inorder traversal of binary tree */ void inorder(Node root) { if (root != null) { inorder(root.left); System.out.print(root.key + \"\"); inorder(root.right); } } // Driver program to test the above functions public static void main(String[] args) { BinaryTree tree = new BinaryTree(); // Making above given diagram's binary tree tree.root = new Node(8); tree.root.left = new Node(3); tree.root.left.left = new Node(1); tree.root.left.right = new Node(6); tree.root.left.right.left = new Node(4); tree.root.left.right.right = new Node(7); tree.root.right = new Node(10); tree.root.right.right = new Node(14); tree.root.right.right.left = new Node(13); System.out.println(\"Maximum difference between a node and\" + \" its ancestor is : \" + tree.maxDiff(tree.root)); }} // This code has been contributed by Mayank Jaiswal(mayank_24)", "e": 6569, "s": 3875, "text": null }, { "code": "# Python3 program to find maximum difference# between node and its ancestor _MIN = -2147483648_MAX = 2147483648 # Helper function that allocates a new# node with the given data and None left# and right pointers. class newNode: # Constructor to create a new node def __init__(self, key): self.key = key self.left = None self.right = None \"\"\"Recursive function to calculate maximumancestor-node difference in binary tree.It updates value at 'res' to store theresult. The returned value of this functionis minimum value in subtree rooted with 't' \"\"\"def maxDiffUtil(t, res): \"\"\" Returning Maximum value if node is not there (one child case) \"\"\" if (t == None): return _MAX, res \"\"\" If leaf node then just return node's value \"\"\" if (t.left == None and t.right == None): return t.key, res \"\"\" Recursively calling left and right subtree for minimum value \"\"\" a, res = maxDiffUtil(t.left, res) b, res = maxDiffUtil(t.right, res) val = min(a, b) \"\"\" Updating res if (node value - minimum value from subtree) is bigger than res \"\"\" res = max(res, t.key - val) \"\"\" Returning minimum value got so far \"\"\" return min(val, t.key), res \"\"\" This function mainly calls maxDiffUtil() \"\"\"def maxDiff(root): # Initialising result with minimum value res = _MIN x, res = maxDiffUtil(root, res) return res \"\"\" Helper function to print inordertraversal of binary tree \"\"\"def inorder(root): if (root): inorder(root.left) prf(\"%d \", root.key) inorder(root.right) # Driver Codeif __name__ == '__main__': \"\"\" Let us create Binary Tree shown in above example \"\"\" root = newNode(8) root.left = newNode(3) root.left.left = newNode(1) root.left.right = newNode(6) root.left.right.left = newNode(4) root.left.right.right = newNode(7) root.right = newNode(10) root.right.right = newNode(14) root.right.right.left = newNode(13) print(\"Maximum difference between a node and\", \"its ancestor is :\", maxDiff(root)) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)", "e": 8752, "s": 6569, "text": null }, { "code": "using System; /* C# program to find maximum difference between node and its ancestor */ // A binary tree node has key, pointer to left // and right child public class Node{ public int key; public Node left, right; public Node(int key) { this.key = key; left = right = null; }} /* Class Res created to implement pass by reference of 'res' variable */public class Res{ public int r = int.MinValue;} public class BinaryTree{ public Node root; /* Recursive function to calculate maximum ancestor-node difference in binary tree. It updates value at 'res' to store the result. The returned value of this function is minimum value in subtree rooted with 't' */ public virtual int maxDiffUtil(Node t, Res res) { /* Returning Maximum int value if node is not there (one child case) */ if (t == null) { return int.MaxValue; } /* If leaf node then just return node's value */ if (t.left == null && t.right == null) { return t.key; } /* Recursively calling left and right subtree for minimum value */ int val = Math.Min(maxDiffUtil(t.left, res), maxDiffUtil(t.right, res)); /* Updating res if (node value - minimum value from subtree) is bigger than res */ res.r = Math.Max(res.r, t.key - val); /* Returning minimum value got so far */ return Math.Min(val, t.key); } /* This function mainly calls maxDiffUtil() */ public virtual int maxDiff(Node root) { // Initialising result with minimum int value Res res = new Res(); maxDiffUtil(root, res); return res.r; } /* Helper function to print inorder traversal of binary tree */ public virtual void inorder(Node root) { if (root != null) { inorder(root.left); Console.Write(root.key + \"\"); inorder(root.right); } } // Driver program to test the above functions public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); // Making above given diagram's binary tree tree.root = new Node(8); tree.root.left = new Node(3); tree.root.left.left = new Node(1); tree.root.left.right = new Node(6); tree.root.left.right.left = new Node(4); tree.root.left.right.right = new Node(7); tree.root.right = new Node(10); tree.root.right.right = new Node(14); tree.root.right.right.left = new Node(13); Console.WriteLine(\"Maximum difference between a node and\" + \" its ancestor is : \" + tree.maxDiff(tree.root)); }} // This code is contributed by Shrikant13", "e": 11495, "s": 8752, "text": null }, { "code": "<script>/* javascript program to find maximum difference between node and its ancestor */ // A binary tree node has key, pointer to left// and right childclass Node { constructor(key) { this.key = key; this.left = this.right = null; }} /* * Class Res created to implement pass by reference of 'res' variable */class Res {constructor(){ this.r = Number.MIN_VALUE; }} var root; /* * Recursive function to calculate maximum ancestor-node difference in binary * tree. It updates value at 'res' to store the result. The returned value of * this function is minimum value in subtree rooted with 't' */ function maxDiffUtil( t, res) { /* * Returning Maximum var value if node is not there (one child case) */ if (t == null) return Number.MAX_VALUE; /* If leaf node then just return node's value */ if (t.left == null && t.right == null) return t.key; /* * Recursively calling left and right subtree for minimum value */ var val = Math.min(maxDiffUtil(t.left, res), maxDiffUtil(t.right, res)); /* * Updating res if (node value - minimum value from subtree) is bigger than res */ res.r = Math.max(res.r, t.key - val); /* Returning minimum value got so far */ return Math.min(val, t.key); } /* This function mainly calls maxDiffUtil() */ function maxDiff( root) { // Initialising result with minimum var value res = new Res(); maxDiffUtil(root, res); return res.r; } /* * Helper function to print inorder traversal of binary tree */ function inorder( root) { if (root !=null) { inorder(root.left); document.write(root.key + \"\"); inorder(root.right); } } // Driver program to test the above functions // Making above given diagram's binary tree root = new Node(8); root.left = new Node(3); root.left.left = new Node(1); root.left.right = new Node(6); root.left.right.left = new Node(4); root.left.right.right = new Node(7); root.right = new Node(10); root.right.right = new Node(14); root.right.right.left = new Node(13); document.write(\"Maximum difference between a node and\" + \" its ancestor is : \" + maxDiff(root)); // This code contributed by umadevi9616</script>", "e": 13953, "s": 11495, "text": null }, { "code": null, "e": 13963, "s": 13953, "text": "Output : " }, { "code": null, "e": 14024, "s": 13963, "text": "Maximum difference between a node and its ancestor is : 7 \n " }, { "code": null, "e": 14968, "s": 14024, "text": "Maximum difference between node and its ancestor in Binary Tree | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersMaximum difference between node and its ancestor in Binary Tree | GeeksforGeeksInfoShoppingTap 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 laterShareCopy linkWatch on0:000:000:00 / 2:59•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=d3ceg_7NcEY\" 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": 15182, "s": 14968, "text": "?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 15194, "s": 15182, "text": "shrikanth13" }, { "code": null, "e": 15209, "s": 15194, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 15222, "s": 15209, "text": "Akanksha_Rai" }, { "code": null, "e": 15234, "s": 15222, "text": "umadevi9616" }, { "code": null, "e": 15250, "s": 15234, "text": "simranarora5sos" }, { "code": null, "e": 15263, "s": 15250, "text": "simmytarika5" }, { "code": null, "e": 15280, "s": 15263, "text": "surinderdawra388" }, { "code": null, "e": 15287, "s": 15280, "text": "Amazon" }, { "code": null, "e": 15292, "s": 15287, "text": "Tree" }, { "code": null, "e": 15299, "s": 15292, "text": "Amazon" }, { "code": null, "e": 15304, "s": 15299, "text": "Tree" } ]
Python – Moving an object in PyGame
06 Mar, 2020 Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit. In this tutorial, we are going to learn how to move an object such that it moves horizontally when pressing the right arrow key or left arrow key on the keyboard and it moves vertically when pressing up arrow key or down arrow key. The main concept of doing this is by changing the co-ordinates of the object and refreshing the screen. When the screen refreshes every time window color gets filled with original color and the new rectangle is formed, so when arrow keys get pressed co-ordinates changes and it appears that the object is moving. Change in Co-ordinates for respective keys pressed : Left arrow key: Decrement in x co-ordinate Right arrow key: Increment in x co-ordinate Up arrow key: Decrement in y co-ordinate Down arrow key: Increment in y co-ordinate Below is the implementation. # import pygame module in this program import pygame # activate the pygame library . # initiate pygame and give permission # to use pygame's functionality. pygame.init() # create the display surface object # of specific dimension..e(500, 500). win = pygame.display.set_mode((500, 500)) # set the pygame window name pygame.display.set_caption("Moving rectangle") # object current co-ordinates x = 200y = 200 # dimensions of the object width = 20height = 20 # velocity / speed of movementvel = 10 # Indicates pygame is runningrun = True # infinite loop while run: # creates time delay of 10ms pygame.time.delay(10) # iterate over the list of Event objects # that was returned by pygame.event.get() method. for event in pygame.event.get(): # if event object type is QUIT # then quitting the pygame # and program both. if event.type == pygame.QUIT: # it will make exit the while loop run = False # stores keys pressed keys = pygame.key.get_pressed() # if left arrow key is pressed if keys[pygame.K_LEFT] and x>0: # decrement in x co-ordinate x -= vel # if left arrow key is pressed if keys[pygame.K_RIGHT] and x<500-width: # increment in x co-ordinate x += vel # if left arrow key is pressed if keys[pygame.K_UP] and y>0: # decrement in y co-ordinate y -= vel # if left arrow key is pressed if keys[pygame.K_DOWN] and y<500-height: # increment in y co-ordinate y += vel # completely fill the surface object # with black colour win.fill((0, 0, 0)) # drawing object on screen which is rectangle here pygame.draw.rect(win, (255, 0, 0), (x, y, width, height)) # it refreshes the window pygame.display.update() # closes the pygame window pygame.quit() Python-PyGame Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Mar, 2020" }, { "code": null, "e": 364, "s": 52, "text": "Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit." }, { "code": null, "e": 596, "s": 364, "text": "In this tutorial, we are going to learn how to move an object such that it moves horizontally when pressing the right arrow key or left arrow key on the keyboard and it moves vertically when pressing up arrow key or down arrow key." }, { "code": null, "e": 909, "s": 596, "text": "The main concept of doing this is by changing the co-ordinates of the object and refreshing the screen. When the screen refreshes every time window color gets filled with original color and the new rectangle is formed, so when arrow keys get pressed co-ordinates changes and it appears that the object is moving." }, { "code": null, "e": 1135, "s": 909, "text": "Change in Co-ordinates for respective keys pressed :\n\nLeft arrow key: Decrement in x co-ordinate\nRight arrow key: Increment in x co-ordinate\nUp arrow key: Decrement in y co-ordinate\nDown arrow key: Increment in y co-ordinate\n" }, { "code": null, "e": 1164, "s": 1135, "text": "Below is the implementation." }, { "code": "# import pygame module in this program import pygame # activate the pygame library . # initiate pygame and give permission # to use pygame's functionality. pygame.init() # create the display surface object # of specific dimension..e(500, 500). win = pygame.display.set_mode((500, 500)) # set the pygame window name pygame.display.set_caption(\"Moving rectangle\") # object current co-ordinates x = 200y = 200 # dimensions of the object width = 20height = 20 # velocity / speed of movementvel = 10 # Indicates pygame is runningrun = True # infinite loop while run: # creates time delay of 10ms pygame.time.delay(10) # iterate over the list of Event objects # that was returned by pygame.event.get() method. for event in pygame.event.get(): # if event object type is QUIT # then quitting the pygame # and program both. if event.type == pygame.QUIT: # it will make exit the while loop run = False # stores keys pressed keys = pygame.key.get_pressed() # if left arrow key is pressed if keys[pygame.K_LEFT] and x>0: # decrement in x co-ordinate x -= vel # if left arrow key is pressed if keys[pygame.K_RIGHT] and x<500-width: # increment in x co-ordinate x += vel # if left arrow key is pressed if keys[pygame.K_UP] and y>0: # decrement in y co-ordinate y -= vel # if left arrow key is pressed if keys[pygame.K_DOWN] and y<500-height: # increment in y co-ordinate y += vel # completely fill the surface object # with black colour win.fill((0, 0, 0)) # drawing object on screen which is rectangle here pygame.draw.rect(win, (255, 0, 0), (x, y, width, height)) # it refreshes the window pygame.display.update() # closes the pygame window pygame.quit()", "e": 3148, "s": 1164, "text": null }, { "code": null, "e": 3162, "s": 3148, "text": "Python-PyGame" }, { "code": null, "e": 3169, "s": 3162, "text": "Python" } ]
std::reverse() in C++
17 Feb, 2021 reverse() is a predefined function in header file algorithm. It is defined as a template in the above mentioned header file. It reverses the order of the elements in the range [first, last) of any container. The time complexity is O(n). Note: 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.Syntax: void reverse(BidirectionalIterator first, BidirectionalIterator last) BidirectionalIterator is an iterator that can be used to access any elements of a container in both forward and backward direction. Examples: Input : 10 11 12 13 14 15 16 17 Output :10 11 12 13 14 17 16 15 Explanation: reverse(v.begin() + 5, v.begin() + 8); In the above function, input we have applied reverse() on the vector from index 5 to index 7. Therefore when we display the vector we get reverse order from index 5 to index 7. CPP // CPP program to illustrate// std::reverse() function of STL#include <algorithm>#include <iostream>#include <vector>using namespace std; int main(){ vector<int> vec1; vector<int>::iterator p; // Inserting elements in vector for (int i = 0; i < 8; i++) { vec1.push_back(i + 10); } // Displaying elements of vector cout<<"Initial Vector:"<<endl; for(p = vec1.begin(); p < vec1.end(); p++) { cout << *p << " "; } cout << endl; cout << "Reverse only from index 5 to 7 in vector:\n"; // Reversing elements from index 5 to index 7 reverse(vec1.begin() + 5, vec1.begin() + 8); // Displaying elements of vector after Reversing for (p = vec1.begin(); p < vec1.end(); p++) { cout << *p << " "; } cout << endl <<endl; vector<int> vec2{ 4, 5, 6, 7 }; cout<<"Initial Vector:"<<endl; for (p = vec2.begin(); p < vec2.end(); p++) { cout << *p << " "; } cout << endl; cout << "Reverse full Vector:"<<endl; // Reversing directly from beginning to end reverse(vec2.begin(), vec2.end()); // Displaying elements of vector after Reversing for (p = vec2.begin(); p < vec2.end(); p++) { cout << *p << " "; } cout << endl; return 0;} Output: Initial Vector: 10 11 12 13 14 15 16 17 Reverse only from index 5 to 7 in vector: 10 11 12 13 14 17 16 15 Initial Vector: 4 5 6 7 Reverse full Vector: 7 6 5 4 Time complexity: O(n)Reverse in STL | Sample Video for C++ Productivity Hacks | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersReverse in STL | Sample Video for C++ Productivity Hacks | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:32•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=-NK9CQTdceg" 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 Hardik Gaur. 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. shobitham1 sunnychaudharyvlsi cpp-algorithm-library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Set in C++ Standard Template Library (STL) Inheritance in C++ unordered_map in C++ STL vector erase() and clear() in C++ C++ Classes and Objects Substring in C++ Object Oriented Programming in C++ Priority Queue in C++ Standard Template Library (STL) Sorting a vector in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Feb, 2021" }, { "code": null, "e": 468, "s": 52, "text": "reverse() is a predefined function in header file algorithm. It is defined as a template in the above mentioned header file. It reverses the order of the elements in the range [first, last) of any container. The time complexity is O(n). Note: 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.Syntax: " }, { "code": null, "e": 670, "s": 468, "text": "void reverse(BidirectionalIterator first, BidirectionalIterator last)\nBidirectionalIterator is an iterator that can be used to access any\nelements of a container in both forward and backward direction." }, { "code": null, "e": 681, "s": 670, "text": "Examples: " }, { "code": null, "e": 974, "s": 681, "text": "Input : 10 11 12 13 14 15 16 17\nOutput :10 11 12 13 14 17 16 15\nExplanation:\nreverse(v.begin() + 5, v.begin() + 8);\nIn the above function, input we have applied reverse() on the vector\nfrom index 5 to index 7.\nTherefore when we display the vector we get reverse order\nfrom index 5 to index 7." }, { "code": null, "e": 978, "s": 974, "text": "CPP" }, { "code": "// CPP program to illustrate// std::reverse() function of STL#include <algorithm>#include <iostream>#include <vector>using namespace std; int main(){ vector<int> vec1; vector<int>::iterator p; // Inserting elements in vector for (int i = 0; i < 8; i++) { vec1.push_back(i + 10); } // Displaying elements of vector cout<<\"Initial Vector:\"<<endl; for(p = vec1.begin(); p < vec1.end(); p++) { cout << *p << \" \"; } cout << endl; cout << \"Reverse only from index 5 to 7 in vector:\\n\"; // Reversing elements from index 5 to index 7 reverse(vec1.begin() + 5, vec1.begin() + 8); // Displaying elements of vector after Reversing for (p = vec1.begin(); p < vec1.end(); p++) { cout << *p << \" \"; } cout << endl <<endl; vector<int> vec2{ 4, 5, 6, 7 }; cout<<\"Initial Vector:\"<<endl; for (p = vec2.begin(); p < vec2.end(); p++) { cout << *p << \" \"; } cout << endl; cout << \"Reverse full Vector:\"<<endl; // Reversing directly from beginning to end reverse(vec2.begin(), vec2.end()); // Displaying elements of vector after Reversing for (p = vec2.begin(); p < vec2.end(); p++) { cout << *p << \" \"; } cout << endl; return 0;}", "e": 2234, "s": 978, "text": null }, { "code": null, "e": 2243, "s": 2234, "text": "Output: " }, { "code": null, "e": 2407, "s": 2243, "text": "Initial Vector:\n10 11 12 13 14 15 16 17 \nReverse only from index 5 to 7 in vector:\n10 11 12 13 14 17 16 15 \n\nInitial Vector:\n4 5 6 7 \nReverse full Vector:\n7 6 5 4 " }, { "code": null, "e": 3358, "s": 2407, "text": "Time complexity: O(n)Reverse in STL | Sample Video for C++ Productivity Hacks | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersReverse in STL | Sample Video for C++ Productivity Hacks | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:32•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=-NK9CQTdceg\" 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": 3782, "s": 3358, "text": "This article is contributed by Hardik Gaur. 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": 3793, "s": 3782, "text": "shobitham1" }, { "code": null, "e": 3812, "s": 3793, "text": "sunnychaudharyvlsi" }, { "code": null, "e": 3834, "s": 3812, "text": "cpp-algorithm-library" }, { "code": null, "e": 3838, "s": 3834, "text": "STL" }, { "code": null, "e": 3842, "s": 3838, "text": "C++" }, { "code": null, "e": 3846, "s": 3842, "text": "STL" }, { "code": null, "e": 3850, "s": 3846, "text": "CPP" }, { "code": null, "e": 3948, "s": 3850, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3975, "s": 3948, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 4018, "s": 3975, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 4037, "s": 4018, "text": "Inheritance in C++" }, { "code": null, "e": 4062, "s": 4037, "text": "unordered_map in C++ STL" }, { "code": null, "e": 4096, "s": 4062, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 4120, "s": 4096, "text": "C++ Classes and Objects" }, { "code": null, "e": 4137, "s": 4120, "text": "Substring in C++" }, { "code": null, "e": 4172, "s": 4137, "text": "Object Oriented Programming in C++" }, { "code": null, "e": 4226, "s": 4172, "text": "Priority Queue in C++ Standard Template Library (STL)" } ]
Getting Started With Testing in Python
11 Aug, 2021 Here we’ll learn how to create a basic test, execute it, and find the bugs before your users do! You’ll learn about the tools available to write and execute tests and also see testing terms like automated, manual, unit and integration tests as well. Example for Unit testing: Python3 # define a functiondef test_sum_numbers(): assert sum([100, 200, 300,400]) == 1000, "Result should be 1000" # define a functiondef test_sum_tuple_values(): assert sum((100, 200, 200,400)) == 1000, "Result should be 1000" # Driver codeif __name__ == "__main__": test_sum_numbers() test_sum_tuple_values() print("Checking whether all tests are passed or not") Output: Traceback (most recent call last): File "....../test_example.py", line 9, in <module> test_sum_tuple_values() File "...../test_example.py", line 5, in test_sum_tuple_values assert sum((100, 200, 200,400)) == 1000, "Result should be 1000" AssertionError: Result should be 1000 In the above example, We have two methods here and when code is executed, second method throws error as the given values do not produce 1000. Test Runner is a library or a testing tool which reads the source code that contains unit tests and a bunch of settings which can be executed and produces its output to the console or log files. There are different Test Runners available in Python. Popular one are unittest nose or nose2 pytest unittest : It is built into the standard python library. import unittest should be the starting line of code for using it. Depends upon the python version, it should differ as later versions of Python supports unittest and earlier versions supported unittest2. Sample snippet of python code using unittest is given below: Python3 # import libraryimport unittest # create a classclass TestXXXXX(unittest.TestCase): # define a function def test_xxxxxxx(self): data = [100, 200, 300] result = sum(data) self.assertEqual(result, 6000) # driver codeif __name__ == '__main__': unittest.main() Output: ====================================================================== .F FAIL: test_xxxxxxx (__main__.TestXXXXX) ---------------------------------------------------------------------- Traceback (most recent call last): File "......py", line 8, in test_xxxxxxx self.assertEqual(result, 6000) AssertionError: 600 != 6000 ---------------------------------------------------------------------- Ran 1 test in 0.001s FAILED (failures=1) nose or nose2: This is an open source application and similar to unittest only.It is compatible with numerous kinds of tests that are written using unittest framework. nose2 is the recent version one, and they are installed by using. pip install nose2 pytest: It supports unittest test cases execution. It has benefits like supporting built in assert statement, filtering of test cases, returning from last failing test etc Python3 def test_sum_numbers_using_pytest(): assert sum([700, 900]) == 1600, "Resultant should be 1600" def test_sum_tuple_using_pytest(): assert sum((700,1900)) == 1600, "Resultant should be 1600" No need to write the class, command line entry point etc., For writing a test, need to know what is going to get tested.Does it cover unit testing and/or integration testing?All kind of necessary inputs (it can range between integer, float, type data types etc., ) and the code for their execution and get the output and compare the output with expected result. For writing a test, need to know what is going to get tested. Does it cover unit testing and/or integration testing? All kind of necessary inputs (it can range between integer, float, type data types etc., ) and the code for their execution and get the output and compare the output with expected result. Assertion is nothing but validating the output against a known response. i.e. in above code, we have passed the list containing 3 values namely 10, 20 and 30, and we know that its multiplication result is 6000. So as a last step in code, we will be writing assertion code and above code comes up with assertEqual and surely it will give the output as 6000 and hence the testcase passes. unittest has lots of methods to assert on the values, types, and existence of variables. Let us see few : .assertEqual(one,two) means one == two (Our above example) .assertTrue(expr) means boolean(expr) is True .assertFalse(expr) means boolean(expr) is False .assertIs(one,two) means one is two We have opposite methods too like: .assertIsNot(one,two) means one is not two. .assertIsNone(x) vs .assertIsNone(x) .assertIn(x, y) vs .assertNotIn(x, y) .assertIsInstance(m, n) vs .assertNotIsInstance(m,n) Continuous execution of piece of code has the possibility to alter other things to change like attribute of a class or even a value in the database. So these are need to be decided before doing testing. Refactoring of code needs to be considered to break the side effects and write repeatable and simple unit tests. We can run unittest or pytest by following the steps and this is applicable for running all tests in a directory: First from project tool window, select the tests directoryThen, on the context menu, choose “UnitTests in” or “PyTests in “ For individual test,Via main toolbar by using Run or Debug commandVia context menu by using Run or Debug by clicking the specific file First from project tool window, select the tests directory Then, on the context menu, choose “UnitTests in” or “PyTests in “ For individual test,Via main toolbar by using Run or Debug commandVia context menu by using Run or Debug by clicking the specific file Via main toolbar by using Run or Debug command Via context menu by using Run or Debug by clicking the specific file Based on unittest, Django and Flask makes things easier, and they have their testing framework: Django Test Runner: The Django startapp template will have created a tests.py file inside your application directory. If you don’t have that already, you can create it with the following contents: Python3 from django.test import TestCase class RequiredTestCases(TestCase): # Write all Test methods For executing the test suit, we need to give as: python manage.py test Use unittest and Flask : Flask requires that the app be imported in file and then set in test mode. You can instantiate a test client and use the test client to make requests to any routes in your application. All the test client instantiation is done in the setUp() method of your test case. Python3 # import our application fileimport my_app # import libraryimport unittest class FlaskTestCase(unittest.TestCase): def setUp(self): my_app.app.testing = True self.app = my_app.app.test_client() def test_home(self): result = self.app.get('/') Test cases can be executed by using below command (via command line) : python -m unittest discover Fixture is used which is nothing but the data that is created as an input and reusing them. Parameterization can be followed which is nothing but running the same test several times by passing different values and expecting the same result. Need to cover different scenarios like handling expected failures, writing integration tests, testing in multiple environments etc. Below example shows how to write test for bad data type: Python3 import unittest class TestSumDifferentPatterns(unittest.TestCase): def test_list_tuple_values(self): # Summation of numbers present # in a tuple value data = (10*2, 200*2) result = sum(data) self.assertEqual(result, 600) def test_bad_data_type(self): data = "alpha value passed instead of numeric" # Because of the below condition, TypeError # occurs and hence it will not proceed # to next step with self.assertRaises(TypeError): result = sum(data) if __name__ == '__main__': unittest.main() Output .F ====================================================================== FAIL: test_list_tuple_values (__main__.TestSumDifferentPatterns) ---------------------------------------------------------------------- Traceback (most recent call last): File "......py", line 10, in test_list_tuple_values self.assertEqual(result, 600) AssertionError: 420 != 600 ---------------------------------------------------------------------- Ran 2 tests in 0.001s FAILED (failures=1) Continuous Integration/Continuous Deployment tools are available. They help to run tests, compile, publish and also deploy into production.https://travis-ci.com/ is one among them which works well with Python and it is an open source project. Login into the site and create.travis.yml with the below contents: language: python python:<Include the versions as 2.7 or 3.7 whichever required> install:– pip install -r <your requirements file> script: – python -m unittest discover Above file instructs “Travis CI” to look into this file and for given Python versions, the test cases are getting tested by installing the necessary packages as given in the requirements file and finally run below command to run the test. python -m unittest discover Results are on the website against your credential anikaseth98 kapoorsagar226 python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Aug, 2021" }, { "code": null, "e": 302, "s": 52, "text": "Here we’ll learn how to create a basic test, execute it, and find the bugs before your users do! You’ll learn about the tools available to write and execute tests and also see testing terms like automated, manual, unit and integration tests as well." }, { "code": null, "e": 328, "s": 302, "text": "Example for Unit testing:" }, { "code": null, "e": 336, "s": 328, "text": "Python3" }, { "code": "# define a functiondef test_sum_numbers(): assert sum([100, 200, 300,400]) == 1000, \"Result should be 1000\" # define a functiondef test_sum_tuple_values(): assert sum((100, 200, 200,400)) == 1000, \"Result should be 1000\" # Driver codeif __name__ == \"__main__\": test_sum_numbers() test_sum_tuple_values() print(\"Checking whether all tests are passed or not\")", "e": 717, "s": 336, "text": null }, { "code": null, "e": 725, "s": 717, "text": "Output:" }, { "code": null, "e": 1009, "s": 725, "text": "Traceback (most recent call last):\n File \"....../test_example.py\", line 9, in <module>\n test_sum_tuple_values()\n File \"...../test_example.py\", line 5, in test_sum_tuple_values\n assert sum((100, 200, 200,400)) == 1000, \"Result should be 1000\"\nAssertionError: Result should be 1000" }, { "code": null, "e": 1152, "s": 1009, "text": "In the above example, We have two methods here and when code is executed, second method throws error as the given values do not produce 1000. " }, { "code": null, "e": 1418, "s": 1152, "text": "Test Runner is a library or a testing tool which reads the source code that contains unit tests and a bunch of settings which can be executed and produces its output to the console or log files. There are different Test Runners available in Python. Popular one are " }, { "code": null, "e": 1427, "s": 1418, "text": "unittest" }, { "code": null, "e": 1441, "s": 1427, "text": "nose or nose2" }, { "code": null, "e": 1448, "s": 1441, "text": "pytest" }, { "code": null, "e": 1771, "s": 1448, "text": "unittest : It is built into the standard python library. import unittest should be the starting line of code for using it. Depends upon the python version, it should differ as later versions of Python supports unittest and earlier versions supported unittest2. Sample snippet of python code using unittest is given below:" }, { "code": null, "e": 1779, "s": 1771, "text": "Python3" }, { "code": "# import libraryimport unittest # create a classclass TestXXXXX(unittest.TestCase): # define a function def test_xxxxxxx(self): data = [100, 200, 300] result = sum(data) self.assertEqual(result, 6000) # driver codeif __name__ == '__main__': unittest.main()", "e": 2081, "s": 1779, "text": null }, { "code": null, "e": 2089, "s": 2081, "text": "Output:" }, { "code": null, "e": 2525, "s": 2089, "text": "======================================================================\n.F\nFAIL: test_xxxxxxx (__main__.TestXXXXX)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"......py\", line 8, in test_xxxxxxx\n self.assertEqual(result, 6000)\nAssertionError: 600 != 6000\n----------------------------------------------------------------------\nRan 1 test in 0.001s\nFAILED (failures=1)" }, { "code": null, "e": 2760, "s": 2525, "text": "nose or nose2: This is an open source application and similar to unittest only.It is compatible with numerous kinds of tests that are written using unittest framework. nose2 is the recent version one, and they are installed by using. " }, { "code": null, "e": 2779, "s": 2760, "text": "pip install nose2 " }, { "code": null, "e": 2951, "s": 2779, "text": "pytest: It supports unittest test cases execution. It has benefits like supporting built in assert statement, filtering of test cases, returning from last failing test etc" }, { "code": null, "e": 2959, "s": 2951, "text": "Python3" }, { "code": "def test_sum_numbers_using_pytest(): assert sum([700, 900]) == 1600, \"Resultant should be 1600\" def test_sum_tuple_using_pytest(): assert sum((700,1900)) == 1600, \"Resultant should be 1600\"", "e": 3155, "s": 2959, "text": null }, { "code": null, "e": 3217, "s": 3158, "text": "No need to write the class, command line entry point etc.," }, { "code": null, "e": 3522, "s": 3219, "text": "For writing a test, need to know what is going to get tested.Does it cover unit testing and/or integration testing?All kind of necessary inputs (it can range between integer, float, type data types etc., ) and the code for their execution and get the output and compare the output with expected result." }, { "code": null, "e": 3584, "s": 3522, "text": "For writing a test, need to know what is going to get tested." }, { "code": null, "e": 3639, "s": 3584, "text": "Does it cover unit testing and/or integration testing?" }, { "code": null, "e": 3827, "s": 3639, "text": "All kind of necessary inputs (it can range between integer, float, type data types etc., ) and the code for their execution and get the output and compare the output with expected result." }, { "code": null, "e": 4217, "s": 3829, "text": "Assertion is nothing but validating the output against a known response. i.e. in above code, we have passed the list containing 3 values namely 10, 20 and 30, and we know that its multiplication result is 6000. So as a last step in code, we will be writing assertion code and above code comes up with assertEqual and surely it will give the output as 6000 and hence the testcase passes. " }, { "code": null, "e": 4326, "s": 4219, "text": "unittest has lots of methods to assert on the values, types, and existence of variables. Let us see few : " }, { "code": null, "e": 4521, "s": 4328, "text": ".assertEqual(one,two) means one == two (Our above example) \n.assertTrue(expr) means boolean(expr) is True \n.assertFalse(expr) means boolean(expr) is False \n.assertIs(one,two) means one is two " }, { "code": null, "e": 4558, "s": 4523, "text": "We have opposite methods too like:" }, { "code": null, "e": 4737, "s": 4560, "text": " .assertIsNot(one,two) means one is not two. \n.assertIsNone(x) vs .assertIsNone(x) \n.assertIn(x, y) vs .assertNotIn(x, y) \n.assertIsInstance(m, n) vs .assertNotIsInstance(m,n) " }, { "code": null, "e": 5056, "s": 4739, "text": "Continuous execution of piece of code has the possibility to alter other things to change like attribute of a class or even a value in the database. So these are need to be decided before doing testing. Refactoring of code needs to be considered to break the side effects and write repeatable and simple unit tests. " }, { "code": null, "e": 5174, "s": 5060, "text": "We can run unittest or pytest by following the steps and this is applicable for running all tests in a directory:" }, { "code": null, "e": 5435, "s": 5176, "text": "First from project tool window, select the tests directoryThen, on the context menu, choose “UnitTests in” or “PyTests in “ For individual test,Via main toolbar by using Run or Debug commandVia context menu by using Run or Debug by clicking the specific file" }, { "code": null, "e": 5494, "s": 5435, "text": "First from project tool window, select the tests directory" }, { "code": null, "e": 5695, "s": 5494, "text": "Then, on the context menu, choose “UnitTests in” or “PyTests in “ For individual test,Via main toolbar by using Run or Debug commandVia context menu by using Run or Debug by clicking the specific file" }, { "code": null, "e": 5742, "s": 5695, "text": "Via main toolbar by using Run or Debug command" }, { "code": null, "e": 5811, "s": 5742, "text": "Via context menu by using Run or Debug by clicking the specific file" }, { "code": null, "e": 5909, "s": 5813, "text": "Based on unittest, Django and Flask makes things easier, and they have their testing framework:" }, { "code": null, "e": 6109, "s": 5911, "text": " Django Test Runner: The Django startapp template will have created a tests.py file inside your application directory. If you don’t have that already, you can create it with the following contents:" }, { "code": null, "e": 6119, "s": 6111, "text": "Python3" }, { "code": "from django.test import TestCase class RequiredTestCases(TestCase): # Write all Test methods", "e": 6215, "s": 6119, "text": null }, { "code": null, "e": 6267, "s": 6218, "text": "For executing the test suit, we need to give as:" }, { "code": null, "e": 6291, "s": 6269, "text": "python manage.py test" }, { "code": null, "e": 6503, "s": 6293, "text": "Use unittest and Flask : Flask requires that the app be imported in file and then set in test mode. You can instantiate a test client and use the test client to make requests to any routes in your application." }, { "code": null, "e": 6589, "s": 6505, "text": "All the test client instantiation is done in the setUp() method of your test case. " }, { "code": null, "e": 6599, "s": 6591, "text": "Python3" }, { "code": "# import our application fileimport my_app # import libraryimport unittest class FlaskTestCase(unittest.TestCase): def setUp(self): my_app.app.testing = True self.app = my_app.app.test_client() def test_home(self): result = self.app.get('/')", "e": 6870, "s": 6599, "text": null }, { "code": null, "e": 6941, "s": 6870, "text": "Test cases can be executed by using below command (via command line) :" }, { "code": null, "e": 6970, "s": 6941, "text": " python -m unittest discover" }, { "code": null, "e": 7062, "s": 6970, "text": "Fixture is used which is nothing but the data that is created as an input and reusing them." }, { "code": null, "e": 7211, "s": 7062, "text": "Parameterization can be followed which is nothing but running the same test several times by passing different values and expecting the same result." }, { "code": null, "e": 7343, "s": 7211, "text": "Need to cover different scenarios like handling expected failures, writing integration tests, testing in multiple environments etc." }, { "code": null, "e": 7400, "s": 7343, "text": "Below example shows how to write test for bad data type:" }, { "code": null, "e": 7408, "s": 7400, "text": "Python3" }, { "code": "import unittest class TestSumDifferentPatterns(unittest.TestCase): def test_list_tuple_values(self): # Summation of numbers present # in a tuple value data = (10*2, 200*2) result = sum(data) self.assertEqual(result, 600) def test_bad_data_type(self): data = \"alpha value passed instead of numeric\" # Because of the below condition, TypeError # occurs and hence it will not proceed # to next step with self.assertRaises(TypeError): result = sum(data) if __name__ == '__main__': unittest.main()", "e": 7999, "s": 7408, "text": null }, { "code": null, "e": 8006, "s": 7999, "text": "Output" }, { "code": null, "e": 8477, "s": 8006, "text": ".F\n======================================================================\nFAIL: test_list_tuple_values (__main__.TestSumDifferentPatterns)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"......py\", line 10, in test_list_tuple_values\n self.assertEqual(result, 600)\nAssertionError: 420 != 600\n----------------------------------------------------------------------\nRan 2 tests in 0.001s\nFAILED (failures=1)" }, { "code": null, "e": 8787, "s": 8477, "text": "Continuous Integration/Continuous Deployment tools are available. They help to run tests, compile, publish and also deploy into production.https://travis-ci.com/ is one among them which works well with Python and it is an open source project. Login into the site and create.travis.yml with the below contents:" }, { "code": null, "e": 8867, "s": 8787, "text": "language: python python:<Include the versions as 2.7 or 3.7 whichever required>" }, { "code": null, "e": 8917, "s": 8867, "text": "install:– pip install -r <your requirements file>" }, { "code": null, "e": 8955, "s": 8917, "text": "script: – python -m unittest discover" }, { "code": null, "e": 9194, "s": 8955, "text": "Above file instructs “Travis CI” to look into this file and for given Python versions, the test cases are getting tested by installing the necessary packages as given in the requirements file and finally run below command to run the test." }, { "code": null, "e": 9224, "s": 9194, "text": " python -m unittest discover " }, { "code": null, "e": 9276, "s": 9224, "text": " Results are on the website against your credential" }, { "code": null, "e": 9288, "s": 9276, "text": "anikaseth98" }, { "code": null, "e": 9303, "s": 9288, "text": "kapoorsagar226" }, { "code": null, "e": 9318, "s": 9303, "text": "python-utility" }, { "code": null, "e": 9325, "s": 9318, "text": "Python" } ]
How to Publish Python package at PyPi using Twine module?
19 Oct, 2021 Python is so flexible and easy to use because of its available packages that are hosted on pypi.org, Let’s see how to publish your own package on PyPi using Twine module. You must have account of pypi.org, if don’t create an account The twine library is created to simplify uploading packages in pypi. To install twine library. pip install twine Get your package ready. Step 1: Prepare and organize the package Create a folder name must be same as package name. (Ensure that the name of your package does not pre-exist in PyPi) Inside this create another folder with same name or same package name, inside that put all the .py files with a single compulsorily __init__.py file and all folders/programs must be imported in __init__.py . Now outside of programs folder and inside the root folder, Setup.py file, README.md file and License.txt file must be created. Below is the flow diagram of the hierarchy: For the sub-folder akshaypawar-tut: Step 2: Creating README.md file The .md files are mark down files just as markup languages, it has it’s own syntax,it is used as a User-Friendly Readme file which will be displayed on home page. You may use extensions for VS Code or any online editors like https://dillinger.io/ to create Readme.md . Step3: Creating License.txt file Your package must have license, If you don’t have any concern to sharing it all over world you may use License.txt. If your package has policies you may use any online license maker website like https://choosealicense.com/ . Step 4: Create Setup.py File Your package must have a Setup.py file as it’s one of binding component of package, It describes dependencies of the package and author version, etc. Below is the code for general Setup.py . One needs to use their own credentials. Python3 import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( # Here is the module name. name="akshaypawar_tut", # version of the module version="0.0.1", # Name of Author author="Akshay Pawar", # your Email address author_email="akshaygpawar15@gmail.com", # #Small Description about module # description="adding number", # long_description=long_description, # Specifying that we are using markdown file for description long_description=long_description, long_description_content_type="text/markdown", # Any link to reach this module, ***if*** you have any webpage or github profile # url="https://github.com/username/", packages=setuptools.find_packages(), # if module has dependencies i.e. if your package rely on other package at pypi.org # then you must add there, in order to download every requirement of package # install_requires=[ # "package1", # "package2", # ], license="MIT", # classifiers like program is suitable for python3, just leave as it is. classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ],) Step 5: Final Stage Here you have to create account on pypi.org also we will be using twine library. The whole package is uploaded in the form of .dist file. To create .dist file use command: # Windows python setup.py bdist_wheel or # Linux/Mac python3 setup.py bdist_wheel You will observe this message on Powershell when the above commands are executed. Now our binary .dist file is created, now we need to upload it using the below command: twine upload dist/* Enter the required credentials regarding pypi.org account and the package will be uploaded. After successful upload you will get a link of your project and all the details Click here to see the uploaded package discussed in the article. saurabh1990aror gabaa406 python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Oct, 2021" }, { "code": null, "e": 199, "s": 28, "text": "Python is so flexible and easy to use because of its available packages that are hosted on pypi.org, Let’s see how to publish your own package on PyPi using Twine module." }, { "code": null, "e": 261, "s": 199, "text": "You must have account of pypi.org, if don’t create an account" }, { "code": null, "e": 356, "s": 261, "text": "The twine library is created to simplify uploading packages in pypi. To install twine library." }, { "code": null, "e": 374, "s": 356, "text": "pip install twine" }, { "code": null, "e": 398, "s": 374, "text": "Get your package ready." }, { "code": null, "e": 439, "s": 398, "text": "Step 1: Prepare and organize the package" }, { "code": null, "e": 556, "s": 439, "text": "Create a folder name must be same as package name. (Ensure that the name of your package does not pre-exist in PyPi)" }, { "code": null, "e": 764, "s": 556, "text": "Inside this create another folder with same name or same package name, inside that put all the .py files with a single compulsorily __init__.py file and all folders/programs must be imported in __init__.py ." }, { "code": null, "e": 935, "s": 764, "text": "Now outside of programs folder and inside the root folder, Setup.py file, README.md file and License.txt file must be created. Below is the flow diagram of the hierarchy:" }, { "code": null, "e": 971, "s": 935, "text": "For the sub-folder akshaypawar-tut:" }, { "code": null, "e": 1003, "s": 971, "text": "Step 2: Creating README.md file" }, { "code": null, "e": 1166, "s": 1003, "text": "The .md files are mark down files just as markup languages, it has it’s own syntax,it is used as a User-Friendly Readme file which will be displayed on home page." }, { "code": null, "e": 1272, "s": 1166, "text": "You may use extensions for VS Code or any online editors like https://dillinger.io/ to create Readme.md ." }, { "code": null, "e": 1305, "s": 1272, "text": "Step3: Creating License.txt file" }, { "code": null, "e": 1530, "s": 1305, "text": "Your package must have license, If you don’t have any concern to sharing it all over world you may use License.txt. If your package has policies you may use any online license maker website like https://choosealicense.com/ ." }, { "code": null, "e": 1559, "s": 1530, "text": "Step 4: Create Setup.py File" }, { "code": null, "e": 1709, "s": 1559, "text": "Your package must have a Setup.py file as it’s one of binding component of package, It describes dependencies of the package and author version, etc." }, { "code": null, "e": 1791, "s": 1709, "text": "Below is the code for general Setup.py . One needs to use their own credentials. " }, { "code": null, "e": 1799, "s": 1791, "text": "Python3" }, { "code": "import setuptools with open(\"README.md\", \"r\") as fh: long_description = fh.read() setuptools.setup( # Here is the module name. name=\"akshaypawar_tut\", # version of the module version=\"0.0.1\", # Name of Author author=\"Akshay Pawar\", # your Email address author_email=\"akshaygpawar15@gmail.com\", # #Small Description about module # description=\"adding number\", # long_description=long_description, # Specifying that we are using markdown file for description long_description=long_description, long_description_content_type=\"text/markdown\", # Any link to reach this module, ***if*** you have any webpage or github profile # url=\"https://github.com/username/\", packages=setuptools.find_packages(), # if module has dependencies i.e. if your package rely on other package at pypi.org # then you must add there, in order to download every requirement of package # install_requires=[ # \"package1\", # \"package2\", # ], license=\"MIT\", # classifiers like program is suitable for python3, just leave as it is. classifiers=[ \"Programming Language :: Python :: 3\", \"License :: OSI Approved :: MIT License\", \"Operating System :: OS Independent\", ],)", "e": 3069, "s": 1799, "text": null }, { "code": null, "e": 3089, "s": 3069, "text": "Step 5: Final Stage" }, { "code": null, "e": 3227, "s": 3089, "text": "Here you have to create account on pypi.org also we will be using twine library. The whole package is uploaded in the form of .dist file." }, { "code": null, "e": 3261, "s": 3227, "text": "To create .dist file use command:" }, { "code": null, "e": 3300, "s": 3261, "text": "# Windows\npython setup.py bdist_wheel " }, { "code": null, "e": 3304, "s": 3300, "text": "or " }, { "code": null, "e": 3346, "s": 3304, "text": "# Linux/Mac\npython3 setup.py bdist_wheel " }, { "code": null, "e": 3428, "s": 3346, "text": "You will observe this message on Powershell when the above commands are executed." }, { "code": null, "e": 3516, "s": 3428, "text": "Now our binary .dist file is created, now we need to upload it using the below command:" }, { "code": null, "e": 3537, "s": 3516, "text": "twine upload dist/* " }, { "code": null, "e": 3629, "s": 3537, "text": "Enter the required credentials regarding pypi.org account and the package will be uploaded." }, { "code": null, "e": 3710, "s": 3629, "text": "After successful upload you will get a link of your project and all the details " }, { "code": null, "e": 3777, "s": 3710, "text": " Click here to see the uploaded package discussed in the article. " }, { "code": null, "e": 3793, "s": 3777, "text": "saurabh1990aror" }, { "code": null, "e": 3802, "s": 3793, "text": "gabaa406" }, { "code": null, "e": 3817, "s": 3802, "text": "python-utility" }, { "code": null, "e": 3824, "s": 3817, "text": "Python" }, { "code": null, "e": 3922, "s": 3824, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3954, "s": 3922, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3981, "s": 3954, "text": "Python Classes and Objects" }, { "code": null, "e": 4012, "s": 3981, "text": "Python | os.path.join() method" }, { "code": null, "e": 4033, "s": 4012, "text": "Python OOPs Concepts" }, { "code": null, "e": 4089, "s": 4033, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4112, "s": 4089, "text": "Introduction To PYTHON" }, { "code": null, "e": 4154, "s": 4112, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4196, "s": 4154, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4235, "s": 4196, "text": "Python | datetime.timedelta() function" } ]
jQuery Highcharts Plugin
08 Jun, 2020 jQuery provides a very modern and highly interactive Highcharts plugin for programmers to implement charts for representing or comparing data for web and mobile applications. It’s multi-platform and supports SVG. You have to download the required files in the working folder so that the programmer can include in the head section of the HTML structure page as implemented in the following programs. Download link: https://www.highcharts.com/blog/download/ Example 1: The following example demonstrates the horizontal bar graph for different states and its population by using Highcharts plugin. <!DOCTYPE HTML><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>jQuery Highcharts Plugin</title> <script src="highcharts.js"></script> <script src="exporting.js"></script> <script src="export-data.js"></script> <script src="accessibility.js"></script> <style type="text/css"> body{ text-align:center; } .highcharts-data-table table, highcharts-figure{ min-width: 310px; max-width: 650px; margin: 2em auto; } #containerDivID{ height: 450px; } .highcharts-data-table table { font-family: Arial; border: 2px solid #e9e9e9; margin: 10px auto; text-align: center; max-width: 500px; width: 90%; } .highcharts-data-table caption { padding: 1em 0; font-size: 1.1em; color: #FFFF; } .highcharts-data-table tr:hover { background: #bedaff; } .highcharts-data-table th { font-weight: 600; padding: 0.5em; } .highcharts-data-table td, .highcharts-data-table th, .highcharts-data-table caption { padding: 0.6em; } .highcharts-data-table thead tr, .highcharts-data-table tr:nth-child(even) { background: #f8f8f8; } </style> </head> <body> <h1 style="color:green">GeeksforGeeks</h1> <b>jQuery Highcharts Plugin</b> <figure class="highcharts-figure"> <div id="containerDivID"></div> <p class="highcharts-description"> Column bar charts showing population data for various states in India. </p> </figure> <script type="text/javascript"> Highcharts.chart('containerDivID', { chart: { type: 'bar' }, title: { text: 'India Population by states' }, xAxis: { categories: ['Karnataka', 'Telangana', 'Punjab', 'Assam', 'Orissa'], }, yAxis: { min: 0, title: { text: 'Population (lakhs)', align: 'high' }, }, tooltip: { valueSuffix: 'lakhs' }, plotOptions: { bar: { dataLabels: { enabled: true } } }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'top', x: -50, y: 100, borderWidth: 5, backgroundColor: Highcharts.defaultOptions .legend.backgroundColor || '#FFFFFF', }, credits: { enabled: false }, series: [{ name: 'Year 2000', data: [1107, 231, 6351, 4203, 2329] }, { name: 'Year 2005', data: [1233, 1526, 1947, 1408, 1261] }, { name: 'Year 2010', data: [1814, 8641, 3714, 4727, 2191] }, { name: 'Year 2015', data: [1276, 1301, 4436, 6238, 2247] }] }); </script> </body></html> Output: Example 2: The following example demonstrates the 3D pie charts representing the access of various website by a single user in a particular year by using Highcharts plugin. <!DOCTYPE HTML><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>jQuery Highcharts Plugin</title> <script src="highcharts.js"></script> <script src="highcharts-3d.js"></script> <script src="exporting.js"></script> <script src="export-data.js"></script> <script src="accessibility.js"></script> <style type="text/css"> body{ text-align: center; } #containerDivID { height: 500px; } .highcharts-figure, .highcharts-data-table table { min-width: 310px; max-width: 600px; margin: 2em auto; } .highcharts-data-table table { font-family: Arial; border-collapse: collapse; border: 2px solid #e9e9e9; margin: 10px auto; text-align: center; width: 90%; max-width: 550px; } .highcharts-data-table td, .highcharts-data-table th, .highcharts-data-table caption { padding: 0.6em; } .highcharts-data-table caption { padding: 2em 0; font-size: 1.3em; color: #FFFF; } .highcharts-data-table th { font-weight: 600; padding: 0.5em; } .highcharts-data-table tr:hover { background: #f8f8f8; } .highcharts-data-table thead tr, .highcharts-data-table tr:nth-child(even) { background: #ffffff; } </style> </head> <body> <h1 style="color:green"> GeeksforGeeks </h1> <b>jQuery Highcharts Plugin</b> <figure class="highcharts-figure"> <div id="containerDivID"></div> <p class="highcharts-description"> This demonstrates the usage of 3D pie chart. Select or de-select any portion from the chart for information. </p> </figure> <script type="text/javascript"> Highcharts.chart('containerDivID', { chart: { type: 'pie', options3d: { enabled: true, alpha: 45, beta: 0 } }, title: { text: 'Websites accessed in 2020' }, accessibility: { point: { valueSuffix: '%' } }, tooltip: { pointFormat: '{series.name}: {point.percentage:.1f}%' }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', depth: 30, dataLabels: { enabled: true, format: '{point.name}' } } }, series: [{ type: 'pie', name: 'Website used', data: [ ['GeeksforGeeks', 55.0], ['NDTV', 27.5], ['youTube', 9.5], ['google', 7.2], ['Others', 1.5] ] }] }); </script> </body></html> Output: Example 3: The above example can be similarly implemented to represent 3D donut pie charts by making simple changes to the jQuery code as follows. The output chart is shown in the below image. <script type="text/javascript"> Highcharts.chart('containerDivID', { chart: { type: 'pie', options3d: { enabled: true, alpha: 45 } }, title: { text: 'Information about monthly grocery' }, subtitle: { text: '3D donut pie charts'+ ' using highcharts plugin' }, plotOptions: { pie: { innerSize: 100, depth: 45 } }, series: [{ name: 'Delivered amount in kgs', data: [ ['Wheat flour', 8], ['Brown Rice', 5], ['Millets', 3], ['Ragi flour', 7], ['Gram flour', 9], ['Oats', 3], ['Lentils', 4], ['Chickpeas', 2], ['Blackbeans', 6] ] }] }); </script> Output : All the charts implemented by using Highcharts plugin can be extended to HighchartTable plugin. With the Highcharts library usage, there exists a way which converts the HTML table data into desired charts. Download link for including the required files in the head section in addition to the Highchart plugin’s files. Example 4: The following example demonstrates the very basic HighchartTable plugin usage showing column chart with monthly expenses. <!DOCTYPE html><html> <head> <title>jQuery HighchartTable Plugin</title> <meta charset="UTF-8"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script> <script src="highcharts.js"></script> <script src="jquery.highchartTable.js"></script> <style> body { font-family: Arial; text-align:center; } #containerDivID{ width:550px; height:auto; } </style> </head> <body> <h1 style="color:green">GeeksforGeeks</h1> <b>jQuery HighchartTable Plugin</b> <div class="containerDivID"> <table class="highchart" data-graph-container-before="1" data-graph-type="column"> <thead> <tr> <th>Month</th> <th>Expenditure</th> </tr> </thead> <tbody> <tr> <td>January</td> <td>18000</td> </tr> <tr> <td>February</td> <td>15000</td> </tr> <tr> <td>March</td> <td>13000</td> </tr> <tr> <td>April</td> <td>22000</td> </tr> <tr> <td>May</td> <td>12000</td> </tr> <tr> <td>June</td> <td>12000</td> </tr> </tbody> </table> </div> <script> $(document).ready(function() { $('table.highchart').highchartTable(); }); </script> </body></html> Output: Example 5: The following example demonstrates line chart using HighchartTable plugin. <!DOCTYPE html><html> <head> <title>jQuery HighchartTable Plugin</title> <meta charset="UTF-8" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script> <script src="highcharts.js"></script> <script src="jquery.highchartTable.js"></script> <style> body { font-family: Arial; text-align: center; } #containerDivID { width: 550px; height: auto; } </style> </head> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <b>jQuery HighchartTable Plugin</b> <div class="containerDivID"> <table class="highchart" data-graph-container-before="1" data-graph-type="line" data-graph-height="310px" data-graph-width="500px"> <caption> This shows line graph for monthly expense </caption> <thead> <tr> <th>Month</th> <th>Expenditure</th> </tr> </thead> <tbody> <tr> <td>January</td> <td>18000</td> </tr> <tr> <td>February</td> <td>15000</td> </tr> <tr> <td>March</td> <td>13000</td> </tr> <tr> <td>April</td> <td>22000</td> </tr> <tr> <td>May</td> <td>12000</td> </tr> </tbody> </table> </div> <script> $(document).ready(function () { $("table.highchart").highchartTable(); }); </script> </body></html> Output : Example 6: The following example demonstrates bubble chart using Highchart plugin which represents data around 3 dimensions. Bubble charts generally plots graph taking x values, y values and z (size) values. The horizontal x and vertical y are value axes and z represents its size. <!DOCTYPE html><html><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>jQuery Highcharts Plugin</title> <script src="highcharts.js"></script> <script src="highcharts-more.js"></script> <script src="exporting.js"></script> <script src="export-data.js"></script> <script src="accessibility.js"></script> <style type="text/css"> body { text-align: center; } .highcharts-figure, .highcharts-data-table table { min-width: 310px; max-width: 600px; margin: 2em auto; } #containerDivID { height: 500px; } .highcharts-data-table table { font-family: Arial; border-collapse: collapse; border: 2px solid #e9e9e9; margin: 10px auto; text-align: center; width: 90%; max-width: 550px; } .highcharts-data-table caption { padding: 2em 0; font-size: 1.3em; color: #ffff; } .highcharts-data-table th { font-weight: 600; padding: 0.5em; } .highcharts-data-table td, .highcharts-data-table th, .highcharts-data-table caption { padding: 0.5em; } .highcharts-data-table thead tr, .highcharts-data-table tr:nth-child(even) { background: #f8f8f8; } .highcharts-data-table tr:hover { background: #ffffff; } </style></head><body> <h1 style="color: green;">GeeksforGeeks</h1> <b>jQuery Highcharts Plugin</b> <figure class="highcharts-figure"> <div id="containerDivID"></div> <p class="highcharts-description"> Bubble chart showing total products with their sales achieved and market shares in percentage. </p> </figure> <script type="text/javascript"> Highcharts.chart("containerDivID", { chart: { type: "bubble", plotBorderWidth: 1, zoomType: "xy", }, legend: { enabled: false, }, title: { text: "Sales and market share of"+ " products in the market", }, accessibility: { point: { valueDescriptionFormat: "{index}. {point.name}, "+ "Product count: {point.x}, "+ "Sales: Rs.{point.y}, "+ "Market share: {point.z}%.", }, }, xAxis: { gridLineWidth: 1, title: { text: "Total number of products sold", }, labels: { format: "{value} ", }, plotLines: [ { color: "black", dashStyle: "dot", width: 2, value: 25, label: { rotation: 0, y: 15, style: { fontStyle: "arial", }, text: "Good number of products sold", }, zIndex: 3, }, ], accessibility: { rangeDescription: "Range: 20 to 30 numbers.", }, }, yAxis: { startOnTick: false, endOnTick: false, title: { text: "Sales achieved", }, labels: { format: "Rs.{value} ", }, maxPadding: 0.2, plotLines: [ { color: "black", dashStyle: "dot", width: 2, value: 50, label: { align: "right", style: { fontStyle: "arial", }, text: "Good number for products sold", x: -10, }, zIndex: 3, }, ], accessibility: { rangeDescription: "Range: 0 to 60, 000 rupees.", }, }, tooltip: { useHTML: true, headerFormat: "<table>", pointFormat: '<tr><th colspan="2">{point.product}</th></tr>' + "<tr><th>Products sold:</th><td>{point.x}</td></tr>" + "<tr><th>Sales achieved :</th><td>Rs.{point.y}</td></tr>" + "<tr><th>Market share:</th><td>{point.z}%</td></tr>", footerFormat: "</table>", followPointer: true, }, plotOptions: { series: { dataLabels: { enabled: true, format: "{point.name}", }, }, }, series: [ { data: [ { x: 16, y: 5900, z: 3, name: "LB", product: "Ladies Bag" }, { x: 14, y: 22340, z: 14.7, name: "Sh", product: "Shoes" }, { x: 20, y: 60000, z: 15.8, name: "Mbl", product: "Mobile" }, { x: 18, y: 23500, z: 12, name: "Bks", product: "Books" }, { x: 22, y: 32200, z: 42, name: "SK", product: "Saving kit" }, { x: 31, y: 55000, z: 35, name: "Cp", product: "Cooking pans" }, { x: 17, y: 46000, z: 40, name: "MK", product: "Makeup kit" }, { x: 37, y: 19000, z: 10, name: "Pi", product: "Piano" }, ], }, ], }); </script></body></html> Output: Example 7: The following example demonstrates area charts using Highcharts plugin. These are similar to line charts as demonstrated earlier with the difference of visualizing data in volumes. <!DOCTYPE html><html><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Highcharts Example</title> <script src="highcharts.js"></script> <script src="exporting.js"></script> <script src="export-data.js"></script> <script src="accessibility.js"></script> <style type="text/css"> body { text-align: center; } .highcharts-figure, .highcharts-data-table table { min-width: 310px; max-width: 600px; margin: 2em auto; } #containerDivID { height: 500px; } .highcharts-data-table table { font-family: Arial; border-collapse: collapse; border: 2px solid #e9e9e9; margin: 10px auto; text-align: center; width: 90%; max-width: 550px; } .highcharts-data-table caption { padding: 2em 0; font-size: 1.3em; color: #ffff; } .highcharts-data-table th { font-weight: 600; padding: 0.5em; } .highcharts-data-table td, .highcharts-data-table th, .highcharts-data-table caption { padding: 0.5em; } .highcharts-data-table thead tr, .highcharts-data-table tr:nth-child(even) { background: #f8f8f8; } .highcharts-data-table tr:hover { background: #ffffff; } </style></head><body> <h1 style="color: green;">GeeksforGeeks</h1> <b>jQuery Highcharts Plugin</b> <figure class="highcharts-figure"> <div id="containerDivID"></div> <p class="highcharts-description"> It demonstrates the basic area chart showing men and women working strength . </p> </figure> <script type="text/javascript"> Highcharts.chart("containerDivID", { chart: { type: "area", }, accessibility: { description: "Image description: An area chart compares"+ " the working strength of the men and women"+ " between 1950 and 2020. The number men or "+ " women are plotted on the Y-axis and the "+ " years on the X-axis. ", }, title: { text: "Men and Women work force", }, xAxis: { allowDecimals: false, labels: { formatter: function () { return this.value; }, }, accessibility: { rangeDescription: "Years between : 1950 to 2020.", }, }, yAxis: { title: { text: "Working strength", }, labels: { formatter: function () { return this.value / 1000 + "k"; }, }, }, tooltip: { pointFormat: "{series.name} reached {point.y:, .0f}"+ " in numbers in year {point.x}", }, plotOptions: { area: { pointStart: 1950, marker: { enabled: false, symbol: "circle", radius: 2, states: { hover: { enabled: true, }, }, }, }, }, series: [ { name: "men", data: [ null, null, 17, 12, 17, 13, 21, 14, 16, 19, 32, 21, 35, 25, 25, 55, 125, 155, 215, 427, 655, 852, 1160, 1617, 1478, 1321, 2138, 4221, 4512, 4502, 4502, 4500, 4501, 5502, 6229, 7189, 8139, 9199, 10538, 18517, 12527, 10475, 11421, 10358, 10295, 10104, 12610, 12401, 11643, 13092, 14478, 15915, 17385, 19055, 21215, 23210, 22010, 23044, 25393, 27935, 21000, 26000, 29000, 28010, 29020, 27010, 25000, 24000, 31982, 32040, 31233, 39197, 45000, ], }, { name: "women", data: [ null, null, 11, 12, 22, 23, 24, 27, 28, 32, 27, 45, 67, 78, 86, 92, 112, 201, 250, 289, 369, 621, 1005, 1436, 2063, 3057, 4618, 5113, 5113, 4954, 4804, 4761, 4717, 4368, 4218, 6444, 9914, 9620, 9326, 9822, 15468, 18020, 17020, 16020, 15507, 14062, 12787, 13287, 14747, 13076, 12551, 12144, 11009, 10950, 10871, 11004, 14304, 23464, 24314, 23086, 22380, 21434, 24126, 27387, 29459, 31056, 29224, 27342, 26662, 26926, 27912, 28909, 28905, 27826, 25079, 25702, 24826, 24605, 30062, 32049, 33852, 35804, 37000, 35020, 33011, 31008, 37431, 43000, 41000, 39000, ], }, ], }); </script></body></html> Output: There are many more beautiful types of charts in the plugin. Programmers can explore and implement according to the application’s requirements. jQuery-Plugin JQuery Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jun, 2020" }, { "code": null, "e": 241, "s": 28, "text": "jQuery provides a very modern and highly interactive Highcharts plugin for programmers to implement charts for representing or comparing data for web and mobile applications. It’s multi-platform and supports SVG." }, { "code": null, "e": 427, "s": 241, "text": "You have to download the required files in the working folder so that the programmer can include in the head section of the HTML structure page as implemented in the following programs." }, { "code": null, "e": 442, "s": 427, "text": "Download link:" }, { "code": null, "e": 484, "s": 442, "text": "https://www.highcharts.com/blog/download/" }, { "code": null, "e": 623, "s": 484, "text": "Example 1: The following example demonstrates the horizontal bar graph for different states and its population by using Highcharts plugin." }, { "code": "<!DOCTYPE HTML><html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <title>jQuery Highcharts Plugin</title> <script src=\"highcharts.js\"></script> <script src=\"exporting.js\"></script> <script src=\"export-data.js\"></script> <script src=\"accessibility.js\"></script> <style type=\"text/css\"> body{ text-align:center; } .highcharts-data-table table, highcharts-figure{ min-width: 310px; max-width: 650px; margin: 2em auto; } #containerDivID{ height: 450px; } .highcharts-data-table table { font-family: Arial; border: 2px solid #e9e9e9; margin: 10px auto; text-align: center; max-width: 500px; width: 90%; } .highcharts-data-table caption { padding: 1em 0; font-size: 1.1em; color: #FFFF; } .highcharts-data-table tr:hover { background: #bedaff; } .highcharts-data-table th { font-weight: 600; padding: 0.5em; } .highcharts-data-table td, .highcharts-data-table th, .highcharts-data-table caption { padding: 0.6em; } .highcharts-data-table thead tr, .highcharts-data-table tr:nth-child(even) { background: #f8f8f8; } </style> </head> <body> <h1 style=\"color:green\">GeeksforGeeks</h1> <b>jQuery Highcharts Plugin</b> <figure class=\"highcharts-figure\"> <div id=\"containerDivID\"></div> <p class=\"highcharts-description\"> Column bar charts showing population data for various states in India. </p> </figure> <script type=\"text/javascript\"> Highcharts.chart('containerDivID', { chart: { type: 'bar' }, title: { text: 'India Population by states' }, xAxis: { categories: ['Karnataka', 'Telangana', 'Punjab', 'Assam', 'Orissa'], }, yAxis: { min: 0, title: { text: 'Population (lakhs)', align: 'high' }, }, tooltip: { valueSuffix: 'lakhs' }, plotOptions: { bar: { dataLabels: { enabled: true } } }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'top', x: -50, y: 100, borderWidth: 5, backgroundColor: Highcharts.defaultOptions .legend.backgroundColor || '#FFFFFF', }, credits: { enabled: false }, series: [{ name: 'Year 2000', data: [1107, 231, 6351, 4203, 2329] }, { name: 'Year 2005', data: [1233, 1526, 1947, 1408, 1261] }, { name: 'Year 2010', data: [1814, 8641, 3714, 4727, 2191] }, { name: 'Year 2015', data: [1276, 1301, 4436, 6238, 2247] }] }); </script> </body></html>", "e": 4614, "s": 623, "text": null }, { "code": null, "e": 4622, "s": 4614, "text": "Output:" }, { "code": null, "e": 4795, "s": 4622, "text": "Example 2: The following example demonstrates the 3D pie charts representing the access of various website by a single user in a particular year by using Highcharts plugin." }, { "code": "<!DOCTYPE HTML><html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <title>jQuery Highcharts Plugin</title> <script src=\"highcharts.js\"></script> <script src=\"highcharts-3d.js\"></script> <script src=\"exporting.js\"></script> <script src=\"export-data.js\"></script> <script src=\"accessibility.js\"></script> <style type=\"text/css\"> body{ text-align: center; } #containerDivID { height: 500px; } .highcharts-figure, .highcharts-data-table table { min-width: 310px; max-width: 600px; margin: 2em auto; } .highcharts-data-table table { font-family: Arial; border-collapse: collapse; border: 2px solid #e9e9e9; margin: 10px auto; text-align: center; width: 90%; max-width: 550px; } .highcharts-data-table td, .highcharts-data-table th, .highcharts-data-table caption { padding: 0.6em; } .highcharts-data-table caption { padding: 2em 0; font-size: 1.3em; color: #FFFF; } .highcharts-data-table th { font-weight: 600; padding: 0.5em; } .highcharts-data-table tr:hover { background: #f8f8f8; } .highcharts-data-table thead tr, .highcharts-data-table tr:nth-child(even) { background: #ffffff; } </style> </head> <body> <h1 style=\"color:green\"> GeeksforGeeks </h1> <b>jQuery Highcharts Plugin</b> <figure class=\"highcharts-figure\"> <div id=\"containerDivID\"></div> <p class=\"highcharts-description\"> This demonstrates the usage of 3D pie chart. Select or de-select any portion from the chart for information. </p> </figure> <script type=\"text/javascript\"> Highcharts.chart('containerDivID', { chart: { type: 'pie', options3d: { enabled: true, alpha: 45, beta: 0 } }, title: { text: 'Websites accessed in 2020' }, accessibility: { point: { valueSuffix: '%' } }, tooltip: { pointFormat: '{series.name}: {point.percentage:.1f}%' }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', depth: 30, dataLabels: { enabled: true, format: '{point.name}' } } }, series: [{ type: 'pie', name: 'Website used', data: [ ['GeeksforGeeks', 55.0], ['NDTV', 27.5], ['youTube', 9.5], ['google', 7.2], ['Others', 1.5] ] }] }); </script> </body></html>", "e": 8885, "s": 4795, "text": null }, { "code": null, "e": 8893, "s": 8885, "text": "Output:" }, { "code": null, "e": 9086, "s": 8893, "text": "Example 3: The above example can be similarly implemented to represent 3D donut pie charts by making simple changes to the jQuery code as follows. The output chart is shown in the below image." }, { "code": "<script type=\"text/javascript\"> Highcharts.chart('containerDivID', { chart: { type: 'pie', options3d: { enabled: true, alpha: 45 } }, title: { text: 'Information about monthly grocery' }, subtitle: { text: '3D donut pie charts'+ ' using highcharts plugin' }, plotOptions: { pie: { innerSize: 100, depth: 45 } }, series: [{ name: 'Delivered amount in kgs', data: [ ['Wheat flour', 8], ['Brown Rice', 5], ['Millets', 3], ['Ragi flour', 7], ['Gram flour', 9], ['Oats', 3], ['Lentils', 4], ['Chickpeas', 2], ['Blackbeans', 6] ] }] }); </script>", "e": 10179, "s": 9086, "text": null }, { "code": null, "e": 10188, "s": 10179, "text": "Output :" }, { "code": null, "e": 10394, "s": 10188, "text": "All the charts implemented by using Highcharts plugin can be extended to HighchartTable plugin. With the Highcharts library usage, there exists a way which converts the HTML table data into desired charts." }, { "code": null, "e": 10506, "s": 10394, "text": "Download link for including the required files in the head section in addition to the Highchart plugin’s files." }, { "code": null, "e": 10639, "s": 10506, "text": "Example 4: The following example demonstrates the very basic HighchartTable plugin usage showing column chart with monthly expenses." }, { "code": "<!DOCTYPE html><html> <head> <title>jQuery HighchartTable Plugin</title> <meta charset=\"UTF-8\"> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js\"> </script> <script src=\"highcharts.js\"></script> <script src=\"jquery.highchartTable.js\"></script> <style> body { font-family: Arial; text-align:center; } #containerDivID{ width:550px; height:auto; } </style> </head> <body> <h1 style=\"color:green\">GeeksforGeeks</h1> <b>jQuery HighchartTable Plugin</b> <div class=\"containerDivID\"> <table class=\"highchart\" data-graph-container-before=\"1\" data-graph-type=\"column\"> <thead> <tr> <th>Month</th> <th>Expenditure</th> </tr> </thead> <tbody> <tr> <td>January</td> <td>18000</td> </tr> <tr> <td>February</td> <td>15000</td> </tr> <tr> <td>March</td> <td>13000</td> </tr> <tr> <td>April</td> <td>22000</td> </tr> <tr> <td>May</td> <td>12000</td> </tr> <tr> <td>June</td> <td>12000</td> </tr> </tbody> </table> </div> <script> $(document).ready(function() { $('table.highchart').highchartTable(); }); </script> </body></html>", "e": 12667, "s": 10639, "text": null }, { "code": null, "e": 12675, "s": 12667, "text": "Output:" }, { "code": null, "e": 12761, "s": 12675, "text": "Example 5: The following example demonstrates line chart using HighchartTable plugin." }, { "code": "<!DOCTYPE html><html> <head> <title>jQuery HighchartTable Plugin</title> <meta charset=\"UTF-8\" /> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js\"> </script> <script src=\"highcharts.js\"></script> <script src=\"jquery.highchartTable.js\"></script> <style> body { font-family: Arial; text-align: center; } #containerDivID { width: 550px; height: auto; } </style> </head> <body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <b>jQuery HighchartTable Plugin</b> <div class=\"containerDivID\"> <table class=\"highchart\" data-graph-container-before=\"1\" data-graph-type=\"line\" data-graph-height=\"310px\" data-graph-width=\"500px\"> <caption> This shows line graph for monthly expense </caption> <thead> <tr> <th>Month</th> <th>Expenditure</th> </tr> </thead> <tbody> <tr> <td>January</td> <td>18000</td> </tr> <tr> <td>February</td> <td>15000</td> </tr> <tr> <td>March</td> <td>13000</td> </tr> <tr> <td>April</td> <td>22000</td> </tr> <tr> <td>May</td> <td>12000</td> </tr> </tbody> </table> </div> <script> $(document).ready(function () { $(\"table.highchart\").highchartTable(); }); </script> </body></html>", "e": 14887, "s": 12761, "text": null }, { "code": null, "e": 14896, "s": 14887, "text": "Output :" }, { "code": null, "e": 15178, "s": 14896, "text": "Example 6: The following example demonstrates bubble chart using Highchart plugin which represents data around 3 dimensions. Bubble charts generally plots graph taking x values, y values and z (size) values. The horizontal x and vertical y are value axes and z represents its size." }, { "code": "<!DOCTYPE html><html><head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <title>jQuery Highcharts Plugin</title> <script src=\"highcharts.js\"></script> <script src=\"highcharts-more.js\"></script> <script src=\"exporting.js\"></script> <script src=\"export-data.js\"></script> <script src=\"accessibility.js\"></script> <style type=\"text/css\"> body { text-align: center; } .highcharts-figure, .highcharts-data-table table { min-width: 310px; max-width: 600px; margin: 2em auto; } #containerDivID { height: 500px; } .highcharts-data-table table { font-family: Arial; border-collapse: collapse; border: 2px solid #e9e9e9; margin: 10px auto; text-align: center; width: 90%; max-width: 550px; } .highcharts-data-table caption { padding: 2em 0; font-size: 1.3em; color: #ffff; } .highcharts-data-table th { font-weight: 600; padding: 0.5em; } .highcharts-data-table td, .highcharts-data-table th, .highcharts-data-table caption { padding: 0.5em; } .highcharts-data-table thead tr, .highcharts-data-table tr:nth-child(even) { background: #f8f8f8; } .highcharts-data-table tr:hover { background: #ffffff; } </style></head><body> <h1 style=\"color: green;\">GeeksforGeeks</h1> <b>jQuery Highcharts Plugin</b> <figure class=\"highcharts-figure\"> <div id=\"containerDivID\"></div> <p class=\"highcharts-description\"> Bubble chart showing total products with their sales achieved and market shares in percentage. </p> </figure> <script type=\"text/javascript\"> Highcharts.chart(\"containerDivID\", { chart: { type: \"bubble\", plotBorderWidth: 1, zoomType: \"xy\", }, legend: { enabled: false, }, title: { text: \"Sales and market share of\"+ \" products in the market\", }, accessibility: { point: { valueDescriptionFormat: \"{index}. {point.name}, \"+ \"Product count: {point.x}, \"+ \"Sales: Rs.{point.y}, \"+ \"Market share: {point.z}%.\", }, }, xAxis: { gridLineWidth: 1, title: { text: \"Total number of products sold\", }, labels: { format: \"{value} \", }, plotLines: [ { color: \"black\", dashStyle: \"dot\", width: 2, value: 25, label: { rotation: 0, y: 15, style: { fontStyle: \"arial\", }, text: \"Good number of products sold\", }, zIndex: 3, }, ], accessibility: { rangeDescription: \"Range: 20 to 30 numbers.\", }, }, yAxis: { startOnTick: false, endOnTick: false, title: { text: \"Sales achieved\", }, labels: { format: \"Rs.{value} \", }, maxPadding: 0.2, plotLines: [ { color: \"black\", dashStyle: \"dot\", width: 2, value: 50, label: { align: \"right\", style: { fontStyle: \"arial\", }, text: \"Good number for products sold\", x: -10, }, zIndex: 3, }, ], accessibility: { rangeDescription: \"Range: 0 to 60, 000 rupees.\", }, }, tooltip: { useHTML: true, headerFormat: \"<table>\", pointFormat: '<tr><th colspan=\"2\">{point.product}</th></tr>' + \"<tr><th>Products sold:</th><td>{point.x}</td></tr>\" + \"<tr><th>Sales achieved :</th><td>Rs.{point.y}</td></tr>\" + \"<tr><th>Market share:</th><td>{point.z}%</td></tr>\", footerFormat: \"</table>\", followPointer: true, }, plotOptions: { series: { dataLabels: { enabled: true, format: \"{point.name}\", }, }, }, series: [ { data: [ { x: 16, y: 5900, z: 3, name: \"LB\", product: \"Ladies Bag\" }, { x: 14, y: 22340, z: 14.7, name: \"Sh\", product: \"Shoes\" }, { x: 20, y: 60000, z: 15.8, name: \"Mbl\", product: \"Mobile\" }, { x: 18, y: 23500, z: 12, name: \"Bks\", product: \"Books\" }, { x: 22, y: 32200, z: 42, name: \"SK\", product: \"Saving kit\" }, { x: 31, y: 55000, z: 35, name: \"Cp\", product: \"Cooking pans\" }, { x: 17, y: 46000, z: 40, name: \"MK\", product: \"Makeup kit\" }, { x: 37, y: 19000, z: 10, name: \"Pi\", product: \"Piano\" }, ], }, ], }); </script></body></html>", "e": 21422, "s": 15178, "text": null }, { "code": null, "e": 21430, "s": 21422, "text": "Output:" }, { "code": null, "e": 21622, "s": 21430, "text": "Example 7: The following example demonstrates area charts using Highcharts plugin. These are similar to line charts as demonstrated earlier with the difference of visualizing data in volumes." }, { "code": "<!DOCTYPE html><html><head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <title>Highcharts Example</title> <script src=\"highcharts.js\"></script> <script src=\"exporting.js\"></script> <script src=\"export-data.js\"></script> <script src=\"accessibility.js\"></script> <style type=\"text/css\"> body { text-align: center; } .highcharts-figure, .highcharts-data-table table { min-width: 310px; max-width: 600px; margin: 2em auto; } #containerDivID { height: 500px; } .highcharts-data-table table { font-family: Arial; border-collapse: collapse; border: 2px solid #e9e9e9; margin: 10px auto; text-align: center; width: 90%; max-width: 550px; } .highcharts-data-table caption { padding: 2em 0; font-size: 1.3em; color: #ffff; } .highcharts-data-table th { font-weight: 600; padding: 0.5em; } .highcharts-data-table td, .highcharts-data-table th, .highcharts-data-table caption { padding: 0.5em; } .highcharts-data-table thead tr, .highcharts-data-table tr:nth-child(even) { background: #f8f8f8; } .highcharts-data-table tr:hover { background: #ffffff; } </style></head><body> <h1 style=\"color: green;\">GeeksforGeeks</h1> <b>jQuery Highcharts Plugin</b> <figure class=\"highcharts-figure\"> <div id=\"containerDivID\"></div> <p class=\"highcharts-description\"> It demonstrates the basic area chart showing men and women working strength . </p> </figure> <script type=\"text/javascript\"> Highcharts.chart(\"containerDivID\", { chart: { type: \"area\", }, accessibility: { description: \"Image description: An area chart compares\"+ \" the working strength of the men and women\"+ \" between 1950 and 2020. The number men or \"+ \" women are plotted on the Y-axis and the \"+ \" years on the X-axis. \", }, title: { text: \"Men and Women work force\", }, xAxis: { allowDecimals: false, labels: { formatter: function () { return this.value; }, }, accessibility: { rangeDescription: \"Years between : 1950 to 2020.\", }, }, yAxis: { title: { text: \"Working strength\", }, labels: { formatter: function () { return this.value / 1000 + \"k\"; }, }, }, tooltip: { pointFormat: \"{series.name} reached {point.y:, .0f}\"+ \" in numbers in year {point.x}\", }, plotOptions: { area: { pointStart: 1950, marker: { enabled: false, symbol: \"circle\", radius: 2, states: { hover: { enabled: true, }, }, }, }, }, series: [ { name: \"men\", data: [ null, null, 17, 12, 17, 13, 21, 14, 16, 19, 32, 21, 35, 25, 25, 55, 125, 155, 215, 427, 655, 852, 1160, 1617, 1478, 1321, 2138, 4221, 4512, 4502, 4502, 4500, 4501, 5502, 6229, 7189, 8139, 9199, 10538, 18517, 12527, 10475, 11421, 10358, 10295, 10104, 12610, 12401, 11643, 13092, 14478, 15915, 17385, 19055, 21215, 23210, 22010, 23044, 25393, 27935, 21000, 26000, 29000, 28010, 29020, 27010, 25000, 24000, 31982, 32040, 31233, 39197, 45000, ], }, { name: \"women\", data: [ null, null, 11, 12, 22, 23, 24, 27, 28, 32, 27, 45, 67, 78, 86, 92, 112, 201, 250, 289, 369, 621, 1005, 1436, 2063, 3057, 4618, 5113, 5113, 4954, 4804, 4761, 4717, 4368, 4218, 6444, 9914, 9620, 9326, 9822, 15468, 18020, 17020, 16020, 15507, 14062, 12787, 13287, 14747, 13076, 12551, 12144, 11009, 10950, 10871, 11004, 14304, 23464, 24314, 23086, 22380, 21434, 24126, 27387, 29459, 31056, 29224, 27342, 26662, 26926, 27912, 28909, 28905, 27826, 25079, 25702, 24826, 24605, 30062, 32049, 33852, 35804, 37000, 35020, 33011, 31008, 37431, 43000, 41000, 39000, ], }, ], }); </script></body></html>", "e": 30448, "s": 21622, "text": null }, { "code": null, "e": 30456, "s": 30448, "text": "Output:" }, { "code": null, "e": 30600, "s": 30456, "text": "There are many more beautiful types of charts in the plugin. Programmers can explore and implement according to the application’s requirements." }, { "code": null, "e": 30614, "s": 30600, "text": "jQuery-Plugin" }, { "code": null, "e": 30621, "s": 30614, "text": "JQuery" } ]
Determine the type of an image in Python using imghdr
08 Feb, 2018 Suppose you are given an image type file and you need to determine the type of that file. In simple words, you need to get the extension of that image type file. This can be used in a project to verify whether the image you have requested for is actually an image and with which extension does it come. imghdr module Use following command for Installation: npm install imghdr Description:The imghdr module determines the type of image contained in a file or byte stream. The imghdr module defines the following function: imghdr.what(filename[, h]) Tests the image data contained in the file named by filename, and returns a string describing the image type. If optional h is provided, the filename is ignored and h is assumed to contain the byte stream to test. Note: The path of the file needs to be correct with its correct name. If the image file and the code file are in the same directory, you don’t need to specify the whole path. Just pass the name of the file as I did in the next example The extensions that can be recognized in module are-‘rgb’, ‘gif’,’ pbm’,’ pgm’,’ ppm’,’ tiff’, ‘rast’, ‘xbm’, ‘jpeg’, ‘bmp’, ‘png’, ‘webp’, ‘exr’. In Python 3.5, extensions ‘exr’ and ‘webp’ are also added. Example : Input : picture.gif Output : gif Input: picture.jpeg Output : jpeg import imghdrx = imghdr.what("picture.gif") #path of image as parameter print(x) Output: gif This is a simple program but used to solve big problems in real life projects. This article is contributed by Rishabh Bansal. 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. Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Feb, 2018" }, { "code": null, "e": 355, "s": 52, "text": "Suppose you are given an image type file and you need to determine the type of that file. In simple words, you need to get the extension of that image type file. This can be used in a project to verify whether the image you have requested for is actually an image and with which extension does it come." }, { "code": null, "e": 369, "s": 355, "text": "imghdr module" }, { "code": null, "e": 409, "s": 369, "text": "Use following command for Installation:" }, { "code": null, "e": 428, "s": 409, "text": "npm install imghdr" }, { "code": null, "e": 573, "s": 428, "text": "Description:The imghdr module determines the type of image contained in a file or byte stream. The imghdr module defines the following function:" }, { "code": null, "e": 600, "s": 573, "text": "imghdr.what(filename[, h])" }, { "code": null, "e": 814, "s": 600, "text": "Tests the image data contained in the file named by filename, and returns a string describing the image type. If optional h is provided, the filename is ignored and h is assumed to contain the byte stream to test." }, { "code": null, "e": 1049, "s": 814, "text": "Note: The path of the file needs to be correct with its correct name. If the image file and the code file are in the same directory, you don’t need to specify the whole path. Just pass the name of the file as I did in the next example" }, { "code": null, "e": 1255, "s": 1049, "text": "The extensions that can be recognized in module are-‘rgb’, ‘gif’,’ pbm’,’ pgm’,’ ppm’,’ tiff’, ‘rast’, ‘xbm’, ‘jpeg’, ‘bmp’, ‘png’, ‘webp’, ‘exr’. In Python 3.5, extensions ‘exr’ and ‘webp’ are also added." }, { "code": null, "e": 1265, "s": 1255, "text": "Example :" }, { "code": null, "e": 1334, "s": 1265, "text": "Input : picture.gif\nOutput : gif\n\nInput: picture.jpeg\nOutput : jpeg\n" }, { "code": "import imghdrx = imghdr.what(\"picture.gif\") #path of image as parameter print(x)", "e": 1416, "s": 1334, "text": null }, { "code": null, "e": 1424, "s": 1416, "text": "Output:" }, { "code": null, "e": 1429, "s": 1424, "text": "gif\n" }, { "code": null, "e": 1508, "s": 1429, "text": "This is a simple program but used to solve big problems in real life projects." }, { "code": null, "e": 1810, "s": 1508, "text": "This article is contributed by Rishabh Bansal. 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": 1935, "s": 1810, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 1942, "s": 1935, "text": "Python" }, { "code": null, "e": 1961, "s": 1942, "text": "Technical Scripter" } ]
std::stol() and std::stoll() functions in C++
21 Jun, 2018 std::stol(): This function converts the string, provided as an argument in the function call, to long int. It parses str interpreting its content as an integral number of the specified base, which is returned as a value of type long int.Syntax:long int stol (const string& str, size_t* idx = 0, int base = 10)Parameters: The function accepts three parameters which are described as below:str: It specifies a string object with the representation of an integral number.idx : It specifies a Pointer to an object of type size_t, whose value is set by the function to position of the next character in str after the numerical value. The parameter can also be a null pointer, in which case it is not used.base : It specifies the numerical base to determine the number system in which the characters are interpreted. If the base is 0, the base to be used is determined by the format in the sequence. The default value is 10.Return Value: The function returns the converted integral number as a value of type long int.// CPP code for illustration// of stol() function.#include <bits/stdc++.h>using namespace std; int main(){ // converting decimal number. string dec_num = "9876543210"; cout << "dec_num = " << stol(dec_num, nullptr, 10) << "\n"; // converting hexadecimal number. string hex_num = "FFFFFF"; cout << "hex_num = " << stol(hex_num, nullptr, 16) << "\n"; // converting binary number. string binary_num = "1111111"; cout << "binary_num = " << stol(binary_num, nullptr, 2) << "\n"; return 0;}Output:dec_num = 9876543210 hex_num = 16777215 binary_num = 127 std::stoll(): This function converts a string, provided as an argument in the function call, to long long int. It parses str interpreting its content as an integral number of the specified base, which is returned as a value of type long long int.Syntax:long long int stoll (const string& str, size_t* idx = 0, int base = 10)Parameters: The function accepts three parameters which are described as below:str: This parameter specifies the String object with the representation of an integral number.idx: This parameter specifies the Pointer to an object of type size_t, whose value is set by the function to a position of the next character in str after the numerical value. This parameter can also be a null pointer, in that case, it is not used.base:This parameter specifies the Numerical base to determine the number system in which the characters are interpreted. If the base is 0, the base used by it is determined by the format in the sequence. The default base is 10.Return Value: The function returns the converted integral number as a value of type long long int.// CPP code for illustration// of stoll() function.#include <bits/stdc++.h>using namespace std; int main(){ // converting decimal number. string dec_num = "9876543210"; cout << "dec_num = " << stoll(dec_num, nullptr, 10) << "\n "; // converting hexadecimal number. string hex_num = "FFFFFF"; cout << "hex_num = " << stoll(hex_num, nullptr, 16) << "\n"; // converting binary number. string binary_num = "1111111"; cout << "binary_num = " << stoll(binary_num, nullptr, 2) << "\n"; return 0;}Output:dec_num = 9876543210 hex_num = 16777215 binary_num = 127 std::stol(): This function converts the string, provided as an argument in the function call, to long int. It parses str interpreting its content as an integral number of the specified base, which is returned as a value of type long int.Syntax:long int stol (const string& str, size_t* idx = 0, int base = 10)Parameters: The function accepts three parameters which are described as below:str: It specifies a string object with the representation of an integral number.idx : It specifies a Pointer to an object of type size_t, whose value is set by the function to position of the next character in str after the numerical value. The parameter can also be a null pointer, in which case it is not used.base : It specifies the numerical base to determine the number system in which the characters are interpreted. If the base is 0, the base to be used is determined by the format in the sequence. The default value is 10.Return Value: The function returns the converted integral number as a value of type long int.// CPP code for illustration// of stol() function.#include <bits/stdc++.h>using namespace std; int main(){ // converting decimal number. string dec_num = "9876543210"; cout << "dec_num = " << stol(dec_num, nullptr, 10) << "\n"; // converting hexadecimal number. string hex_num = "FFFFFF"; cout << "hex_num = " << stol(hex_num, nullptr, 16) << "\n"; // converting binary number. string binary_num = "1111111"; cout << "binary_num = " << stol(binary_num, nullptr, 2) << "\n"; return 0;}Output:dec_num = 9876543210 hex_num = 16777215 binary_num = 127 Syntax: long int stol (const string& str, size_t* idx = 0, int base = 10) Parameters: The function accepts three parameters which are described as below: str: It specifies a string object with the representation of an integral number. idx : It specifies a Pointer to an object of type size_t, whose value is set by the function to position of the next character in str after the numerical value. The parameter can also be a null pointer, in which case it is not used. base : It specifies the numerical base to determine the number system in which the characters are interpreted. If the base is 0, the base to be used is determined by the format in the sequence. The default value is 10. Return Value: The function returns the converted integral number as a value of type long int. // CPP code for illustration// of stol() function.#include <bits/stdc++.h>using namespace std; int main(){ // converting decimal number. string dec_num = "9876543210"; cout << "dec_num = " << stol(dec_num, nullptr, 10) << "\n"; // converting hexadecimal number. string hex_num = "FFFFFF"; cout << "hex_num = " << stol(hex_num, nullptr, 16) << "\n"; // converting binary number. string binary_num = "1111111"; cout << "binary_num = " << stol(binary_num, nullptr, 2) << "\n"; return 0;} dec_num = 9876543210 hex_num = 16777215 binary_num = 127 std::stoll(): This function converts a string, provided as an argument in the function call, to long long int. It parses str interpreting its content as an integral number of the specified base, which is returned as a value of type long long int.Syntax:long long int stoll (const string& str, size_t* idx = 0, int base = 10)Parameters: The function accepts three parameters which are described as below:str: This parameter specifies the String object with the representation of an integral number.idx: This parameter specifies the Pointer to an object of type size_t, whose value is set by the function to a position of the next character in str after the numerical value. This parameter can also be a null pointer, in that case, it is not used.base:This parameter specifies the Numerical base to determine the number system in which the characters are interpreted. If the base is 0, the base used by it is determined by the format in the sequence. The default base is 10.Return Value: The function returns the converted integral number as a value of type long long int.// CPP code for illustration// of stoll() function.#include <bits/stdc++.h>using namespace std; int main(){ // converting decimal number. string dec_num = "9876543210"; cout << "dec_num = " << stoll(dec_num, nullptr, 10) << "\n "; // converting hexadecimal number. string hex_num = "FFFFFF"; cout << "hex_num = " << stoll(hex_num, nullptr, 16) << "\n"; // converting binary number. string binary_num = "1111111"; cout << "binary_num = " << stoll(binary_num, nullptr, 2) << "\n"; return 0;}Output:dec_num = 9876543210 hex_num = 16777215 binary_num = 127 Syntax: long long int stoll (const string& str, size_t* idx = 0, int base = 10) str: This parameter specifies the String object with the representation of an integral number. idx: This parameter specifies the Pointer to an object of type size_t, whose value is set by the function to a position of the next character in str after the numerical value. This parameter can also be a null pointer, in that case, it is not used. base:This parameter specifies the Numerical base to determine the number system in which the characters are interpreted. If the base is 0, the base used by it is determined by the format in the sequence. The default base is 10. Return Value: The function returns the converted integral number as a value of type long long int. // CPP code for illustration// of stoll() function.#include <bits/stdc++.h>using namespace std; int main(){ // converting decimal number. string dec_num = "9876543210"; cout << "dec_num = " << stoll(dec_num, nullptr, 10) << "\n "; // converting hexadecimal number. string hex_num = "FFFFFF"; cout << "hex_num = " << stoll(hex_num, nullptr, 16) << "\n"; // converting binary number. string binary_num = "1111111"; cout << "binary_num = " << stoll(binary_num, nullptr, 2) << "\n"; return 0;} dec_num = 9876543210 hex_num = 16777215 binary_num = 127 Errors and Exceptions: If no conversion could be performed, an invalid_argument exception is thrown. If the value read is out of the range of representable values by a long int, either an invalid_argument or an out_of_range exception is thrown. // CPP code for illustration of stoll()// function when invalid_argument // exception is thrown.#include <bits/stdc++.h>using namespace std; int main() { // An invalid input string that has no // integer part. string invalid_num = "abcf$#@de"; // stoll() throws invalid_argument exception // when conversion process fails. try{ cout << stoll(invalid_num) << "\n"; } // catch invalid_argument exception. catch(const std::invalid_argument){ cerr << "Invalid argument" << "\n"; } return 0;} Output: Runtime Errors: Invalid argument CPP-Functions STL C++ Programs STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Passing a function as a parameter in C++ Const keyword in C++ cout in C++ Program to implement Singly Linked List in C++ using class Different ways to print elements of vector Dynamic _Cast in C++ Why it is important to write "using namespace std" in C++ program? string::npos in C++ with Examples How to convert a Vector to Set in C++ Maximum value of long long int in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jun, 2018" }, { "code": null, "e": 3352, "s": 52, "text": "std::stol(): This function converts the string, provided as an argument in the function call, to long int. It parses str interpreting its content as an integral number of the specified base, which is returned as a value of type long int.Syntax:long int stol (const string& str, size_t* idx = 0, int base = 10)Parameters: The function accepts three parameters which are described as below:str: It specifies a string object with the representation of an integral number.idx : It specifies a Pointer to an object of type size_t, whose value is set by the function to position of the next character in str after the numerical value. The parameter can also be a null pointer, in which case it is not used.base : It specifies the numerical base to determine the number system in which the characters are interpreted. If the base is 0, the base to be used is determined by the format in the sequence. The default value is 10.Return Value: The function returns the converted integral number as a value of type long int.// CPP code for illustration// of stol() function.#include <bits/stdc++.h>using namespace std; int main(){ // converting decimal number. string dec_num = \"9876543210\"; cout << \"dec_num = \" << stol(dec_num, nullptr, 10) << \"\\n\"; // converting hexadecimal number. string hex_num = \"FFFFFF\"; cout << \"hex_num = \" << stol(hex_num, nullptr, 16) << \"\\n\"; // converting binary number. string binary_num = \"1111111\"; cout << \"binary_num = \" << stol(binary_num, nullptr, 2) << \"\\n\"; return 0;}Output:dec_num = 9876543210\nhex_num = 16777215\nbinary_num = 127\nstd::stoll(): This function converts a string, provided as an argument in the function call, to long long int. It parses str interpreting its content as an integral number of the specified base, which is returned as a value of type long long int.Syntax:long long int stoll (const string& str, size_t* idx = 0, int base = 10)Parameters: The function accepts three parameters which are described as below:str: This parameter specifies the String object with the representation of an integral number.idx: This parameter specifies the Pointer to an object of type size_t, whose value is set by the function to a position of the next character in str after the numerical value. This parameter can also be a null pointer, in that case, it is not used.base:This parameter specifies the Numerical base to determine the number system in which the characters are interpreted. If the base is 0, the base used by it is determined by the format in the sequence. The default base is 10.Return Value: The function returns the converted integral number as a value of type long long int.// CPP code for illustration// of stoll() function.#include <bits/stdc++.h>using namespace std; int main(){ // converting decimal number. string dec_num = \"9876543210\"; cout << \"dec_num = \" << stoll(dec_num, nullptr, 10) << \"\\n \"; // converting hexadecimal number. string hex_num = \"FFFFFF\"; cout << \"hex_num = \" << stoll(hex_num, nullptr, 16) << \"\\n\"; // converting binary number. string binary_num = \"1111111\"; cout << \"binary_num = \" << stoll(binary_num, nullptr, 2) << \"\\n\"; return 0;}Output:dec_num = 9876543210\n hex_num = 16777215\nbinary_num = 127\n" }, { "code": null, "e": 4964, "s": 3352, "text": "std::stol(): This function converts the string, provided as an argument in the function call, to long int. It parses str interpreting its content as an integral number of the specified base, which is returned as a value of type long int.Syntax:long int stol (const string& str, size_t* idx = 0, int base = 10)Parameters: The function accepts three parameters which are described as below:str: It specifies a string object with the representation of an integral number.idx : It specifies a Pointer to an object of type size_t, whose value is set by the function to position of the next character in str after the numerical value. The parameter can also be a null pointer, in which case it is not used.base : It specifies the numerical base to determine the number system in which the characters are interpreted. If the base is 0, the base to be used is determined by the format in the sequence. The default value is 10.Return Value: The function returns the converted integral number as a value of type long int.// CPP code for illustration// of stol() function.#include <bits/stdc++.h>using namespace std; int main(){ // converting decimal number. string dec_num = \"9876543210\"; cout << \"dec_num = \" << stol(dec_num, nullptr, 10) << \"\\n\"; // converting hexadecimal number. string hex_num = \"FFFFFF\"; cout << \"hex_num = \" << stol(hex_num, nullptr, 16) << \"\\n\"; // converting binary number. string binary_num = \"1111111\"; cout << \"binary_num = \" << stol(binary_num, nullptr, 2) << \"\\n\"; return 0;}Output:dec_num = 9876543210\nhex_num = 16777215\nbinary_num = 127\n" }, { "code": null, "e": 4972, "s": 4964, "text": "Syntax:" }, { "code": null, "e": 5039, "s": 4972, "text": "long int stol (const string& str, size_t* idx = 0, int base = 10)" }, { "code": null, "e": 5119, "s": 5039, "text": "Parameters: The function accepts three parameters which are described as below:" }, { "code": null, "e": 5200, "s": 5119, "text": "str: It specifies a string object with the representation of an integral number." }, { "code": null, "e": 5433, "s": 5200, "text": "idx : It specifies a Pointer to an object of type size_t, whose value is set by the function to position of the next character in str after the numerical value. The parameter can also be a null pointer, in which case it is not used." }, { "code": null, "e": 5652, "s": 5433, "text": "base : It specifies the numerical base to determine the number system in which the characters are interpreted. If the base is 0, the base to be used is determined by the format in the sequence. The default value is 10." }, { "code": null, "e": 5746, "s": 5652, "text": "Return Value: The function returns the converted integral number as a value of type long int." }, { "code": "// CPP code for illustration// of stol() function.#include <bits/stdc++.h>using namespace std; int main(){ // converting decimal number. string dec_num = \"9876543210\"; cout << \"dec_num = \" << stol(dec_num, nullptr, 10) << \"\\n\"; // converting hexadecimal number. string hex_num = \"FFFFFF\"; cout << \"hex_num = \" << stol(hex_num, nullptr, 16) << \"\\n\"; // converting binary number. string binary_num = \"1111111\"; cout << \"binary_num = \" << stol(binary_num, nullptr, 2) << \"\\n\"; return 0;}", "e": 6282, "s": 5746, "text": null }, { "code": null, "e": 6340, "s": 6282, "text": "dec_num = 9876543210\nhex_num = 16777215\nbinary_num = 127\n" }, { "code": null, "e": 8029, "s": 6340, "text": "std::stoll(): This function converts a string, provided as an argument in the function call, to long long int. It parses str interpreting its content as an integral number of the specified base, which is returned as a value of type long long int.Syntax:long long int stoll (const string& str, size_t* idx = 0, int base = 10)Parameters: The function accepts three parameters which are described as below:str: This parameter specifies the String object with the representation of an integral number.idx: This parameter specifies the Pointer to an object of type size_t, whose value is set by the function to a position of the next character in str after the numerical value. This parameter can also be a null pointer, in that case, it is not used.base:This parameter specifies the Numerical base to determine the number system in which the characters are interpreted. If the base is 0, the base used by it is determined by the format in the sequence. The default base is 10.Return Value: The function returns the converted integral number as a value of type long long int.// CPP code for illustration// of stoll() function.#include <bits/stdc++.h>using namespace std; int main(){ // converting decimal number. string dec_num = \"9876543210\"; cout << \"dec_num = \" << stoll(dec_num, nullptr, 10) << \"\\n \"; // converting hexadecimal number. string hex_num = \"FFFFFF\"; cout << \"hex_num = \" << stoll(hex_num, nullptr, 16) << \"\\n\"; // converting binary number. string binary_num = \"1111111\"; cout << \"binary_num = \" << stoll(binary_num, nullptr, 2) << \"\\n\"; return 0;}Output:dec_num = 9876543210\n hex_num = 16777215\nbinary_num = 127\n" }, { "code": null, "e": 8037, "s": 8029, "text": "Syntax:" }, { "code": null, "e": 8110, "s": 8037, "text": "long long int stoll (const string& str, size_t* idx = 0, int base = 10)" }, { "code": null, "e": 8205, "s": 8110, "text": "str: This parameter specifies the String object with the representation of an integral number." }, { "code": null, "e": 8454, "s": 8205, "text": "idx: This parameter specifies the Pointer to an object of type size_t, whose value is set by the function to a position of the next character in str after the numerical value. This parameter can also be a null pointer, in that case, it is not used." }, { "code": null, "e": 8682, "s": 8454, "text": "base:This parameter specifies the Numerical base to determine the number system in which the characters are interpreted. If the base is 0, the base used by it is determined by the format in the sequence. The default base is 10." }, { "code": null, "e": 8781, "s": 8682, "text": "Return Value: The function returns the converted integral number as a value of type long long int." }, { "code": "// CPP code for illustration// of stoll() function.#include <bits/stdc++.h>using namespace std; int main(){ // converting decimal number. string dec_num = \"9876543210\"; cout << \"dec_num = \" << stoll(dec_num, nullptr, 10) << \"\\n \"; // converting hexadecimal number. string hex_num = \"FFFFFF\"; cout << \"hex_num = \" << stoll(hex_num, nullptr, 16) << \"\\n\"; // converting binary number. string binary_num = \"1111111\"; cout << \"binary_num = \" << stoll(binary_num, nullptr, 2) << \"\\n\"; return 0;}", "e": 9334, "s": 8781, "text": null }, { "code": null, "e": 9393, "s": 9334, "text": "dec_num = 9876543210\n hex_num = 16777215\nbinary_num = 127\n" }, { "code": null, "e": 9638, "s": 9393, "text": "Errors and Exceptions: If no conversion could be performed, an invalid_argument exception is thrown. If the value read is out of the range of representable values by a long int, either an invalid_argument or an out_of_range exception is thrown." }, { "code": "// CPP code for illustration of stoll()// function when invalid_argument // exception is thrown.#include <bits/stdc++.h>using namespace std; int main() { // An invalid input string that has no // integer part. string invalid_num = \"abcf$#@de\"; // stoll() throws invalid_argument exception // when conversion process fails. try{ cout << stoll(invalid_num) << \"\\n\"; } // catch invalid_argument exception. catch(const std::invalid_argument){ cerr << \"Invalid argument\" << \"\\n\"; } return 0;}", "e": 10196, "s": 9638, "text": null }, { "code": null, "e": 10204, "s": 10196, "text": "Output:" }, { "code": null, "e": 10237, "s": 10204, "text": "Runtime Errors:\nInvalid argument" }, { "code": null, "e": 10251, "s": 10237, "text": "CPP-Functions" }, { "code": null, "e": 10255, "s": 10251, "text": "STL" }, { "code": null, "e": 10268, "s": 10255, "text": "C++ Programs" }, { "code": null, "e": 10272, "s": 10268, "text": "STL" }, { "code": null, "e": 10370, "s": 10272, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10411, "s": 10370, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 10432, "s": 10411, "text": "Const keyword in C++" }, { "code": null, "e": 10444, "s": 10432, "text": "cout in C++" }, { "code": null, "e": 10503, "s": 10444, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 10546, "s": 10503, "text": "Different ways to print elements of vector" }, { "code": null, "e": 10567, "s": 10546, "text": "Dynamic _Cast in C++" }, { "code": null, "e": 10634, "s": 10567, "text": "Why it is important to write \"using namespace std\" in C++ program?" }, { "code": null, "e": 10668, "s": 10634, "text": "string::npos in C++ with Examples" }, { "code": null, "e": 10706, "s": 10668, "text": "How to convert a Vector to Set in C++" } ]
numpy.amax() in Python
28 Apr, 2022 The numpy.amax() method returns the maximum of an array or maximum along the axis(if mentioned). Syntax: numpy.amax(arr, axis = None, out = None, keepdims = <class numpy._globals._NoValue>) Parameters – arr : [array_like] input data axis : [int or tuples of int] axis along which we want the max value. Otherwise, it will consider arr to be flattened. out : [ndarray, optional] alternative output array in which to place the result keepdims : [boolean, optional] if this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the all method of sub-classes of ndarray, however any non-default value will be. If the sub-classes sum method does not implement keepdims any exceptions will be raised. Return – Maximum of array – arr[ndarray or scalar], scalar if axis is None; the result is an array of dimension a.ndim – 1, if axis is mentioned. Code – Python # Python Program illustrating# numpy.amax() method import numpy as geek # 1D arrayarr = geek.arange(8)print("arr : ", arr)print("Max of arr : ", geek.amax(arr)) # 2D arrayarr = geek.arange(10).reshape(2, 5)print("\narr : ", arr) # Maximum of the flattened arrayprint("\nMax of arr, axis = None : ", geek.amax(arr)) # Maxima along the first axis# axis 0 means verticalprint("Max of arr, axis = 0 : ", geek.amax(arr, axis = 0)) # Maxima along the second axis# axis 1 means horizontalprint("Max of arr, axis = 1 : ", geek.amax(arr, axis = 1)) Output – arr : [0 1 2 3 4 5 6 7] Max of arr : 7 arr : [[0 1 2 3 4] [5 6 7 8 9]] Max of arr, axis = None : 9 Max of arr, axis = 0 : [5 6 7 8 9] Max of arr, axis = 1 : [4 9] Reference – https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.amax.html Note – These codes won’t run on online IDE’s. So please, run them on your systems to explore the working. This article is contributed by Mohit Gupta_OMG . 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. vinayedula surinderdawra388 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Apr, 2022" }, { "code": null, "e": 157, "s": 52, "text": "The numpy.amax() method returns the maximum of an array or maximum along the axis(if mentioned). Syntax:" }, { "code": null, "e": 242, "s": 157, "text": "numpy.amax(arr, axis = None, out = None, keepdims = <class numpy._globals._NoValue>)" }, { "code": null, "e": 256, "s": 242, "text": "Parameters – " }, { "code": null, "e": 286, "s": 256, "text": "arr : [array_like] input data" }, { "code": null, "e": 405, "s": 286, "text": "axis : [int or tuples of int] axis along which we want the max value. Otherwise, it will consider arr to be flattened." }, { "code": null, "e": 485, "s": 405, "text": "out : [ndarray, optional] alternative output array in which to place the result" }, { "code": null, "e": 944, "s": 485, "text": "keepdims : [boolean, optional] if this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the all method of sub-classes of ndarray, however any non-default value will be. If the sub-classes sum method does not implement keepdims any exceptions will be raised." }, { "code": null, "e": 1098, "s": 944, "text": "Return – Maximum of array – arr[ndarray or scalar], scalar if axis is None; the result is an array of dimension a.ndim – 1, if axis is mentioned. Code – " }, { "code": null, "e": 1105, "s": 1098, "text": "Python" }, { "code": "# Python Program illustrating# numpy.amax() method import numpy as geek # 1D arrayarr = geek.arange(8)print(\"arr : \", arr)print(\"Max of arr : \", geek.amax(arr)) # 2D arrayarr = geek.arange(10).reshape(2, 5)print(\"\\narr : \", arr) # Maximum of the flattened arrayprint(\"\\nMax of arr, axis = None : \", geek.amax(arr)) # Maxima along the first axis# axis 0 means verticalprint(\"Max of arr, axis = 0 : \", geek.amax(arr, axis = 0)) # Maxima along the second axis# axis 1 means horizontalprint(\"Max of arr, axis = 1 : \", geek.amax(arr, axis = 1)) ", "e": 1647, "s": 1105, "text": null }, { "code": null, "e": 1657, "s": 1647, "text": "Output – " }, { "code": null, "e": 1829, "s": 1657, "text": "arr : [0 1 2 3 4 5 6 7]\nMax of arr : 7\n\narr : [[0 1 2 3 4]\n [5 6 7 8 9]]\n\nMax of arr, axis = None : 9\nMax of arr, axis = 0 : [5 6 7 8 9]\nMax of arr, axis = 1 : [4 9]" }, { "code": null, "e": 1918, "s": 1829, "text": "Reference – https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.amax.html " }, { "code": null, "e": 2024, "s": 1918, "text": "Note – These codes won’t run on online IDE’s. So please, run them on your systems to explore the working." }, { "code": null, "e": 2449, "s": 2024, "text": "This article is contributed by Mohit Gupta_OMG . 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": 2460, "s": 2449, "text": "vinayedula" }, { "code": null, "e": 2477, "s": 2460, "text": "surinderdawra388" }, { "code": null, "e": 2484, "s": 2477, "text": "Python" }, { "code": null, "e": 2582, "s": 2484, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2600, "s": 2582, "text": "Python Dictionary" }, { "code": null, "e": 2642, "s": 2600, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2664, "s": 2642, "text": "Enumerate() in Python" }, { "code": null, "e": 2696, "s": 2664, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2725, "s": 2696, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2752, "s": 2725, "text": "Python Classes and Objects" }, { "code": null, "e": 2773, "s": 2752, "text": "Python OOPs Concepts" }, { "code": null, "e": 2809, "s": 2773, "text": "Convert integer to string in Python" }, { "code": null, "e": 2832, "s": 2809, "text": "Introduction To PYTHON" } ]
How to Adjust the Volume of Android Phone Programmatically from the App?
15 Oct, 2020 As stated in the title of this article let’s discuss how to adjust the volume of an Android Phone programmatically from the App. Basically, control the volume in the app mean Increase or Decrease the Volume without the Volume Bar UI Increase or Decrease the Volume with the Volume Bar UI Mute or Unmute the device So we are going to discuss all these three processes step by step. Note that we are going to implement this project using the Kotlin language. To programmatically control the volume in an Android device, follow the following steps: Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language. Step 2: Working with the activity_main.xml file When the setup is ready, go to the activity_main.xml file, which represents the UI of the project. Create two Buttons, one for increasing the volume and the other for decreasing it, one below the other. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/btnUp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_above="@+id/btnDown" android:text="+" /> <Button android:id="@+id/btnDown" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="-" /> </RelativeLayout> Step 3: Working with the MainActivity.kt file In the MainActivity.kt file, declare the two Buttons and an audio manager (refer to the codes). While setting the on click listeners to the buttons, we would use the audio manager to increase or decrease the volume. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import android.media.AudioManagerimport android.os.Bundleimport android.widget.Buttonimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declare Buttons val upBtn = findViewById<Button>(R.id.btnUp) val downBtn = findViewById<Button>(R.id.btnDown) // Declare an audio manager val audioManager = applicationContext.getSystemService(AUDIO_SERVICE) as AudioManager // At the click of upBtn upBtn.setOnClickListener { // ADJUST_RAISE = Raise the volume, FLAG_PLAY_SOUND = make a sound when clicked audioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND) } // At the click of downBtn downBtn.setOnClickListener { // ADJUST_LOWER = Lowers the volume, FLAG_PLAY_SOUND = make a sound when clicked audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND) } }} The only change we have to make is to pass the parameter AudioManager.FLAG_SHOW_UI instead of AudioManager.FLAG_PLAY_SOUND in the MainActivity.kt file. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import android.content.Contextimport android.media.AudioManagerimport android.os.Bundleimport android.widget.Buttonimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declare Buttons val upBtn = findViewById<Button>(R.id.btnUp) val downBtn = findViewById<Button>(R.id.btnDown) // Declare an audio manager val audioManager = applicationContext.getSystemService(Context.AUDIO_SERVICE) as AudioManager // At the click of upBtn upBtn.setOnClickListener { // ADJUST_RAISE = Raise the volume, FLAG_SHOW_UI = show changes made to volume bar audioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI) } // At the click of downBtn downBtn.setOnClickListener { // ADJUST_LOWER = LOWER the volume, FLAG_SHOW_UI = show changes made to volume bar audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI) } }} It can be seen that the volume increases when “+” is clicked, and similarly, it decreases when “-” is clicked. When the phone becomes completely mute, changes can be seen on the volume bar. Step 1: Working with the activity_main.xml file When the setup is ready, go to the activity_main.xml file, which represents the UI of the project. Create two Buttons, one to mute and the other to unmute the device, one below the other. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/btnMute" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:text="Mute" android:layout_above="@+id/btnUnmute" /> <Button android:id="@+id/btnUnmute" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Unmute" /> </RelativeLayout> Step 2: Working with the MainActivity.kt file In the MainActivity.kt file, declare the two Buttons and an audio manager (refer to the codes). While setting the on click listeners to the buttons, we would use the audio manager to mute or unmute the device. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import android.content.Contextimport android.media.AudioManagerimport android.os.Bundleimport android.widget.Buttonimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declare Buttons val muteBtn = findViewById<Button>(R.id.btnMute) val unmuteBtn = findViewById<Button>(R.id.btnUnmute) // Declare an audio manager val audioManager = applicationContext.getSystemService(Context.AUDIO_SERVICE) as AudioManager muteBtn.setOnClickListener { // ADJUST_Mute = Mutes the device, FLAG_SHOW_UI = show changes made to volume bar audioManager.adjustVolume(AudioManager.ADJUST_MUTE, AudioManager.FLAG_SHOW_UI) } unmuteBtn.setOnClickListener { // ADJUST_Unmute = Unmutes the device, FLAG_SHOW_UI = show changes made to volume bar audioManager.adjustVolume(AudioManager.ADJUST_UNMUTE, AudioManager.FLAG_SHOW_UI) } }} android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n15 Oct, 2020" }, { "code": null, "e": 229, "s": 53, "text": "As stated in the title of this article let’s discuss how to adjust the volume of an Android Phone programmatically from the App. Basically, control the volume in the app mean " }, { "code": null, "e": 287, "s": 229, "text": "Increase or Decrease the Volume without the Volume Bar UI" }, { "code": null, "e": 342, "s": 287, "text": "Increase or Decrease the Volume with the Volume Bar UI" }, { "code": null, "e": 368, "s": 342, "text": "Mute or Unmute the device" }, { "code": null, "e": 512, "s": 368, "text": "So we are going to discuss all these three processes step by step. Note that we are going to implement this project using the Kotlin language. " }, { "code": null, "e": 601, "s": 512, "text": "To programmatically control the volume in an Android device, follow the following steps:" }, { "code": null, "e": 630, "s": 601, "text": "Step 1: Create a New Project" }, { "code": null, "e": 794, "s": 630, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language." }, { "code": null, "e": 842, "s": 794, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 1096, "s": 842, "text": "When the setup is ready, go to the activity_main.xml file, which represents the UI of the project. Create two Buttons, one for increasing the volume and the other for decreasing it, one below the other. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 1100, "s": 1096, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/btnUp\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_above=\"@+id/btnDown\" android:text=\"+\" /> <Button android:id=\"@+id/btnDown\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:text=\"-\" /> </RelativeLayout>", "e": 1918, "s": 1100, "text": null }, { "code": null, "e": 1964, "s": 1918, "text": "Step 3: Working with the MainActivity.kt file" }, { "code": null, "e": 2302, "s": 1964, "text": "In the MainActivity.kt file, declare the two Buttons and an audio manager (refer to the codes). While setting the on click listeners to the buttons, we would use the audio manager to increase or decrease the volume. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 2309, "s": 2302, "text": "Kotlin" }, { "code": "import android.media.AudioManagerimport android.os.Bundleimport android.widget.Buttonimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declare Buttons val upBtn = findViewById<Button>(R.id.btnUp) val downBtn = findViewById<Button>(R.id.btnDown) // Declare an audio manager val audioManager = applicationContext.getSystemService(AUDIO_SERVICE) as AudioManager // At the click of upBtn upBtn.setOnClickListener { // ADJUST_RAISE = Raise the volume, FLAG_PLAY_SOUND = make a sound when clicked audioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND) } // At the click of downBtn downBtn.setOnClickListener { // ADJUST_LOWER = Lowers the volume, FLAG_PLAY_SOUND = make a sound when clicked audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND) } }}", "e": 3429, "s": 2309, "text": null }, { "code": null, "e": 3703, "s": 3429, "text": "The only change we have to make is to pass the parameter AudioManager.FLAG_SHOW_UI instead of AudioManager.FLAG_PLAY_SOUND in the MainActivity.kt file. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 3710, "s": 3703, "text": "Kotlin" }, { "code": "import android.content.Contextimport android.media.AudioManagerimport android.os.Bundleimport android.widget.Buttonimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declare Buttons val upBtn = findViewById<Button>(R.id.btnUp) val downBtn = findViewById<Button>(R.id.btnDown) // Declare an audio manager val audioManager = applicationContext.getSystemService(Context.AUDIO_SERVICE) as AudioManager // At the click of upBtn upBtn.setOnClickListener { // ADJUST_RAISE = Raise the volume, FLAG_SHOW_UI = show changes made to volume bar audioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI) } // At the click of downBtn downBtn.setOnClickListener { // ADJUST_LOWER = LOWER the volume, FLAG_SHOW_UI = show changes made to volume bar audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI) } }}", "e": 4869, "s": 3710, "text": null }, { "code": null, "e": 5059, "s": 4869, "text": "It can be seen that the volume increases when “+” is clicked, and similarly, it decreases when “-” is clicked. When the phone becomes completely mute, changes can be seen on the volume bar." }, { "code": null, "e": 5107, "s": 5059, "text": "Step 1: Working with the activity_main.xml file" }, { "code": null, "e": 5346, "s": 5107, "text": "When the setup is ready, go to the activity_main.xml file, which represents the UI of the project. Create two Buttons, one to mute and the other to unmute the device, one below the other. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 5350, "s": 5346, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/btnMute\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:text=\"Mute\" android:layout_above=\"@+id/btnUnmute\" /> <Button android:id=\"@+id/btnUnmute\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:text=\"Unmute\" /> </RelativeLayout>", "e": 6183, "s": 5350, "text": null }, { "code": null, "e": 6229, "s": 6183, "text": "Step 2: Working with the MainActivity.kt file" }, { "code": null, "e": 6561, "s": 6229, "text": "In the MainActivity.kt file, declare the two Buttons and an audio manager (refer to the codes). While setting the on click listeners to the buttons, we would use the audio manager to mute or unmute the device. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 6568, "s": 6561, "text": "Kotlin" }, { "code": "import android.content.Contextimport android.media.AudioManagerimport android.os.Bundleimport android.widget.Buttonimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declare Buttons val muteBtn = findViewById<Button>(R.id.btnMute) val unmuteBtn = findViewById<Button>(R.id.btnUnmute) // Declare an audio manager val audioManager = applicationContext.getSystemService(Context.AUDIO_SERVICE) as AudioManager muteBtn.setOnClickListener { // ADJUST_Mute = Mutes the device, FLAG_SHOW_UI = show changes made to volume bar audioManager.adjustVolume(AudioManager.ADJUST_MUTE, AudioManager.FLAG_SHOW_UI) } unmuteBtn.setOnClickListener { // ADJUST_Unmute = Unmutes the device, FLAG_SHOW_UI = show changes made to volume bar audioManager.adjustVolume(AudioManager.ADJUST_UNMUTE, AudioManager.FLAG_SHOW_UI) } }}", "e": 7677, "s": 6568, "text": null }, { "code": null, "e": 7685, "s": 7677, "text": "android" }, { "code": null, "e": 7693, "s": 7685, "text": "Android" }, { "code": null, "e": 7700, "s": 7693, "text": "Kotlin" }, { "code": null, "e": 7708, "s": 7700, "text": "Android" } ]
Rearrange Odd and Even values in Alternate Fashion in Ascending Order
15 Sep, 2021 Given an array of integers (both odd and even), the task is to arrange them in such a way that odd and even values come in alternate fashion in non-decreasing order(ascending) respectively. If the smallest value is Even then we have to print Even-Odd pattern. If the smallest value is Odd then we have to print Odd-Even pattern. Note: No. of odd elements must be equal to No. of even elements in the input array.Examples: Input: arr[] = {1, 3, 2, 5, 4, 7, 10} Output: 1, 2, 3, 4, 5, 10, 7 Smallest value is 1(Odd) so output will be Odd-Even pattern.Input: arr[] = {9, 8, 13, 2, 19, 14} Output: 2, 9, 8, 13, 14, 19 Smallest value is 2(Even) so output will be Even-Odd pattern. Asked In: Microsoft Tech-Set-Go-2018 Algorithm: Sort the given array.Insert Even values in List-1 and Odd values in List-2.Now if the smallest value is even, then insert an even value from list 1 and odd value from list 2 to original array and so on.But if the smallest value is odd, then insert an odd value from list 2 and even value from list 1 to original array and so on. Sort the given array. Insert Even values in List-1 and Odd values in List-2. Now if the smallest value is even, then insert an even value from list 1 and odd value from list 2 to original array and so on. But if the smallest value is odd, then insert an odd value from list 2 and even value from list 1 to original array and so on. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; void AlternateRearrange(int arr[], int n){ // Sort the array sort(arr, arr + n); vector<int> v1; // to insert even values vector<int> v2; // to insert odd values for (int i = 0; i < n; i++) if (arr[i] % 2 == 0) v1.push_back(arr[i]); else v2.push_back(arr[i]); int index = 0, i = 0, j = 0; bool flag = false; // Set flag to true if first element is even if (arr[0] % 2 == 0) flag = true; // Start rearranging array while (index < n) { // If first element is even if (flag == true) { arr[index++] = v1[i++]; flag = !flag; } // Else, first element is Odd else { arr[index++] = v2[j++]; flag = !flag; } } // Print the rearranged array for (i = 0; i < n; i++) cout << arr[i] << " ";} // Driver codeint main(){ int arr[] = { 9, 8, 13, 2, 19, 14 }; int n = sizeof(arr) / sizeof(int); AlternateRearrange(arr, n); return 0;} // Java implementation of the above approach import java.util.* ; class GFG{ static void AlternateRearrange(int arr[], int n) { // Sort the array // Collection.sort() sorts the // collection in ascending order Arrays.sort(arr) ; Vector v1 = new Vector(); // to insert even values Vector v2 = new Vector(); // to insert odd values for (int i = 0; i < n; i++) if (arr[i] % 2 == 0) v1.add(arr[i]); else v2.add(arr[i]); int index = 0, i = 0, j = 0; boolean flag = false; // Set flag to true if first element is even if (arr[0] % 2 == 0) flag = true; // Start rearranging array while (index < n) { // If first element is even if (flag == true) { arr[index] = (int)v1.get(i); i += 1 ; index += 1 ; flag = !flag; } // Else, first element is Odd else { arr[index] = (int)v2.get(j) ; j += 1 ; index += 1 ; flag = !flag; } } // Print the rearranged array for (i = 0; i < n; i++) System.out.print(arr[i] + " "); } // Driver code public static void main(String []args) { int arr[] = { 9, 8, 13, 2, 19, 14 }; int n = arr.length ; AlternateRearrange(arr, n); }} // This code is contributed by aishwarya.27 # Python3 implementation of the above approachdef AlternateRearrange(arr, n): # Sort the array arr.sort() v1 = list() # to insert even values v2 = list() # to insert odd values for i in range(n): if (arr[i] % 2 == 0): v1.append(arr[i]) else: v2.append(arr[i]) index = 0 i = 0 j = 0 flag = False # Set flag to true if first element is even if (arr[0] % 2 == 0): flag = True # Start rearranging array while (index < n): # If first element is even if (flag == True and i < len(v1)): arr[index] = v1[i] index += 1 i += 1 flag = ~flag # Else, first element is Odd elif j < len(v2): arr[index] = v2[j] index += 1 j += 1 flag = ~flag # Print the rearranged array for i in range(n): print(arr[i], end=" ") # Driver codearr = [9, 8, 13, 2, 19, 14, 21, 23, 25]n = len(arr) AlternateRearrange(arr, n) # This code is contributed# by Mohit Kumar 29. // C# implementation of the above approach using System;using System.Collections;class GFG{ static void AlternateRearrange(int []arr, int n) { // Sort the array // Collection.sort() sorts the // collection in ascending order Array.Sort(arr) ; ArrayList v1 = new ArrayList(); // to insert even values ArrayList v2 = new ArrayList(); // to insert odd values for (int j = 0; j < n; j++) if (arr[j] % 2 == 0) v1.Add(arr[j]); else v2.Add(arr[j]); int index = 0, i = 0, k = 0; bool flag = false; // Set flag to true if first element is even if (arr[0] % 2 == 0) flag = true; // Start rearranging array while (index < n) { // If first element is even if (flag == true) { arr[index] = (int)v1[i]; i += 1 ; index += 1 ; flag = !flag; } // Else, first element is Odd else { arr[index] = (int)v2[k] ; k += 1 ; index += 1 ; flag = !flag; } } // Print the rearranged array for (i = 0; i < n; i++) Console.Write(arr[i] + " "); } // Driver code static void Main() { int []arr = { 9, 8, 13, 2, 19, 14 }; int n = arr.Length ; AlternateRearrange(arr, n); }} // This code is contributed by mits <?php// PHP implementation of the above approachfunction AlternateRearrange($arr, $n){ // Sort the array sort($arr); $v1 = array(); // to insert even values $v2 = array(); // to insert odd values for ($i = 0; $i < $n; $i++) if ($arr[$i] % 2 == 0) array_push($v1, $arr[$i]); else array_push($v2, $arr[$i]); $index = 0; $i = 0; $j = 0; $flag = false; // Set flag to true if first element is even if ($arr[0] % 2 == 0) $flag = true; // Start rearranging array while ($index < $n) { // If first element is even if ($flag == true) { $arr[$index++] = $v1[$i++]; $flag = !$flag; } // Else, first element is Odd else { $arr[$index++] = $v2[$j++]; $flag = !$flag; } } // Print the rearranged array for ($i = 0; $i < $n; $i++) echo $arr[$i], " " ;} // Driver code$arr = array( 9, 8, 13, 2, 19, 14 );$n = sizeof($arr); AlternateRearrange($arr, $n); // This code is contributed by Ryuga?> <script> // Javascript implementation of the above approach function AlternateRearrange(arr, n){ // Sort the array arr.sort((a,b)=>a-b); var v1 = []; // to insert even values var v2 = []; // to insert odd values for (var i = 0; i < n; i++) if (arr[i] % 2 == 0) v1.push(arr[i]); else v2.push(arr[i]); var index = 0, i = 0, j = 0; var flag = false; // Set flag to true if first element is even if (arr[0] % 2 == 0) flag = true; // Start rearranging array while (index < n) { // If first element is even if (flag == true) { arr[index++] = v1[i++]; flag = !flag; } // Else, first element is Odd else { arr[index++] = v2[j++]; flag = !flag; } } // Print the rearranged array for (i = 0; i < n; i++) document.write( arr[i] + " ");} // Driver codevar arr = [9, 8, 13, 2, 19, 14];var n = arr.length;AlternateRearrange(arr, n); </script> 2 9 8 13 14 19 Time Complexity: O(N * logN)Auxiliary Space: O(N) mohit kumar 29 ankthon aishwarya.27 Mithun Kumar famously pankajsharmagfg shubham suroshe array-rearrange cpp-vector Microsoft Algorithms Arrays Sorting Microsoft Arrays Sorting Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation What is Hashing | A Complete Tutorial Understanding Time Complexity with Simple Examples Find if there is a path between two vertices in an undirected graph Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Largest Sum Contiguous Subarray Arrays in C/C++
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Sep, 2021" }, { "code": null, "e": 244, "s": 52, "text": "Given an array of integers (both odd and even), the task is to arrange them in such a way that odd and even values come in alternate fashion in non-decreasing order(ascending) respectively. " }, { "code": null, "e": 314, "s": 244, "text": "If the smallest value is Even then we have to print Even-Odd pattern." }, { "code": null, "e": 383, "s": 314, "text": "If the smallest value is Odd then we have to print Odd-Even pattern." }, { "code": null, "e": 478, "s": 383, "text": "Note: No. of odd elements must be equal to No. of even elements in the input array.Examples: " }, { "code": null, "e": 732, "s": 478, "text": "Input: arr[] = {1, 3, 2, 5, 4, 7, 10} Output: 1, 2, 3, 4, 5, 10, 7 Smallest value is 1(Odd) so output will be Odd-Even pattern.Input: arr[] = {9, 8, 13, 2, 19, 14} Output: 2, 9, 8, 13, 14, 19 Smallest value is 2(Even) so output will be Even-Odd pattern." }, { "code": null, "e": 770, "s": 732, "text": "Asked In: Microsoft Tech-Set-Go-2018 " }, { "code": null, "e": 783, "s": 770, "text": "Algorithm: " }, { "code": null, "e": 1112, "s": 783, "text": "Sort the given array.Insert Even values in List-1 and Odd values in List-2.Now if the smallest value is even, then insert an even value from list 1 and odd value from list 2 to original array and so on.But if the smallest value is odd, then insert an odd value from list 2 and even value from list 1 to original array and so on." }, { "code": null, "e": 1134, "s": 1112, "text": "Sort the given array." }, { "code": null, "e": 1189, "s": 1134, "text": "Insert Even values in List-1 and Odd values in List-2." }, { "code": null, "e": 1317, "s": 1189, "text": "Now if the smallest value is even, then insert an even value from list 1 and odd value from list 2 to original array and so on." }, { "code": null, "e": 1444, "s": 1317, "text": "But if the smallest value is odd, then insert an odd value from list 2 and even value from list 1 to original array and so on." }, { "code": null, "e": 1497, "s": 1444, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1501, "s": 1497, "text": "C++" }, { "code": null, "e": 1506, "s": 1501, "text": "Java" }, { "code": null, "e": 1514, "s": 1506, "text": "Python3" }, { "code": null, "e": 1517, "s": 1514, "text": "C#" }, { "code": null, "e": 1521, "s": 1517, "text": "PHP" }, { "code": null, "e": 1532, "s": 1521, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; void AlternateRearrange(int arr[], int n){ // Sort the array sort(arr, arr + n); vector<int> v1; // to insert even values vector<int> v2; // to insert odd values for (int i = 0; i < n; i++) if (arr[i] % 2 == 0) v1.push_back(arr[i]); else v2.push_back(arr[i]); int index = 0, i = 0, j = 0; bool flag = false; // Set flag to true if first element is even if (arr[0] % 2 == 0) flag = true; // Start rearranging array while (index < n) { // If first element is even if (flag == true) { arr[index++] = v1[i++]; flag = !flag; } // Else, first element is Odd else { arr[index++] = v2[j++]; flag = !flag; } } // Print the rearranged array for (i = 0; i < n; i++) cout << arr[i] << \" \";} // Driver codeint main(){ int arr[] = { 9, 8, 13, 2, 19, 14 }; int n = sizeof(arr) / sizeof(int); AlternateRearrange(arr, n); return 0;}", "e": 2635, "s": 1532, "text": null }, { "code": "// Java implementation of the above approach import java.util.* ; class GFG{ static void AlternateRearrange(int arr[], int n) { // Sort the array // Collection.sort() sorts the // collection in ascending order Arrays.sort(arr) ; Vector v1 = new Vector(); // to insert even values Vector v2 = new Vector(); // to insert odd values for (int i = 0; i < n; i++) if (arr[i] % 2 == 0) v1.add(arr[i]); else v2.add(arr[i]); int index = 0, i = 0, j = 0; boolean flag = false; // Set flag to true if first element is even if (arr[0] % 2 == 0) flag = true; // Start rearranging array while (index < n) { // If first element is even if (flag == true) { arr[index] = (int)v1.get(i); i += 1 ; index += 1 ; flag = !flag; } // Else, first element is Odd else { arr[index] = (int)v2.get(j) ; j += 1 ; index += 1 ; flag = !flag; } } // Print the rearranged array for (i = 0; i < n; i++) System.out.print(arr[i] + \" \"); } // Driver code public static void main(String []args) { int arr[] = { 9, 8, 13, 2, 19, 14 }; int n = arr.length ; AlternateRearrange(arr, n); }} // This code is contributed by aishwarya.27", "e": 4239, "s": 2635, "text": null }, { "code": "# Python3 implementation of the above approachdef AlternateRearrange(arr, n): # Sort the array arr.sort() v1 = list() # to insert even values v2 = list() # to insert odd values for i in range(n): if (arr[i] % 2 == 0): v1.append(arr[i]) else: v2.append(arr[i]) index = 0 i = 0 j = 0 flag = False # Set flag to true if first element is even if (arr[0] % 2 == 0): flag = True # Start rearranging array while (index < n): # If first element is even if (flag == True and i < len(v1)): arr[index] = v1[i] index += 1 i += 1 flag = ~flag # Else, first element is Odd elif j < len(v2): arr[index] = v2[j] index += 1 j += 1 flag = ~flag # Print the rearranged array for i in range(n): print(arr[i], end=\" \") # Driver codearr = [9, 8, 13, 2, 19, 14, 21, 23, 25]n = len(arr) AlternateRearrange(arr, n) # This code is contributed# by Mohit Kumar 29.", "e": 5300, "s": 4239, "text": null }, { "code": "// C# implementation of the above approach using System;using System.Collections;class GFG{ static void AlternateRearrange(int []arr, int n) { // Sort the array // Collection.sort() sorts the // collection in ascending order Array.Sort(arr) ; ArrayList v1 = new ArrayList(); // to insert even values ArrayList v2 = new ArrayList(); // to insert odd values for (int j = 0; j < n; j++) if (arr[j] % 2 == 0) v1.Add(arr[j]); else v2.Add(arr[j]); int index = 0, i = 0, k = 0; bool flag = false; // Set flag to true if first element is even if (arr[0] % 2 == 0) flag = true; // Start rearranging array while (index < n) { // If first element is even if (flag == true) { arr[index] = (int)v1[i]; i += 1 ; index += 1 ; flag = !flag; } // Else, first element is Odd else { arr[index] = (int)v2[k] ; k += 1 ; index += 1 ; flag = !flag; } } // Print the rearranged array for (i = 0; i < n; i++) Console.Write(arr[i] + \" \"); } // Driver code static void Main() { int []arr = { 9, 8, 13, 2, 19, 14 }; int n = arr.Length ; AlternateRearrange(arr, n); }} // This code is contributed by mits", "e": 6888, "s": 5300, "text": null }, { "code": "<?php// PHP implementation of the above approachfunction AlternateRearrange($arr, $n){ // Sort the array sort($arr); $v1 = array(); // to insert even values $v2 = array(); // to insert odd values for ($i = 0; $i < $n; $i++) if ($arr[$i] % 2 == 0) array_push($v1, $arr[$i]); else array_push($v2, $arr[$i]); $index = 0; $i = 0; $j = 0; $flag = false; // Set flag to true if first element is even if ($arr[0] % 2 == 0) $flag = true; // Start rearranging array while ($index < $n) { // If first element is even if ($flag == true) { $arr[$index++] = $v1[$i++]; $flag = !$flag; } // Else, first element is Odd else { $arr[$index++] = $v2[$j++]; $flag = !$flag; } } // Print the rearranged array for ($i = 0; $i < $n; $i++) echo $arr[$i], \" \" ;} // Driver code$arr = array( 9, 8, 13, 2, 19, 14 );$n = sizeof($arr); AlternateRearrange($arr, $n); // This code is contributed by Ryuga?>", "e": 7976, "s": 6888, "text": null }, { "code": "<script> // Javascript implementation of the above approach function AlternateRearrange(arr, n){ // Sort the array arr.sort((a,b)=>a-b); var v1 = []; // to insert even values var v2 = []; // to insert odd values for (var i = 0; i < n; i++) if (arr[i] % 2 == 0) v1.push(arr[i]); else v2.push(arr[i]); var index = 0, i = 0, j = 0; var flag = false; // Set flag to true if first element is even if (arr[0] % 2 == 0) flag = true; // Start rearranging array while (index < n) { // If first element is even if (flag == true) { arr[index++] = v1[i++]; flag = !flag; } // Else, first element is Odd else { arr[index++] = v2[j++]; flag = !flag; } } // Print the rearranged array for (i = 0; i < n; i++) document.write( arr[i] + \" \");} // Driver codevar arr = [9, 8, 13, 2, 19, 14];var n = arr.length;AlternateRearrange(arr, n); </script>", "e": 8992, "s": 7976, "text": null }, { "code": null, "e": 9007, "s": 8992, "text": "2 9 8 13 14 19" }, { "code": null, "e": 9059, "s": 9009, "text": "Time Complexity: O(N * logN)Auxiliary Space: O(N)" }, { "code": null, "e": 9074, "s": 9059, "text": "mohit kumar 29" }, { "code": null, "e": 9082, "s": 9074, "text": "ankthon" }, { "code": null, "e": 9095, "s": 9082, "text": "aishwarya.27" }, { "code": null, "e": 9108, "s": 9095, "text": "Mithun Kumar" }, { "code": null, "e": 9117, "s": 9108, "text": "famously" }, { "code": null, "e": 9133, "s": 9117, "text": "pankajsharmagfg" }, { "code": null, "e": 9149, "s": 9133, "text": "shubham suroshe" }, { "code": null, "e": 9165, "s": 9149, "text": "array-rearrange" }, { "code": null, "e": 9176, "s": 9165, "text": "cpp-vector" }, { "code": null, "e": 9186, "s": 9176, "text": "Microsoft" }, { "code": null, "e": 9197, "s": 9186, "text": "Algorithms" }, { "code": null, "e": 9204, "s": 9197, "text": "Arrays" }, { "code": null, "e": 9212, "s": 9204, "text": "Sorting" }, { "code": null, "e": 9222, "s": 9212, "text": "Microsoft" }, { "code": null, "e": 9229, "s": 9222, "text": "Arrays" }, { "code": null, "e": 9237, "s": 9229, "text": "Sorting" }, { "code": null, "e": 9248, "s": 9237, "text": "Algorithms" }, { "code": null, "e": 9346, "s": 9248, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9371, "s": 9346, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 9420, "s": 9371, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 9458, "s": 9420, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 9509, "s": 9458, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 9577, "s": 9509, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 9592, "s": 9577, "text": "Arrays in Java" }, { "code": null, "e": 9638, "s": 9592, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 9706, "s": 9638, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 9738, "s": 9706, "text": "Largest Sum Contiguous Subarray" } ]
How to Scrape Web Data from Google using Python?
29 Dec, 2020 Prerequisites: Python Requests, Implementing Web Scraping in Python with BeautifulSoup Web scraping is a technique to fetch data from websites. While surfing on the web, many websites don’t allow the user to save data for personal use. One way is to manually copy-paste the data, which both tedious and time-consuming. Web Scraping is the automation of the data extraction process from websites. In this article, we will scrape the weather update from google’s search result. Modules Requisred BeautifulSoup: This module is used for iterating, searching, and modifying the parse tree over the HTML or XML parser. To download it type the below command in the terminal.pip install beautifulsoup4 pip install beautifulsoup4 Requests: Requests library is one of the integral part of Python for making HTTP requests to a specified URL. To download it type the below command in the terminal.pip install requests pip install requests Below is the implementation. import requestsfrom bs4 import BeautifulSoup # Enter the City Namecity = input("Enter the City Name: ")search = "Weather in {}".format(city) # URL url = f"https://www.google.com / search?&q ={search}" # Sending HTTP requestreq = requests.get(url) # Pulling HTTP data from internetsor = BeautifulSoup(req.text, "html.parser") # Finding temperature in Celsiustemp = sor.find("div", class_='BNeawe').text print(temp) Output : Python web-scraping-exercises Python-requests Web-scraping Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON
[ { "code": null, "e": 53, "s": 25, "text": "\n29 Dec, 2020" }, { "code": null, "e": 140, "s": 53, "text": "Prerequisites: Python Requests, Implementing Web Scraping in Python with BeautifulSoup" }, { "code": null, "e": 449, "s": 140, "text": "Web scraping is a technique to fetch data from websites. While surfing on the web, many websites don’t allow the user to save data for personal use. One way is to manually copy-paste the data, which both tedious and time-consuming. Web Scraping is the automation of the data extraction process from websites." }, { "code": null, "e": 529, "s": 449, "text": "In this article, we will scrape the weather update from google’s search result." }, { "code": null, "e": 547, "s": 529, "text": "Modules Requisred" }, { "code": null, "e": 747, "s": 547, "text": "BeautifulSoup: This module is used for iterating, searching, and modifying the parse tree over the HTML or XML parser. To download it type the below command in the terminal.pip install beautifulsoup4" }, { "code": null, "e": 774, "s": 747, "text": "pip install beautifulsoup4" }, { "code": null, "e": 959, "s": 774, "text": "Requests: Requests library is one of the integral part of Python for making HTTP requests to a specified URL. To download it type the below command in the terminal.pip install requests" }, { "code": null, "e": 980, "s": 959, "text": "pip install requests" }, { "code": null, "e": 1009, "s": 980, "text": "Below is the implementation." }, { "code": "import requestsfrom bs4 import BeautifulSoup # Enter the City Namecity = input(\"Enter the City Name: \")search = \"Weather in {}\".format(city) # URL url = f\"https://www.google.com / search?&q ={search}\" # Sending HTTP requestreq = requests.get(url) # Pulling HTTP data from internetsor = BeautifulSoup(req.text, \"html.parser\") # Finding temperature in Celsiustemp = sor.find(\"div\", class_='BNeawe').text print(temp)", "e": 1433, "s": 1009, "text": null }, { "code": null, "e": 1442, "s": 1433, "text": "Output :" }, { "code": null, "e": 1472, "s": 1442, "text": "Python web-scraping-exercises" }, { "code": null, "e": 1488, "s": 1472, "text": "Python-requests" }, { "code": null, "e": 1501, "s": 1488, "text": "Web-scraping" }, { "code": null, "e": 1508, "s": 1501, "text": "Python" }, { "code": null, "e": 1606, "s": 1508, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1624, "s": 1606, "text": "Python Dictionary" }, { "code": null, "e": 1666, "s": 1624, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1688, "s": 1666, "text": "Enumerate() in Python" }, { "code": null, "e": 1714, "s": 1688, "text": "Python String | replace()" }, { "code": null, "e": 1746, "s": 1714, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1775, "s": 1746, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1802, "s": 1775, "text": "Python Classes and Objects" }, { "code": null, "e": 1823, "s": 1802, "text": "Python OOPs Concepts" }, { "code": null, "e": 1859, "s": 1823, "text": "Convert integer to string in Python" } ]
Zero-day Exploit (Cyber Security Attack)
29 Jun, 2022 In this IT era, majority of the cyberspaces are vulnerable to different kinds of attacks. Zero-day exploit is a type of cyber security attack that occur on the same day the software, hardware or firmware flaw is detected by the manufacturer. As it’s been zero days since the security flaw was last exploit, the attack is termed as zero-day exploit or zero-day attack. This kind of cyber-attacks are considered dangerous because the developer have not had the chance to fix the flaw yet. Zero-day exploit typically targets large organizations, government departments, firmware, hardware devices, IoT, users having access to valuable business data, etc. Working of Zero-day Exploit: A software is developed and released without knowing the fact that it has a security vulnerability. An attacker identifies or exploits this vulnerability before the developers identifies or fixes the same. While still the vulnerability is open and unpatched, exploiting the vulnerability, the hacker attacks and compromises the software which can lead to data theft, unauthorized access or crashing of the software itself. After the attacker attacks the target, the public or developer identifies the attack and tries to figure out the patch. The developer identifies the fix and releases the update to safe guard its new user. Zero-day Exploit Detection: Probability of detecting zero day exploit is rare or in other words, the attack leaves no opportunity for detection. But there are a few ways to identify the existing known vulnerabilities. Signature Based – In this method, the occurrence pattern of known vulnerability can be detected with the help of pattern matching. Even though this method cannot detect the malware code used for zero-day exploit, it is capable of detecting known attacks like SQL injection that may lead to zero-day vulnerability. While a developer may not be able to detect zero-day attack, the system firewall may be able to detect and protect against few known specific attack types such as XSS , SQL injection, etc.Statistical Techniques – By monitoring the normal activity, this technique learns the normal behavior of the network. When the system identifies any deviation from normal profile it will detect a probability of vulnerability.Behavior Based – The implementation of behavior based detection typically depends on a ‘honeypot’. A honeypot is a security mechanism that is developed to detect the presence of hackers or hacking attempts.Hybrid Techniques – This hybrid technique use the advantage of statistical, behavioral and traditional signature based defense mechanism. They are comparatively more effective as the weaknesses of any single detection technique will not break the security. Signature Based – In this method, the occurrence pattern of known vulnerability can be detected with the help of pattern matching. Even though this method cannot detect the malware code used for zero-day exploit, it is capable of detecting known attacks like SQL injection that may lead to zero-day vulnerability. While a developer may not be able to detect zero-day attack, the system firewall may be able to detect and protect against few known specific attack types such as XSS , SQL injection, etc. Statistical Techniques – By monitoring the normal activity, this technique learns the normal behavior of the network. When the system identifies any deviation from normal profile it will detect a probability of vulnerability. Behavior Based – The implementation of behavior based detection typically depends on a ‘honeypot’. A honeypot is a security mechanism that is developed to detect the presence of hackers or hacking attempts. Hybrid Techniques – This hybrid technique use the advantage of statistical, behavioral and traditional signature based defense mechanism. They are comparatively more effective as the weaknesses of any single detection technique will not break the security. Zero-day Exploit Prevention : As zero-day exploits cannot be easily discovered, prevention of the zero-day exploit becomes difficult. There is hardly any ways to protect against zero-day exploit as we don’t have any idea about its occurrence well in advance. We can reduce the level of risk opting any of the following strategies: Implementation of IP security protocol ( IPSec). Usage of virtual local area networks. Deployment of intrusion detection system (IDS) or intrusion prevention system (IPS). Usage of network access control protocols. Usage of security schemes such as Wi-Fi Protected Access 2. Keeping all systems up to date. Performing periodic vulnerability scanning. Example Cases of Zero-day Exploit : CVE-2016-4117 – This zero-day attack exploited one of the previously undiscovered flaws in Adobe Flash Player. CVE-2016-0167 – This is a privilege escalation attack targeting win32k Windows Graphics subsystem Microsoft Windows. CVE-2017-0199 – This zero-day attack exploited one of the previously undisclosed vulnerability in Microsoft Office RTF documents. Stuxnet worm – This zero-day exploit targeted supervisory control and data acquisition (SCADA) systems. sahithya3chow rkbhola5 Cyber-security Network-security Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Wireless Application Protocol GSM in Wireless Communication Secure Socket Layer (SSL) Mobile Internet Protocol (or Mobile IP) Advanced Encryption Standard (AES) Introduction of Mobile Ad hoc Network (MANET) Cryptography and its Types Dynamic Host Configuration Protocol (DHCP) Difference between MANET and VANET Difference between FDMA, TDMA and CDMA
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jun, 2022" }, { "code": null, "e": 119, "s": 28, "text": "In this IT era, majority of the cyberspaces are vulnerable to different kinds of attacks. " }, { "code": null, "e": 682, "s": 119, "text": "Zero-day exploit is a type of cyber security attack that occur on the same day the software, hardware or firmware flaw is detected by the manufacturer. As it’s been zero days since the security flaw was last exploit, the attack is termed as zero-day exploit or zero-day attack. This kind of cyber-attacks are considered dangerous because the developer have not had the chance to fix the flaw yet. Zero-day exploit typically targets large organizations, government departments, firmware, hardware devices, IoT, users having access to valuable business data, etc. " }, { "code": null, "e": 712, "s": 682, "text": "Working of Zero-day Exploit: " }, { "code": null, "e": 1340, "s": 712, "text": "A software is developed and released without knowing the fact that it has a security vulnerability. An attacker identifies or exploits this vulnerability before the developers identifies or fixes the same. While still the vulnerability is open and unpatched, exploiting the vulnerability, the hacker attacks and compromises the software which can lead to data theft, unauthorized access or crashing of the software itself. After the attacker attacks the target, the public or developer identifies the attack and tries to figure out the patch. The developer identifies the fix and releases the update to safe guard its new user." }, { "code": null, "e": 1372, "s": 1343, "text": "Zero-day Exploit Detection: " }, { "code": null, "e": 1562, "s": 1372, "text": "Probability of detecting zero day exploit is rare or in other words, the attack leaves no opportunity for detection. But there are a few ways to identify the existing known vulnerabilities." }, { "code": null, "e": 2752, "s": 1562, "text": "Signature Based – In this method, the occurrence pattern of known vulnerability can be detected with the help of pattern matching. Even though this method cannot detect the malware code used for zero-day exploit, it is capable of detecting known attacks like SQL injection that may lead to zero-day vulnerability. While a developer may not be able to detect zero-day attack, the system firewall may be able to detect and protect against few known specific attack types such as XSS , SQL injection, etc.Statistical Techniques – By monitoring the normal activity, this technique learns the normal behavior of the network. When the system identifies any deviation from normal profile it will detect a probability of vulnerability.Behavior Based – The implementation of behavior based detection typically depends on a ‘honeypot’. A honeypot is a security mechanism that is developed to detect the presence of hackers or hacking attempts.Hybrid Techniques – This hybrid technique use the advantage of statistical, behavioral and traditional signature based defense mechanism. They are comparatively more effective as the weaknesses of any single detection technique will not break the security." }, { "code": null, "e": 3255, "s": 2752, "text": "Signature Based – In this method, the occurrence pattern of known vulnerability can be detected with the help of pattern matching. Even though this method cannot detect the malware code used for zero-day exploit, it is capable of detecting known attacks like SQL injection that may lead to zero-day vulnerability. While a developer may not be able to detect zero-day attack, the system firewall may be able to detect and protect against few known specific attack types such as XSS , SQL injection, etc." }, { "code": null, "e": 3481, "s": 3255, "text": "Statistical Techniques – By monitoring the normal activity, this technique learns the normal behavior of the network. When the system identifies any deviation from normal profile it will detect a probability of vulnerability." }, { "code": null, "e": 3688, "s": 3481, "text": "Behavior Based – The implementation of behavior based detection typically depends on a ‘honeypot’. A honeypot is a security mechanism that is developed to detect the presence of hackers or hacking attempts." }, { "code": null, "e": 3945, "s": 3688, "text": "Hybrid Techniques – This hybrid technique use the advantage of statistical, behavioral and traditional signature based defense mechanism. They are comparatively more effective as the weaknesses of any single detection technique will not break the security." }, { "code": null, "e": 4276, "s": 3945, "text": "Zero-day Exploit Prevention : As zero-day exploits cannot be easily discovered, prevention of the zero-day exploit becomes difficult. There is hardly any ways to protect against zero-day exploit as we don’t have any idea about its occurrence well in advance. We can reduce the level of risk opting any of the following strategies:" }, { "code": null, "e": 4325, "s": 4276, "text": "Implementation of IP security protocol ( IPSec)." }, { "code": null, "e": 4363, "s": 4325, "text": "Usage of virtual local area networks." }, { "code": null, "e": 4448, "s": 4363, "text": "Deployment of intrusion detection system (IDS) or intrusion prevention system (IPS)." }, { "code": null, "e": 4491, "s": 4448, "text": "Usage of network access control protocols." }, { "code": null, "e": 4551, "s": 4491, "text": "Usage of security schemes such as Wi-Fi Protected Access 2." }, { "code": null, "e": 4583, "s": 4551, "text": "Keeping all systems up to date." }, { "code": null, "e": 4627, "s": 4583, "text": "Performing periodic vulnerability scanning." }, { "code": null, "e": 4663, "s": 4627, "text": "Example Cases of Zero-day Exploit :" }, { "code": null, "e": 4774, "s": 4663, "text": "CVE-2016-4117 – This zero-day attack exploited one of the previously undiscovered flaws in Adobe Flash Player." }, { "code": null, "e": 4891, "s": 4774, "text": "CVE-2016-0167 – This is a privilege escalation attack targeting win32k Windows Graphics subsystem Microsoft Windows." }, { "code": null, "e": 5021, "s": 4891, "text": "CVE-2017-0199 – This zero-day attack exploited one of the previously undisclosed vulnerability in Microsoft Office RTF documents." }, { "code": null, "e": 5125, "s": 5021, "text": "Stuxnet worm – This zero-day exploit targeted supervisory control and data acquisition (SCADA) systems." }, { "code": null, "e": 5139, "s": 5125, "text": "sahithya3chow" }, { "code": null, "e": 5148, "s": 5139, "text": "rkbhola5" }, { "code": null, "e": 5163, "s": 5148, "text": "Cyber-security" }, { "code": null, "e": 5180, "s": 5163, "text": "Network-security" }, { "code": null, "e": 5198, "s": 5180, "text": "Computer Networks" }, { "code": null, "e": 5216, "s": 5198, "text": "Computer Networks" }, { "code": null, "e": 5314, "s": 5216, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5344, "s": 5314, "text": "Wireless Application Protocol" }, { "code": null, "e": 5374, "s": 5344, "text": "GSM in Wireless Communication" }, { "code": null, "e": 5400, "s": 5374, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 5440, "s": 5400, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 5475, "s": 5440, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 5521, "s": 5475, "text": "Introduction of Mobile Ad hoc Network (MANET)" }, { "code": null, "e": 5548, "s": 5521, "text": "Cryptography and its Types" }, { "code": null, "e": 5591, "s": 5548, "text": "Dynamic Host Configuration Protocol (DHCP)" }, { "code": null, "e": 5626, "s": 5591, "text": "Difference between MANET and VANET" } ]
Python | Count occurrences of a character in string
22 Nov, 2018 Given a string, the task is to count the frequency of a single character in that string. This particular operation on string is quite useful in many applications such as removing duplicates or detecting unwanted characters. Method #1 : Naive method Iterate the entire string for that particular character and then increase the counter when we encounter the particular character. # Python3 code to demonstrate # occurrence frequency using # naive method # initializing string test_str = "GeeksforGeeks" # using naive method to get count # counting e count = 0 for i in test_str: if i == 'e': count = count + 1 # printing result print ("Count of e in GeeksforGeeks is : " + str(count)) Output : Count of e in GeeksforGeeks is : 4 Method #2 : Using count() Using count() is the most conventional method in Python to get the occurrence of any element in any container. This is easy to code and remember and hence quite popular. # Python3 code to demonstrate # occurrence frequency using # count() # initializing string test_str = "GeeksforGeeks" # using count() to get count # counting e counter = test_str.count('e') # printing result print ("Count of e in GeeksforGeeks is : " + str(counter)) Output : Count of e in GeeksforGeeks is : 4 Method #3 : Using collections.Counter() This is the lesser known method to get the occurrence of the element across any container in Python. This also performs the task similar to above two method, just is a function of a different library i.e collections. # Python3 code to demonstrate # occurrence frequency using # collections.Counter()from collections import Counter # initializing string test_str = "GeeksforGeeks" # using collections.Counter() to get count # counting e count = Counter(test_str) # printing result print ("Count of e in GeeksforGeeks is : " + str(count['e'])) Output : Count of e in GeeksforGeeks is : 4 Method #4 : Using lambda + sum() + map() Lambda functions, along with sum() and map() can achieve this particular task of counting the total occurrences of particular element in a string. This uses sum() to sum up all the occurrences obtained using map(). # Python3 code to demonstrate # occurrence frequency using # lambda + sum() + map() # initializing string test_str = "GeeksforGeeks" # using lambda + sum() + map() to get count # counting e count = sum(map(lambda x : 1 if 'e' in x else 0, test_str)) # printing result print ("Count of e in GeeksforGeeks is : " + str(count)) Output : Count of e in GeeksforGeeks is : 4 Method #5 : Using re + findall() Regular Expressions can help us to achieve many coding tasks related to strings. They can also facilitate us in achieving the task of finding the occurrence of element in string. # Python3 code to demonstrate # occurrence frequency using # re + findall()import re # initializing string test_str = "GeeksforGeeks" # using re + findall() to get count # counting e count = len(re.findall("e", test_str)) # printing result print ("Count of e in GeeksforGeeks is : " + str(count)) Output : Count of e in GeeksforGeeks is : 4 Python string-programs python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python | os.path.join() method Create a Pandas DataFrame from Lists Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python OOPs Concepts How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Nov, 2018" }, { "code": null, "e": 276, "s": 52, "text": "Given a string, the task is to count the frequency of a single character in that string. This particular operation on string is quite useful in many applications such as removing duplicates or detecting unwanted characters." }, { "code": null, "e": 301, "s": 276, "text": "Method #1 : Naive method" }, { "code": null, "e": 431, "s": 301, "text": "Iterate the entire string for that particular character and then increase the counter when we encounter the particular character." }, { "code": "# Python3 code to demonstrate # occurrence frequency using # naive method # initializing string test_str = \"GeeksforGeeks\" # using naive method to get count # counting e count = 0 for i in test_str: if i == 'e': count = count + 1 # printing result print (\"Count of e in GeeksforGeeks is : \" + str(count))", "e": 779, "s": 431, "text": null }, { "code": null, "e": 788, "s": 779, "text": "Output :" }, { "code": null, "e": 823, "s": 788, "text": "Count of e in GeeksforGeeks is : 4" }, { "code": null, "e": 851, "s": 825, "text": "Method #2 : Using count()" }, { "code": null, "e": 1021, "s": 851, "text": "Using count() is the most conventional method in Python to get the occurrence of any element in any container. This is easy to code and remember and hence quite popular." }, { "code": "# Python3 code to demonstrate # occurrence frequency using # count() # initializing string test_str = \"GeeksforGeeks\" # using count() to get count # counting e counter = test_str.count('e') # printing result print (\"Count of e in GeeksforGeeks is : \" + str(counter))", "e": 1318, "s": 1021, "text": null }, { "code": null, "e": 1327, "s": 1318, "text": "Output :" }, { "code": null, "e": 1363, "s": 1327, "text": "Count of e in GeeksforGeeks is : 4\n" }, { "code": null, "e": 1405, "s": 1365, "text": "Method #3 : Using collections.Counter()" }, { "code": null, "e": 1622, "s": 1405, "text": "This is the lesser known method to get the occurrence of the element across any container in Python. This also performs the task similar to above two method, just is a function of a different library i.e collections." }, { "code": "# Python3 code to demonstrate # occurrence frequency using # collections.Counter()from collections import Counter # initializing string test_str = \"GeeksforGeeks\" # using collections.Counter() to get count # counting e count = Counter(test_str) # printing result print (\"Count of e in GeeksforGeeks is : \" + str(count['e']))", "e": 1973, "s": 1622, "text": null }, { "code": null, "e": 1982, "s": 1973, "text": "Output :" }, { "code": null, "e": 2018, "s": 1982, "text": "Count of e in GeeksforGeeks is : 4\n" }, { "code": null, "e": 2061, "s": 2020, "text": "Method #4 : Using lambda + sum() + map()" }, { "code": null, "e": 2276, "s": 2061, "text": "Lambda functions, along with sum() and map() can achieve this particular task of counting the total occurrences of particular element in a string. This uses sum() to sum up all the occurrences obtained using map()." }, { "code": "# Python3 code to demonstrate # occurrence frequency using # lambda + sum() + map() # initializing string test_str = \"GeeksforGeeks\" # using lambda + sum() + map() to get count # counting e count = sum(map(lambda x : 1 if 'e' in x else 0, test_str)) # printing result print (\"Count of e in GeeksforGeeks is : \" + str(count))", "e": 2632, "s": 2276, "text": null }, { "code": null, "e": 2641, "s": 2632, "text": "Output :" }, { "code": null, "e": 2677, "s": 2641, "text": "Count of e in GeeksforGeeks is : 4\n" }, { "code": null, "e": 2711, "s": 2677, "text": " Method #5 : Using re + findall()" }, { "code": null, "e": 2890, "s": 2711, "text": "Regular Expressions can help us to achieve many coding tasks related to strings. They can also facilitate us in achieving the task of finding the occurrence of element in string." }, { "code": "# Python3 code to demonstrate # occurrence frequency using # re + findall()import re # initializing string test_str = \"GeeksforGeeks\" # using re + findall() to get count # counting e count = len(re.findall(\"e\", test_str)) # printing result print (\"Count of e in GeeksforGeeks is : \" + str(count))", "e": 3218, "s": 2890, "text": null }, { "code": null, "e": 3227, "s": 3218, "text": "Output :" }, { "code": null, "e": 3263, "s": 3227, "text": "Count of e in GeeksforGeeks is : 4\n" }, { "code": null, "e": 3286, "s": 3263, "text": "Python string-programs" }, { "code": null, "e": 3300, "s": 3286, "text": "python-string" }, { "code": null, "e": 3307, "s": 3300, "text": "Python" }, { "code": null, "e": 3405, "s": 3307, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3437, "s": 3405, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3466, "s": 3437, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3493, "s": 3466, "text": "Python Classes and Objects" }, { "code": null, "e": 3529, "s": 3493, "text": "Convert integer to string in Python" }, { "code": null, "e": 3560, "s": 3529, "text": "Python | os.path.join() method" }, { "code": null, "e": 3597, "s": 3560, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 3620, "s": 3597, "text": "Introduction To PYTHON" }, { "code": null, "e": 3676, "s": 3620, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3697, "s": 3676, "text": "Python OOPs Concepts" } ]
Prolog - Inputs and Outputs
In this chapter, we will see some techniques to handle inputs and outputs through prolog. We will use some built in predicates to do these tasks, and also see file handling techniques. Following topics will be discussed in detail − Handling inputs and outputs Handling inputs and outputs File handling using Prolog File handling using Prolog Using some external file to read lines and terms Using some external file to read lines and terms Character manipulation for input and output Character manipulation for input and output Constructing and decomposing atoms Constructing and decomposing atoms Consulting prolog files into other prolog program techniques. Consulting prolog files into other prolog program techniques. So far we have seen that we can write a program and the query on the console to execute. In some cases, we print something on the console, that are written in our prolog code. So here we will see that writing and reading tasks in more detail using prolog. So this will be the input and output handling techniques. To write the output we can use the write() predicate. This predicate takes the parameter as input, and writes the content into the console by default. write() can also write in files. Let us see some examples of write() function. | ?- write(56). 56 yes | ?- write('hello'). hello yes | ?- write('hello'),nl,write('world'). hello world yes | ?- write("ABCDE") . [65,66,67,68,69] yes From the above example, we can see that the write() predicate can write the contents into the console. We can use ’nl’ to create a new line. And from this example, it is clear that, if we want to print some string on the console, we have to use single quotes (‘string‘). But if we use double quote (“string”), then it will return a list of ASCII values. The read() predicate is used to read from console. User can write something in the console, that can be taken as input and process it. The read() is generally used to read from console, but this can also be used to read from files. Now let us see one example to see how read() works. cube :- write('Write a number: '), read(Number), process(Number). process(stop) :- !. process(Number) :- C is Number * Number * Number, write('Cube of '),write(Number),write(': '),write(C),nl, cube. | ?- [read_write]. compiling D:/TP Prolog/Sample_Codes/read_write.pl for byte code... D:/TP Prolog/Sample_Codes/read_write.pl compiled, 9 lines read - 1226 bytes written, 12 ms (15 ms) yes | ?- cube. Write a number: 2. Cube of 2: 8 Write a number: 10. Cube of 10: 1000 Write a number: 12. Cube of 12: 1728 Write a number: 8. Cube of 8: 512 Write a number: stop . (31 ms) yes | ?- The tab() is one additional predicate that can be used to put some blank-spaces while we write something. So it takes a number as an argument, and prints those many number of blank spaces. | ?- write('hello'),tab(15),write('world'). hello world yes | ?- write('We'),tab(5),write('will'),tab(5),write('use'),tab(5),write('tabs'). We will use tabs yes | ?- In this section, we will see how we can use files to read from, and write into the files. There are some built-in predicates, that can be used to read from file and write into it. If we want to write into a file, except the console, we can write the tell() predicate. This tell()predicate takes filename as argument. If that file is not present, then create a new file, and write into it. That file will be opened until we write the told command. We can open more than one file using tell(). When told is called, all files will be closed. | ?- told('myFile.txt'). uncaught exception: error(existence_error(procedure,told/1),top_level/0) | ?- told("myFile.txt"). uncaught exception: error(existence_error(procedure,told/1),top_level/0) | ?- tell('myFile.txt'). yes | ?- tell('myFile.txt'). yes | ?- write('Hello World'). yes | ?- write(' Writing into a file'),tab(5),write('myFile.txt'),nl. yes | ?- write("Write some ASCII values"). yes | ?- told. yes | ?- Hello World Writing into a file myFile.txt [87,114,105,116,101,32,115,111,109,101,32,65,83,67,73,73,32,118,97,108,117,101,115] Similarly, we can also read from files. Let us see some example of reading from file. When we want to read from file, not from the keyboard, we have to change current input stream. So we can use see() predicate. This will take filename as input. When the read operation is completed, then we will use seen command. likes(lili, cat). likes(jhon,dog). | ?- see('sample_predicate.txt'), read(X), read(Y), seen, read(Z). the_end. X = end_of_file Y = end_of_file Z = the_end yes | ?- So from this example, we can see that using the see() predicate we can read from the file. Now after using seen command, the control transfers to the console again. So finally it takes input from console. We have seen how to read specific contents (few lines) of a file. Now if we want to read/process all the contents of a file, we need to write a clause to process file (process_file), until we reach the end of the file. process_file :- read(Line), Line \== end_of_file, % when Line is not not end of file, call process. process(Line). process_file :- !. % use cut to stop backtracking process(Line):- %this will print the line into the console write(Line),nl, process_file. likes(lili, cat). likes(jhon,dog). domestic(dog). domestic(cat). | ?- [process_file]. compiling D:/TP Prolog/Sample_Codes/process_file.pl for byte code... D:/TP Prolog/Sample_Codes/process_file.pl compiled, 9 lines read - 774 bytes written, 23 ms yes | ?- see('sample_predicate.txt'), process_file, seen. likes(lili,cat) likes(jhon,dog) domestic(dog) domestic(cat) true ? (15 ms) yes | ?- Using read() and write() we can read or write the value of atoms, predicates, strings, etc. Now in this section we will see how to write single characters into the current output stream, or how to read from current input stream. So there are some predefined predicates to do these tasks. We can use put(C) to write one character at a time into the current output stream. The output stream can be a file or the console. This C can be a character or an ASCII code in other version of Prolog like SWI prolog, but in GNU prolog, it supports only the ASCII value. To use the character instead of ASCII, we can use put_char(C). | ?- put(97),put(98),put(99),put(100),put(101). abcde yes | ?- put(97),put(66),put(99),put(100),put(101). aBcde (15 ms) yes | ?- put(65),put(66),put(99),put(100),put(101). ABcde yes | ?-put_char('h'),put_char('e'),put_char('l'),put_char('l'),put_char('o'). hello yes | ?- To read a single character from the current input stream, we can use the get_char(C) predicate. This will take the character. if we want the ASCII code, we can use get_code(C). | ?- get_char(X). A. X = 'A' yes uncaught exception: error(syntax_error('user_input:6 (char:689) expression expected'),read_term/3) | ?- get_code(X). A. X = 65 yes uncaught exception: error(syntax_error('user_input:7 (char:14) expression expected'),read_term/3) | ?- The atom constructing means from a list of characters, we can make one atom, or from a list of ASCII values also we can make atoms. To do this, we have to use atom_chars() and atom_codes() predicates. In both cases, the first argument will be one variable, and the second argument will be a list. So atom_chars() constructs atom from characters, but atom_codes() construct atoms from ASCII sequence. | ?- atom_chars(X, ['t','i','g','e','r']). X = tiger yes | ?- atom_chars(A, ['t','o','m']). A = tom yes | ?- atom_codes(X, [97,98,99,100,101]). X = abcde yes | ?- atom_codes(A, [97,98,99]). A = abc yes | ?- The atom decomposing means from an atom, we can get a sequence of characters, or a sequence ASCII codes. To do this, we have to use the same atom_chars() and atom_codes() predicates. But one difference is that, in both cases, the first argument will be one atom, and the second argument will be a variable. So atom_chars() decomposes atom to characters, but atom_codes() decomposes atoms to ASCII sequence. | ?- atom_chars(tiger,X). X = [t,i,g,e,r] yes | ?- atom_chars(tom,A). A = [t,o,m] yes | ?- atom_codes(tiger,X). X = [116,105,103,101,114] yes | ?- atom_codes(tom,A). A = [116,111,109] (16 ms) yes | ?- The consulting is a technique, that is used to merge the predicates from different files. We can use the consult() predicate, and pass the filename to attach the predicates. Let us see one example program to understand this concept. Suppose we have two files, namely, prog1.pl and prog2.pl. likes(mary,cat). likes(joy,rabbit). likes(tim,duck). likes(suman,mouse). likes(angshu,deer). | ?- [prog1]. compiling D:/TP Prolog/Sample_Codes/prog1.pl for byte code... D:/TP Prolog/Sample_Codes/prog1.pl compiled, 2 lines read - 443 bytes written, 23 ms yes | ?- likes(joy,rabbit). yes | ?- likes(suman,mouse). no | ?- consult('prog2.pl'). compiling D:/TP Prolog/Sample_Codes/prog2.pl for byte code... D:/TP Prolog/Sample_Codes/prog2.pl compiled, 1 lines read - 366 bytes written, 20 ms warning: D:/TP Prolog/Sample_Codes/prog2.pl:1: redefining procedure likes/2 D:/TP Prolog/Sample_Codes/prog1.pl:1: previous definition yes | ?- likes(suman,mouse). yes | ?- likes(joy,rabbit). no | ?- Now from this output we can understand that this is not as simple as it seems. If two files have completely different clauses, then it will work fine. But if there are same predicates, then while we try to consult the file, it will check the predicates from the second file, when it finds some match, it simply deletes all of the entry of the same predicates from the local database, then load them again from the second file.
[ { "code": null, "e": 2411, "s": 2226, "text": "In this chapter, we will see some techniques to handle inputs and outputs through prolog. We will use some built in predicates to do these tasks, and also see file handling techniques." }, { "code": null, "e": 2458, "s": 2411, "text": "Following topics will be discussed in detail −" }, { "code": null, "e": 2486, "s": 2458, "text": "Handling inputs and outputs" }, { "code": null, "e": 2514, "s": 2486, "text": "Handling inputs and outputs" }, { "code": null, "e": 2541, "s": 2514, "text": "File handling using Prolog" }, { "code": null, "e": 2568, "s": 2541, "text": "File handling using Prolog" }, { "code": null, "e": 2617, "s": 2568, "text": "Using some external file to read lines and terms" }, { "code": null, "e": 2666, "s": 2617, "text": "Using some external file to read lines and terms" }, { "code": null, "e": 2710, "s": 2666, "text": "Character manipulation for input and output" }, { "code": null, "e": 2754, "s": 2710, "text": "Character manipulation for input and output" }, { "code": null, "e": 2789, "s": 2754, "text": "Constructing and decomposing atoms" }, { "code": null, "e": 2824, "s": 2789, "text": "Constructing and decomposing atoms" }, { "code": null, "e": 2886, "s": 2824, "text": "Consulting prolog files into other prolog program techniques." }, { "code": null, "e": 2948, "s": 2886, "text": "Consulting prolog files into other prolog program techniques." }, { "code": null, "e": 3262, "s": 2948, "text": "So far we have seen that we can write a program and the query on the console to execute. In some cases, we print something on the console, that are written in our prolog code. So here we will see that writing and reading tasks in more detail using prolog. So this will be the input and output handling techniques." }, { "code": null, "e": 3492, "s": 3262, "text": "To write the output we can use the write() predicate. This predicate takes the parameter as input, and writes the content into the console by default. write() can also write in files. Let us see some examples of write() function." }, { "code": null, "e": 3648, "s": 3492, "text": "| ?- write(56).\n56\n\nyes\n| ?- write('hello').\nhello\n\nyes\n| ?- write('hello'),nl,write('world').\nhello\nworld\n\nyes\n| ?- write(\"ABCDE\")\n.\n[65,66,67,68,69]\n\nyes" }, { "code": null, "e": 4002, "s": 3648, "text": "From the above example, we can see that the write() predicate can write the contents into the console. We can use ’nl’ to create a new line. And from this example, it is clear that, if we want to print some string on the console, we have to use single quotes (‘string‘). But if we use double quote (“string”), then it will return a list of ASCII values." }, { "code": null, "e": 4286, "s": 4002, "text": "The read() predicate is used to read from console. User can write something in the console, that can be taken as input and process it. The read() is generally used to read from console, but this can also be used to read from files. Now let us see one example to see how read() works." }, { "code": null, "e": 4500, "s": 4286, "text": "cube :-\n write('Write a number: '),\n read(Number),\n process(Number).\nprocess(stop) :- !.\nprocess(Number) :-\n C is Number * Number * Number,\n write('Cube of '),write(Number),write(': '),write(C),nl, cube." }, { "code": null, "e": 4883, "s": 4500, "text": "| ?- [read_write].\ncompiling D:/TP Prolog/Sample_Codes/read_write.pl for byte code...\nD:/TP Prolog/Sample_Codes/read_write.pl compiled, 9 lines read - 1226 bytes written, 12 ms\n\n(15 ms) yes\n| ?- cube.\nWrite a number: 2.\nCube of 2: 8\nWrite a number: 10.\nCube of 10: 1000\nWrite a number: 12.\nCube of 12: 1728\nWrite a number: 8.\nCube of 8: 512\nWrite a number: stop\n.\n\n(31 ms) yes\n| ?-\n" }, { "code": null, "e": 5072, "s": 4883, "text": "The tab() is one additional predicate that can be used to put some blank-spaces while we write something. So it takes a number as an argument, and prints those many number of blank spaces." }, { "code": null, "e": 5255, "s": 5072, "text": "| ?- write('hello'),tab(15),write('world').\nhello world\n\nyes\n| ?- write('We'),tab(5),write('will'),tab(5),write('use'),tab(5),write('tabs').\nWe will use tabs\n\nyes\n| ?-" }, { "code": null, "e": 5435, "s": 5255, "text": "In this section, we will see how we can use files to read from, and write into the files. There are some built-in predicates, that can be used to read from file and write into it." }, { "code": null, "e": 5794, "s": 5435, "text": "If we want to write into a file, except the console, we can write the tell() predicate. This tell()predicate takes filename as argument. If that file is not present, then create a new file, and write into it. That file will be opened until we write the told command. We can open more than one file using tell(). When told is called, all files will be closed." }, { "code": null, "e": 6218, "s": 5794, "text": "| ?- told('myFile.txt').\nuncaught exception: error(existence_error(procedure,told/1),top_level/0)\n| ?- told(\"myFile.txt\").\nuncaught exception: error(existence_error(procedure,told/1),top_level/0)\n| ?- tell('myFile.txt').\n\nyes\n| ?- tell('myFile.txt').\n\nyes\n| ?- write('Hello World').\n\nyes\n| ?- write(' Writing into a file'),tab(5),write('myFile.txt'),nl.\n\nyes\n| ?- write(\"Write some ASCII values\").\n\nyes\n| ?- told.\n\nyes\n| ?-" }, { "code": null, "e": 6350, "s": 6218, "text": "Hello World Writing into a file myFile.txt\n[87,114,105,116,101,32,115,111,109,101,32,65,83,67,73,73,32,118,97,108,117,101,115]\n" }, { "code": null, "e": 6436, "s": 6350, "text": "Similarly, we can also read from files. Let us see some example of reading from file." }, { "code": null, "e": 6665, "s": 6436, "text": "When we want to read from file, not from the keyboard, we have to change current input stream. So we can use see() predicate. This will take filename as input. When the read operation is completed, then we will use seen command." }, { "code": null, "e": 6700, "s": 6665, "text": "likes(lili, cat).\nlikes(jhon,dog)." }, { "code": null, "e": 6832, "s": 6700, "text": "| ?- see('sample_predicate.txt'),\nread(X),\nread(Y),\nseen,\nread(Z).\nthe_end.\n\nX = end_of_file\nY = end_of_file\nZ = the_end\n\nyes\n| ?-\n" }, { "code": null, "e": 7037, "s": 6832, "text": "So from this example, we can see that using the see() predicate we can read from the file. Now after using seen command, the control transfers to the console again. So finally it takes input from console." }, { "code": null, "e": 7256, "s": 7037, "text": "We have seen how to read specific contents (few lines) of a file. Now if we want to read/process all the contents of a file, we need to write a clause to process file (process_file), until we reach the end of the file." }, { "code": null, "e": 7526, "s": 7256, "text": "process_file :-\n read(Line),\n Line \\== end_of_file, % when Line is not not end of file, call process.\n process(Line).\nprocess_file :- !. % use cut to stop backtracking\n\nprocess(Line):- %this will print the line into the console\n write(Line),nl,\n process_file." }, { "code": null, "e": 7591, "s": 7526, "text": "likes(lili, cat).\nlikes(jhon,dog).\ndomestic(dog).\ndomestic(cat)." }, { "code": null, "e": 7919, "s": 7591, "text": "| ?- [process_file].\ncompiling D:/TP Prolog/Sample_Codes/process_file.pl for byte code...\nD:/TP Prolog/Sample_Codes/process_file.pl compiled, 9 lines read - 774 bytes written, 23 ms\n\nyes\n| ?- see('sample_predicate.txt'), process_file, seen.\nlikes(lili,cat)\nlikes(jhon,dog)\ndomestic(dog)\ndomestic(cat)\n\ntrue ?\n\n(15 ms) yes\n| ?-\n" }, { "code": null, "e": 8207, "s": 7919, "text": "Using read() and write() we can read or write the value of atoms, predicates, strings, etc. Now in this section we will see how to write single characters into the current output stream, or how to read from current input stream. So there are some predefined predicates to do these tasks." }, { "code": null, "e": 8541, "s": 8207, "text": "We can use put(C) to write one character at a time into the current output stream. The output stream can be a file or the console. This C can be a character or an ASCII code in other version of Prolog like SWI prolog, but in GNU prolog, it supports only the ASCII value. To use the character instead of ASCII, we can use put_char(C)." }, { "code": null, "e": 8817, "s": 8541, "text": "| ?- put(97),put(98),put(99),put(100),put(101).\nabcde\n\nyes\n| ?- put(97),put(66),put(99),put(100),put(101).\naBcde\n\n(15 ms) yes\n| ?- put(65),put(66),put(99),put(100),put(101).\nABcde\n\nyes\n| ?-put_char('h'),put_char('e'),put_char('l'),put_char('l'),put_char('o').\nhello\n\nyes\n| ?-" }, { "code": null, "e": 8994, "s": 8817, "text": "To read a single character from the current input stream, we can use the get_char(C) predicate. This will take the character. if we want the ASCII code, we can use get_code(C)." }, { "code": null, "e": 9265, "s": 8994, "text": "| ?- get_char(X).\nA.\n\nX = 'A'\n\nyes\nuncaught exception: error(syntax_error('user_input:6 (char:689) expression expected'),read_term/3)\n| ?- get_code(X).\nA.\n\nX = 65\n\nyes\nuncaught exception: error(syntax_error('user_input:7 (char:14) expression expected'),read_term/3)\n| ?-" }, { "code": null, "e": 9665, "s": 9265, "text": "The atom constructing means from a list of characters, we can make one atom, or from a list of ASCII values also we can make atoms. To do this, we have to use atom_chars() and atom_codes() predicates. In both cases, the first argument will be one variable, and the second argument will be a list. So atom_chars() constructs atom from characters, but atom_codes() construct atoms from ASCII sequence." }, { "code": null, "e": 9880, "s": 9665, "text": "| ?- atom_chars(X, ['t','i','g','e','r']).\n\nX = tiger\n\nyes\n| ?- atom_chars(A, ['t','o','m']).\n\nA = tom\n\nyes\n| ?- atom_codes(X, [97,98,99,100,101]).\n\nX = abcde\n\nyes\n| ?- atom_codes(A, [97,98,99]).\n\nA = abc\n\nyes\n| ?-" }, { "code": null, "e": 10287, "s": 9880, "text": "The atom decomposing means from an atom, we can get a sequence of characters, or a sequence ASCII codes. To do this, we have to use the same atom_chars() and atom_codes() predicates. But one difference is that, in both cases, the first argument will be one atom, and the second argument will be a variable. So atom_chars() decomposes atom to characters, but atom_codes() decomposes atoms to ASCII sequence." }, { "code": null, "e": 10496, "s": 10287, "text": "| ?- atom_chars(tiger,X).\n\nX = [t,i,g,e,r]\n\nyes\n| ?- atom_chars(tom,A).\n\nA = [t,o,m]\n\nyes\n| ?- atom_codes(tiger,X).\n\nX = [116,105,103,101,114]\n\nyes\n| ?- atom_codes(tom,A).\n\nA = [116,111,109]\n\n(16 ms) yes\n| ?-" }, { "code": null, "e": 10729, "s": 10496, "text": "The consulting is a technique, that is used to merge the predicates from different files. We can use the consult() predicate, and pass the filename to attach the predicates. Let us see one example program to understand this concept." }, { "code": null, "e": 10787, "s": 10729, "text": "Suppose we have two files, namely, prog1.pl and prog2.pl." }, { "code": null, "e": 10840, "s": 10787, "text": "likes(mary,cat).\nlikes(joy,rabbit).\nlikes(tim,duck)." }, { "code": null, "e": 10880, "s": 10840, "text": "likes(suman,mouse).\nlikes(angshu,deer)." }, { "code": null, "e": 11498, "s": 10880, "text": "| ?- [prog1].\ncompiling D:/TP Prolog/Sample_Codes/prog1.pl for byte code...\nD:/TP Prolog/Sample_Codes/prog1.pl compiled, 2 lines read - 443 bytes written, 23 ms\n\nyes\n| ?- likes(joy,rabbit).\n\nyes\n| ?- likes(suman,mouse).\n\nno\n| ?- consult('prog2.pl').\ncompiling D:/TP Prolog/Sample_Codes/prog2.pl for byte code...\nD:/TP Prolog/Sample_Codes/prog2.pl compiled, 1 lines read - 366 bytes written, 20 ms\nwarning: D:/TP Prolog/Sample_Codes/prog2.pl:1: redefining procedure likes/2\n D:/TP Prolog/Sample_Codes/prog1.pl:1: previous definition\n \nyes\n| ?- likes(suman,mouse).\n\nyes\n| ?- likes(joy,rabbit).\n\nno\n| ?-\n" } ]
Smaller on Left | Practice | GeeksforGeeks
Given an array arr[ ] of N positive integers, the task is to find the greatest element on the left of every element in the array which is strictly smaller than itself, if this element does not exist for an index print "-1". Example 1: Input: N = 5 arr[] = {2, 3, 4, 5, 1} Output: -1 2 3 4 -1 Explanation: Greatest element on the left of 3 smaller than itself is 2, for 4 it is 3 and for 5 it is 1. Since 2 is the first element and no element on its left is present, so it's greatest smaller element will be -1 and for 1 no element smaller than itself is present on its left, so it's greatest smaller element is -1. Example 2: Input: N = 3 arr[] = {1, 2, 3} Output: -1 1 2 Your Task: This is a function problem. The input is already taken care of by the driver code. You only need to complete the function Smallestonleft() that takes an array arr[ ] and sizeOfArray N, and return the required answer. The driver code takes care of the printing. Expected Time Complexity: O(N*Log(N)). Expected Auxiliary Space: O(N). Constraints: 1 ≤ N ≤ 106 1 ≤ arr[i] ≤ 108 0 sumitsinghrajput786gwalior2 weeks ago public static int[] Smallestonleft (int arr[], int n) { // Complete the function int[] ans = new int[n]; TreeSet<Integer> ts = new TreeSet<>(); for(int i=0;i<n;i++){ Integer low = ts.lower(arr[i]); if(low==null){ ans[i]=-1; } else{ ans[i]=low; } ts.add(arr[i]); } return ans; } +1 shubhamrikhari86513 weeks ago vector<int> Smallestonleft(int arr[], int n){ vector<int>ans; set<int>s; for(int i=0; i<n; i++) { auto k = s.lower_bound(arr[i]); if(k == s.begin()) { ans.push_back(-1); } else { k--; ans.push_back(*k); } s.insert(arr[i]); } return ans;} 0 patildhiren443 weeks ago JAVA - static int[] Smallestonleft (int arr[], int n) { TreeSet<Integer> ts = new TreeSet<>(); int i=0; int[]res = new int[n]; for(int ele : arr){ Integer low = ts.lower(ele); if(low == null){ res[i]=-1; }else{ res[i]=low; } i++; ts.add(ele); } return res; } +1 1ashishchauhan20021 month ago vector<int> Smallestonleft(int arr[], int n){ vector<int>v(n,-1); set<int>s; for(int i=0 ;i<n; i++){ s.insert(arr[i]); auto x = s.find(arr[i]); if(x != s.begin()){ --x; v[i] = *(x); } } return v; } 0 orton10421 month ago #C++ Easy solution vector<int> Smallestonleft(int arr[], int n){set<int> s;vector<int> v;for(int i=0;i<n;i++){ auto it=s.lower_bound(arr[i]); if(it==s.begin()) v.push_back(-1); else {it--; v.push_back(*it);} s.insert(arr[i]);}return v;} 0 orton1042 This comment was deleted. +1 abhishekjadhav91722 months ago Can Anyone tell me why Stack is not working in this problem?? vector<int> Smallestonleft(int arr[], int n){ vector<int>brr(n,0); stack<int> s; for(int i = 0; i < n; i++) { if(s.empty()) { brr[i] = -1; s.push(arr[i]); } else { while(!s.empty()) { if(s.top() < arr[i]) { brr[i] = s.top(); s.push(arr[i]); break; } else { s.pop(); } } if(s.empty()) { brr[i] = -1; s.push(arr[i]); } } return brr; } 0 shubhankardey29sep2 months ago //Using TreeSet, please upvote if u like the solution class Complete{ // Function for finding maximum and value pair public static int[] Smallestonleft (int arr[], int n) { // Complete the function TreeSet<Integer> set = new TreeSet<>(); int []res = new int[n]; int idx = 0; for(int i=0;i<n;i++) { if(set.size()==0 || arr[i]==1) res[idx++] = -1; else { int val = -1; int flag = 0; int t = arr[i]-1; if(set.contains(t)) { val = t; flag = 1; } while(flag==0 && !set.contains(t) && t>0) { if(set.contains(t-1)) { val = t-1; flag = 1; break; } t--; } res[idx++] = val; } set.add(arr[i]); } return res; } } +4 starcode012 months ago Can Anyone tell me why Stack is not working in this problem?? 0 neerajkhatri1802 months ago vector<int> Smallestonleft(int arr[], int n){ // Complete the function vector<int> v; stack<int> s; for(int i=0;i<n;i++) { while(!s.empty() and arr[i]<=s.top()) s.pop(); if(s.empty()) v.push_back(-1); else v.push_back(s.top()); s.push(arr[i]); } return v;} wrong answer reason 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. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems 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": 462, "s": 238, "text": "Given an array arr[ ] of N positive integers, the task is to find the greatest element on the left of every element in the array which is strictly smaller than itself, if this element does not exist for an index print \"-1\"." }, { "code": null, "e": 473, "s": 462, "text": "Example 1:" }, { "code": null, "e": 862, "s": 473, "text": "Input:\nN = 5\narr[] = {2, 3, 4, 5, 1}\nOutput: \n-1 2 3 4 -1\nExplanation:\nGreatest element on the left of 3 smaller \nthan itself is 2, for 4 it is 3 and for 5 \nit is 1. Since 2 is the first element and \nno element on its left is present, so it's \ngreatest smaller element will be -1 and for \n1 no element smaller than itself is present \non its left, so it's greatest smaller element \nis -1.\n" }, { "code": null, "e": 873, "s": 862, "text": "Example 2:" }, { "code": null, "e": 921, "s": 873, "text": "Input:\nN = 3\narr[] = {1, 2, 3} \nOutput:\n-1 1 2 " }, { "code": null, "e": 1193, "s": 921, "text": "Your Task:\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function Smallestonleft() that takes an array arr[ ] and sizeOfArray N, and return the required answer. The driver code takes care of the printing." }, { "code": null, "e": 1264, "s": 1193, "text": "Expected Time Complexity: O(N*Log(N)).\nExpected Auxiliary Space: O(N)." }, { "code": null, "e": 1306, "s": 1264, "text": "Constraints:\n1 ≤ N ≤ 106\n1 ≤ arr[i] ≤ 108" }, { "code": null, "e": 1308, "s": 1306, "text": "0" }, { "code": null, "e": 1346, "s": 1308, "text": "sumitsinghrajput786gwalior2 weeks ago" }, { "code": null, "e": 1761, "s": 1346, "text": "public static int[] Smallestonleft (int arr[], int n) { // Complete the function int[] ans = new int[n]; TreeSet<Integer> ts = new TreeSet<>(); for(int i=0;i<n;i++){ Integer low = ts.lower(arr[i]); if(low==null){ ans[i]=-1; } else{ ans[i]=low; } ts.add(arr[i]); } return ans; }" }, { "code": null, "e": 1764, "s": 1761, "text": "+1" }, { "code": null, "e": 1794, "s": 1764, "text": "shubhamrikhari86513 weeks ago" }, { "code": null, "e": 2108, "s": 1794, "text": "vector<int> Smallestonleft(int arr[], int n){ vector<int>ans; set<int>s; for(int i=0; i<n; i++) { auto k = s.lower_bound(arr[i]); if(k == s.begin()) { ans.push_back(-1); } else { k--; ans.push_back(*k); } s.insert(arr[i]); } return ans;}" }, { "code": null, "e": 2110, "s": 2108, "text": "0" }, { "code": null, "e": 2135, "s": 2110, "text": "patildhiren443 weeks ago" }, { "code": null, "e": 2143, "s": 2135, "text": "JAVA - " }, { "code": null, "e": 2576, "s": 2143, "text": "static int[] Smallestonleft (int arr[], int n) {\n TreeSet<Integer> ts = new TreeSet<>();\n \n int i=0;\n int[]res = new int[n];\n for(int ele : arr){\n Integer low = ts.lower(ele);\n \n if(low == null){\n res[i]=-1;\n }else{\n res[i]=low;\n }\n i++;\n \n ts.add(ele);\n }\n \n return res;\n }" }, { "code": null, "e": 2579, "s": 2576, "text": "+1" }, { "code": null, "e": 2609, "s": 2579, "text": "1ashishchauhan20021 month ago" }, { "code": null, "e": 2868, "s": 2609, "text": "vector<int> Smallestonleft(int arr[], int n){ vector<int>v(n,-1); set<int>s; for(int i=0 ;i<n; i++){ s.insert(arr[i]); auto x = s.find(arr[i]); if(x != s.begin()){ --x; v[i] = *(x); } } return v; }" }, { "code": null, "e": 2870, "s": 2868, "text": "0" }, { "code": null, "e": 2891, "s": 2870, "text": "orton10421 month ago" }, { "code": null, "e": 2910, "s": 2891, "text": "#C++ Easy solution" }, { "code": null, "e": 3151, "s": 2910, "text": "vector<int> Smallestonleft(int arr[], int n){set<int> s;vector<int> v;for(int i=0;i<n;i++){ auto it=s.lower_bound(arr[i]); if(it==s.begin()) v.push_back(-1); else {it--; v.push_back(*it);} s.insert(arr[i]);}return v;}" }, { "code": null, "e": 3153, "s": 3151, "text": "0" }, { "code": null, "e": 3163, "s": 3153, "text": "orton1042" }, { "code": null, "e": 3189, "s": 3163, "text": "This comment was deleted." }, { "code": null, "e": 3192, "s": 3189, "text": "+1" }, { "code": null, "e": 3223, "s": 3192, "text": "abhishekjadhav91722 months ago" }, { "code": null, "e": 3285, "s": 3223, "text": "Can Anyone tell me why Stack is not working in this problem??" }, { "code": null, "e": 4041, "s": 3287, "text": "vector<int> Smallestonleft(int arr[], int n){ vector<int>brr(n,0); stack<int> s; for(int i = 0; i < n; i++) { if(s.empty()) { brr[i] = -1; s.push(arr[i]); } else { while(!s.empty()) { if(s.top() < arr[i]) { brr[i] = s.top(); s.push(arr[i]); break; } else { s.pop(); } } if(s.empty()) { brr[i] = -1; s.push(arr[i]); } } return brr; }" }, { "code": null, "e": 4043, "s": 4041, "text": "0" }, { "code": null, "e": 4074, "s": 4043, "text": "shubhankardey29sep2 months ago" }, { "code": null, "e": 5198, "s": 4074, "text": "//Using TreeSet, please upvote if u like the solution\nclass Complete{\n \n \n // Function for finding maximum and value pair\n public static int[] Smallestonleft (int arr[], int n) {\n // Complete the function\n TreeSet<Integer> set = new TreeSet<>();\n int []res = new int[n];\n int idx = 0;\n for(int i=0;i<n;i++)\n {\n if(set.size()==0 || arr[i]==1)\n res[idx++] = -1;\n \n else\n {\n int val = -1;\n int flag = 0;\n int t = arr[i]-1;\n if(set.contains(t))\n {\n val = t;\n flag = 1;\n }\n while(flag==0 && !set.contains(t) && t>0)\n {\n if(set.contains(t-1))\n {\n val = t-1;\n flag = 1;\n break;\n }\n t--;\n }\n res[idx++] = val;\n }\n set.add(arr[i]);\n }\n return res;\n }\n}" }, { "code": null, "e": 5201, "s": 5198, "text": "+4" }, { "code": null, "e": 5224, "s": 5201, "text": "starcode012 months ago" }, { "code": null, "e": 5286, "s": 5224, "text": "Can Anyone tell me why Stack is not working in this problem??" }, { "code": null, "e": 5290, "s": 5288, "text": "0" }, { "code": null, "e": 5318, "s": 5290, "text": "neerajkhatri1802 months ago" }, { "code": null, "e": 5637, "s": 5318, "text": "vector<int> Smallestonleft(int arr[], int n){ // Complete the function vector<int> v; stack<int> s; for(int i=0;i<n;i++) { while(!s.empty() and arr[i]<=s.top()) s.pop(); if(s.empty()) v.push_back(-1); else v.push_back(s.top()); s.push(arr[i]); } return v;}" }, { "code": null, "e": 5659, "s": 5639, "text": "wrong answer reason" }, { "code": null, "e": 5805, "s": 5659, "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": 5841, "s": 5805, "text": " Login to access your submissions. " }, { "code": null, "e": 5851, "s": 5841, "text": "\nProblem\n" }, { "code": null, "e": 5861, "s": 5851, "text": "\nContest\n" }, { "code": null, "e": 5924, "s": 5861, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6109, "s": 5924, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6393, "s": 6109, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 6539, "s": 6393, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 6616, "s": 6539, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 6657, "s": 6616, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 6685, "s": 6657, "text": "Disable browser extensions." }, { "code": null, "e": 6756, "s": 6685, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 6943, "s": 6756, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
Program to add two binary strings, and return also as binary string in C++
Suppose we have two binary strings a and b, we have to add these binary numbers and find their sum, also as a string. So, if the input is like a = "10110", b = "10010", then the output will be "101000". To solve this, we will follow these steps − ret := empty string na := size of a, nb := size of b i := na - 1, j := nb - 1 carry := 0 while (i >= 0 or j >= 0), do:addA := (if i >= 0, then a[i] - ASCII of '0', otherwise 0)addB := (if j >= 0, then b[j] - ASCII of '0', otherwise 0)sum := addA + addB + carrycarry := sum / 2sum := sum mod 2ret := ret concatenate sum(decrease i by 1)(decrease j by 1) addA := (if i >= 0, then a[i] - ASCII of '0', otherwise 0) addB := (if j >= 0, then b[j] - ASCII of '0', otherwise 0) sum := addA + addB + carry carry := sum / 2 sum := sum mod 2 ret := ret concatenate sum (decrease i by 1) (decrease j by 1) if carry is non-zero, then:ret := ret concatenate carry ret := ret concatenate carry reverse the array ret return ret Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: string solve(string a, string b){ string ret = ""; int na = a.size(); int nb = b.size(); int i = na - 1; int j = nb - 1; int carry = 0; while(i >= 0 || j >= 0){ int addA = i >= 0 ? a[i] - '0' : 0; int addB = j >= 0 ? b[j] - '0' : 0; int sum = addA + addB + carry; carry = sum / 2; sum %= 2; ret += to_string(sum); i--; j--; } if(carry) ret += to_string(carry); reverse(ret.begin(), ret.end()); return ret; } }; main(){ string a = "10110", b = "10010"; Solution ob; cout << ob.solve(a, b); } "10110","10010" 101000
[ { "code": null, "e": 1305, "s": 1187, "text": "Suppose we have two binary strings a and b, we have to add these binary numbers and find their sum, also as a string." }, { "code": null, "e": 1390, "s": 1305, "text": "So, if the input is like a = \"10110\", b = \"10010\", then the output will be \"101000\"." }, { "code": null, "e": 1434, "s": 1390, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1454, "s": 1434, "text": "ret := empty string" }, { "code": null, "e": 1487, "s": 1454, "text": "na := size of a, nb := size of b" }, { "code": null, "e": 1512, "s": 1487, "text": "i := na - 1, j := nb - 1" }, { "code": null, "e": 1523, "s": 1512, "text": "carry := 0" }, { "code": null, "e": 1787, "s": 1523, "text": "while (i >= 0 or j >= 0), do:addA := (if i >= 0, then a[i] - ASCII of '0', otherwise 0)addB := (if j >= 0, then b[j] - ASCII of '0', otherwise 0)sum := addA + addB + carrycarry := sum / 2sum := sum mod 2ret := ret concatenate sum(decrease i by 1)(decrease j by 1)" }, { "code": null, "e": 1846, "s": 1787, "text": "addA := (if i >= 0, then a[i] - ASCII of '0', otherwise 0)" }, { "code": null, "e": 1905, "s": 1846, "text": "addB := (if j >= 0, then b[j] - ASCII of '0', otherwise 0)" }, { "code": null, "e": 1932, "s": 1905, "text": "sum := addA + addB + carry" }, { "code": null, "e": 1949, "s": 1932, "text": "carry := sum / 2" }, { "code": null, "e": 1966, "s": 1949, "text": "sum := sum mod 2" }, { "code": null, "e": 1993, "s": 1966, "text": "ret := ret concatenate sum" }, { "code": null, "e": 2011, "s": 1993, "text": "(decrease i by 1)" }, { "code": null, "e": 2029, "s": 2011, "text": "(decrease j by 1)" }, { "code": null, "e": 2085, "s": 2029, "text": "if carry is non-zero, then:ret := ret concatenate carry" }, { "code": null, "e": 2114, "s": 2085, "text": "ret := ret concatenate carry" }, { "code": null, "e": 2136, "s": 2114, "text": "reverse the array ret" }, { "code": null, "e": 2147, "s": 2136, "text": "return ret" }, { "code": null, "e": 2217, "s": 2147, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2228, "s": 2217, "text": " Live Demo" }, { "code": null, "e": 2949, "s": 2228, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n string solve(string a, string b){\n string ret = \"\";\n int na = a.size();\n int nb = b.size();\n int i = na - 1;\n int j = nb - 1;\n int carry = 0;\n while(i >= 0 || j >= 0){\n int addA = i >= 0 ? a[i] - '0' : 0;\n int addB = j >= 0 ? b[j] - '0' : 0;\n int sum = addA + addB + carry;\n carry = sum / 2;\n sum %= 2;\n ret += to_string(sum);\n i--;\n j--;\n }\n if(carry)\n ret += to_string(carry); reverse(ret.begin(), ret.end());\n return ret;\n }\n};\nmain(){\n string a = \"10110\", b = \"10010\"; Solution ob;\n cout << ob.solve(a, b);\n}" }, { "code": null, "e": 2965, "s": 2949, "text": "\"10110\",\"10010\"" }, { "code": null, "e": 2972, "s": 2965, "text": "101000" } ]
Modify contents of Linked List
03 Jul, 2022 Given a singly linked list containing n nodes. Modify the value of first half nodes such that 1st node’s new value is equal to the last node’s value minus first node’s current value, 2nd node’s new value is equal to the second last node’s value minus 2nd node’s current value, likewise for first half nodes. If n is odd then the value of the middle node remains unchanged. (No extra memory to be used). Examples: Input : 10 -> 4 -> 5 -> 3 -> 6 Output : 4 -> 1 -> 5 -> 3 -> 6 Input : 2 -> 9 -> 8 -> 12 -> 7 -> 10 Output : -8 -> 2 -> -4 -> 12 -> 7 -> 10 Asked in Amazon Interview Approach: The following steps are: Split the list from the middle. Perform front and back split. If the number of elements is odd, the extra element should go in the 1st(front) list.Reverse the 2nd(back) list.Perform the required subtraction while traversing both list simultaneously.Again reverse the 2nd list.Concatenate the 2nd list back to the end of the 1st list. Split the list from the middle. Perform front and back split. If the number of elements is odd, the extra element should go in the 1st(front) list. Reverse the 2nd(back) list. Perform the required subtraction while traversing both list simultaneously. Again reverse the 2nd list. Concatenate the 2nd list back to the end of the 1st list. C++ Java Python3 C# Javascript // C++ implementation to modify the contents of // the linked list#include <bits/stdc++.h>using namespace std; /* Linked list node */struct Node{ int data; struct Node* next;}; /* function prototype for printing the list */void printList(struct Node*); /* Function to insert a node at the beginning of the linked list */void push(struct Node **head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list at the end of the new node */ new_node->next = *head_ref; /* move the head to point to the new node */ *head_ref = new_node;} /* Split the nodes of the given list into front and back halves, and return the two lists using the reference parameters. Uses the fast/slow pointer strategy. */void frontAndBackSplit(struct Node *head, struct Node **front_ref, struct Node **back_ref){ Node *slow, *fast; slow = head; fast = head->next; /* Advance 'fast' two nodes, and advance 'slow' one node */ while (fast != NULL) { fast = fast->next; if (fast != NULL) { slow = slow->next; fast = fast->next; } } /* 'slow' is before the midpoint in the list, so split it in two at that point. */ *front_ref = head; *back_ref = slow->next; slow->next = NULL;} /* Function to reverse the linked list */void reverseList(struct Node **head_ref){ struct Node *current, *prev, *next; current = *head_ref; prev = NULL; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } *head_ref = prev;} // perform the required subtraction operation on// the 1st half of the linked listvoid modifyTheContentsOf1stHalf(struct Node *front, struct Node *back){ // traversing both the lists simultaneously while (back != NULL) { // subtraction operation and node data // modification front->data = front->data - back->data; front = front->next; back = back->next; }} // function to concatenate the 2nd(back) list at the end of// the 1st(front) list and returns the head of the new liststruct Node* concatFrontAndBackList(struct Node *front, struct Node *back){ struct Node *head = front; while (front->next != NULL) front = front->next; front->next = back; return head;} // function to modify the contents of the linked liststruct Node* modifyTheList(struct Node *head){ // if list is empty or contains only single node if (!head || head->next == NULL) return head; struct Node *front, *back; // split the list into two halves // front and back lists frontAndBackSplit(head, &front, &back); // reverse the 2nd(back) list reverseList(&back); // modify the contents of 1st half modifyTheContentsOf1stHalf(front, back); // agains reverse the 2nd(back) list reverseList(&back); // concatenating the 2nd list back to the // end of the 1st list head = concatFrontAndBackList(front, back); // pointer to the modified list return head;} // function to print the linked listvoid printList(struct Node *head){ if (!head) return; while (head->next != NULL) { cout << head->data << " -> "; head = head->next; } cout << head->data << endl;} // Driver program to test aboveint main(){ struct Node *head = NULL; // creating the linked list push(&head, 10); push(&head, 7); push(&head, 12); push(&head, 8); push(&head, 9); push(&head, 2); // modify the linked list head = modifyTheList(head); // print the modified linked list cout << "Modified List:" << endl; printList(head); return 0;} // Java implementation to modify the contents // of the linked listclass GFG{ /* Linked list node */static class Node{ int data; Node next;}; /* Function to insert a node at the beginning of the linked list */static Node push(Node head_ref, int new_data){ /* allocate node */ Node new_node =new Node(); /* put in the data */ new_node.data = new_data; /* link the old list at the end of the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; return head_ref;} static Node front,back; /* Split the nodes of the given list into front and back halves,and return the two lists using the reference parameters.Uses the fast/slow pointer strategy. */static void frontAndBackSplit( Node head){ Node slow, fast; slow = head; fast = head.next; /* Advance 'fast' two nodes, and advance 'slow' one node */ while (fast != null) { fast = fast.next; if (fast != null) { slow = slow.next; fast = fast.next; } } /* 'slow' is before the midpoint in the list, so split it in two at that point. */ front = head; back = slow.next; slow.next = null;} /* Function to reverse the linked list */static Node reverseList( Node head_ref){ Node current, prev, next; current = head_ref; prev = null; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } head_ref = prev; return head_ref;} // perform the required subtraction operation // on the 1st half of the linked liststatic void modifyTheContentsOf1stHalf(){ Node front1 = front, back1 = back; // traversing both the lists simultaneously while (back1 != null) { // subtraction operation and node data // modification front1.data = front1.data - back1.data; front1 = front1.next; back1 = back1.next; }} // function to concatenate the 2nd(back) list // at the end of the 1st(front) list and // returns the head of the new liststatic Node concatFrontAndBackList(Node front, Node back){ Node head = front; if(front == null)return back; while (front.next != null) front = front.next; front.next = back; return head;} // function to modify the contents of the linked liststatic Node modifyTheList( Node head){ // if list is empty or contains only single node if (head == null || head.next == null) return head; front = null; back = null; // split the list into two halves // front and back lists frontAndBackSplit(head); // reverse the 2nd(back) list back = reverseList(back); // modify the contents of 1st half modifyTheContentsOf1stHalf(); // agains reverse the 2nd(back) list back = reverseList(back); // concatenating the 2nd list back to the // end of the 1st list head = concatFrontAndBackList(front, back); // pointer to the modified list return head;} // function to print the linked liststatic void printList( Node head){ if (head == null) return; while (head.next != null) { System.out.print(head.data + " -> "); head = head.next; } System.out.println(head.data );} // Driver Codepublic static void main(String args[]){ Node head = null; // creating the linked list head = push(head, 10); head = push(head, 7); head = push(head, 12); head = push(head, 8); head = push(head, 9); head = push(head, 2); // modify the linked list head = modifyTheList(head); // print the modified linked list System.out.println( "Modified List:" ); printList(head);}} // This code is contributed by Arnab Kundu # Python3 implementation to modify the contents # of the linked list # Linked list node class Node: def __init__(self, data): self.data = data self.next = None # Function to insert a node at the beginning # of the linked list def push(head_ref, new_data): # allocate node new_node =Node(0) # put in the data new_node.data = new_data # link the old list at the end #of the new node new_node.next = head_ref # move the head to point to the new node head_ref = new_node return head_ref front = Noneback = None # Split the nodes of the given list # into front and back halves,# and return the two lists # using the reference parameters.# Uses the fast/slow pointer strategy. def frontAndBackSplit( head): global front global back slow = None fast = None slow = head fast = head.next # Advance 'fast' two nodes, and # advance 'slow' one node while (fast != None): fast = fast.next if (fast != None): slow = slow.next fast = fast.next # 'slow' is before the midpoint in the list, # so split it in two at that point. front = head back = slow.next slow.next = None return head # Function to reverse the linked list def reverseList( head_ref): current = None prev = None next = None current = head_ref prev = None while (current != None): next = current.next current.next = prev prev = current current = next head_ref = prev return head_ref # perform the required subtraction operation # on the 1st half of the linked listdef modifyTheContentsOf1stHalf(): global front global back front1 = front back1 = back # traversing both the lists simultaneously while (back1 != None): # subtraction operation and node data # modification front1.data = front1.data - back1.data front1 = front1.next back1 = back1.next # function to concatenate the 2nd(back) list # at the end of the 1st(front) list and # returns the head of the new listdef concatFrontAndBackList( front, back): head = front if(front == None): return back while (front.next != None): front = front.next front.next = back return head # function to modify the contents of the linked listdef modifyTheList( head): global front global back # if list is empty or contains only single node if (head == None or head.next == None): return head front = None back = None # split the list into two halves # front and back lists frontAndBackSplit(head) # reverse the 2nd(back) list back = reverseList(back) # modify the contents of 1st half modifyTheContentsOf1stHalf() # agains reverse the 2nd(back) list back = reverseList(back) # concatenating the 2nd list back to the # end of the 1st list head = concatFrontAndBackList(front, back) # pointer to the modified list return head # function to print the linked listdef printList( head): if (head == None): return while (head.next != None): print(head.data , " -> ",end="") head = head.next print(head.data ) # Driver Code head = None # creating the linked listhead = push(head, 10)head = push(head, 7)head = push(head, 12)head = push(head, 8)head = push(head, 9)head = push(head, 2) # modify the linked listhead = modifyTheList(head) # print the modified linked listprint( "Modified List:" )printList(head) # This code is contributed by Arnab Kundu // C# implementation to modify the // contents of the linked listusing System; class GFG{ /* Linked list node */public class Node{ public int data; public Node next;}; /* Function to insert a node at the beginning of the linked list */static Node push(Node head_ref, int new_data){ /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list at the end of the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; return head_ref;} static Node front, back; /* Split the nodes of the given list into front and back halves,and return the two lists using the reference parameters.Uses the fast/slow pointer strategy. */static void frontAndBackSplit( Node head){ Node slow, fast; slow = head; fast = head.next; /* Advance 'fast' two nodes, and advance 'slow' one node */ while (fast != null) { fast = fast.next; if (fast != null) { slow = slow.next; fast = fast.next; } } /* 'slow' is before the midpoint in the list, so split it in two at that point. */ front = head; back = slow.next; slow.next = null;} /* Function to reverse the linked list */static Node reverseList(Node head_ref){ Node current, prev, next; current = head_ref; prev = null; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } head_ref = prev; return head_ref;} // perform the required subtraction operation // on the 1st half of the linked liststatic void modifyTheContentsOf1stHalf(){ Node front1 = front, back1 = back; // traversing both the lists simultaneously while (back1 != null) { // subtraction operation and node data // modification front1.data = front1.data - back1.data; front1 = front1.next; back1 = back1.next; }} // function to concatenate the 2nd(back) list // at the end of the 1st(front) list and // returns the head of the new liststatic Node concatFrontAndBackList(Node front, Node back){ Node head = front; if(front == null) return back; while (front.next != null) front = front.next; front.next = back; return head;} // function to modify the contents of// the linked liststatic Node modifyTheList(Node head){ // if list is empty or contains // only single node if (head == null || head.next == null) return head; front = null; back = null; // split the list into two halves // front and back lists frontAndBackSplit(head); // reverse the 2nd(back) list back = reverseList(back); // modify the contents of 1st half modifyTheContentsOf1stHalf(); // agains reverse the 2nd(back) list back = reverseList(back); // concatenating the 2nd list back to the // end of the 1st list head = concatFrontAndBackList(front, back); // pointer to the modified list return head;} // function to print the linked liststatic void printList( Node head){ if (head == null) return; while (head.next != null) { Console.Write(head.data + " -> "); head = head.next; } Console.WriteLine(head.data );} // Driver Codepublic static void Main(){ Node head = null; // creating the linked list head = push(head, 10); head = push(head, 7); head = push(head, 12); head = push(head, 8); head = push(head, 9); head = push(head, 2); // modify the linked list head = modifyTheList(head); // print the modified linked list Console.WriteLine( "Modified List:" ); printList(head);}} // This code is contributed by PrinciRaj1992 <script> // JavaScript implementation to modify the // contents of the linked list /* Linked list node */ class Node { constructor() { this.data = 0; this.next = null; } } /* Function to insert a node at the beginning of the linked list */ function push(head_ref, new_data) { /* allocate node */ var new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list at the end of the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; return head_ref; } var front, back; /* Split the nodes of the given list into front and back halves, and return the two lists using the reference parameters. Uses the fast/slow pointer strategy. */ function frontAndBackSplit(head) { var slow, fast; slow = head; fast = head.next; /* Advance 'fast' two nodes, and advance 'slow' one node */ while (fast != null) { fast = fast.next; if (fast != null) { slow = slow.next; fast = fast.next; } } /* 'slow' is before the midpoint in the list, so split it in two at that point. */ front = head; back = slow.next; slow.next = null; } /* Function to reverse the linked list */ function reverseList(head_ref) { var current, prev, next; current = head_ref; prev = null; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } head_ref = prev; return head_ref; } // perform the required subtraction operation // on the 1st half of the linked list function modifyTheContentsOf1stHalf() { var front1 = front, back1 = back; // traversing both the lists simultaneously while (back1 != null) { // subtraction operation and node data // modification front1.data = front1.data - back1.data; front1 = front1.next; back1 = back1.next; } } // function to concatenate the 2nd(back) list // at the end of the 1st(front) list and // returns the head of the new list function concatFrontAndBackList(front, back) { var head = front; if (front == null) return back; while (front.next != null) front = front.next; front.next = back; return head; } // function to modify the contents of // the linked list function modifyTheList(head) { // if list is empty or contains // only single node if (head == null || head.next == null) return head; front = null; back = null; // split the list into two halves // front and back lists frontAndBackSplit(head); // reverse the 2nd(back) list back = reverseList(back); // modify the contents of 1st half modifyTheContentsOf1stHalf(); // agains reverse the 2nd(back) list back = reverseList(back); // concatenating the 2nd list back to the // end of the 1st list head = concatFrontAndBackList(front, back); // pointer to the modified list return head; } // function to print the linked list function printList(head) { if (head == null) return; while (head.next != null) { document.write(head.data + " -> "); head = head.next; } document.write(head.data + "<br>"); } // Driver Code var head = null; // creating the linked list head = push(head, 10); head = push(head, 7); head = push(head, 12); head = push(head, 8); head = push(head, 9); head = push(head, 2); // modify the linked list head = modifyTheList(head); // print the modified linked list document.write("Modified List: <br>"); printList(head); </script> Output: Modified List: -8 -> 2 -> -4 -> 12 -> 7 -> 10 Time Complexity: O(n), where n in the number of nodes. Space complexity: O(1) since using constant space to modify pointers Another approach (Using Stack) : 1. Find the starting point of second half Linked List. 2. Push all elements of second half list into stack s. 3. Traverse list starting from head using temp until stack is not empty and do Modify temp->data by subtracting the top element of stack for every node. Below is the implementation using stack. C++ Java Python3 C# Javascript // C++ implementation to modify the// contents of the linked list#include <bits/stdc++.h>using namespace std; // Linked list nodestruct Node{ int data; struct Node* next;}; // function prototype for printing the listvoid printList(struct Node*); // Function to insert a node at the// beginning of the linked listvoid push(struct Node **head_ref, int new_data){ // allocate nodestruct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // put in the datanew_node->data = new_data; // link the old list at the end of the new nodenew_node->next = *head_ref; // move the head to point to the new node*head_ref = new_node;} // function to print the linked listvoid printList(struct Node *head){ if (!head) return; while (head->next != NULL) { cout << head->data << " -> "; head = head->next; } cout << head->data << endl;} // Function to middle node of list.Node* find_mid(Node *head){ Node *temp = head, *slow = head, *fast = head ; while(fast && fast->next) { // Advance 'fast' two nodes, and // advance 'slow' one node slow = slow->next ; fast = fast->next->next ; } // If number of nodes are odd then update slow // by slow->next; if(fast) slow = slow->next ; return slow ;} // function to modify the contents of the linked list.void modifyTheList(struct Node *head, struct Node *slow){// Create Stack. stack <int> s;Node *temp = head ; while(slow){ s.push( slow->data ) ; slow = slow->next ;} // Traverse the list by using temp until stack is empty.while( !s.empty() ){ temp->data = temp->data - s.top() ; temp = temp->next ; s.pop() ;} } // Driver program to test aboveint main(){ struct Node *head = NULL, *mid ; // creating the linked list push(&head, 10); push(&head, 7); push(&head, 12); push(&head, 8); push(&head, 9); push(&head, 2); // Call Function to Find the starting point of second half of list. mid = find_mid(head) ; // Call function to modify the contents of the linked list. modifyTheList( head, mid); // print the modified linked list cout << "Modified List:" << endl; printList(head); return 0;} // This is contributed by Mr. Gera // Java implementation to modify the// contents of the linked listimport java.util.*; class GFG { // Linked list node static class Node { int data; Node next; }; // Function to insert a node at the // beginning of the linked list static Node push(Node head_ref, int new_data) { // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // link the old list at the end of the new node new_node.next = head_ref; // move the head to point to the new node head_ref = new_node; return head_ref; } // function to print the linked list static void printList(Node head) { if (head == null) { return; } while (head.next != null) { System.out.print(head.data + "->"); head = head.next; } System.out.print(head.data + "\n"); } // Function to middle node of list. static Node find_mid(Node head) { Node temp = head, slow = head, fast = head; while (fast != null && fast.next != null) { // Advance 'fast' two nodes, and // advance 'slow' one node slow = slow.next; fast = fast.next.next; } // If number of nodes are odd then update slow // by slow.next; if (fast != null) { slow = slow.next; } return slow; } // function to modify the contents of the linked list. static void modifyTheList(Node head, Node slow) { // Create Stack. Stack<Integer> s = new Stack<Integer>(); Node temp = head; while (slow != null) { s.add(slow.data); slow = slow.next; } // Traverse the list by using temp until stack is empty. while (!s.empty()) { temp.data = temp.data - s.peek(); temp = temp.next; s.pop(); } } // Driver program to test above public static void main(String[] args) { Node head = null, mid; // creating the linked list head = push(head, 10); head = push(head, 7); head = push(head, 12); head = push(head, 8); head = push(head, 9); head = push(head, 2); // Call Function to Find the starting // point of second half of list. mid = find_mid(head); // Call function to modify // the contents of the linked list. modifyTheList(head, mid); // print the modified linked list System.out.print("Modified List:" + "\n"); printList(head); }} // This code is contributed by Rajput-Ji # Python3 implementation to modify the# contents of the linked list # Linked list nodeclass Node: def __init__(self): self.data = 0 self.next = None # Function to insert a node at the# beginning of the linked listdef append(head_ref, new_data): # Allocate node new_node = Node() # Put in the data new_node.data = new_data # Link the old list at the end # of the new node new_node.next = head_ref # Move the head to point to the new node head_ref = new_node return head_ref # Function to print the linked listdef printList(head): if (not head): return; while (head.next != None): print(head.data, end = ' -> ') head = head.next print(head.data) # Function to middle node of list.def find_mid(head): temp = head slow = head fast = head while (fast and fast.next): # Advance 'fast' two nodes, and # advance 'slow' one node slow = slow.next fast = fast.next.next # If number of nodes are odd then # update slow by slow.next; if (fast): slow = slow.next return slow # Function to modify the contents of # the linked list.def modifyTheList(head, slow): # Create Stack. s = [] temp = head while (slow): s.append(slow.data) slow = slow.next # Traverse the list by using # temp until stack is empty. while (len(s) != 0): temp.data = temp.data - s[-1] temp = temp.next s.pop() # Driver codeif __name__=='__main__': head = None # creating the linked list head = append(head, 10) head = append(head, 7) head = append(head, 12) head = append(head, 8) head = append(head, 9) head = append(head, 2) # Call Function to Find the # starting point of second half of list. mid = find_mid(head) # Call function to modify the # contents of the linked list. modifyTheList( head, mid) # Print the modified linked list print("Modified List:") printList(head) # This code is contributed by rutvik_56 // C# implementation to modify the// contents of the linked listusing System;using System.Collections.Generic; class GFG { // Linked list node public class Node { public int data; public Node next; }; // Function to insert a node at the // beginning of the linked list static Node push(Node head_ref, int new_data) { // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // link the old list at the end of the new node new_node.next = head_ref; // move the head to point to the new node head_ref = new_node; return head_ref; } // function to print the linked list static void printList(Node head) { if (head == null) { return; } while (head.next != null) { Console.Write(head.data + "->"); head = head.next; } Console.Write(head.data + "\n"); } // Function to middle node of list. static Node find_mid(Node head) { Node temp = head, slow = head, fast = head; while (fast != null && fast.next != null) { // Advance 'fast' two nodes, and // advance 'slow' one node slow = slow.next; fast = fast.next.next; } // If number of nodes are odd then update slow // by slow.next; if (fast != null) { slow = slow.next; } return slow; } // function to modify the contents of the linked list. static void modifyTheList(Node head, Node slow) { // Create Stack. Stack<int> s = new Stack<int>(); Node temp = head; while (slow != null) { s.Push(slow.data); slow = slow.next; } // Traverse the list by using temp until stack is empty. while (s.Count != 0) { temp.data = temp.data - s.Peek(); temp = temp.next; s.Pop(); } } // Driver code public static void Main(String[] args) { Node head = null, mid; // creating the linked list head = push(head, 10); head = push(head, 7); head = push(head, 12); head = push(head, 8); head = push(head, 9); head = push(head, 2); // Call Function to Find the starting // point of second half of list. mid = find_mid(head); // Call function to modify // the contents of the linked list. modifyTheList(head, mid); // print the modified linked list Console.Write("Modified List:" + "\n"); printList(head); }} // This code is contributed by PrinciRaj1992 <script> // JavaScript implementation to modify the// contents of the linked list // Linked list nodeclass Node { constructor(val) { this.data = val; this.next = null; }} // Function to insert a node at the // beginning of the linked list function push(head_ref , new_data) { // allocate node var new_node = new Node(); // put in the data new_node.data = new_data; // link the old list at the end of the new node new_node.next = head_ref; // move the head to point to the new node head_ref = new_node; return head_ref; } // function to print the linked list function printList(head) { if (head == null) { return; } while (head.next != null) { document.write(head.data + "->"); head = head.next; } document.write(head.data + "<br/>"); } // Function to middle node of list. function find_mid(head) { var temp = head, slow = head, fast = head; while (fast != null && fast.next != null) { // Advance 'fast' two nodes, and // advance 'slow' one node slow = slow.next; fast = fast.next.next; } // If number of nodes are odd then update slow // by slow.next; if (fast != null) { slow = slow.next; } return slow; } // function to modify the contents of the linked list. function modifyTheList(head, slow) { // Create Stack. var s = []; var temp = head; while (slow != null) { s.push(slow.data); slow = slow.next; } // Traverse the list by using temp until stack is empty. while (s.length!=0) { temp.data = temp.data - s.pop(); temp = temp.next; } } // Driver program to test above var head = null, mid; // creating the linked list head = push(head, 10); head = push(head, 7); head = push(head, 12); head = push(head, 8); head = push(head, 9); head = push(head, 2); // Call Function to Find the starting // point of second half of list. mid = find_mid(head); // Call function to modify // the contents of the linked list. modifyTheList(head, mid); // print the modified linked list document.write("Modified List:" + "<br/>"); printList(head); // This code contributed by Rajput-Ji </script> Output: Modified List: -8 -> 2 -> -4 -> 12 -> 7 -> 10 Time Complexity : O(n) Space Complexity : O(n/2)References: https://www.careercup.com/question?id=5657550909341696 andrew1234 princiraj1992 Rajput-Ji rutvik_56 khushboogoyal499 rdtank surinderdawra388 arorakashish0911 polymatir3j Amazon Linked List Amazon Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Merge two sorted linked lists What is Data Structure: Types, Classifications and Applications Find the middle of a given linked list Linked List vs Array Merge Sort for Linked Lists Implementing a Linked List in Java using Class Add two numbers represented by linked lists | Set 1 Detect and Remove Loop in a Linked List Queue - Linked List Implementation
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Jul, 2022" }, { "code": null, "e": 457, "s": 54, "text": "Given a singly linked list containing n nodes. Modify the value of first half nodes such that 1st node’s new value is equal to the last node’s value minus first node’s current value, 2nd node’s new value is equal to the second last node’s value minus 2nd node’s current value, likewise for first half nodes. If n is odd then the value of the middle node remains unchanged. (No extra memory to be used)." }, { "code": null, "e": 469, "s": 457, "text": "Examples: " }, { "code": null, "e": 609, "s": 469, "text": "Input : 10 -> 4 -> 5 -> 3 -> 6\nOutput : 4 -> 1 -> 5 -> 3 -> 6\n\nInput : 2 -> 9 -> 8 -> 12 -> 7 -> 10\nOutput : -8 -> 2 -> -4 -> 12 -> 7 -> 10" }, { "code": null, "e": 636, "s": 609, "text": "Asked in Amazon Interview " }, { "code": null, "e": 671, "s": 636, "text": "Approach: The following steps are:" }, { "code": null, "e": 1005, "s": 671, "text": "Split the list from the middle. Perform front and back split. If the number of elements is odd, the extra element should go in the 1st(front) list.Reverse the 2nd(back) list.Perform the required subtraction while traversing both list simultaneously.Again reverse the 2nd list.Concatenate the 2nd list back to the end of the 1st list." }, { "code": null, "e": 1153, "s": 1005, "text": "Split the list from the middle. Perform front and back split. If the number of elements is odd, the extra element should go in the 1st(front) list." }, { "code": null, "e": 1181, "s": 1153, "text": "Reverse the 2nd(back) list." }, { "code": null, "e": 1257, "s": 1181, "text": "Perform the required subtraction while traversing both list simultaneously." }, { "code": null, "e": 1285, "s": 1257, "text": "Again reverse the 2nd list." }, { "code": null, "e": 1343, "s": 1285, "text": "Concatenate the 2nd list back to the end of the 1st list." }, { "code": null, "e": 1347, "s": 1343, "text": "C++" }, { "code": null, "e": 1352, "s": 1347, "text": "Java" }, { "code": null, "e": 1360, "s": 1352, "text": "Python3" }, { "code": null, "e": 1363, "s": 1360, "text": "C#" }, { "code": null, "e": 1374, "s": 1363, "text": "Javascript" }, { "code": "// C++ implementation to modify the contents of // the linked list#include <bits/stdc++.h>using namespace std; /* Linked list node */struct Node{ int data; struct Node* next;}; /* function prototype for printing the list */void printList(struct Node*); /* Function to insert a node at the beginning of the linked list */void push(struct Node **head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list at the end of the new node */ new_node->next = *head_ref; /* move the head to point to the new node */ *head_ref = new_node;} /* Split the nodes of the given list into front and back halves, and return the two lists using the reference parameters. Uses the fast/slow pointer strategy. */void frontAndBackSplit(struct Node *head, struct Node **front_ref, struct Node **back_ref){ Node *slow, *fast; slow = head; fast = head->next; /* Advance 'fast' two nodes, and advance 'slow' one node */ while (fast != NULL) { fast = fast->next; if (fast != NULL) { slow = slow->next; fast = fast->next; } } /* 'slow' is before the midpoint in the list, so split it in two at that point. */ *front_ref = head; *back_ref = slow->next; slow->next = NULL;} /* Function to reverse the linked list */void reverseList(struct Node **head_ref){ struct Node *current, *prev, *next; current = *head_ref; prev = NULL; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } *head_ref = prev;} // perform the required subtraction operation on// the 1st half of the linked listvoid modifyTheContentsOf1stHalf(struct Node *front, struct Node *back){ // traversing both the lists simultaneously while (back != NULL) { // subtraction operation and node data // modification front->data = front->data - back->data; front = front->next; back = back->next; }} // function to concatenate the 2nd(back) list at the end of// the 1st(front) list and returns the head of the new liststruct Node* concatFrontAndBackList(struct Node *front, struct Node *back){ struct Node *head = front; while (front->next != NULL) front = front->next; front->next = back; return head;} // function to modify the contents of the linked liststruct Node* modifyTheList(struct Node *head){ // if list is empty or contains only single node if (!head || head->next == NULL) return head; struct Node *front, *back; // split the list into two halves // front and back lists frontAndBackSplit(head, &front, &back); // reverse the 2nd(back) list reverseList(&back); // modify the contents of 1st half modifyTheContentsOf1stHalf(front, back); // agains reverse the 2nd(back) list reverseList(&back); // concatenating the 2nd list back to the // end of the 1st list head = concatFrontAndBackList(front, back); // pointer to the modified list return head;} // function to print the linked listvoid printList(struct Node *head){ if (!head) return; while (head->next != NULL) { cout << head->data << \" -> \"; head = head->next; } cout << head->data << endl;} // Driver program to test aboveint main(){ struct Node *head = NULL; // creating the linked list push(&head, 10); push(&head, 7); push(&head, 12); push(&head, 8); push(&head, 9); push(&head, 2); // modify the linked list head = modifyTheList(head); // print the modified linked list cout << \"Modified List:\" << endl; printList(head); return 0;} ", "e": 5424, "s": 1374, "text": null }, { "code": "// Java implementation to modify the contents // of the linked listclass GFG{ /* Linked list node */static class Node{ int data; Node next;}; /* Function to insert a node at the beginning of the linked list */static Node push(Node head_ref, int new_data){ /* allocate node */ Node new_node =new Node(); /* put in the data */ new_node.data = new_data; /* link the old list at the end of the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; return head_ref;} static Node front,back; /* Split the nodes of the given list into front and back halves,and return the two lists using the reference parameters.Uses the fast/slow pointer strategy. */static void frontAndBackSplit( Node head){ Node slow, fast; slow = head; fast = head.next; /* Advance 'fast' two nodes, and advance 'slow' one node */ while (fast != null) { fast = fast.next; if (fast != null) { slow = slow.next; fast = fast.next; } } /* 'slow' is before the midpoint in the list, so split it in two at that point. */ front = head; back = slow.next; slow.next = null;} /* Function to reverse the linked list */static Node reverseList( Node head_ref){ Node current, prev, next; current = head_ref; prev = null; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } head_ref = prev; return head_ref;} // perform the required subtraction operation // on the 1st half of the linked liststatic void modifyTheContentsOf1stHalf(){ Node front1 = front, back1 = back; // traversing both the lists simultaneously while (back1 != null) { // subtraction operation and node data // modification front1.data = front1.data - back1.data; front1 = front1.next; back1 = back1.next; }} // function to concatenate the 2nd(back) list // at the end of the 1st(front) list and // returns the head of the new liststatic Node concatFrontAndBackList(Node front, Node back){ Node head = front; if(front == null)return back; while (front.next != null) front = front.next; front.next = back; return head;} // function to modify the contents of the linked liststatic Node modifyTheList( Node head){ // if list is empty or contains only single node if (head == null || head.next == null) return head; front = null; back = null; // split the list into two halves // front and back lists frontAndBackSplit(head); // reverse the 2nd(back) list back = reverseList(back); // modify the contents of 1st half modifyTheContentsOf1stHalf(); // agains reverse the 2nd(back) list back = reverseList(back); // concatenating the 2nd list back to the // end of the 1st list head = concatFrontAndBackList(front, back); // pointer to the modified list return head;} // function to print the linked liststatic void printList( Node head){ if (head == null) return; while (head.next != null) { System.out.print(head.data + \" -> \"); head = head.next; } System.out.println(head.data );} // Driver Codepublic static void main(String args[]){ Node head = null; // creating the linked list head = push(head, 10); head = push(head, 7); head = push(head, 12); head = push(head, 8); head = push(head, 9); head = push(head, 2); // modify the linked list head = modifyTheList(head); // print the modified linked list System.out.println( \"Modified List:\" ); printList(head);}} // This code is contributed by Arnab Kundu", "e": 9329, "s": 5424, "text": null }, { "code": "# Python3 implementation to modify the contents # of the linked list # Linked list node class Node: def __init__(self, data): self.data = data self.next = None # Function to insert a node at the beginning # of the linked list def push(head_ref, new_data): # allocate node new_node =Node(0) # put in the data new_node.data = new_data # link the old list at the end #of the new node new_node.next = head_ref # move the head to point to the new node head_ref = new_node return head_ref front = Noneback = None # Split the nodes of the given list # into front and back halves,# and return the two lists # using the reference parameters.# Uses the fast/slow pointer strategy. def frontAndBackSplit( head): global front global back slow = None fast = None slow = head fast = head.next # Advance 'fast' two nodes, and # advance 'slow' one node while (fast != None): fast = fast.next if (fast != None): slow = slow.next fast = fast.next # 'slow' is before the midpoint in the list, # so split it in two at that point. front = head back = slow.next slow.next = None return head # Function to reverse the linked list def reverseList( head_ref): current = None prev = None next = None current = head_ref prev = None while (current != None): next = current.next current.next = prev prev = current current = next head_ref = prev return head_ref # perform the required subtraction operation # on the 1st half of the linked listdef modifyTheContentsOf1stHalf(): global front global back front1 = front back1 = back # traversing both the lists simultaneously while (back1 != None): # subtraction operation and node data # modification front1.data = front1.data - back1.data front1 = front1.next back1 = back1.next # function to concatenate the 2nd(back) list # at the end of the 1st(front) list and # returns the head of the new listdef concatFrontAndBackList( front, back): head = front if(front == None): return back while (front.next != None): front = front.next front.next = back return head # function to modify the contents of the linked listdef modifyTheList( head): global front global back # if list is empty or contains only single node if (head == None or head.next == None): return head front = None back = None # split the list into two halves # front and back lists frontAndBackSplit(head) # reverse the 2nd(back) list back = reverseList(back) # modify the contents of 1st half modifyTheContentsOf1stHalf() # agains reverse the 2nd(back) list back = reverseList(back) # concatenating the 2nd list back to the # end of the 1st list head = concatFrontAndBackList(front, back) # pointer to the modified list return head # function to print the linked listdef printList( head): if (head == None): return while (head.next != None): print(head.data , \" -> \",end=\"\") head = head.next print(head.data ) # Driver Code head = None # creating the linked listhead = push(head, 10)head = push(head, 7)head = push(head, 12)head = push(head, 8)head = push(head, 9)head = push(head, 2) # modify the linked listhead = modifyTheList(head) # print the modified linked listprint( \"Modified List:\" )printList(head) # This code is contributed by Arnab Kundu", "e": 13056, "s": 9329, "text": null }, { "code": "// C# implementation to modify the // contents of the linked listusing System; class GFG{ /* Linked list node */public class Node{ public int data; public Node next;}; /* Function to insert a node at the beginning of the linked list */static Node push(Node head_ref, int new_data){ /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list at the end of the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; return head_ref;} static Node front, back; /* Split the nodes of the given list into front and back halves,and return the two lists using the reference parameters.Uses the fast/slow pointer strategy. */static void frontAndBackSplit( Node head){ Node slow, fast; slow = head; fast = head.next; /* Advance 'fast' two nodes, and advance 'slow' one node */ while (fast != null) { fast = fast.next; if (fast != null) { slow = slow.next; fast = fast.next; } } /* 'slow' is before the midpoint in the list, so split it in two at that point. */ front = head; back = slow.next; slow.next = null;} /* Function to reverse the linked list */static Node reverseList(Node head_ref){ Node current, prev, next; current = head_ref; prev = null; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } head_ref = prev; return head_ref;} // perform the required subtraction operation // on the 1st half of the linked liststatic void modifyTheContentsOf1stHalf(){ Node front1 = front, back1 = back; // traversing both the lists simultaneously while (back1 != null) { // subtraction operation and node data // modification front1.data = front1.data - back1.data; front1 = front1.next; back1 = back1.next; }} // function to concatenate the 2nd(back) list // at the end of the 1st(front) list and // returns the head of the new liststatic Node concatFrontAndBackList(Node front, Node back){ Node head = front; if(front == null) return back; while (front.next != null) front = front.next; front.next = back; return head;} // function to modify the contents of// the linked liststatic Node modifyTheList(Node head){ // if list is empty or contains // only single node if (head == null || head.next == null) return head; front = null; back = null; // split the list into two halves // front and back lists frontAndBackSplit(head); // reverse the 2nd(back) list back = reverseList(back); // modify the contents of 1st half modifyTheContentsOf1stHalf(); // agains reverse the 2nd(back) list back = reverseList(back); // concatenating the 2nd list back to the // end of the 1st list head = concatFrontAndBackList(front, back); // pointer to the modified list return head;} // function to print the linked liststatic void printList( Node head){ if (head == null) return; while (head.next != null) { Console.Write(head.data + \" -> \"); head = head.next; } Console.WriteLine(head.data );} // Driver Codepublic static void Main(){ Node head = null; // creating the linked list head = push(head, 10); head = push(head, 7); head = push(head, 12); head = push(head, 8); head = push(head, 9); head = push(head, 2); // modify the linked list head = modifyTheList(head); // print the modified linked list Console.WriteLine( \"Modified List:\" ); printList(head);}} // This code is contributed by PrinciRaj1992", "e": 17019, "s": 13056, "text": null }, { "code": "<script> // JavaScript implementation to modify the // contents of the linked list /* Linked list node */ class Node { constructor() { this.data = 0; this.next = null; } } /* Function to insert a node at the beginning of the linked list */ function push(head_ref, new_data) { /* allocate node */ var new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list at the end of the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; return head_ref; } var front, back; /* Split the nodes of the given list into front and back halves, and return the two lists using the reference parameters. Uses the fast/slow pointer strategy. */ function frontAndBackSplit(head) { var slow, fast; slow = head; fast = head.next; /* Advance 'fast' two nodes, and advance 'slow' one node */ while (fast != null) { fast = fast.next; if (fast != null) { slow = slow.next; fast = fast.next; } } /* 'slow' is before the midpoint in the list, so split it in two at that point. */ front = head; back = slow.next; slow.next = null; } /* Function to reverse the linked list */ function reverseList(head_ref) { var current, prev, next; current = head_ref; prev = null; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } head_ref = prev; return head_ref; } // perform the required subtraction operation // on the 1st half of the linked list function modifyTheContentsOf1stHalf() { var front1 = front, back1 = back; // traversing both the lists simultaneously while (back1 != null) { // subtraction operation and node data // modification front1.data = front1.data - back1.data; front1 = front1.next; back1 = back1.next; } } // function to concatenate the 2nd(back) list // at the end of the 1st(front) list and // returns the head of the new list function concatFrontAndBackList(front, back) { var head = front; if (front == null) return back; while (front.next != null) front = front.next; front.next = back; return head; } // function to modify the contents of // the linked list function modifyTheList(head) { // if list is empty or contains // only single node if (head == null || head.next == null) return head; front = null; back = null; // split the list into two halves // front and back lists frontAndBackSplit(head); // reverse the 2nd(back) list back = reverseList(back); // modify the contents of 1st half modifyTheContentsOf1stHalf(); // agains reverse the 2nd(back) list back = reverseList(back); // concatenating the 2nd list back to the // end of the 1st list head = concatFrontAndBackList(front, back); // pointer to the modified list return head; } // function to print the linked list function printList(head) { if (head == null) return; while (head.next != null) { document.write(head.data + \" -> \"); head = head.next; } document.write(head.data + \"<br>\"); } // Driver Code var head = null; // creating the linked list head = push(head, 10); head = push(head, 7); head = push(head, 12); head = push(head, 8); head = push(head, 9); head = push(head, 2); // modify the linked list head = modifyTheList(head); // print the modified linked list document.write(\"Modified List: <br>\"); printList(head); </script>", "e": 21195, "s": 17019, "text": null }, { "code": null, "e": 21204, "s": 21195, "text": "Output: " }, { "code": null, "e": 21250, "s": 21204, "text": "Modified List:\n-8 -> 2 -> -4 -> 12 -> 7 -> 10" }, { "code": null, "e": 21305, "s": 21250, "text": "Time Complexity: O(n), where n in the number of nodes." }, { "code": null, "e": 21374, "s": 21305, "text": "Space complexity: O(1) since using constant space to modify pointers" }, { "code": null, "e": 21670, "s": 21374, "text": "Another approach (Using Stack) : 1. Find the starting point of second half Linked List. 2. Push all elements of second half list into stack s. 3. Traverse list starting from head using temp until stack is not empty and do Modify temp->data by subtracting the top element of stack for every node." }, { "code": null, "e": 21712, "s": 21670, "text": "Below is the implementation using stack. " }, { "code": null, "e": 21716, "s": 21712, "text": "C++" }, { "code": null, "e": 21721, "s": 21716, "text": "Java" }, { "code": null, "e": 21729, "s": 21721, "text": "Python3" }, { "code": null, "e": 21732, "s": 21729, "text": "C#" }, { "code": null, "e": 21743, "s": 21732, "text": "Javascript" }, { "code": "// C++ implementation to modify the// contents of the linked list#include <bits/stdc++.h>using namespace std; // Linked list nodestruct Node{ int data; struct Node* next;}; // function prototype for printing the listvoid printList(struct Node*); // Function to insert a node at the// beginning of the linked listvoid push(struct Node **head_ref, int new_data){ // allocate nodestruct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // put in the datanew_node->data = new_data; // link the old list at the end of the new nodenew_node->next = *head_ref; // move the head to point to the new node*head_ref = new_node;} // function to print the linked listvoid printList(struct Node *head){ if (!head) return; while (head->next != NULL) { cout << head->data << \" -> \"; head = head->next; } cout << head->data << endl;} // Function to middle node of list.Node* find_mid(Node *head){ Node *temp = head, *slow = head, *fast = head ; while(fast && fast->next) { // Advance 'fast' two nodes, and // advance 'slow' one node slow = slow->next ; fast = fast->next->next ; } // If number of nodes are odd then update slow // by slow->next; if(fast) slow = slow->next ; return slow ;} // function to modify the contents of the linked list.void modifyTheList(struct Node *head, struct Node *slow){// Create Stack. stack <int> s;Node *temp = head ; while(slow){ s.push( slow->data ) ; slow = slow->next ;} // Traverse the list by using temp until stack is empty.while( !s.empty() ){ temp->data = temp->data - s.top() ; temp = temp->next ; s.pop() ;} } // Driver program to test aboveint main(){ struct Node *head = NULL, *mid ; // creating the linked list push(&head, 10); push(&head, 7); push(&head, 12); push(&head, 8); push(&head, 9); push(&head, 2); // Call Function to Find the starting point of second half of list. mid = find_mid(head) ; // Call function to modify the contents of the linked list. modifyTheList( head, mid); // print the modified linked list cout << \"Modified List:\" << endl; printList(head); return 0;} // This is contributed by Mr. Gera", "e": 24034, "s": 21743, "text": null }, { "code": "// Java implementation to modify the// contents of the linked listimport java.util.*; class GFG { // Linked list node static class Node { int data; Node next; }; // Function to insert a node at the // beginning of the linked list static Node push(Node head_ref, int new_data) { // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // link the old list at the end of the new node new_node.next = head_ref; // move the head to point to the new node head_ref = new_node; return head_ref; } // function to print the linked list static void printList(Node head) { if (head == null) { return; } while (head.next != null) { System.out.print(head.data + \"->\"); head = head.next; } System.out.print(head.data + \"\\n\"); } // Function to middle node of list. static Node find_mid(Node head) { Node temp = head, slow = head, fast = head; while (fast != null && fast.next != null) { // Advance 'fast' two nodes, and // advance 'slow' one node slow = slow.next; fast = fast.next.next; } // If number of nodes are odd then update slow // by slow.next; if (fast != null) { slow = slow.next; } return slow; } // function to modify the contents of the linked list. static void modifyTheList(Node head, Node slow) { // Create Stack. Stack<Integer> s = new Stack<Integer>(); Node temp = head; while (slow != null) { s.add(slow.data); slow = slow.next; } // Traverse the list by using temp until stack is empty. while (!s.empty()) { temp.data = temp.data - s.peek(); temp = temp.next; s.pop(); } } // Driver program to test above public static void main(String[] args) { Node head = null, mid; // creating the linked list head = push(head, 10); head = push(head, 7); head = push(head, 12); head = push(head, 8); head = push(head, 9); head = push(head, 2); // Call Function to Find the starting // point of second half of list. mid = find_mid(head); // Call function to modify // the contents of the linked list. modifyTheList(head, mid); // print the modified linked list System.out.print(\"Modified List:\" + \"\\n\"); printList(head); }} // This code is contributed by Rajput-Ji", "e": 26785, "s": 24034, "text": null }, { "code": "# Python3 implementation to modify the# contents of the linked list # Linked list nodeclass Node: def __init__(self): self.data = 0 self.next = None # Function to insert a node at the# beginning of the linked listdef append(head_ref, new_data): # Allocate node new_node = Node() # Put in the data new_node.data = new_data # Link the old list at the end # of the new node new_node.next = head_ref # Move the head to point to the new node head_ref = new_node return head_ref # Function to print the linked listdef printList(head): if (not head): return; while (head.next != None): print(head.data, end = ' -> ') head = head.next print(head.data) # Function to middle node of list.def find_mid(head): temp = head slow = head fast = head while (fast and fast.next): # Advance 'fast' two nodes, and # advance 'slow' one node slow = slow.next fast = fast.next.next # If number of nodes are odd then # update slow by slow.next; if (fast): slow = slow.next return slow # Function to modify the contents of # the linked list.def modifyTheList(head, slow): # Create Stack. s = [] temp = head while (slow): s.append(slow.data) slow = slow.next # Traverse the list by using # temp until stack is empty. while (len(s) != 0): temp.data = temp.data - s[-1] temp = temp.next s.pop() # Driver codeif __name__=='__main__': head = None # creating the linked list head = append(head, 10) head = append(head, 7) head = append(head, 12) head = append(head, 8) head = append(head, 9) head = append(head, 2) # Call Function to Find the # starting point of second half of list. mid = find_mid(head) # Call function to modify the # contents of the linked list. modifyTheList( head, mid) # Print the modified linked list print(\"Modified List:\") printList(head) # This code is contributed by rutvik_56", "e": 28975, "s": 26785, "text": null }, { "code": "// C# implementation to modify the// contents of the linked listusing System;using System.Collections.Generic; class GFG { // Linked list node public class Node { public int data; public Node next; }; // Function to insert a node at the // beginning of the linked list static Node push(Node head_ref, int new_data) { // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // link the old list at the end of the new node new_node.next = head_ref; // move the head to point to the new node head_ref = new_node; return head_ref; } // function to print the linked list static void printList(Node head) { if (head == null) { return; } while (head.next != null) { Console.Write(head.data + \"->\"); head = head.next; } Console.Write(head.data + \"\\n\"); } // Function to middle node of list. static Node find_mid(Node head) { Node temp = head, slow = head, fast = head; while (fast != null && fast.next != null) { // Advance 'fast' two nodes, and // advance 'slow' one node slow = slow.next; fast = fast.next.next; } // If number of nodes are odd then update slow // by slow.next; if (fast != null) { slow = slow.next; } return slow; } // function to modify the contents of the linked list. static void modifyTheList(Node head, Node slow) { // Create Stack. Stack<int> s = new Stack<int>(); Node temp = head; while (slow != null) { s.Push(slow.data); slow = slow.next; } // Traverse the list by using temp until stack is empty. while (s.Count != 0) { temp.data = temp.data - s.Peek(); temp = temp.next; s.Pop(); } } // Driver code public static void Main(String[] args) { Node head = null, mid; // creating the linked list head = push(head, 10); head = push(head, 7); head = push(head, 12); head = push(head, 8); head = push(head, 9); head = push(head, 2); // Call Function to Find the starting // point of second half of list. mid = find_mid(head); // Call function to modify // the contents of the linked list. modifyTheList(head, mid); // print the modified linked list Console.Write(\"Modified List:\" + \"\\n\"); printList(head); }} // This code is contributed by PrinciRaj1992", "e": 31742, "s": 28975, "text": null }, { "code": "<script> // JavaScript implementation to modify the// contents of the linked list // Linked list nodeclass Node { constructor(val) { this.data = val; this.next = null; }} // Function to insert a node at the // beginning of the linked list function push(head_ref , new_data) { // allocate node var new_node = new Node(); // put in the data new_node.data = new_data; // link the old list at the end of the new node new_node.next = head_ref; // move the head to point to the new node head_ref = new_node; return head_ref; } // function to print the linked list function printList(head) { if (head == null) { return; } while (head.next != null) { document.write(head.data + \"->\"); head = head.next; } document.write(head.data + \"<br/>\"); } // Function to middle node of list. function find_mid(head) { var temp = head, slow = head, fast = head; while (fast != null && fast.next != null) { // Advance 'fast' two nodes, and // advance 'slow' one node slow = slow.next; fast = fast.next.next; } // If number of nodes are odd then update slow // by slow.next; if (fast != null) { slow = slow.next; } return slow; } // function to modify the contents of the linked list. function modifyTheList(head, slow) { // Create Stack. var s = []; var temp = head; while (slow != null) { s.push(slow.data); slow = slow.next; } // Traverse the list by using temp until stack is empty. while (s.length!=0) { temp.data = temp.data - s.pop(); temp = temp.next; } } // Driver program to test above var head = null, mid; // creating the linked list head = push(head, 10); head = push(head, 7); head = push(head, 12); head = push(head, 8); head = push(head, 9); head = push(head, 2); // Call Function to Find the starting // point of second half of list. mid = find_mid(head); // Call function to modify // the contents of the linked list. modifyTheList(head, mid); // print the modified linked list document.write(\"Modified List:\" + \"<br/>\"); printList(head); // This code contributed by Rajput-Ji </script>", "e": 34314, "s": 31742, "text": null }, { "code": null, "e": 34323, "s": 34314, "text": "Output: " }, { "code": null, "e": 34369, "s": 34323, "text": "Modified List:\n-8 -> 2 -> -4 -> 12 -> 7 -> 10" }, { "code": null, "e": 34484, "s": 34369, "text": "Time Complexity : O(n) Space Complexity : O(n/2)References: https://www.careercup.com/question?id=5657550909341696" }, { "code": null, "e": 34495, "s": 34484, "text": "andrew1234" }, { "code": null, "e": 34509, "s": 34495, "text": "princiraj1992" }, { "code": null, "e": 34519, "s": 34509, "text": "Rajput-Ji" }, { "code": null, "e": 34529, "s": 34519, "text": "rutvik_56" }, { "code": null, "e": 34546, "s": 34529, "text": "khushboogoyal499" }, { "code": null, "e": 34553, "s": 34546, "text": "rdtank" }, { "code": null, "e": 34570, "s": 34553, "text": "surinderdawra388" }, { "code": null, "e": 34587, "s": 34570, "text": "arorakashish0911" }, { "code": null, "e": 34599, "s": 34587, "text": "polymatir3j" }, { "code": null, "e": 34606, "s": 34599, "text": "Amazon" }, { "code": null, "e": 34618, "s": 34606, "text": "Linked List" }, { "code": null, "e": 34625, "s": 34618, "text": "Amazon" }, { "code": null, "e": 34637, "s": 34625, "text": "Linked List" }, { "code": null, "e": 34735, "s": 34637, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34767, "s": 34735, "text": "Introduction to Data Structures" }, { "code": null, "e": 34797, "s": 34767, "text": "Merge two sorted linked lists" }, { "code": null, "e": 34861, "s": 34797, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 34900, "s": 34861, "text": "Find the middle of a given linked list" }, { "code": null, "e": 34921, "s": 34900, "text": "Linked List vs Array" }, { "code": null, "e": 34949, "s": 34921, "text": "Merge Sort for Linked Lists" }, { "code": null, "e": 34996, "s": 34949, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 35048, "s": 34996, "text": "Add two numbers represented by linked lists | Set 1" }, { "code": null, "e": 35088, "s": 35048, "text": "Detect and Remove Loop in a Linked List" } ]
Vue.js Methods
10 Sep, 2021 A Vue method is an object associated with the Vue instance. Functions are defined inside the methods object. Methods are useful when you need to perform some action with v-on directive on an element to handle events. Functions defined inside the methods object can be further called for performing actions. Syntax: methods : { // We can add our functions here } Syntax for single file components: export default { methods: { // We can add our functions here } } In the following examples, we use Vue.js to show the working of methods. Example 1: HTML <!DOCTYPE html><html> <head> <script src= "https://unpkg.com/vue"> </script></head> <body> <div style="text-align: center;" id = "home"> <!-- Rendering data to DOM --> <h1 style="color: seagreen;">{{title}}</h1> <h2>Title : {{name}}</h2> <h2>Topic : {{topic}}</h2> <!-- Calling function in methods --> <h2>{{show()}}</h2> </div> </body><script type="text/javascript"> // Creating Vue Instance var vm = new Vue({ // Assigning id of DOM in parameter el: '#home', // Assigning values of parameter data: { title : "Geeks for Geeks", name : "Vue.js", topic : "Instances" }, // Creating methods methods : { // Creating function show: function(){ return "Welcome to this tutorial on " + this.name + " - " + this.topic; } } });</script> </html> Output: Vue App Example 2: HTML <!DOCTYPE html><html> <head> <script src= "https://unpkg.com/vue"> </script></head> <body> <div style="text-align: center;" id = "home"> <!-- Rendering data to DOM --> <h1 style="color: seagreen;">{{title}}</h1> <h2>Title : {{name}}</h2> <!-- Calling function in methods --> <button @click="show()">Click me</button> <h2 id="view"></h2> </div></body> <script type="text/javascript"> // Creating Vue Instance var vm = new Vue({ // Assigning id of DOM in parameter el: '#home', // Assigning values of parameter data: { title : "Geeks for Geeks", name : "Vue.js | Methods", }, // Creating methods methods : { // Creating function show: function(){ // Setting text in element document.getElementById("view") .innerHTML = "Hi, This is Vue" // Hiding text after 2 seconds setTimeout(() => { document.getElementById("view") .innerHTML = "" }, 2000); } } });</script> </html> Output: Before clicking the button: Before click After clicking the button: After click anikakapoor Vue.JS JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Sep, 2021" }, { "code": null, "e": 335, "s": 28, "text": "A Vue method is an object associated with the Vue instance. Functions are defined inside the methods object. Methods are useful when you need to perform some action with v-on directive on an element to handle events. Functions defined inside the methods object can be further called for performing actions." }, { "code": null, "e": 343, "s": 335, "text": "Syntax:" }, { "code": null, "e": 392, "s": 343, "text": "methods : {\n // We can add our functions here\n}" }, { "code": null, "e": 427, "s": 392, "text": "Syntax for single file components:" }, { "code": null, "e": 500, "s": 427, "text": "export default {\n methods: {\n // We can add our functions here\n }\n}" }, { "code": null, "e": 573, "s": 500, "text": "In the following examples, we use Vue.js to show the working of methods." }, { "code": null, "e": 584, "s": 573, "text": "Example 1:" }, { "code": null, "e": 589, "s": 584, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <script src= \"https://unpkg.com/vue\"> </script></head> <body> <div style=\"text-align: center;\" id = \"home\"> <!-- Rendering data to DOM --> <h1 style=\"color: seagreen;\">{{title}}</h1> <h2>Title : {{name}}</h2> <h2>Topic : {{topic}}</h2> <!-- Calling function in methods --> <h2>{{show()}}</h2> </div> </body><script type=\"text/javascript\"> // Creating Vue Instance var vm = new Vue({ // Assigning id of DOM in parameter el: '#home', // Assigning values of parameter data: { title : \"Geeks for Geeks\", name : \"Vue.js\", topic : \"Instances\" }, // Creating methods methods : { // Creating function show: function(){ return \"Welcome to this tutorial on \" + this.name + \" - \" + this.topic; } } });</script> </html>", "e": 1565, "s": 589, "text": null }, { "code": null, "e": 1576, "s": 1568, "text": "Output:" }, { "code": null, "e": 1586, "s": 1578, "text": "Vue App" }, { "code": null, "e": 1599, "s": 1588, "text": "Example 2:" }, { "code": null, "e": 1606, "s": 1601, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <script src= \"https://unpkg.com/vue\"> </script></head> <body> <div style=\"text-align: center;\" id = \"home\"> <!-- Rendering data to DOM --> <h1 style=\"color: seagreen;\">{{title}}</h1> <h2>Title : {{name}}</h2> <!-- Calling function in methods --> <button @click=\"show()\">Click me</button> <h2 id=\"view\"></h2> </div></body> <script type=\"text/javascript\"> // Creating Vue Instance var vm = new Vue({ // Assigning id of DOM in parameter el: '#home', // Assigning values of parameter data: { title : \"Geeks for Geeks\", name : \"Vue.js | Methods\", }, // Creating methods methods : { // Creating function show: function(){ // Setting text in element document.getElementById(\"view\") .innerHTML = \"Hi, This is Vue\" // Hiding text after 2 seconds setTimeout(() => { document.getElementById(\"view\") .innerHTML = \"\" }, 2000); } } });</script> </html>", "e": 2838, "s": 1606, "text": null }, { "code": null, "e": 2849, "s": 2841, "text": "Output:" }, { "code": null, "e": 2881, "s": 2851, "text": "Before clicking the button: " }, { "code": null, "e": 2894, "s": 2881, "text": "Before click" }, { "code": null, "e": 2923, "s": 2894, "text": "After clicking the button: " }, { "code": null, "e": 2935, "s": 2923, "text": "After click" }, { "code": null, "e": 2949, "s": 2937, "text": "anikakapoor" }, { "code": null, "e": 2956, "s": 2949, "text": "Vue.JS" }, { "code": null, "e": 2967, "s": 2956, "text": "JavaScript" }, { "code": null, "e": 2984, "s": 2967, "text": "Web Technologies" } ]
Convert OpenCV image to PIL image in Python
17 Dec, 2020 OpenCV is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human. When it is integrated with various libraries, such as Numpy which is a highly optimized library for numerical operations, then the number of weapons increases in your Arsenal i.e whatever operations one can do in Numpy can be combined with OpenCV. Python Imaging Library (expansion of PIL) is the de facto image processing package for Python language. It incorporates lightweight image processing tools that aid in editing, creating and saving images. Support for Python Imaging Library got discontinued in 2011, but a project named pillow forked the original PIL project and added Python3.x support to it. Pillow was announced as a replacement for PIL for future usage. Pillow supports numerous image file formats including BMP, PNG, JPEG, and TIFF. The library encourages adding support for newer formats in the library by creating new file decoders. The basic difference between OpenCV image and PIL image is OpenCV follows BGR color convention and PIL follows RGB color convention and the method of converting will be based on this difference. Import module We will take the input image using imread method of cv2 library. Syntax: imread(path, flag) Parameters: path: A string representing the path of the image to be read.flag: It specifies how the image should be read. Its default value is cv2.IMREAD_COLOR. path: A string representing the path of the image to be read. flag: It specifies how the image should be read. Its default value is cv2.IMREAD_COLOR. Return Value: This method returns an image that is loaded from the specified file. Then we will use cv2.cvtColor() method of cv2 library to change the color convention. Syntax: cvtColor(src, code[, dst[, dstCn]]) Parameters: src: It is the image whose color space is to be changed.code: It is the color space conversion code.dst: It is the output image of the same size and depth as src image. It is an optional parameter.dstCn: It is the number of channels in the destination image. If the parameter is 0 then the number of the channels is derived automatically from src and code. It is an optional parameter. src: It is the image whose color space is to be changed. code: It is the color space conversion code. dst: It is the output image of the same size and depth as src image. It is an optional parameter. dstCn: It is the number of channels in the destination image. If the parameter is 0 then the number of the channels is derived automatically from src and code. It is an optional parameter. Return Value: It returns an image. Displaying the image. You will notice that both the images will be identical even after conversion. Hence, we can say that we have successfully converted an OpenCV image to a PIL Image. Given below is the implementation using the above approach. Program: Python3 # Python program to convert from openCV2 to PIL import cv2from PIL import Image # Open image using openCV2opencv_image = cv2.imread("logo.png") # Notice the COLOR_BGR2RGB which means that the color is# converted from BGR to RGBcolor_coverted = cv2.cvtColor(opencv_image, cv2.COLOR_BGR2RGB) # Displaying the Scanned Image by using cv2.imshow() methodcv2.imshow("OpenCV Image", opencv_image) # Displaying the converted imagepil_image = Image.fromarray(color_coverted)pil_image.show() # waits for user to press any key# (this is necessary to avoid Python kernel form crashing)cv2.waitKey(0) # closing all open windowscv2.destroyAllWindows() Input: Output: OpenCV Image: PIL Image: Picked Python-OpenCV Python-pil Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Dec, 2020" }, { "code": null, "e": 556, "s": 28, "text": "OpenCV is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human. When it is integrated with various libraries, such as Numpy which is a highly optimized library for numerical operations, then the number of weapons increases in your Arsenal i.e whatever operations one can do in Numpy can be combined with OpenCV." }, { "code": null, "e": 1161, "s": 556, "text": "Python Imaging Library (expansion of PIL) is the de facto image processing package for Python language. It incorporates lightweight image processing tools that aid in editing, creating and saving images. Support for Python Imaging Library got discontinued in 2011, but a project named pillow forked the original PIL project and added Python3.x support to it. Pillow was announced as a replacement for PIL for future usage. Pillow supports numerous image file formats including BMP, PNG, JPEG, and TIFF. The library encourages adding support for newer formats in the library by creating new file decoders." }, { "code": null, "e": 1356, "s": 1161, "text": "The basic difference between OpenCV image and PIL image is OpenCV follows BGR color convention and PIL follows RGB color convention and the method of converting will be based on this difference." }, { "code": null, "e": 1370, "s": 1356, "text": "Import module" }, { "code": null, "e": 1435, "s": 1370, "text": "We will take the input image using imread method of cv2 library." }, { "code": null, "e": 1443, "s": 1435, "text": "Syntax:" }, { "code": null, "e": 1462, "s": 1443, "text": "imread(path, flag)" }, { "code": null, "e": 1474, "s": 1462, "text": "Parameters:" }, { "code": null, "e": 1623, "s": 1474, "text": "path: A string representing the path of the image to be read.flag: It specifies how the image should be read. Its default value is cv2.IMREAD_COLOR." }, { "code": null, "e": 1685, "s": 1623, "text": "path: A string representing the path of the image to be read." }, { "code": null, "e": 1773, "s": 1685, "text": "flag: It specifies how the image should be read. Its default value is cv2.IMREAD_COLOR." }, { "code": null, "e": 1856, "s": 1773, "text": "Return Value: This method returns an image that is loaded from the specified file." }, { "code": null, "e": 1942, "s": 1856, "text": "Then we will use cv2.cvtColor() method of cv2 library to change the color convention." }, { "code": null, "e": 1950, "s": 1942, "text": "Syntax:" }, { "code": null, "e": 1986, "s": 1950, "text": "cvtColor(src, code[, dst[, dstCn]])" }, { "code": null, "e": 1998, "s": 1986, "text": "Parameters:" }, { "code": null, "e": 2384, "s": 1998, "text": "src: It is the image whose color space is to be changed.code: It is the color space conversion code.dst: It is the output image of the same size and depth as src image. It is an optional parameter.dstCn: It is the number of channels in the destination image. If the parameter is 0 then the number of the channels is derived automatically from src and code. It is an optional parameter." }, { "code": null, "e": 2441, "s": 2384, "text": "src: It is the image whose color space is to be changed." }, { "code": null, "e": 2486, "s": 2441, "text": "code: It is the color space conversion code." }, { "code": null, "e": 2584, "s": 2486, "text": "dst: It is the output image of the same size and depth as src image. It is an optional parameter." }, { "code": null, "e": 2773, "s": 2584, "text": "dstCn: It is the number of channels in the destination image. If the parameter is 0 then the number of the channels is derived automatically from src and code. It is an optional parameter." }, { "code": null, "e": 2808, "s": 2773, "text": "Return Value: It returns an image." }, { "code": null, "e": 2830, "s": 2808, "text": "Displaying the image." }, { "code": null, "e": 2994, "s": 2830, "text": "You will notice that both the images will be identical even after conversion. Hence, we can say that we have successfully converted an OpenCV image to a PIL Image." }, { "code": null, "e": 3054, "s": 2994, "text": "Given below is the implementation using the above approach." }, { "code": null, "e": 3063, "s": 3054, "text": "Program:" }, { "code": null, "e": 3071, "s": 3063, "text": "Python3" }, { "code": "# Python program to convert from openCV2 to PIL import cv2from PIL import Image # Open image using openCV2opencv_image = cv2.imread(\"logo.png\") # Notice the COLOR_BGR2RGB which means that the color is# converted from BGR to RGBcolor_coverted = cv2.cvtColor(opencv_image, cv2.COLOR_BGR2RGB) # Displaying the Scanned Image by using cv2.imshow() methodcv2.imshow(\"OpenCV Image\", opencv_image) # Displaying the converted imagepil_image = Image.fromarray(color_coverted)pil_image.show() # waits for user to press any key# (this is necessary to avoid Python kernel form crashing)cv2.waitKey(0) # closing all open windowscv2.destroyAllWindows()", "e": 3716, "s": 3071, "text": null }, { "code": null, "e": 3723, "s": 3716, "text": "Input:" }, { "code": null, "e": 3731, "s": 3723, "text": "Output:" }, { "code": null, "e": 3745, "s": 3731, "text": "OpenCV Image:" }, { "code": null, "e": 3756, "s": 3745, "text": "PIL Image:" }, { "code": null, "e": 3765, "s": 3758, "text": "Picked" }, { "code": null, "e": 3779, "s": 3765, "text": "Python-OpenCV" }, { "code": null, "e": 3790, "s": 3779, "text": "Python-pil" }, { "code": null, "e": 3814, "s": 3790, "text": "Technical Scripter 2020" }, { "code": null, "e": 3821, "s": 3814, "text": "Python" }, { "code": null, "e": 3840, "s": 3821, "text": "Technical Scripter" }, { "code": null, "e": 3938, "s": 3840, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3970, "s": 3938, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3997, "s": 3970, "text": "Python Classes and Objects" }, { "code": null, "e": 4028, "s": 3997, "text": "Python | os.path.join() method" }, { "code": null, "e": 4049, "s": 4028, "text": "Python OOPs Concepts" }, { "code": null, "e": 4105, "s": 4049, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4128, "s": 4105, "text": "Introduction To PYTHON" }, { "code": null, "e": 4170, "s": 4128, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4212, "s": 4170, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4251, "s": 4212, "text": "Python | datetime.timedelta() function" } ]
Rename column by index in Pandas
26 Dec, 2020 Prerequisites: Pandas A column of a data frame can be changed using the position it is in known as its index. Just by the use of index a column can be renamed. This article discusses all such possible methods. Import required python library. Create data Provide index of the column to be renamed as argument to rename() function. Pandas rename() method is used to rename any index, column or row. Syntax: rename(mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False, level=None) Parameters: mapper, index and columns: Dictionary value, key refers to the old name and value refers to new name. Only one of these parameters can be used at once. axis: int or string value, 0/’row’ for Rows and 1/’columns’ for Columns copy: Copies underlying data if True. inplace: Makes changes in original Data Frame if True. level: Used to specify level in case data frame is having multiple level index. Return Type: Data frame with new names Given below are various implementation to achieve our required functionality: Example 1: Switching both column names with each other using column index. Python3 import pandas as pd # Sample DataFramedf = pd.DataFrame({'a': [1, 2], 'b': [3, 4]}) # Changing columns name with index numberdf.columns.values[0] = "b"df.columns.values[1] = "a" # Displaydisplay(df) Output: Example 2: Using another method to rename the column with index. Python3 import pandas as pd # Sample DataFramedf = pd.DataFrame({'a': [1, 2], 'b': [3, 4]}) # Changing columns name with index numbersu = df.rename(columns={df.columns[1]: 'new'}) # Displaydisplay(su) Output: Example 3: Renaming two/more columns in a single command using an index number. Python3 import pandas as pd # Sample DataFramedf = pd.DataFrame({'a': [1, 2], 'b': [3, 4], 'c': [7, 8]}) # Changing columns name with index numbermapping = {df.columns[0]: 'new0', df.columns[1]: 'new1'}su = df.rename(columns=mapping) # Displaydisplay(su) Output: Example 4: Renaming column name with an index number of the CSV file. File in use: Data1.csv Link: Click here Python3 import pandas as pd # reading a csv filedf1 = pd.read_csv("data1.csv") # change 2nd column name with index numberdf1.columns.values[2] = "city" # Display DataFramedisplay(df1) Output: Picked Python pandas-dataFrame Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Dec, 2020" }, { "code": null, "e": 50, "s": 28, "text": "Prerequisites: Pandas" }, { "code": null, "e": 239, "s": 50, "text": "A column of a data frame can be changed using the position it is in known as its index. Just by the use of index a column can be renamed. This article discusses all such possible methods. " }, { "code": null, "e": 271, "s": 239, "text": "Import required python library." }, { "code": null, "e": 283, "s": 271, "text": "Create data" }, { "code": null, "e": 359, "s": 283, "text": "Provide index of the column to be renamed as argument to rename() function." }, { "code": null, "e": 426, "s": 359, "text": "Pandas rename() method is used to rename any index, column or row." }, { "code": null, "e": 529, "s": 426, "text": "Syntax: rename(mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False, level=None)" }, { "code": null, "e": 541, "s": 529, "text": "Parameters:" }, { "code": null, "e": 693, "s": 541, "text": "mapper, index and columns: Dictionary value, key refers to the old name and value refers to new name. Only one of these parameters can be used at once." }, { "code": null, "e": 765, "s": 693, "text": "axis: int or string value, 0/’row’ for Rows and 1/’columns’ for Columns" }, { "code": null, "e": 803, "s": 765, "text": "copy: Copies underlying data if True." }, { "code": null, "e": 858, "s": 803, "text": "inplace: Makes changes in original Data Frame if True." }, { "code": null, "e": 938, "s": 858, "text": "level: Used to specify level in case data frame is having multiple level index." }, { "code": null, "e": 977, "s": 938, "text": "Return Type: Data frame with new names" }, { "code": null, "e": 1055, "s": 977, "text": "Given below are various implementation to achieve our required functionality:" }, { "code": null, "e": 1130, "s": 1055, "text": "Example 1: Switching both column names with each other using column index." }, { "code": null, "e": 1138, "s": 1130, "text": "Python3" }, { "code": "import pandas as pd # Sample DataFramedf = pd.DataFrame({'a': [1, 2], 'b': [3, 4]}) # Changing columns name with index numberdf.columns.values[0] = \"b\"df.columns.values[1] = \"a\" # Displaydisplay(df)", "e": 1340, "s": 1138, "text": null }, { "code": null, "e": 1348, "s": 1340, "text": "Output:" }, { "code": null, "e": 1413, "s": 1348, "text": "Example 2: Using another method to rename the column with index." }, { "code": null, "e": 1421, "s": 1413, "text": "Python3" }, { "code": "import pandas as pd # Sample DataFramedf = pd.DataFrame({'a': [1, 2], 'b': [3, 4]}) # Changing columns name with index numbersu = df.rename(columns={df.columns[1]: 'new'}) # Displaydisplay(su)", "e": 1617, "s": 1421, "text": null }, { "code": null, "e": 1625, "s": 1617, "text": "Output:" }, { "code": null, "e": 1705, "s": 1625, "text": "Example 3: Renaming two/more columns in a single command using an index number." }, { "code": null, "e": 1713, "s": 1705, "text": "Python3" }, { "code": "import pandas as pd # Sample DataFramedf = pd.DataFrame({'a': [1, 2], 'b': [3, 4], 'c': [7, 8]}) # Changing columns name with index numbermapping = {df.columns[0]: 'new0', df.columns[1]: 'new1'}su = df.rename(columns=mapping) # Displaydisplay(su)", "e": 1963, "s": 1713, "text": null }, { "code": null, "e": 1971, "s": 1963, "text": "Output:" }, { "code": null, "e": 2041, "s": 1971, "text": "Example 4: Renaming column name with an index number of the CSV file." }, { "code": null, "e": 2064, "s": 2041, "text": "File in use: Data1.csv" }, { "code": null, "e": 2081, "s": 2064, "text": "Link: Click here" }, { "code": null, "e": 2089, "s": 2081, "text": "Python3" }, { "code": "import pandas as pd # reading a csv filedf1 = pd.read_csv(\"data1.csv\") # change 2nd column name with index numberdf1.columns.values[2] = \"city\" # Display DataFramedisplay(df1)", "e": 2268, "s": 2089, "text": null }, { "code": null, "e": 2276, "s": 2268, "text": "Output:" }, { "code": null, "e": 2283, "s": 2276, "text": "Picked" }, { "code": null, "e": 2307, "s": 2283, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2330, "s": 2307, "text": "Python Pandas-exercise" }, { "code": null, "e": 2344, "s": 2330, "text": "Python-pandas" }, { "code": null, "e": 2351, "s": 2344, "text": "Python" }, { "code": null, "e": 2449, "s": 2351, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2481, "s": 2449, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2508, "s": 2481, "text": "Python Classes and Objects" }, { "code": null, "e": 2529, "s": 2508, "text": "Python OOPs Concepts" }, { "code": null, "e": 2552, "s": 2529, "text": "Introduction To PYTHON" }, { "code": null, "e": 2608, "s": 2552, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2639, "s": 2608, "text": "Python | os.path.join() method" }, { "code": null, "e": 2681, "s": 2639, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2723, "s": 2681, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2762, "s": 2723, "text": "Python | datetime.timedelta() function" } ]
Finding the smallest positive integer not present in an array in JavaScript
We are required to write a JavaScript function that takes in array of integers as the first and the only argument. Our function should find and return that smallest positive integer which is not present in the array. For example − If the input array is − const arr = [4, 2, -1, 0, 3, 9, 1, -5]; Then the output should be − const output = 5; because 1, 2, 3, 4 are already present in the array and 5 is the smallest positive integer absent from the array. Following is the code − const arr = [4, 2, -1, 0, 3, 9, 1, -5]; const findSmallestMissing = (arr = []) => { let count = 1; if(!arr?.length){ return count; }; while(arr.indexOf(count) !== -1){ count++; }; return count; }; console.log(findSmallestMissing(arr)); Following is the console output − 5
[ { "code": null, "e": 1302, "s": 1187, "text": "We are required to write a JavaScript function that takes in array of integers as the first and the only argument." }, { "code": null, "e": 1404, "s": 1302, "text": "Our function should find and return that smallest positive integer which is not present in the array." }, { "code": null, "e": 1418, "s": 1404, "text": "For example −" }, { "code": null, "e": 1442, "s": 1418, "text": "If the input array is −" }, { "code": null, "e": 1482, "s": 1442, "text": "const arr = [4, 2, -1, 0, 3, 9, 1, -5];" }, { "code": null, "e": 1510, "s": 1482, "text": "Then the output should be −" }, { "code": null, "e": 1528, "s": 1510, "text": "const output = 5;" }, { "code": null, "e": 1642, "s": 1528, "text": "because 1, 2, 3, 4 are already present in the array and 5 is the smallest positive integer absent from the array." }, { "code": null, "e": 1666, "s": 1642, "text": "Following is the code −" }, { "code": null, "e": 1932, "s": 1666, "text": "const arr = [4, 2, -1, 0, 3, 9, 1, -5];\nconst findSmallestMissing = (arr = []) => {\n let count = 1;\n if(!arr?.length){\n return count;\n };\n while(arr.indexOf(count) !== -1){\n count++;\n };\n return count;\n};\nconsole.log(findSmallestMissing(arr));" }, { "code": null, "e": 1966, "s": 1932, "text": "Following is the console output −" }, { "code": null, "e": 1968, "s": 1966, "text": "5" } ]
How to add and remove properties from objects in JavaScript ?
13 Jan, 2022 In this article, we will try to understand how to add properties to an object as well as how to add or remove the properties from an object in JavaScript. Before we actually go and see the addition and removal of properties from an object let us first understand the basics of an object in JavaScript. Object: An object in JavaScript is the collection of properties. A single property in a JavaScript object is actually the association between the name (or key ) and a value. An object can contain a different number of properties which is further having different names as well as values. Syntax: By using the following syntax one can easily create an object with a different number of properties. let object_name = { property_name: value, ... } Now that we have understood the basic details associated with the object in JavaScript, let us see some examples to add properties in an object as well as how to remove properties from an object. Adding/Removing Properties from an Object: As depicted in the above pictorial representation, we can easily add or remove several properties from an object in JavaScript by following certain methods or techniques. For adding any property, one could either use object_name.property_name = value (or) object_name[“property_name”] = value. For deleting any property, one could easily use delete object_name.property_name (or) delete object_name[“property_name”]. Let us see some examples in order to have a better understanding of how to add and remove properties from an object. Example 1: In this example, we first create an object, and further we will be adding some properties to it. Javascript <script> let object = { name: "ABC", email: "xyz@abc.com" }; console.log(object); // Adding some properties into the // above created object... object.age = 10; object.contact = 123467890; object.place = "Earth"; object["country"]= "India"; console.log(object);</script> Output: { name: 'ABC', email: 'xyz@abc.com' } { name: 'ABC', email: 'xyz@abc.com', age: 10, contact: 123467890, place: 'Earth', country: 'India' } Example 2: In this example, we will first create an object and then remove some properties. Javascript <script> let object = { name: "ABC", email: "xyz@abc.com", age: 10, contact: 1234567890, place: "Earth", country: "India", }; console.log(object); // Removing some properties // from the above created object delete object.age; // age property deletion console.log(object); // country property deletion delete object["country"]; console.log(object); delete object.place; // place property deletion console.log(object);</script> Output: { name: 'ABC', email: 'xyz@abc.com', age: 10, contact: 1234567890, place: 'Earth', country: 'India' } { name: 'ABC', email: 'xyz@abc.com', contact: 1234567890, place: 'Earth', country: 'India' } { name: 'ABC', email: 'xyz@abc.com', contact: 1234567890, place: 'Earth' } { name: 'ABC', email: 'xyz@abc.com', contact: 1234567890 } Example-3: In this example we will remove properties from the object by using another approach. This is the newest approach which doesn’t alter the original object. This approach is called Object Destructuring with rest parameters usage. Javascript let person_data = { first_name: "ABC", last_name: "DEF", age: 20, eye_color: "brown", place: "XYZ",}; let { eye_color, ...remainingObject } = person_data;console.log("Original Object...");console.log(person_data);console.log("Remaining Object.....");console.log(remainingObject); //Another way of Object Destructuing Approach Implementation...... let property_name = "place";let { [property_name]: removedProperty, ...restObject } = person_data;console.log("Remaining Object");console.log(restObject); //Another way of Object Destructuing Approach Implementation......let { place, age, ...leftObject } = person_data;console.log("Remaining Object");console.log(leftObject); // This code is contributed by Aman Singla.... Output: Original Object... { first_name: 'ABC', last_name: 'DEF', age: 20, eye_color: 'brown', place: 'XYZ' } Remaining Object..... { first_name: 'ABC', last_name: 'DEF', age: 20, place: 'XYZ' } Remaining Object { first_name: 'ABC', last_name: 'DEF', age: 20, eye_color: 'brown' } Remaining Object { first_name: 'ABC', last_name: 'DEF', eye_color: 'brown' } amansingla javascript-object JavaScript-Questions Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Jan, 2022" }, { "code": null, "e": 209, "s": 54, "text": "In this article, we will try to understand how to add properties to an object as well as how to add or remove the properties from an object in JavaScript." }, { "code": null, "e": 356, "s": 209, "text": "Before we actually go and see the addition and removal of properties from an object let us first understand the basics of an object in JavaScript." }, { "code": null, "e": 364, "s": 356, "text": "Object:" }, { "code": null, "e": 421, "s": 364, "text": "An object in JavaScript is the collection of properties." }, { "code": null, "e": 530, "s": 421, "text": "A single property in a JavaScript object is actually the association between the name (or key ) and a value." }, { "code": null, "e": 644, "s": 530, "text": "An object can contain a different number of properties which is further having different names as well as values." }, { "code": null, "e": 753, "s": 644, "text": "Syntax: By using the following syntax one can easily create an object with a different number of properties." }, { "code": null, "e": 809, "s": 753, "text": "let object_name =\n{\n property_name: value,\n ...\n}" }, { "code": null, "e": 1005, "s": 809, "text": "Now that we have understood the basic details associated with the object in JavaScript, let us see some examples to add properties in an object as well as how to remove properties from an object." }, { "code": null, "e": 1048, "s": 1005, "text": "Adding/Removing Properties from an Object:" }, { "code": null, "e": 1219, "s": 1048, "text": "As depicted in the above pictorial representation, we can easily add or remove several properties from an object in JavaScript by following certain methods or techniques." }, { "code": null, "e": 1342, "s": 1219, "text": "For adding any property, one could either use object_name.property_name = value (or) object_name[“property_name”] = value." }, { "code": null, "e": 1466, "s": 1342, "text": "For deleting any property, one could easily use delete object_name.property_name (or) delete object_name[“property_name”]." }, { "code": null, "e": 1583, "s": 1466, "text": "Let us see some examples in order to have a better understanding of how to add and remove properties from an object." }, { "code": null, "e": 1691, "s": 1583, "text": "Example 1: In this example, we first create an object, and further we will be adding some properties to it." }, { "code": null, "e": 1702, "s": 1691, "text": "Javascript" }, { "code": "<script> let object = { name: \"ABC\", email: \"xyz@abc.com\" }; console.log(object); // Adding some properties into the // above created object... object.age = 10; object.contact = 123467890; object.place = \"Earth\"; object[\"country\"]= \"India\"; console.log(object);</script>", "e": 2021, "s": 1702, "text": null }, { "code": null, "e": 2029, "s": 2021, "text": "Output:" }, { "code": null, "e": 2180, "s": 2029, "text": "{ name: 'ABC', email: 'xyz@abc.com' }\n{\n name: 'ABC',\n email: 'xyz@abc.com',\n age: 10,\n contact: 123467890,\n place: 'Earth',\n country: 'India'\n}" }, { "code": null, "e": 2272, "s": 2180, "text": "Example 2: In this example, we will first create an object and then remove some properties." }, { "code": null, "e": 2283, "s": 2272, "text": "Javascript" }, { "code": "<script> let object = { name: \"ABC\", email: \"xyz@abc.com\", age: 10, contact: 1234567890, place: \"Earth\", country: \"India\", }; console.log(object); // Removing some properties // from the above created object delete object.age; // age property deletion console.log(object); // country property deletion delete object[\"country\"]; console.log(object); delete object.place; // place property deletion console.log(object);</script>", "e": 2798, "s": 2283, "text": null }, { "code": null, "e": 2806, "s": 2798, "text": "Output:" }, { "code": null, "e": 3170, "s": 2806, "text": "{\n name: 'ABC',\n email: 'xyz@abc.com',\n age: 10,\n contact: 1234567890,\n place: 'Earth',\n country: 'India'\n}\n{\n name: 'ABC',\n email: 'xyz@abc.com',\n contact: 1234567890,\n place: 'Earth',\n country: 'India'\n}\n{\n name: 'ABC',\n email: 'xyz@abc.com',\n contact: 1234567890,\n place: 'Earth'\n}\n{\n name: 'ABC', \n email: 'xyz@abc.com', \n contact: 1234567890\n}" }, { "code": null, "e": 3181, "s": 3170, "text": "Example-3:" }, { "code": null, "e": 3266, "s": 3181, "text": "In this example we will remove properties from the object by using another approach." }, { "code": null, "e": 3335, "s": 3266, "text": "This is the newest approach which doesn’t alter the original object." }, { "code": null, "e": 3408, "s": 3335, "text": "This approach is called Object Destructuring with rest parameters usage." }, { "code": null, "e": 3419, "s": 3408, "text": "Javascript" }, { "code": "let person_data = { first_name: \"ABC\", last_name: \"DEF\", age: 20, eye_color: \"brown\", place: \"XYZ\",}; let { eye_color, ...remainingObject } = person_data;console.log(\"Original Object...\");console.log(person_data);console.log(\"Remaining Object.....\");console.log(remainingObject); //Another way of Object Destructuing Approach Implementation...... let property_name = \"place\";let { [property_name]: removedProperty, ...restObject } = person_data;console.log(\"Remaining Object\");console.log(restObject); //Another way of Object Destructuing Approach Implementation......let { place, age, ...leftObject } = person_data;console.log(\"Remaining Object\");console.log(leftObject); // This code is contributed by Aman Singla....", "e": 4159, "s": 3419, "text": null }, { "code": null, "e": 4167, "s": 4159, "text": "Output:" }, { "code": null, "e": 4522, "s": 4167, "text": "Original Object...\n{ first_name: 'ABC', last_name: 'DEF', age: 20, \n eye_color: 'brown', place: 'XYZ' }\nRemaining Object.....\n{ first_name: 'ABC', last_name: 'DEF', age: 20, place: 'XYZ' }\nRemaining Object\n{ first_name: 'ABC', last_name: 'DEF', age: 20, eye_color: 'brown' }\nRemaining Object\n{ first_name: 'ABC', last_name: 'DEF', eye_color: 'brown' }" }, { "code": null, "e": 4533, "s": 4522, "text": "amansingla" }, { "code": null, "e": 4551, "s": 4533, "text": "javascript-object" }, { "code": null, "e": 4572, "s": 4551, "text": "JavaScript-Questions" }, { "code": null, "e": 4579, "s": 4572, "text": "Picked" }, { "code": null, "e": 4590, "s": 4579, "text": "JavaScript" }, { "code": null, "e": 4607, "s": 4590, "text": "Web Technologies" }, { "code": null, "e": 4705, "s": 4607, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4766, "s": 4705, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4806, "s": 4766, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4847, "s": 4806, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 4889, "s": 4847, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 4911, "s": 4889, "text": "JavaScript | Promises" }, { "code": null, "e": 4944, "s": 4911, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 5006, "s": 4944, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5067, "s": 5006, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5117, "s": 5067, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
What is the use of tilde operator (~) in R?
Tilde operator is used to define the relationship between dependent variable and independent variables in a statistical model formula. The variable on the left-hand side of tilde operator is the dependent variable and the variable(s) on the right-hand side of tilde operator is/are called the independent variable(s). So, tilde operator helps to define that dependent variable depends on the independent variable(s) that are on the right-hand side of tilde operator. > Regression_Model <- lm(y~ x1 + x2 + x3) Here, the object Regression_Model stores the formula for linear regression model created by using function lm and y is the dependent variable and x1, x2, and x3 are independent variables. This model can be created by using a dot (.) if we want to include all the independent variables but for this purpose, we should have all the variables stored in a data frame. > Regression_Data <- data.frame(x1, x2, x3, y) > Regression_Model_New < - lm(y~ . , data = Regression_Data) This will have the same output as the previous model, but we cannot use tilde with dot if we want to create a model with few variables. Suppose you want to create a new model with x1 and x3 only then it can be done as follows − > Regression_Model_New1 <- lm(y~ x1 + x3, data = Regression_Data) But we cannot do it using dot with tilde as − > Regression_Model_New2_Incorrect <- lm(y~ . + x3, data = Regression_Data) https://www.tutorialspoint.com/how-to-write-text-and-output-it-as-a-text-file-using-r
[ { "code": null, "e": 1654, "s": 1187, "text": "Tilde operator is used to define the relationship between dependent variable and independent variables in a statistical model formula. The variable on the left-hand side of tilde operator is the dependent variable and the variable(s) on the right-hand side of tilde operator is/are called the independent variable(s). So, tilde operator helps to define that dependent variable depends on the independent variable(s) that are on the right-hand side of tilde operator." }, { "code": null, "e": 1696, "s": 1654, "text": "> Regression_Model <- lm(y~ x1 + x2 + x3)" }, { "code": null, "e": 1884, "s": 1696, "text": "Here, the object Regression_Model stores the formula for linear regression model created by using function lm and y is the dependent variable and x1, x2, and x3 are independent variables." }, { "code": null, "e": 2060, "s": 1884, "text": "This model can be created by using a dot (.) if we want to include all the independent variables but for this purpose, we should have all the variables stored in a data frame." }, { "code": null, "e": 2168, "s": 2060, "text": "> Regression_Data <- data.frame(x1, x2, x3, y)\n> Regression_Model_New < - lm(y~ . , data = Regression_Data)" }, { "code": null, "e": 2304, "s": 2168, "text": "This will have the same output as the previous model, but we cannot use tilde with dot if we want to create a model with few variables." }, { "code": null, "e": 2396, "s": 2304, "text": "Suppose you want to create a new model with x1 and x3 only then it can be done as follows −" }, { "code": null, "e": 2463, "s": 2396, "text": "> Regression_Model_New1 <- lm(y~ x1 + x3, data = Regression_Data)\n" }, { "code": null, "e": 2509, "s": 2463, "text": "But we cannot do it using dot with tilde as −" }, { "code": null, "e": 2584, "s": 2509, "text": "> Regression_Model_New2_Incorrect <- lm(y~ . + x3, data = Regression_Data)" }, { "code": null, "e": 2670, "s": 2584, "text": "https://www.tutorialspoint.com/how-to-write-text-and-output-it-as-a-text-file-using-r" } ]
Count pairs in a sorted array whose sum is less than x
08 Jul, 2022 Given a sorted integer array and number x, the task is to count pairs in array whose sum is less than x. Examples: Input : arr[] = {1, 3, 7, 9, 10, 11} x = 7 Output : 1 There is only one pair (1, 3) Input : arr[] = {1, 2, 3, 4, 5, 6, 7, 8} x = 7 Output : 6 Pairs are (1, 2), (1, 3), (1, 4), (1, 5) (2, 3) and (2, 4) A simple solution of this problem run two loops to generate all pairs and one by one and check if current pair’s sum is less than x or not. An Efficient solution of this problem is take initial and last value of index in l and r variable. 1) Initialize two variables l and r to find the candidate elements in the sorted array. (a) l = 0 (b) r = n - 1 2) Initialize : result = 0 2) Loop while l < r. // If current left and current // right have sum smaller than x, // the all elements from l+1 to r // form a pair with current (a) If (arr[l] + arr[r] < x) result = result + (r - l) (b) Else r--; 3) Return result Below is the implementation of above steps. C++ Java Python3 C# PHP Javascript // C++ program to count pairs in an array// whose sum is less than given number x#include<bits/stdc++.h>using namespace std; // Function to count pairs in array// with sum less than x.int findPairs(int arr[],int n,int x){ int l = 0, r = n-1; int result = 0; while (l < r) { // If current left and current // right have sum smaller than x, // the all elements from l+1 to r // form a pair with current l. if (arr[l] + arr[r] < x) { result += (r - l); l++; } // Move to smaller value else r--; } return result;} // Driven codeint main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; int n = sizeof(arr)/sizeof(int); int x = 7; cout << findPairs(arr, n, x); return 0;} // Java program to count pairs in an array// whose sum is less than given number xclass GFG { // Function to count pairs in array // with sum less than x. static int findPairs(int arr[], int n, int x) { int l = 0, r = n - 1; int result = 0; while (l < r) { // If current left and current // right have sum smaller than x, // the all elements from l+1 to r // form a pair with current l. if (arr[l] + arr[r] < x) { result += (r - l); l++; } // Move to smaller value else r--; } return result; } // Driver method public static void main(String[] args) { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; int n = arr.length; int x = 7; System.out.print(findPairs(arr, n, x)); }} // This code is contributed by Anant Agarwal. # Python3 program to count pairs# in an array whose sum is less# than given number x # Function to count pairs in array# with sum less than x.def findPairs(arr, n, x): l = 0; r = n-1 result = 0 while (l < r): # If current left and current # right have sum smaller than x, # the all elements from l+1 to r # form a pair with current l. if (arr[l] + arr[r] < x): result += (r - l) l += 1 # Move to smaller value else: r -= 1 return result # Driver Codearr = [1, 2, 3, 4, 5, 6, 7, 8]n = len(arr)x = 7print(findPairs(arr, n, x)) # This code is contributed by Anant Agarwal. // C# program to count pairs in// an array whose sum is less// than given number xusing System; class GFG { // Function to count pairs in array // with sum less than x. static int findPairs(int []arr, int n, int x) { int l = 0, r = n - 1; int result = 0; while (l < r) { // If current left and current // right have sum smaller than x, // the all elements from l+1 to r // form a pair with current l. if (arr[l] + arr[r] < x) { result += (r - l); l++; } // Move to smaller value else r--; } return result; } // Driver code public static void Main(String[] args) { int []arr = {1, 2, 3, 4, 5, 6, 7, 8}; int n = arr.Length; int x = 7; Console.Write(findPairs(arr, n, x)); }} // This code is contributed by parashar... <?php// PHP program to count pairs in an array// whose sum is less than given number x // Function to count pairs in array// with sum less than x.function findPairs($arr,$n,$x){ $l = 0; $r = $n - 1; $result = 0; while ($l < $r) { // If current left and current // right have sum smaller than x, // the all elements from l+1 to r // form a pair with current l. if ($arr[$l] + $arr[$r] < $x) { $result += ($r - $l); $l++; } // Move to smaller value else $r--; } return $result;} // Driver Code $arr = array(1, 2, 3, 4, 5, 6, 7, 8); $n = sizeof($arr) / sizeof($arr[0]); $x = 7; echo findPairs($arr, $n, $x); return 0; // This code is contributed by nitin mittal.?> <script>//javascript program to count pairs in an array// whose sum is less than given number x// Function to count pairs in array// with sum less than x.function findPairs(arr,n,x){ let l = 0, r = n-1; let result = 0; while (l < r) { // If current left and current // right have sum smaller than x, // the all elements from l+1 to r // form a pair with current l. if (arr[l] + arr[r] < x) { result += (r - l); l++; } // Move to smaller value else r--; } return result;} let arr = [1, 2, 3, 4, 5, 6, 7, 8]; let n = arr.length; let x = 7; document.write(findPairs(arr,n,x)); // This code is contributed by vaibhavrabadiya117.</script> 6 Time complexity : O(n) Auxiliary Space : O(1) Using Policy Based Data structure: Its also works for the unsorted array C++ #include <iostream>using namespace std;#include <ext/pb_ds/assoc_container.hpp>#include <ext/pb_ds/tree_policy.hpp>using namespace __gnu_pbds;#define ordered_set \ tree<pair<int, int>, null_type, less<pair<int, int> >, \ rb_tree_tag, tree_order_statistics_node_update> int countPair(vector<int> v, int sum){ int ans = 0; ordered_set st; int y = 0; for (auto i = v.rbegin(); i != v.rend(); i++) { int num = *i; if (st.empty()) st.insert({ num, y }); else { int left = sum - num; ans += st.order_of_key({ left, -1 }); st.insert({ num, y }); } y++; } return ans;}int main(){ int n; cin >> n; vector<int> v{ 1, 2, 3, 4, 5, 6, 7, 8 }; int sum = 7; cout << countPair(v, sum); return 0;} 6 Time complexity : O(n) Auxiliary Space : O(n) Extension: If array is unsorted, then we can sort the array first and then apply above method to solve in O(n Log n) time and Auxiliary Space required = O(n), where n represents the size of the given array. Related Articles: Count all distinct pairs with difference equal to k Count pairs with given sum This article is contributed by DANISH_RAZA . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. parashar nitin mittal vaibhavrabadiya117 shivamgoel150 tamanna17122007 hardikkoriintern 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 Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Introduction to Arrays K'th Smallest/Largest Element in Unsorted Array | Set 1 Subset Sum Problem | DP-25 Introduction to Data Structures Python | Using 2D arrays/lists the right way
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jul, 2022" }, { "code": null, "e": 157, "s": 52, "text": "Given a sorted integer array and number x, the task is to count pairs in array whose sum is less than x." }, { "code": null, "e": 168, "s": 157, "text": "Examples: " }, { "code": null, "e": 402, "s": 168, "text": "Input : arr[] = {1, 3, 7, 9, 10, 11}\n x = 7\nOutput : 1\nThere is only one pair (1, 3)\n\nInput : arr[] = {1, 2, 3, 4, 5, 6, 7, 8}\n x = 7\nOutput : 6\nPairs are (1, 2), (1, 3), (1, 4), (1, 5)\n (2, 3) and (2, 4) " }, { "code": null, "e": 542, "s": 402, "text": "A simple solution of this problem run two loops to generate all pairs and one by one and check if current pair’s sum is less than x or not." }, { "code": null, "e": 642, "s": 542, "text": "An Efficient solution of this problem is take initial and last value of index in l and r variable. " }, { "code": null, "e": 1100, "s": 642, "text": "1) Initialize two variables l and r to find the candidate \n elements in the sorted array.\n (a) l = 0\n (b) r = n - 1\n2) Initialize : result = 0\n2) Loop while l < r.\n\n // If current left and current\n // right have sum smaller than x,\n // the all elements from l+1 to r\n // form a pair with current\n (a) If (arr[l] + arr[r] < x) \n result = result + (r - l) \n \n (b) Else\n r--;\n \n3) Return result" }, { "code": null, "e": 1145, "s": 1100, "text": "Below is the implementation of above steps. " }, { "code": null, "e": 1149, "s": 1145, "text": "C++" }, { "code": null, "e": 1154, "s": 1149, "text": "Java" }, { "code": null, "e": 1162, "s": 1154, "text": "Python3" }, { "code": null, "e": 1165, "s": 1162, "text": "C#" }, { "code": null, "e": 1169, "s": 1165, "text": "PHP" }, { "code": null, "e": 1180, "s": 1169, "text": "Javascript" }, { "code": "// C++ program to count pairs in an array// whose sum is less than given number x#include<bits/stdc++.h>using namespace std; // Function to count pairs in array// with sum less than x.int findPairs(int arr[],int n,int x){ int l = 0, r = n-1; int result = 0; while (l < r) { // If current left and current // right have sum smaller than x, // the all elements from l+1 to r // form a pair with current l. if (arr[l] + arr[r] < x) { result += (r - l); l++; } // Move to smaller value else r--; } return result;} // Driven codeint main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; int n = sizeof(arr)/sizeof(int); int x = 7; cout << findPairs(arr, n, x); return 0;}", "e": 1971, "s": 1180, "text": null }, { "code": "// Java program to count pairs in an array// whose sum is less than given number xclass GFG { // Function to count pairs in array // with sum less than x. static int findPairs(int arr[], int n, int x) { int l = 0, r = n - 1; int result = 0; while (l < r) { // If current left and current // right have sum smaller than x, // the all elements from l+1 to r // form a pair with current l. if (arr[l] + arr[r] < x) { result += (r - l); l++; } // Move to smaller value else r--; } return result; } // Driver method public static void main(String[] args) { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; int n = arr.length; int x = 7; System.out.print(findPairs(arr, n, x)); }} // This code is contributed by Anant Agarwal.", "e": 2987, "s": 1971, "text": null }, { "code": "# Python3 program to count pairs# in an array whose sum is less# than given number x # Function to count pairs in array# with sum less than x.def findPairs(arr, n, x): l = 0; r = n-1 result = 0 while (l < r): # If current left and current # right have sum smaller than x, # the all elements from l+1 to r # form a pair with current l. if (arr[l] + arr[r] < x): result += (r - l) l += 1 # Move to smaller value else: r -= 1 return result # Driver Codearr = [1, 2, 3, 4, 5, 6, 7, 8]n = len(arr)x = 7print(findPairs(arr, n, x)) # This code is contributed by Anant Agarwal.", "e": 3682, "s": 2987, "text": null }, { "code": "// C# program to count pairs in// an array whose sum is less// than given number xusing System; class GFG { // Function to count pairs in array // with sum less than x. static int findPairs(int []arr, int n, int x) { int l = 0, r = n - 1; int result = 0; while (l < r) { // If current left and current // right have sum smaller than x, // the all elements from l+1 to r // form a pair with current l. if (arr[l] + arr[r] < x) { result += (r - l); l++; } // Move to smaller value else r--; } return result; } // Driver code public static void Main(String[] args) { int []arr = {1, 2, 3, 4, 5, 6, 7, 8}; int n = arr.Length; int x = 7; Console.Write(findPairs(arr, n, x)); }} // This code is contributed by parashar...", "e": 4728, "s": 3682, "text": null }, { "code": "<?php// PHP program to count pairs in an array// whose sum is less than given number x // Function to count pairs in array// with sum less than x.function findPairs($arr,$n,$x){ $l = 0; $r = $n - 1; $result = 0; while ($l < $r) { // If current left and current // right have sum smaller than x, // the all elements from l+1 to r // form a pair with current l. if ($arr[$l] + $arr[$r] < $x) { $result += ($r - $l); $l++; } // Move to smaller value else $r--; } return $result;} // Driver Code $arr = array(1, 2, 3, 4, 5, 6, 7, 8); $n = sizeof($arr) / sizeof($arr[0]); $x = 7; echo findPairs($arr, $n, $x); return 0; // This code is contributed by nitin mittal.?>", "e": 5538, "s": 4728, "text": null }, { "code": "<script>//javascript program to count pairs in an array// whose sum is less than given number x// Function to count pairs in array// with sum less than x.function findPairs(arr,n,x){ let l = 0, r = n-1; let result = 0; while (l < r) { // If current left and current // right have sum smaller than x, // the all elements from l+1 to r // form a pair with current l. if (arr[l] + arr[r] < x) { result += (r - l); l++; } // Move to smaller value else r--; } return result;} let arr = [1, 2, 3, 4, 5, 6, 7, 8]; let n = arr.length; let x = 7; document.write(findPairs(arr,n,x)); // This code is contributed by vaibhavrabadiya117.</script>", "e": 6302, "s": 5538, "text": null }, { "code": null, "e": 6304, "s": 6302, "text": "6" }, { "code": null, "e": 6350, "s": 6304, "text": "Time complexity : O(n) Auxiliary Space : O(1)" }, { "code": null, "e": 6385, "s": 6350, "text": "Using Policy Based Data structure:" }, { "code": null, "e": 6424, "s": 6385, "text": "Its also works for the unsorted array " }, { "code": null, "e": 6428, "s": 6424, "text": "C++" }, { "code": "#include <iostream>using namespace std;#include <ext/pb_ds/assoc_container.hpp>#include <ext/pb_ds/tree_policy.hpp>using namespace __gnu_pbds;#define ordered_set \\ tree<pair<int, int>, null_type, less<pair<int, int> >, \\ rb_tree_tag, tree_order_statistics_node_update> int countPair(vector<int> v, int sum){ int ans = 0; ordered_set st; int y = 0; for (auto i = v.rbegin(); i != v.rend(); i++) { int num = *i; if (st.empty()) st.insert({ num, y }); else { int left = sum - num; ans += st.order_of_key({ left, -1 }); st.insert({ num, y }); } y++; } return ans;}int main(){ int n; cin >> n; vector<int> v{ 1, 2, 3, 4, 5, 6, 7, 8 }; int sum = 7; cout << countPair(v, sum); return 0;}", "e": 7282, "s": 6428, "text": null }, { "code": null, "e": 7284, "s": 7282, "text": "6" }, { "code": null, "e": 7330, "s": 7284, "text": "Time complexity : O(n) Auxiliary Space : O(n)" }, { "code": null, "e": 7537, "s": 7330, "text": "Extension: If array is unsorted, then we can sort the array first and then apply above method to solve in O(n Log n) time and Auxiliary Space required = O(n), where n represents the size of the given array." }, { "code": null, "e": 7634, "s": 7537, "text": "Related Articles: Count all distinct pairs with difference equal to k Count pairs with given sum" }, { "code": null, "e": 7930, "s": 7634, "text": "This article is contributed by DANISH_RAZA . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 7939, "s": 7930, "text": "parashar" }, { "code": null, "e": 7952, "s": 7939, "text": "nitin mittal" }, { "code": null, "e": 7971, "s": 7952, "text": "vaibhavrabadiya117" }, { "code": null, "e": 7985, "s": 7971, "text": "shivamgoel150" }, { "code": null, "e": 8001, "s": 7985, "text": "tamanna17122007" }, { "code": null, "e": 8018, "s": 8001, "text": "hardikkoriintern" }, { "code": null, "e": 8025, "s": 8018, "text": "Arrays" }, { "code": null, "e": 8032, "s": 8025, "text": "Arrays" }, { "code": null, "e": 8130, "s": 8032, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8198, "s": 8130, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 8242, "s": 8198, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 8274, "s": 8242, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 8322, "s": 8274, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 8336, "s": 8322, "text": "Linear Search" }, { "code": null, "e": 8359, "s": 8336, "text": "Introduction to Arrays" }, { "code": null, "e": 8415, "s": 8359, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 8442, "s": 8415, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 8474, "s": 8442, "text": "Introduction to Data Structures" } ]
PySpark dataframe add column based on other columns
23 Aug, 2021 In this article, we are going to see how to add columns based on another column to the Pyspark Dataframe. Creating Dataframe for demonstration: Here we are going to create a dataframe from a list of the given dataset. Python3 # Create a spark sessionfrom pyspark.sql import SparkSessionspark = SparkSession.builder.appName('SparkExamples').getOrCreate() # Create a spark dataframecolumns = ["Name", "Course_Name", "Months", "Course_Fees", "Discount", "Start_Date", "Payment_Done"]data = [ ("Amit Pathak", "Python", 3, 10000, 1000, "02-07-2021", True), ("Shikhar Mishra", "Soft skills", 2, 8000, 800, "07-10-2021", False), ("Shivani Suvarna", "Accounting", 6, 15000, 1500, "20-08-2021", True), ("Pooja Jain", "Data Science", 12, 60000, 900, "02-12-2021", False),] df = spark.createDataFrame(data).toDF(*columns) # View the dataframedf.show() Output: It is used to change the value, convert the datatype of an existing column, create a new column, and many more. Syntax: df.withColumn(colName, col) Returns: A new :class:`DataFrame` by adding a column or replacing the existing column that has the same name. Python3 new_df = df.withColumn('After_discount', df.Course_Fees - df.Discount)new_df.show() Output: Here we will use SQL query inside the Pyspark, We will create a temp view of the table with the help of createTempView() and the life of this temp is up to the life of the sparkSession. registerTempTable() will create the temp table if it is not available or if it is available then replace it. Then after creating the table select the table by SQL clause which will take all the values as a string. Python3 df.registerTempTable('table')newDF = spark.sql('select *, Course_Fees - Discount as Total from table')newDF.show() Output: In this method, we will define the user define a function that will take two parameters and return the total price. This function allows us to create a new function as per our requirements. Now we define the data type of the UDF function and create the functions which will return the values which is the sum of all values in the row. Python3 # import the functions as F from pyspark.sqlimport pyspark.sql.functions as Ffrom pyspark.sql.types import IntegerType # define the sum_coldef Total(Course_Fees, Discount): res = Course_Fees - Discount return res # integer datatype is definednew_f = F.udf(Total, IntegerType()) # calling and creating the new# col as udf_method_sumnew_df = df.withColumn( "Total_price", new_f("Course_Fees", "Discount")) # Showing the Dataframenew_df.show() Output: Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Aug, 2021" }, { "code": null, "e": 160, "s": 54, "text": "In this article, we are going to see how to add columns based on another column to the Pyspark Dataframe." }, { "code": null, "e": 198, "s": 160, "text": "Creating Dataframe for demonstration:" }, { "code": null, "e": 272, "s": 198, "text": "Here we are going to create a dataframe from a list of the given dataset." }, { "code": null, "e": 280, "s": 272, "text": "Python3" }, { "code": "# Create a spark sessionfrom pyspark.sql import SparkSessionspark = SparkSession.builder.appName('SparkExamples').getOrCreate() # Create a spark dataframecolumns = [\"Name\", \"Course_Name\", \"Months\", \"Course_Fees\", \"Discount\", \"Start_Date\", \"Payment_Done\"]data = [ (\"Amit Pathak\", \"Python\", 3, 10000, 1000, \"02-07-2021\", True), (\"Shikhar Mishra\", \"Soft skills\", 2, 8000, 800, \"07-10-2021\", False), (\"Shivani Suvarna\", \"Accounting\", 6, 15000, 1500, \"20-08-2021\", True), (\"Pooja Jain\", \"Data Science\", 12, 60000, 900, \"02-12-2021\", False),] df = spark.createDataFrame(data).toDF(*columns) # View the dataframedf.show()", "e": 956, "s": 280, "text": null }, { "code": null, "e": 964, "s": 956, "text": "Output:" }, { "code": null, "e": 1076, "s": 964, "text": "It is used to change the value, convert the datatype of an existing column, create a new column, and many more." }, { "code": null, "e": 1112, "s": 1076, "text": "Syntax: df.withColumn(colName, col)" }, { "code": null, "e": 1223, "s": 1112, "text": "Returns: A new :class:`DataFrame` by adding a column or replacing the existing column that has the same name. " }, { "code": null, "e": 1231, "s": 1223, "text": "Python3" }, { "code": "new_df = df.withColumn('After_discount', df.Course_Fees - df.Discount)new_df.show()", "e": 1337, "s": 1231, "text": null }, { "code": null, "e": 1345, "s": 1337, "text": "Output:" }, { "code": null, "e": 1640, "s": 1345, "text": "Here we will use SQL query inside the Pyspark, We will create a temp view of the table with the help of createTempView() and the life of this temp is up to the life of the sparkSession. registerTempTable() will create the temp table if it is not available or if it is available then replace it." }, { "code": null, "e": 1745, "s": 1640, "text": "Then after creating the table select the table by SQL clause which will take all the values as a string." }, { "code": null, "e": 1753, "s": 1745, "text": "Python3" }, { "code": "df.registerTempTable('table')newDF = spark.sql('select *, Course_Fees - Discount as Total from table')newDF.show()", "e": 1868, "s": 1753, "text": null }, { "code": null, "e": 1876, "s": 1868, "text": "Output:" }, { "code": null, "e": 2066, "s": 1876, "text": "In this method, we will define the user define a function that will take two parameters and return the total price. This function allows us to create a new function as per our requirements." }, { "code": null, "e": 2211, "s": 2066, "text": "Now we define the data type of the UDF function and create the functions which will return the values which is the sum of all values in the row." }, { "code": null, "e": 2219, "s": 2211, "text": "Python3" }, { "code": "# import the functions as F from pyspark.sqlimport pyspark.sql.functions as Ffrom pyspark.sql.types import IntegerType # define the sum_coldef Total(Course_Fees, Discount): res = Course_Fees - Discount return res # integer datatype is definednew_f = F.udf(Total, IntegerType()) # calling and creating the new# col as udf_method_sumnew_df = df.withColumn( \"Total_price\", new_f(\"Course_Fees\", \"Discount\")) # Showing the Dataframenew_df.show()", "e": 2671, "s": 2219, "text": null }, { "code": null, "e": 2679, "s": 2671, "text": "Output:" }, { "code": null, "e": 2686, "s": 2679, "text": "Picked" }, { "code": null, "e": 2701, "s": 2686, "text": "Python-Pyspark" }, { "code": null, "e": 2708, "s": 2701, "text": "Python" }, { "code": null, "e": 2806, "s": 2708, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2824, "s": 2806, "text": "Python Dictionary" }, { "code": null, "e": 2866, "s": 2824, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2901, "s": 2866, "text": "Read a file line by line in Python" }, { "code": null, "e": 2927, "s": 2901, "text": "Python String | replace()" }, { "code": null, "e": 2959, "s": 2927, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2988, "s": 2959, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3015, "s": 2988, "text": "Python Classes and Objects" }, { "code": null, "e": 3036, "s": 3015, "text": "Python OOPs Concepts" }, { "code": null, "e": 3072, "s": 3036, "text": "Convert integer to string in Python" } ]
How to ignore mouse interaction on overlay image using JavaScript ?
22 Jun, 2020 Ignoring mouse interaction on overlay image can be controlled by a CSS property namely pointer-events.It is a property that defines if an element of the page will react to the pointer-events. Syntax: pointer-events: auto\none; Example: The following example demonstrates the use of pointer-events property. <!DOCTYPE html><html> <head> <title>CSS pointer events</title> <style> .main { position: relative; width: 450px; font: 25px Verdana; } .overlay { position: absolute; left: 0px; top: 0; width: 225px; height: 225px; } .pointer-events-none { pointer-events: none; } </style> <script> window.onload = function () { document.getElementById( "enable-disable-pointer-events") .onclick = function () { document.getElementById("overlay") .className = "overlay " + ((this.checked) ? "pointer-events-none" : ""); }; }; </script></head> <body> <div class="main"> <a href="https://www.geeksforgeeks.org/"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200618233603/gfg3.png"></a> GeeksforGeeks: A computer Science portal for Geeks. <div id="overlay" class="overlay"></div> <p> <input id="enable-disable-pointer-events" type="checkbox"> <label for="enable-disable-pointer-events"> Disable pointer events for image </label> </p> </div></body> </html> Output:When the checkbox was not selected:When the checkbox is selected: Final Output: CSS-Misc HTML-Misc JavaScript-Misc Picked CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Form validation using jQuery REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2020" }, { "code": null, "e": 220, "s": 28, "text": "Ignoring mouse interaction on overlay image can be controlled by a CSS property namely pointer-events.It is a property that defines if an element of the page will react to the pointer-events." }, { "code": null, "e": 228, "s": 220, "text": "Syntax:" }, { "code": null, "e": 255, "s": 228, "text": "pointer-events: auto\\none;" }, { "code": null, "e": 335, "s": 255, "text": "Example: The following example demonstrates the use of pointer-events property." }, { "code": "<!DOCTYPE html><html> <head> <title>CSS pointer events</title> <style> .main { position: relative; width: 450px; font: 25px Verdana; } .overlay { position: absolute; left: 0px; top: 0; width: 225px; height: 225px; } .pointer-events-none { pointer-events: none; } </style> <script> window.onload = function () { document.getElementById( \"enable-disable-pointer-events\") .onclick = function () { document.getElementById(\"overlay\") .className = \"overlay \" + ((this.checked) ? \"pointer-events-none\" : \"\"); }; }; </script></head> <body> <div class=\"main\"> <a href=\"https://www.geeksforgeeks.org/\"> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200618233603/gfg3.png\"></a> GeeksforGeeks: A computer Science portal for Geeks. <div id=\"overlay\" class=\"overlay\"></div> <p> <input id=\"enable-disable-pointer-events\" type=\"checkbox\"> <label for=\"enable-disable-pointer-events\"> Disable pointer events for image </label> </p> </div></body> </html>", "e": 1522, "s": 335, "text": null }, { "code": null, "e": 1595, "s": 1522, "text": "Output:When the checkbox was not selected:When the checkbox is selected:" }, { "code": null, "e": 1609, "s": 1595, "text": "Final Output:" }, { "code": null, "e": 1618, "s": 1609, "text": "CSS-Misc" }, { "code": null, "e": 1628, "s": 1618, "text": "HTML-Misc" }, { "code": null, "e": 1644, "s": 1628, "text": "JavaScript-Misc" }, { "code": null, "e": 1651, "s": 1644, "text": "Picked" }, { "code": null, "e": 1655, "s": 1651, "text": "CSS" }, { "code": null, "e": 1660, "s": 1655, "text": "HTML" }, { "code": null, "e": 1671, "s": 1660, "text": "JavaScript" }, { "code": null, "e": 1688, "s": 1671, "text": "Web Technologies" }, { "code": null, "e": 1715, "s": 1688, "text": "Web technologies Questions" }, { "code": null, "e": 1720, "s": 1715, "text": "HTML" }, { "code": null, "e": 1818, "s": 1720, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1857, "s": 1818, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1896, "s": 1857, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 1935, "s": 1896, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 1972, "s": 1935, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 2001, "s": 1972, "text": "Form validation using jQuery" }, { "code": null, "e": 2025, "s": 2001, "text": "REST API (Introduction)" }, { "code": null, "e": 2078, "s": 2025, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2138, "s": 2078, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 2199, "s": 2138, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
PyQt5 QListWidget – Current Selected Row Signal
01 Aug, 2020 In this article we will see how we can get the current selected row changed signal of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Current row property holds the row of the current item. Depending on the current selection mode, the row may also be selected with the help of setCurrentRow method. This signal is emitted whenever the current item changes. In order to do this we will use currentRowChanged method with the list widget object. Syntax : list_widget.currentRowChanged.connect(method) Argument : It takes method as argument Return : It returns None Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 60) # list widget items item1 = QListWidgetItem("A") item2 = QListWidgetItem("B") item3 = QListWidgetItem("C") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) # setting current row list_widget.setCurrentRow(2) # creating a label label = QLabel("GeesforGeeks", self) # setting geometry to the label label.setGeometry(230, 80, 300, 80) # making label multi line label.setWordWrap(True) # getting row changed signal list_widget.currentRowChanged.connect(lambda: label.setText("Row Changed Signal")) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt-QListWidget Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Aug, 2020" }, { "code": null, "e": 561, "s": 28, "text": "In this article we will see how we can get the current selected row changed signal of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Current row property holds the row of the current item. Depending on the current selection mode, the row may also be selected with the help of setCurrentRow method. This signal is emitted whenever the current item changes." }, { "code": null, "e": 647, "s": 561, "text": "In order to do this we will use currentRowChanged method with the list widget object." }, { "code": null, "e": 702, "s": 647, "text": "Syntax : list_widget.currentRowChanged.connect(method)" }, { "code": null, "e": 741, "s": 702, "text": "Argument : It takes method as argument" }, { "code": null, "e": 766, "s": 741, "text": "Return : It returns None" }, { "code": null, "e": 794, "s": 766, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 60) # list widget items item1 = QListWidgetItem(\"A\") item2 = QListWidgetItem(\"B\") item3 = QListWidgetItem(\"C\") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) # setting current row list_widget.setCurrentRow(2) # creating a label label = QLabel(\"GeesforGeeks\", self) # setting geometry to the label label.setGeometry(230, 80, 300, 80) # making label multi line label.setWordWrap(True) # getting row changed signal list_widget.currentRowChanged.connect(lambda: label.setText(\"Row Changed Signal\")) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 2328, "s": 794, "text": null }, { "code": null, "e": 2337, "s": 2328, "text": "Output :" }, { "code": null, "e": 2361, "s": 2337, "text": "Python PyQt-QListWidget" }, { "code": null, "e": 2372, "s": 2361, "text": "Python-gui" }, { "code": null, "e": 2384, "s": 2372, "text": "Python-PyQt" }, { "code": null, "e": 2391, "s": 2384, "text": "Python" } ]
What is negative infinity in JavaScript?
30 Aug, 2019 The negative infinity in JavaScript is a constant value which is used to represent a value which is the lowest available. This means that no other number is lesser than this value. It can be generated using a self-made function or by an arithmetic operation. Note: JavaScript shows the NEGATIVE_INFINITY value as -Infinity. Negative infinity is different from mathematical infinity in the following ways: Negative infinity results in 0 when divided by any other number.When divided by itself or positive infinity, negative infinity return NaNNegative infinity, when divided by any positive number (apart from positive infinity) is negative infinity.Negative infinity, divided by any negative number (apart from negative infinity) is positive infinity.If we multiply negative infinity with NaN, we will get NaN as a result.The product of NaN and negative infinity is 0.The product of two negative infinities is always a positive infinity.The product of both positive and negative infinity is always negative infinity. Negative infinity results in 0 when divided by any other number. When divided by itself or positive infinity, negative infinity return NaN Negative infinity, when divided by any positive number (apart from positive infinity) is negative infinity. Negative infinity, divided by any negative number (apart from negative infinity) is positive infinity. If we multiply negative infinity with NaN, we will get NaN as a result. The product of NaN and negative infinity is 0. The product of two negative infinities is always a positive infinity. The product of both positive and negative infinity is always negative infinity. Syntax: Number.NEGATIVE_INFINITY Example 1: <!DOCTYPE html><html> <body> <style> h1 { color: green; } </style> <h1>GeeksforGeeks</h1> <h1> What is negative infinity in JavaScript? </h1> <button onclick="geekNegativeInfinity()"> Generate negative infinite </button> <p id="geek"></p> <script> function geekNegativeInfinity() { //negative value greater than the //largest representable number in JavaScript var n = (-Number.MAX_VALUE) * 2; document.getElementById("geek").innerHTML = n; } </script> </body> </html> Output: Example 2: <script> function checkNegativeInfinity(x) { if (x === Number.NEGATIVE_INFINITY) { return 'Number is -Infinity'; } else { return 'Number is not -Infinity'; } } console.log(checkNegativeInfinity(2)); </script> Output Supported Browsers: Google Chrome Mozilla Firefox Apple Safari Opera Internet Explorer/Edge JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to Open URL in New Tab using JavaScript ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Aug, 2019" }, { "code": null, "e": 287, "s": 28, "text": "The negative infinity in JavaScript is a constant value which is used to represent a value which is the lowest available. This means that no other number is lesser than this value. It can be generated using a self-made function or by an arithmetic operation." }, { "code": null, "e": 352, "s": 287, "text": "Note: JavaScript shows the NEGATIVE_INFINITY value as -Infinity." }, { "code": null, "e": 433, "s": 352, "text": "Negative infinity is different from mathematical infinity in the following ways:" }, { "code": null, "e": 1045, "s": 433, "text": "Negative infinity results in 0 when divided by any other number.When divided by itself or positive infinity, negative infinity return NaNNegative infinity, when divided by any positive number (apart from positive infinity) is negative infinity.Negative infinity, divided by any negative number (apart from negative infinity) is positive infinity.If we multiply negative infinity with NaN, we will get NaN as a result.The product of NaN and negative infinity is 0.The product of two negative infinities is always a positive infinity.The product of both positive and negative infinity is always negative infinity." }, { "code": null, "e": 1110, "s": 1045, "text": "Negative infinity results in 0 when divided by any other number." }, { "code": null, "e": 1184, "s": 1110, "text": "When divided by itself or positive infinity, negative infinity return NaN" }, { "code": null, "e": 1292, "s": 1184, "text": "Negative infinity, when divided by any positive number (apart from positive infinity) is negative infinity." }, { "code": null, "e": 1395, "s": 1292, "text": "Negative infinity, divided by any negative number (apart from negative infinity) is positive infinity." }, { "code": null, "e": 1467, "s": 1395, "text": "If we multiply negative infinity with NaN, we will get NaN as a result." }, { "code": null, "e": 1514, "s": 1467, "text": "The product of NaN and negative infinity is 0." }, { "code": null, "e": 1584, "s": 1514, "text": "The product of two negative infinities is always a positive infinity." }, { "code": null, "e": 1664, "s": 1584, "text": "The product of both positive and negative infinity is always negative infinity." }, { "code": null, "e": 1672, "s": 1664, "text": "Syntax:" }, { "code": null, "e": 1697, "s": 1672, "text": "Number.NEGATIVE_INFINITY" }, { "code": null, "e": 1708, "s": 1697, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <body> <style> h1 { color: green; } </style> <h1>GeeksforGeeks</h1> <h1> What is negative infinity in JavaScript? </h1> <button onclick=\"geekNegativeInfinity()\"> Generate negative infinite </button> <p id=\"geek\"></p> <script> function geekNegativeInfinity() { //negative value greater than the //largest representable number in JavaScript var n = (-Number.MAX_VALUE) * 2; document.getElementById(\"geek\").innerHTML = n; } </script> </body> </html>", "e": 2309, "s": 1708, "text": null }, { "code": null, "e": 2317, "s": 2309, "text": "Output:" }, { "code": null, "e": 2328, "s": 2317, "text": "Example 2:" }, { "code": "<script> function checkNegativeInfinity(x) { if (x === Number.NEGATIVE_INFINITY) { return 'Number is -Infinity'; } else { return 'Number is not -Infinity'; } } console.log(checkNegativeInfinity(2)); </script>", "e": 2587, "s": 2328, "text": null }, { "code": null, "e": 2594, "s": 2587, "text": "Output" }, { "code": null, "e": 2614, "s": 2594, "text": "Supported Browsers:" }, { "code": null, "e": 2628, "s": 2614, "text": "Google Chrome" }, { "code": null, "e": 2644, "s": 2628, "text": "Mozilla Firefox" }, { "code": null, "e": 2657, "s": 2644, "text": "Apple Safari" }, { "code": null, "e": 2663, "s": 2657, "text": "Opera" }, { "code": null, "e": 2686, "s": 2663, "text": "Internet Explorer/Edge" }, { "code": null, "e": 2702, "s": 2686, "text": "JavaScript-Misc" }, { "code": null, "e": 2709, "s": 2702, "text": "Picked" }, { "code": null, "e": 2720, "s": 2709, "text": "JavaScript" }, { "code": null, "e": 2737, "s": 2720, "text": "Web Technologies" }, { "code": null, "e": 2764, "s": 2737, "text": "Web technologies Questions" }, { "code": null, "e": 2862, "s": 2764, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2923, "s": 2862, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2995, "s": 2923, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3035, "s": 2995, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3076, "s": 3035, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3122, "s": 3076, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 3184, "s": 3122, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3217, "s": 3184, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3278, "s": 3217, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3328, "s": 3278, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to remove underline from link using JavaScript ?
23 Apr, 2020 Given a link and the task is to remove the underline from the anchor element with the help of JavaScript. There are two approaches that are discussed below: Approach 1: Use textDecoration property of JavaScript to perform this operation. It can be set to many values but, in this example it has been set to none. Example:<!DOCTYPE HTML><html> <head> <title> How to remove underline from link using JavaScript? </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"></p> <a id="link" href="#">This is Link</a> <br><br> <button onclick="GFG_Fun()"> Click Here </button> <p id="GFG_DOWN"></p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = "Click on the button to " + "perform the operation"; function GFG_Fun() { var el = document.getElementById('link'); el.style.textDecoration = "none"; el_down.innerHTML = "Underline Removed"; } </script></body> </html> <!DOCTYPE HTML><html> <head> <title> How to remove underline from link using JavaScript? </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"></p> <a id="link" href="#">This is Link</a> <br><br> <button onclick="GFG_Fun()"> Click Here </button> <p id="GFG_DOWN"></p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = "Click on the button to " + "perform the operation"; function GFG_Fun() { var el = document.getElementById('link'); el.style.textDecoration = "none"; el_down.innerHTML = "Underline Removed"; } </script></body> </html> Output: Approach 2: Use textDecoration property of JavaScript to perform the operation. But, in this example we are setting the value to line-through. Example:<!DOCTYPE HTML><html> <head> <title> How to remove underline from link using JavaScript? </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"></p> <a id="link" href="#">This is Link</a> <br><br> <button onclick="GFG_Fun()"> Click Here </button> <p id="GFG_DOWN"></p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = "Click on the button to " + "perform the operation"; function GFG_Fun() { var el = document.getElementById('link'); el.style.textDecoration = "line-through"; el_down.innerHTML = "Underline Removed"; } </script></body> </html> <!DOCTYPE HTML><html> <head> <title> How to remove underline from link using JavaScript? </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"></p> <a id="link" href="#">This is Link</a> <br><br> <button onclick="GFG_Fun()"> Click Here </button> <p id="GFG_DOWN"></p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = "Click on the button to " + "perform the operation"; function GFG_Fun() { var el = document.getElementById('link'); el.style.textDecoration = "line-through"; el_down.innerHTML = "Underline Removed"; } </script></body> </html> Output: CSS-Misc HTML-Misc JavaScript-Misc CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? How to position a div at the bottom of its container using CSS? How to Upload Image into Database and Display it using PHP ? Build a Survey Form using HTML and CSS REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Apr, 2020" }, { "code": null, "e": 185, "s": 28, "text": "Given a link and the task is to remove the underline from the anchor element with the help of JavaScript. There are two approaches that are discussed below:" }, { "code": null, "e": 341, "s": 185, "text": "Approach 1: Use textDecoration property of JavaScript to perform this operation. It can be set to many values but, in this example it has been set to none." }, { "code": null, "e": 1223, "s": 341, "text": "Example:<!DOCTYPE HTML><html> <head> <title> How to remove underline from link using JavaScript? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> <a id=\"link\" href=\"#\">This is Link</a> <br><br> <button onclick=\"GFG_Fun()\"> Click Here </button> <p id=\"GFG_DOWN\"></p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = \"Click on the button to \" + \"perform the operation\"; function GFG_Fun() { var el = document.getElementById('link'); el.style.textDecoration = \"none\"; el_down.innerHTML = \"Underline Removed\"; } </script></body> </html>" }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to remove underline from link using JavaScript? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> <a id=\"link\" href=\"#\">This is Link</a> <br><br> <button onclick=\"GFG_Fun()\"> Click Here </button> <p id=\"GFG_DOWN\"></p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = \"Click on the button to \" + \"perform the operation\"; function GFG_Fun() { var el = document.getElementById('link'); el.style.textDecoration = \"none\"; el_down.innerHTML = \"Underline Removed\"; } </script></body> </html>", "e": 2097, "s": 1223, "text": null }, { "code": null, "e": 2105, "s": 2097, "text": "Output:" }, { "code": null, "e": 2248, "s": 2105, "text": "Approach 2: Use textDecoration property of JavaScript to perform the operation. But, in this example we are setting the value to line-through." }, { "code": null, "e": 3140, "s": 2248, "text": "Example:<!DOCTYPE HTML><html> <head> <title> How to remove underline from link using JavaScript? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> <a id=\"link\" href=\"#\">This is Link</a> <br><br> <button onclick=\"GFG_Fun()\"> Click Here </button> <p id=\"GFG_DOWN\"></p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = \"Click on the button to \" + \"perform the operation\"; function GFG_Fun() { var el = document.getElementById('link'); el.style.textDecoration = \"line-through\"; el_down.innerHTML = \"Underline Removed\"; } </script></body> </html>" }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to remove underline from link using JavaScript? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> <a id=\"link\" href=\"#\">This is Link</a> <br><br> <button onclick=\"GFG_Fun()\"> Click Here </button> <p id=\"GFG_DOWN\"></p> <script> var el_up = document.getElementById('GFG_UP'); var el_down = document.getElementById('GFG_DOWN'); el_up.innerHTML = \"Click on the button to \" + \"perform the operation\"; function GFG_Fun() { var el = document.getElementById('link'); el.style.textDecoration = \"line-through\"; el_down.innerHTML = \"Underline Removed\"; } </script></body> </html>", "e": 4024, "s": 3140, "text": null }, { "code": null, "e": 4032, "s": 4024, "text": "Output:" }, { "code": null, "e": 4041, "s": 4032, "text": "CSS-Misc" }, { "code": null, "e": 4051, "s": 4041, "text": "HTML-Misc" }, { "code": null, "e": 4067, "s": 4051, "text": "JavaScript-Misc" }, { "code": null, "e": 4071, "s": 4067, "text": "CSS" }, { "code": null, "e": 4076, "s": 4071, "text": "HTML" }, { "code": null, "e": 4087, "s": 4076, "text": "JavaScript" }, { "code": null, "e": 4104, "s": 4087, "text": "Web Technologies" }, { "code": null, "e": 4131, "s": 4104, "text": "Web technologies Questions" }, { "code": null, "e": 4136, "s": 4131, "text": "HTML" }, { "code": null, "e": 4234, "s": 4136, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4273, "s": 4234, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 4312, "s": 4273, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 4376, "s": 4312, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 4437, "s": 4376, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 4476, "s": 4437, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 4500, "s": 4476, "text": "REST API (Introduction)" }, { "code": null, "e": 4553, "s": 4500, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 4613, "s": 4553, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 4674, "s": 4613, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
How to swap elements in the matrix in MATLAB?
24 Jan, 2022 In this article, we will see the swapping of elements into a matrix in MATLAB. Different methods are illustrated below: In this method, we are simply changing the elements of particular rows and columns in the specified rows and columns respectively. Example 1: Matlab % MATLAB code for 2*2 matrix. its first and% second elements of the first column are being swappedA = [5 10 15 20] % Swapping the first and second elements of the first columnA([1 2]) = A([2 1]) Output: A = 5 10 15 20 A = 15 10 5 20 Example 2: Matlab % MATLAB code for 3*3 matrix. The second and third elements of the first% column are being swapped. And later, the first and second elements% of the second column of the swapped matrix are swapped again.A = [5 10 15 20 25 30 35 40 45] % Swapping the second and third elements of the first columnA([2 3]) = A([3 2]) % Swapping the first and second elements of the second column% of the above swapped matrixA([4 5]) = A([5 4]) Output: A = 5 10 15 20 25 30 35 40 45 A = 5 10 15 35 25 30 20 40 45 A = 5 25 15 35 10 30 20 40 45 In this approach, we are using the combination of randperm() and size() functions. The randperm() function is used for the random permutation of integers of the specified matrix. Syntax: randperm(A) Parameters: This function accepts a parameter. A: This is the specified matrix. The size() function is used to return the size of each dimension of the specified array “X” or the size of the specified matrix “X”. Syntax: size(X) [m,n] = size(X) size(X,dim) [d1,d2,d3,...,dn] = size(X) Here, size(X) returns the size of each dimension of the specified array “X” in a vector d with ndims(X) elements. [m,n] = size(X) returns the size of the specified matrix “X” in the separate variables m and n. size(X,dim) returns the size of the dimension of “X” specified by scalar dim. [d1,d2,d3,...,dn] = size(X) returns the sizes of the first n dimensions of the specified array “X” in separate variables. Parameters: This function accepts two parameters, which are illustrated below: X: It is the specified array or matrix or dimension. dim: It is the scalar value for the specified dimension “X” Example 1: Matlab % MATLAB code for swapping element% of the array row-wise% Initializing an arrayA = [1 2 3 4 5 6 7 8 9]; % Calling the randperm() function with% size() as its parameterrandom = A(randperm(size(A, 1)),:) Output: random = 7 8 9 1 2 3 4 5 6 Example 2: Matlab % MATLAB code for swapping elements% of the array column-wise% Initializing an arrayA = [1 2 3 4 5 6 7 8 9]; % Calling the randperm() function with% size() as its parameterrandom = A(:, randperm(size(A, 1))) Output: random = 3 1 2 6 4 5 9 7 8 prachisoda1234 saurabh1990aror MATLAB Matrix-Programs MATLAB-programs MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB? How to Solve Histogram Equalization Numerical Problem in MATLAB? Adaptive Histogram Equalization in Image Processing Using MATLAB MRI Image Segmentation in MATLAB How to detect duplicate values and its indices within an array in MATLAB? Double Integral in MATLAB Classes and Object in MATLAB How to remove space in a string in MATLAB? How to Normalize a Histogram in MATLAB? Forward and Inverse Fourier Transform of an Image in MATLAB
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jan, 2022" }, { "code": null, "e": 148, "s": 28, "text": "In this article, we will see the swapping of elements into a matrix in MATLAB. Different methods are illustrated below:" }, { "code": null, "e": 280, "s": 148, "text": " In this method, we are simply changing the elements of particular rows and columns in the specified rows and columns respectively." }, { "code": null, "e": 291, "s": 280, "text": "Example 1:" }, { "code": null, "e": 298, "s": 291, "text": "Matlab" }, { "code": "% MATLAB code for 2*2 matrix. its first and% second elements of the first column are being swappedA = [5 10 15 20] % Swapping the first and second elements of the first columnA([1 2]) = A([2 1])", "e": 503, "s": 298, "text": null }, { "code": null, "e": 511, "s": 503, "text": "Output:" }, { "code": null, "e": 559, "s": 511, "text": "A =\n 5 10\n 15 20\nA =\n 15 10\n 5 20" }, { "code": null, "e": 570, "s": 559, "text": "Example 2:" }, { "code": null, "e": 577, "s": 570, "text": "Matlab" }, { "code": "% MATLAB code for 3*3 matrix. The second and third elements of the first% column are being swapped. And later, the first and second elements% of the second column of the swapped matrix are swapped again.A = [5 10 15 20 25 30 35 40 45] % Swapping the second and third elements of the first columnA([2 3]) = A([3 2]) % Swapping the first and second elements of the second column% of the above swapped matrixA([4 5]) = A([5 4])", "e": 1016, "s": 577, "text": null }, { "code": null, "e": 1024, "s": 1016, "text": "Output:" }, { "code": null, "e": 1171, "s": 1024, "text": "A =\n 5 10 15\n 20 25 30\n 35 40 45\nA =\n 5 10 15\n 35 25 30\n 20 40 45\nA =\n 5 25 15\n 35 10 30\n 20 40 45" }, { "code": null, "e": 1256, "s": 1171, "text": " In this approach, we are using the combination of randperm() and size() functions. " }, { "code": null, "e": 1352, "s": 1256, "text": "The randperm() function is used for the random permutation of integers of the specified matrix." }, { "code": null, "e": 1361, "s": 1352, "text": "Syntax: " }, { "code": null, "e": 1373, "s": 1361, "text": "randperm(A)" }, { "code": null, "e": 1420, "s": 1373, "text": "Parameters: This function accepts a parameter." }, { "code": null, "e": 1453, "s": 1420, "text": "A: This is the specified matrix." }, { "code": null, "e": 1586, "s": 1453, "text": "The size() function is used to return the size of each dimension of the specified array “X” or the size of the specified matrix “X”." }, { "code": null, "e": 1594, "s": 1586, "text": "Syntax:" }, { "code": null, "e": 1602, "s": 1594, "text": "size(X)" }, { "code": null, "e": 1618, "s": 1602, "text": "[m,n] = size(X)" }, { "code": null, "e": 1630, "s": 1618, "text": "size(X,dim)" }, { "code": null, "e": 1658, "s": 1630, "text": "[d1,d2,d3,...,dn] = size(X)" }, { "code": null, "e": 1664, "s": 1658, "text": "Here," }, { "code": null, "e": 1772, "s": 1664, "text": "size(X) returns the size of each dimension of the specified array “X” in a vector d with ndims(X) elements." }, { "code": null, "e": 1868, "s": 1772, "text": "[m,n] = size(X) returns the size of the specified matrix “X” in the separate variables m and n." }, { "code": null, "e": 1946, "s": 1868, "text": "size(X,dim) returns the size of the dimension of “X” specified by scalar dim." }, { "code": null, "e": 2068, "s": 1946, "text": "[d1,d2,d3,...,dn] = size(X) returns the sizes of the first n dimensions of the specified array “X” in separate variables." }, { "code": null, "e": 2147, "s": 2068, "text": "Parameters: This function accepts two parameters, which are illustrated below:" }, { "code": null, "e": 2200, "s": 2147, "text": "X: It is the specified array or matrix or dimension." }, { "code": null, "e": 2260, "s": 2200, "text": "dim: It is the scalar value for the specified dimension “X”" }, { "code": null, "e": 2272, "s": 2260, "text": "Example 1: " }, { "code": null, "e": 2279, "s": 2272, "text": "Matlab" }, { "code": "% MATLAB code for swapping element% of the array row-wise% Initializing an arrayA = [1 2 3 4 5 6 7 8 9]; % Calling the randperm() function with% size() as its parameterrandom = A(randperm(size(A, 1)),:)", "e": 2490, "s": 2279, "text": null }, { "code": null, "e": 2498, "s": 2490, "text": "Output:" }, { "code": null, "e": 2543, "s": 2498, "text": "random =\n 7 8 9\n 1 2 3\n 4 5 6" }, { "code": null, "e": 2554, "s": 2543, "text": "Example 2:" }, { "code": null, "e": 2561, "s": 2554, "text": "Matlab" }, { "code": "% MATLAB code for swapping elements% of the array column-wise% Initializing an arrayA = [1 2 3 4 5 6 7 8 9]; % Calling the randperm() function with% size() as its parameterrandom = A(:, randperm(size(A, 1)))", "e": 2777, "s": 2561, "text": null }, { "code": null, "e": 2785, "s": 2777, "text": "Output:" }, { "code": null, "e": 2830, "s": 2785, "text": "random =\n 3 1 2\n 6 4 5\n 9 7 8" }, { "code": null, "e": 2845, "s": 2830, "text": "prachisoda1234" }, { "code": null, "e": 2861, "s": 2845, "text": "saurabh1990aror" }, { "code": null, "e": 2884, "s": 2861, "text": "MATLAB Matrix-Programs" }, { "code": null, "e": 2900, "s": 2884, "text": "MATLAB-programs" }, { "code": null, "e": 2907, "s": 2900, "text": "MATLAB" }, { "code": null, "e": 3005, "s": 2907, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3084, "s": 3005, "text": "How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?" }, { "code": null, "e": 3149, "s": 3084, "text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?" }, { "code": null, "e": 3214, "s": 3149, "text": "Adaptive Histogram Equalization in Image Processing Using MATLAB" }, { "code": null, "e": 3247, "s": 3214, "text": "MRI Image Segmentation in MATLAB" }, { "code": null, "e": 3321, "s": 3247, "text": "How to detect duplicate values and its indices within an array in MATLAB?" }, { "code": null, "e": 3347, "s": 3321, "text": "Double Integral in MATLAB" }, { "code": null, "e": 3376, "s": 3347, "text": "Classes and Object in MATLAB" }, { "code": null, "e": 3419, "s": 3376, "text": "How to remove space in a string in MATLAB?" }, { "code": null, "e": 3459, "s": 3419, "text": "How to Normalize a Histogram in MATLAB?" } ]
JSTL - SQL <sql:query> Tag
The <sql:query> tag executes an SQL SELECT statement and saves the result in a scoped variable. The <sql:query> tag has the following attributes − To start with the basic concept, let us create an Employees table in the TEST database and create few records in that table as follows − Follow these steps to create the Employees table − Open a Command Prompt and change to the installation directory as follows − C:\> C:\>cd Program Files\MySQL\bin C:\Program Files\MySQL\bin> Login to the database as follows C:\Program Files\MySQL\bin>mysql -u root -p Enter password: ******** mysql> Create the Employee table in the TEST database as follows − − mysql> use TEST; mysql> create table Employees ( id int not null, age int not null, first varchar (255), last varchar (255) ); Query OK, 0 rows affected (0.08 sec) mysql> We will now create few records in Employee table as follows − mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali'); Query OK, 1 row affected (0.05 sec) mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma'); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan'); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal'); Query OK, 1 row affected (0.00 sec) mysql> Let us now create a JSP which will make use of <sql:query> to execute an SQL SELECT statement as follows − <%@ page import = "java.io.*,java.util.*,java.sql.*"%> <%@ page import = "javax.servlet.http.*,javax.servlet.*" %> <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c"%> <%@ taglib uri = "http://java.sun.com/jsp/jstl/sql" prefix = "sql"%> <html> <head> <title>JSTL sql:query Tag</title> </head> <body> <sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver" url = "jdbc:mysql://localhost/TEST" user = "root" password = "pass123"/> <sql:query dataSource = "${snapshot}" var = "result"> SELECT * from Employees; </sql:query> <table border = "1" width = "100%"> <tr> <th>Emp ID</th> <th>First Name</th> <th>Last Name</th> <th>Age</th> </tr> <c:forEach var = "row" items = "${result.rows}"> <tr> <td> <c:out value = "${row.id}"/></td> <td> <c:out value = "${row.first}"/></td> <td> <c:out value = "${row.last}"/></td> <td> <c:out value = "${row.age}"/></td> </tr> </c:forEach> </table> </body> </html> Access the above JSP, which should display the following result − +-------------+----------------+-----------------+-----------------+ | Emp ID | First Name | Last Name | Age | +-------------+----------------+-----------------+-----------------+ | 100 | Zara | Ali | 18 | | 101 | Mahnaz | Fatma | 25 | | 102 | Zaid | Khan | 30 | | 103 | Sumit | Mittal | 28 | +-------------+----------------+-----------------+-----------------+ 108 Lectures 11 hours Chaand Sheikh 517 Lectures 57 hours Chaand Sheikh 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 44 Lectures 15 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2335, "s": 2239, "text": "The <sql:query> tag executes an SQL SELECT statement and saves the result in a scoped variable." }, { "code": null, "e": 2386, "s": 2335, "text": "The <sql:query> tag has the following attributes −" }, { "code": null, "e": 2523, "s": 2386, "text": "To start with the basic concept, let us create an Employees table in the TEST database and create few records in that table as follows −" }, { "code": null, "e": 2574, "s": 2523, "text": "Follow these steps to create the Employees table −" }, { "code": null, "e": 2650, "s": 2574, "text": "Open a Command Prompt and change to the installation directory as follows −" }, { "code": null, "e": 2714, "s": 2650, "text": "C:\\>\nC:\\>cd Program Files\\MySQL\\bin\nC:\\Program Files\\MySQL\\bin>" }, { "code": null, "e": 2747, "s": 2714, "text": "Login to the database as follows" }, { "code": null, "e": 2823, "s": 2747, "text": "C:\\Program Files\\MySQL\\bin>mysql -u root -p\nEnter password: ********\nmysql>" }, { "code": null, "e": 2885, "s": 2823, "text": "Create the Employee table in the TEST database as follows − −" }, { "code": null, "e": 3086, "s": 2885, "text": "mysql> use TEST;\nmysql> create table Employees\n (\n id int not null,\n age int not null,\n first varchar (255),\n last varchar (255)\n );\nQuery OK, 0 rows affected (0.08 sec)\nmysql>" }, { "code": null, "e": 3148, "s": 3086, "text": "We will now create few records in Employee table as follows −" }, { "code": null, "e": 3564, "s": 3148, "text": "mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');\nQuery OK, 1 row affected (0.05 sec)\n \nmysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma');\nQuery OK, 1 row affected (0.00 sec)\n \nmysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');\nQuery OK, 1 row affected (0.00 sec)\n \nmysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');\nQuery OK, 1 row affected (0.00 sec)\n \nmysql>" }, { "code": null, "e": 3671, "s": 3564, "text": "Let us now create a JSP which will make use of <sql:query> to execute an SQL SELECT statement as follows −" }, { "code": null, "e": 4864, "s": 3671, "text": "<%@ page import = \"java.io.*,java.util.*,java.sql.*\"%>\n<%@ page import = \"javax.servlet.http.*,javax.servlet.*\" %>\n<%@ taglib uri = \"http://java.sun.com/jsp/jstl/core\" prefix = \"c\"%>\n<%@ taglib uri = \"http://java.sun.com/jsp/jstl/sql\" prefix = \"sql\"%>\n\n<html>\n <head>\n <title>JSTL sql:query Tag</title>\n </head>\n\n <body>\n <sql:setDataSource var = \"snapshot\" driver = \"com.mysql.jdbc.Driver\"\n url = \"jdbc:mysql://localhost/TEST\"\n user = \"root\" password = \"pass123\"/>\n\n <sql:query dataSource = \"${snapshot}\" var = \"result\">\n SELECT * from Employees;\n </sql:query>\n \n <table border = \"1\" width = \"100%\">\n <tr>\n <th>Emp ID</th>\n <th>First Name</th>\n <th>Last Name</th>\n <th>Age</th>\n </tr>\n \n <c:forEach var = \"row\" items = \"${result.rows}\">\n <tr>\n <td> <c:out value = \"${row.id}\"/></td>\n <td> <c:out value = \"${row.first}\"/></td>\n <td> <c:out value = \"${row.last}\"/></td>\n <td> <c:out value = \"${row.age}\"/></td>\n </tr>\n </c:forEach>\n </table>\n\n </body>\n</html>" }, { "code": null, "e": 4930, "s": 4864, "text": "Access the above JSP, which should display the following result −" }, { "code": null, "e": 5483, "s": 4930, "text": "+-------------+----------------+-----------------+-----------------+\n| Emp ID | First Name | Last Name | Age |\n+-------------+----------------+-----------------+-----------------+\n| 100 | Zara | Ali | 18 |\n| 101 | Mahnaz | Fatma | 25 |\n| 102 | Zaid | Khan | 30 |\n| 103 | Sumit | Mittal | 28 |\n+-------------+----------------+-----------------+-----------------+\n" }, { "code": null, "e": 5518, "s": 5483, "text": "\n 108 Lectures \n 11 hours \n" }, { "code": null, "e": 5533, "s": 5518, "text": " Chaand Sheikh" }, { "code": null, "e": 5568, "s": 5533, "text": "\n 517 Lectures \n 57 hours \n" }, { "code": null, "e": 5583, "s": 5568, "text": " Chaand Sheikh" }, { "code": null, "e": 5618, "s": 5583, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5632, "s": 5618, "text": " Karthikeya T" }, { "code": null, "e": 5667, "s": 5632, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5683, "s": 5667, "text": " TELCOMA Global" }, { "code": null, "e": 5716, "s": 5683, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 5732, "s": 5716, "text": " TELCOMA Global" }, { "code": null, "e": 5766, "s": 5732, "text": "\n 44 Lectures \n 15 hours \n" }, { "code": null, "e": 5774, "s": 5766, "text": " Uplatz" }, { "code": null, "e": 5781, "s": 5774, "text": " Print" }, { "code": null, "e": 5792, "s": 5781, "text": " Add Notes" } ]
How to create a Toggle Button in JavaFX?
A button is a component, which performs an action (like submit, login, etc..) when pressed. It is usually labeled with a text or an image specifying the respective action. A toggle button indicates whether it is elected or not, using toggle button(s) you can switch between multiple states. Generally, multiple toggle buttons are grouped and you can select only one at a time. You can create a toggle button in JavaFX by instantiating the javafx.scene.control.ToggleButton class. You can assign a toggle button to a group using the setToggleGroup() method. Only one button will be selected in a toggle group, unlike the radio button if you click on the selected toggle button it will be un-selected. import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.ToggleButton; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.Stage; public class ToggledButtonExample extends Application { @Override public void start(Stage stage) { //Creating toggle buttons ToggleButton button1 = new ToggleButton("Java"); ToggleButton button2 = new ToggleButton("Python"); ToggleButton button3 = new ToggleButton("C++"); //Toggle button group ToggleGroup group = new ToggleGroup(); button1.setToggleGroup(group); button2.setToggleGroup(group); button3.setToggleGroup(group); //Adding the toggle button to the pane VBox box = new VBox(5); box.setFillWidth(false); box.setPadding(new Insets(5, 5, 5, 50)); box.getChildren().addAll(button1, button2, button3); //Setting the stage Scene scene = new Scene(box, 595, 150, Color.BEIGE); stage.setTitle("Toggled Button Example"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1234, "s": 1062, "text": "A button is a component, which performs an action (like submit, login, etc..) when pressed. It is usually labeled with a text or an image specifying the respective action." }, { "code": null, "e": 1439, "s": 1234, "text": "A toggle button indicates whether it is elected or not, using toggle button(s) you can switch between multiple states. Generally, multiple toggle buttons are grouped and you can select only one at a time." }, { "code": null, "e": 1619, "s": 1439, "text": "You can create a toggle button in JavaFX by instantiating the javafx.scene.control.ToggleButton class. You can assign a toggle button to a group using the setToggleGroup() method." }, { "code": null, "e": 1762, "s": 1619, "text": "Only one button will be selected in a toggle group, unlike the radio button if you click\non the selected toggle button it will be un-selected." }, { "code": null, "e": 2991, "s": 1762, "text": "import javafx.application.Application;\nimport javafx.geometry.Insets;\nimport javafx.scene.Scene;\nimport javafx.scene.control.ToggleButton;\nimport javafx.scene.control.ToggleGroup;\nimport javafx.scene.layout.VBox;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\npublic class ToggledButtonExample extends Application {\n @Override\n public void start(Stage stage) {\n //Creating toggle buttons\n ToggleButton button1 = new ToggleButton(\"Java\");\n ToggleButton button2 = new ToggleButton(\"Python\");\n ToggleButton button3 = new ToggleButton(\"C++\");\n //Toggle button group\n ToggleGroup group = new ToggleGroup();\n button1.setToggleGroup(group);\n button2.setToggleGroup(group);\n button3.setToggleGroup(group);\n //Adding the toggle button to the pane\n VBox box = new VBox(5);\n box.setFillWidth(false);\n box.setPadding(new Insets(5, 5, 5, 50));\n box.getChildren().addAll(button1, button2, button3);\n //Setting the stage\n Scene scene = new Scene(box, 595, 150, Color.BEIGE);\n stage.setTitle(\"Toggled Button Example\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" } ]
PATHCONTAINS function
Returns TRUE if the specified item exists within the specified path. Otherwise, returns FALSE. PATHCONTAINS (<path>, <item>) path A string created as the result of evaluating a PATH function. item A text expression to look for in the path result. TRUE or FALSE. If the item is an integer number, it is converted to text and then the function is evaluated. If conversion fails, then the function returns an error. = PATHCONTAINS("OrgEmp0001|OrgEmp0002|OrgEmp0006|OrgEmp0014", "OrgEmp000 7") returns FALSE. = PATHCONTAINS("OrgEmp0001|OrgEmp0002|OrgEmp0006|OrgEmp0014", "OrgEmp000 6") returns TRUE. 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2096, "s": 2001, "text": "Returns TRUE if the specified item exists within the specified path. Otherwise, returns FALSE." }, { "code": null, "e": 2128, "s": 2096, "text": "PATHCONTAINS (<path>, <item>) \n" }, { "code": null, "e": 2133, "s": 2128, "text": "path" }, { "code": null, "e": 2195, "s": 2133, "text": "A string created as the result of evaluating a PATH function." }, { "code": null, "e": 2200, "s": 2195, "text": "item" }, { "code": null, "e": 2250, "s": 2200, "text": "A text expression to look for in the path result." }, { "code": null, "e": 2265, "s": 2250, "text": "TRUE or FALSE." }, { "code": null, "e": 2416, "s": 2265, "text": "If the item is an integer number, it is converted to text and then the function is evaluated. If conversion fails, then the function returns an error." }, { "code": null, "e": 2600, "s": 2416, "text": "= PATHCONTAINS(\"OrgEmp0001|OrgEmp0002|OrgEmp0006|OrgEmp0014\", \"OrgEmp000 7\") returns FALSE. \n= PATHCONTAINS(\"OrgEmp0001|OrgEmp0002|OrgEmp0006|OrgEmp0014\", \"OrgEmp000 6\") returns TRUE." }, { "code": null, "e": 2635, "s": 2600, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 2649, "s": 2635, "text": " Abhay Gadiya" }, { "code": null, "e": 2682, "s": 2649, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 2696, "s": 2682, "text": " Randy Minder" }, { "code": null, "e": 2731, "s": 2696, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 2745, "s": 2731, "text": " Randy Minder" }, { "code": null, "e": 2752, "s": 2745, "text": " Print" }, { "code": null, "e": 2763, "s": 2752, "text": " Add Notes" } ]
Python Pandas CategoricalIndex - Reorder categories
To eorder categories, use the CategoricalIndex reorder_categories() method in Pandas. At first, import the required libraries − import pandas as pd CategoricalIndex can only take on a limited, and usually fixed, number of possible values. Set the categories for the categorical using the "categories" parameter. Treat the categorical as ordered using the "ordered" parameter − catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"]) Display the CategoricalIndex − print("CategoricalIndex...\n",catIndex) Get the categories − print("\nDisplayingCategories from CategoricalIndex...\n",catIndex.categories) Reorder categories using reorder_categories(). Set the categories in new order as a parameter − print("\nCategoricalIndex after reordering categories...\n",catIndex.reorder_categories(["r", "s", "q", "p"])) Following is the code − import pandas as pd # CategoricalIndex can only take on a limited,and usually fixed, number of possible values (categories # Set the categories for the categorical using the "categories" parameter # Treat the categorical as ordered using the "ordered" parameter catIndex = pd.CategoricalIndex(["p", "q", "r", "s","p", "q", "r", "s"], ordered=True, categories=["p", "q", "r", "s"]) # Display the CategoricalIndex print("CategoricalIndex...\n",catIndex) # Get the categories print("\nDisplayingCategories from CategoricalIndex...\n",catIndex.categories) # Reorder categories using reorder_categories() # Set the categories in new order as a parameter print("\nCategoricalIndex after reordering categories...\n",catIndex.reorder_categories(["r", "s", "q", "p"])) This will produce the following output − CategoricalIndex... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category') DisplayingCategories from CategoricalIndex... Index(['p', 'q', 'r', 's'], dtype='object') CategoricalIndex after reordering categories... CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['r', 's', 'q', 'p'], ordered=True, dtype='category')
[ { "code": null, "e": 1190, "s": 1062, "text": "To eorder categories, use the CategoricalIndex reorder_categories() method in Pandas. At first, import the required libraries −" }, { "code": null, "e": 1210, "s": 1190, "text": "import pandas as pd" }, { "code": null, "e": 1439, "s": 1210, "text": "CategoricalIndex can only take on a limited, and usually fixed, number of possible values. Set the categories for the categorical using the \"categories\" parameter. Treat the categorical as ordered using the \"ordered\" parameter −" }, { "code": null, "e": 1558, "s": 1439, "text": "catIndex = pd.CategoricalIndex([\"p\", \"q\", \"r\", \"s\",\"p\", \"q\", \"r\", \"s\"], ordered=True, categories=[\"p\", \"q\", \"r\", \"s\"])" }, { "code": null, "e": 1589, "s": 1558, "text": "Display the CategoricalIndex −" }, { "code": null, "e": 1630, "s": 1589, "text": "print(\"CategoricalIndex...\\n\",catIndex)\n" }, { "code": null, "e": 1651, "s": 1630, "text": "Get the categories −" }, { "code": null, "e": 1730, "s": 1651, "text": "print(\"\\nDisplayingCategories from CategoricalIndex...\\n\",catIndex.categories)" }, { "code": null, "e": 1826, "s": 1730, "text": "Reorder categories using reorder_categories(). Set the categories in new order as a parameter −" }, { "code": null, "e": 1937, "s": 1826, "text": "print(\"\\nCategoricalIndex after reordering categories...\\n\",catIndex.reorder_categories([\"r\", \"s\", \"q\", \"p\"]))" }, { "code": null, "e": 1961, "s": 1937, "text": "Following is the code −" }, { "code": null, "e": 2725, "s": 1961, "text": "import pandas as pd\n\n# CategoricalIndex can only take on a limited,and usually fixed, number of possible values (categories\n# Set the categories for the categorical using the \"categories\" parameter\n# Treat the categorical as ordered using the \"ordered\" parameter\ncatIndex = pd.CategoricalIndex([\"p\", \"q\", \"r\", \"s\",\"p\", \"q\", \"r\", \"s\"], ordered=True, categories=[\"p\", \"q\", \"r\", \"s\"])\n\n# Display the CategoricalIndex\nprint(\"CategoricalIndex...\\n\",catIndex)\n\n# Get the categories\nprint(\"\\nDisplayingCategories from CategoricalIndex...\\n\",catIndex.categories)\n\n# Reorder categories using reorder_categories()\n# Set the categories in new order as a parameter\nprint(\"\\nCategoricalIndex after reordering categories...\\n\",catIndex.reorder_categories([\"r\", \"s\", \"q\", \"p\"]))" }, { "code": null, "e": 2766, "s": 2725, "text": "This will produce the following output −" }, { "code": null, "e": 3174, "s": 2766, "text": "CategoricalIndex...\nCategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')\n\nDisplayingCategories from CategoricalIndex...\nIndex(['p', 'q', 'r', 's'], dtype='object')\n\nCategoricalIndex after reordering categories...\nCategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['r', 's', 'q', 'p'], ordered=True, dtype='category')" } ]
Construct Pushdown automata for L = {0n1m2(n+m) | m,n ≥ 0} - GeeksforGeeks
23 Aug, 2018 Prerequisite – Pushdown automata, NPDA for accepting the language L = {ambnc(m+n) | m,n ≥ 1}PDA plays a very important role in task of compiler designing. That is why there is a need to have a good practice on PDA. Our objective is to construct a PDA which accepts a string of the form {(0^n)(1^m)(2^(n+m))} Example- Input: 00001112222222 Output: Accepted Input: 00011112222 Output: Not Accepted Approach used in this PDA –There can be four cases while processing the given input string. Case 1- m=0: In this cases the input string will be of the form {0n2n}. In this condition, keep on pushing 0’s in the stack until we encounter with 2. On receiving 2 check if top of stack is 0, then pop it from the stack. Keep on popping 0’s until all the 2’s of the string are processed. If we reach to the end of input string and stack becomes empty, then reached to the final state i.e. Accepts the input string else move to dead state. Case 2- n=0: In this cases the input string will be of the form {1m2m}. In this condition, keep on pushing 1’s in the stack until we encounter with 2. On receiving 2 check if top of stack is 1, then pop it from the stack. Keep on popping 1’s until all the 2’s of the string are processed. If we reach to the end of input string and stack becomes empty, then reached to the final state i.e. Accepts the input string else move to dead state. Case 3- m, n>0: In this cases the input string will be of the form {0n1m2(n+m)}. In this condition, keep on pushing 0’s and 1’s in the stack until we encounter with 2. On receiving 2 check if top of stack is 1 or 0, then pop it (1 or 0) from the stack. Keep on poping 1’s or 0’s until all the 2’s of the input string are processed. If we reach to the end of input string and stack becomes empty, then reach to final state i.e. accept the input string else move to dead state. Case 4- m=0, n=0: In this case the input string will be empty. Therefore directly jump to final state. GATE CS Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Layers of OSI Model ACID Properties in DBMS TCP/IP Model Page Replacement Algorithms in Operating Systems Types of Operating Systems Difference between DFA and NFA Design 101 sequence detector (Mealy machine) Closure properties of Regular languages Conversion of Epsilon-NFA to NFA Boyer-Moore Majority Voting Algorithm
[ { "code": null, "e": 29836, "s": 29808, "text": "\n23 Aug, 2018" }, { "code": null, "e": 30144, "s": 29836, "text": "Prerequisite – Pushdown automata, NPDA for accepting the language L = {ambnc(m+n) | m,n ≥ 1}PDA plays a very important role in task of compiler designing. That is why there is a need to have a good practice on PDA. Our objective is to construct a PDA which accepts a string of the form {(0^n)(1^m)(2^(n+m))}" }, { "code": null, "e": 30153, "s": 30144, "text": "Example-" }, { "code": null, "e": 30234, "s": 30153, "text": "Input: 00001112222222\nOutput: Accepted\n\nInput: 00011112222\nOutput: Not Accepted " }, { "code": null, "e": 30326, "s": 30234, "text": "Approach used in this PDA –There can be four cases while processing the given input string." }, { "code": null, "e": 30766, "s": 30326, "text": "Case 1- m=0: In this cases the input string will be of the form {0n2n}. In this condition, keep on pushing 0’s in the stack until we encounter with 2. On receiving 2 check if top of stack is 0, then pop it from the stack. Keep on popping 0’s until all the 2’s of the string are processed. If we reach to the end of input string and stack becomes empty, then reached to the final state i.e. Accepts the input string else move to dead state." }, { "code": null, "e": 31206, "s": 30766, "text": "Case 2- n=0: In this cases the input string will be of the form {1m2m}. In this condition, keep on pushing 1’s in the stack until we encounter with 2. On receiving 2 check if top of stack is 1, then pop it from the stack. Keep on popping 1’s until all the 2’s of the string are processed. If we reach to the end of input string and stack becomes empty, then reached to the final state i.e. Accepts the input string else move to dead state." }, { "code": null, "e": 31682, "s": 31206, "text": "Case 3- m, n>0: In this cases the input string will be of the form {0n1m2(n+m)}. In this condition, keep on pushing 0’s and 1’s in the stack until we encounter with 2. On receiving 2 check if top of stack is 1 or 0, then pop it (1 or 0) from the stack. Keep on poping 1’s or 0’s until all the 2’s of the input string are processed. If we reach to the end of input string and stack becomes empty, then reach to final state i.e. accept the input string else move to dead state." }, { "code": null, "e": 31785, "s": 31682, "text": "Case 4- m=0, n=0: In this case the input string will be empty. Therefore directly jump to final state." }, { "code": null, "e": 31793, "s": 31785, "text": "GATE CS" }, { "code": null, "e": 31826, "s": 31793, "text": "Theory of Computation & Automata" }, { "code": null, "e": 31924, "s": 31826, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31944, "s": 31924, "text": "Layers of OSI Model" }, { "code": null, "e": 31968, "s": 31944, "text": "ACID Properties in DBMS" }, { "code": null, "e": 31981, "s": 31968, "text": "TCP/IP Model" }, { "code": null, "e": 32030, "s": 31981, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 32057, "s": 32030, "text": "Types of Operating Systems" }, { "code": null, "e": 32088, "s": 32057, "text": "Difference between DFA and NFA" }, { "code": null, "e": 32133, "s": 32088, "text": "Design 101 sequence detector (Mealy machine)" }, { "code": null, "e": 32173, "s": 32133, "text": "Closure properties of Regular languages" }, { "code": null, "e": 32206, "s": 32173, "text": "Conversion of Epsilon-NFA to NFA" } ]
Aptitude - Calendar Online Quiz
Following quiz provides Multiple Choice Questions (MCQs) related to Calendar. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz. Q 1 - On What dates of March 2005 did Friday fall? A - 5th, 12th, 17th and 24th B - 4th, 11th, 18th and 25th C - 6th, 13th, 20th and 27th D - 7th, 14th, 21th and 28th To begin with we discover the day on 1.3.2005. 1.3.2005= (2004 year+ period from 1.1.2005 to 1.3.2005 Odd days in 1600 years = 0 Odd days in 400 years = 0 4 years = (1 jump year+ 3 normal years) = (1*2+3*1) odd days = 5 odd days. Jan + Feb + March 31 + 28 + 1 = 60 days = (8 weeks +4 days)=4 odd days. ∴ Total number of odd days = (0+0+5+4) =9=2 odd days. ∴ 1.3.2005 was Tuesday. So, Friday lies on 4.3.2005. Thus, Friday lies on 4th, 11th, 18th and 25th of March, 2005. Q 2 - Jan.1, 2007 was Monday. What day of the week lies on Jan 1, 2008? A - Monday B - Tuesday C - Wednesday D - Sunday The year 2007 is a common year. So, it has 1 odd day. First day of the year 2007 was Monday. First day of the year 2008 will be 1 day past Monday. Subsequently, it will be Tuesday. Q 3 - Jan.1 2008 is Tuesday. What date of the week lies on Jan 1, 2009? A - Monday B - Wednesday C - Thursday D - Friday The year 2008 is a jump year. So, it has 2 odd days. First day of the year 2008 is Tuesday (Given). In this way, first day of the year 2009 is 2 days past Tuesday. Subsequently, it will be Thursday. Q 4 - On sixth March, 2005 Monday falls. What was the day of the week on sixth March, 2004? A - Sunday B - Saturday C - Tuesday D - Wednesday The year 2004 is a jump year. In this way, it has 2 odd days. ∴ The day on sixth March, 2005 will be 2 days. past the day on sixth Walk, 2004. Yet, sixth March, 2005 is Monday. ∴ sixth March, 2004 is Saturday. Q 5 - What was the week's day on seventeenth June, 1988? A - Monday B - Tuesday C - Wednesday D - Thursday 17th June, 1998= (1997 year Period structure 1.1.1998 to 17.6.1998) Odd days in 1600 year=0. Odd days in 300 year = (5*3) =1. 97 year has 24 jump year +73 standard years. = 24*2 + 73*1 = 48 + 73 = 121 odd days = 17 weeks + 2 odd days = 2 odd days = 2 odd days. ∴ 1998 years have (0+1+2) = 3 odd days Jan to June = (31+29+31+30+31) = 152 days Add 17 days of June. = 152 + 17 = 169 days = 24 weeks + 1 days = 1 odd day. ∴ Total number of odd day = 3 + 1 = 4 odd days. Hence 17.06.1998 was Thursday. Q 6 - What will be the day of the week on fifteenth 2010? A - Sunday B - Monday C - Tuesday D - Friday fifteenth August,2010 =(2009 years+ Period from 1.1.2010 to 15.8.2010) Odd days in 1600 years = 0. Odd days in 400 years = 0. 9 year = (2 jump year +7 conventional years) = (2*2+7*1) = 11 odd days= 4 odd days Jan + feb + March + April + May + June + July + august 31+28+31+30+31+30+31+15 = 227 days =(32 weeks +3 days ) = 3 odd days Aggregate no. of odd days = (0+0+4+3) =7 = 0 odd day Given day is Sunday. Q 7 - The last day of a century can't be: A - Monday B - Wednesday C - Tuesday D - Friday 100 years contain 5 odd days. ∴ Last day of first century is Friday. 200 years contain (5*2) = 3 odd days. ∴ Last day of second century is Wednesday. 300 year contain (5*3) =15=1 odd day. ∴ Last day of third century is Monday. 400 year contain 0 odd days. ∴ Last day of fourth century is Sunday. The cycle is repeated. ∴ Last day of a century can't be Tuesday or Thursday or Saturday. Q 8 - How number of days are present in x weeks x days? A - 7x2 B - 8x C - 14x D - 7 x weeks x days=(7x+x) days=8x days. Q 9 - It was Sunday on Jan 1, 2006. Discover the week's day on Jan 1, 2010. A - Sunday B - Saturday C - Friday D - Wednesday On 31st December,2005 it was Saturday. Number of odd days frame the year 2006 to the year 2009=(1+1+2+1)=5 days. ∴ On 31st December 2009 , it was Thursday. In this way, on first jan, 2010 it is Friday. 87 Lectures 22.5 hours Programming Line Print Add Notes Bookmark this page
[ { "code": null, "e": 4214, "s": 3892, "text": "Following quiz provides Multiple Choice Questions (MCQs) related to Calendar. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz." }, { "code": null, "e": 4265, "s": 4214, "text": "Q 1 - On What dates of March 2005 did Friday fall?" }, { "code": null, "e": 4294, "s": 4265, "text": "A - 5th, 12th, 17th and 24th" }, { "code": null, "e": 4323, "s": 4294, "text": "B - 4th, 11th, 18th and 25th" }, { "code": null, "e": 4352, "s": 4323, "text": "C - 6th, 13th, 20th and 27th" }, { "code": null, "e": 4381, "s": 4352, "text": "D - 7th, 14th, 21th and 28th" }, { "code": null, "e": 4857, "s": 4381, "text": "To begin with we discover the day on 1.3.2005.\n1.3.2005= (2004 year+ period from 1.1.2005 to 1.3.2005\n\nOdd days in 1600 years = 0\nOdd days in 400 years = 0\n\n4 years = (1 jump year+ 3 normal years)\n= (1*2+3*1) odd days = 5 odd days. \n\nJan + Feb + March\n31 + 28 + 1 = 60 days = (8 weeks +4 days)=4 odd days.\n∴ Total number of odd days = (0+0+5+4) =9=2 odd days.\n\n∴ 1.3.2005 was Tuesday. So, Friday lies on 4.3.2005.\nThus, Friday lies on 4th, 11th, 18th and 25th of March, 2005." }, { "code": null, "e": 4929, "s": 4857, "text": "Q 2 - Jan.1, 2007 was Monday. What day of the week lies on Jan 1, 2008?" }, { "code": null, "e": 4940, "s": 4929, "text": "A - Monday" }, { "code": null, "e": 4952, "s": 4940, "text": "B - Tuesday" }, { "code": null, "e": 4966, "s": 4952, "text": "C - Wednesday" }, { "code": null, "e": 4977, "s": 4966, "text": "D - Sunday" }, { "code": null, "e": 5159, "s": 4977, "text": "The year 2007 is a common year.\nSo, it has 1 odd day.\n\nFirst day of the year 2007 was Monday.\nFirst day of the year 2008 will be 1 day past Monday.\nSubsequently, it will be Tuesday." }, { "code": null, "e": 5231, "s": 5159, "text": "Q 3 - Jan.1 2008 is Tuesday. What date of the week lies on Jan 1, 2009?" }, { "code": null, "e": 5242, "s": 5231, "text": "A - Monday" }, { "code": null, "e": 5256, "s": 5242, "text": "B - Wednesday" }, { "code": null, "e": 5269, "s": 5256, "text": "C - Thursday" }, { "code": null, "e": 5281, "s": 5269, "text": "D - Friday " }, { "code": null, "e": 5482, "s": 5281, "text": "The year 2008 is a jump year.\nSo, it has 2 odd days.\nFirst day of the year 2008 is Tuesday (Given).\n\nIn this way, first day of the year 2009 is \n2 days past Tuesday.\nSubsequently, it will be Thursday." }, { "code": null, "e": 5574, "s": 5482, "text": "Q 4 - On sixth March, 2005 Monday falls. What was the day of the week on sixth March, 2004?" }, { "code": null, "e": 5585, "s": 5574, "text": "A - Sunday" }, { "code": null, "e": 5598, "s": 5585, "text": "B - Saturday" }, { "code": null, "e": 5610, "s": 5598, "text": "C - Tuesday" }, { "code": null, "e": 5624, "s": 5610, "text": "D - Wednesday" }, { "code": null, "e": 5836, "s": 5624, "text": "The year 2004 is a jump year. \nIn this way, it has 2 odd days.\n∴ The day on sixth March, 2005 will be 2 days.\n\npast the day on sixth Walk, 2004.\nYet, sixth March, 2005 is Monday.\n∴ sixth March, 2004 is Saturday." }, { "code": null, "e": 5893, "s": 5836, "text": "Q 5 - What was the week's day on seventeenth June, 1988?" }, { "code": null, "e": 5904, "s": 5893, "text": "A - Monday" }, { "code": null, "e": 5916, "s": 5904, "text": "B - Tuesday" }, { "code": null, "e": 5930, "s": 5916, "text": "C - Wednesday" }, { "code": null, "e": 5943, "s": 5930, "text": "D - Thursday" }, { "code": null, "e": 6443, "s": 5943, "text": "17th June, 1998= (1997 year Period structure 1.1.1998 to 17.6.1998)\nOdd days in 1600 year=0.\nOdd days in 300 year = (5*3) =1.\n97 year has 24 jump year +73 standard years.\n= 24*2 + 73*1\n= 48 + 73\n= 121 odd days\n= 17 weeks + 2 odd days = 2 odd days\n= 2 odd days.\n∴ 1998 years have (0+1+2) = 3 odd days\n\nJan to June = (31+29+31+30+31)\n= 152 days\n\nAdd 17 days of June.\n= 152 + 17\n= 169 days\n= 24 weeks + 1 days\n= 1 odd day.\n\n∴ Total number of odd day = 3 + 1 = 4 odd days.\nHence 17.06.1998 was Thursday." }, { "code": null, "e": 6501, "s": 6443, "text": "Q 6 - What will be the day of the week on fifteenth 2010?" }, { "code": null, "e": 6512, "s": 6501, "text": "A - Sunday" }, { "code": null, "e": 6523, "s": 6512, "text": "B - Monday" }, { "code": null, "e": 6535, "s": 6523, "text": "C - Tuesday" }, { "code": null, "e": 6546, "s": 6535, "text": "D - Friday" }, { "code": null, "e": 6957, "s": 6546, "text": "fifteenth August,2010 =(2009 years+ Period from 1.1.2010 to 15.8.2010)\nOdd days in 1600 years = 0.\nOdd days in 400 years = 0.\n\n9 year = (2 jump year +7 conventional years)\n= (2*2+7*1) = 11 odd days= 4 odd days\n\nJan + feb + March + April + May + June + July + august\n31+28+31+30+31+30+31+15 = 227 days =(32 weeks +3 days )\n= 3 odd days\n\nAggregate no. of odd days = (0+0+4+3) =7\n= 0 odd day\n\nGiven day is Sunday." }, { "code": null, "e": 7000, "s": 6957, "text": "Q 7 - The last day of a century can't be: " }, { "code": null, "e": 7011, "s": 7000, "text": "A - Monday" }, { "code": null, "e": 7025, "s": 7011, "text": "B - Wednesday" }, { "code": null, "e": 7037, "s": 7025, "text": "C - Tuesday" }, { "code": null, "e": 7048, "s": 7037, "text": "D - Friday" }, { "code": null, "e": 7438, "s": 7048, "text": "100 years contain 5 odd days.\n∴ Last day of first century is Friday. \n\n200 years contain (5*2) = 3 odd days.\n∴ Last day of second century is Wednesday.\n\n300 year contain (5*3) =15=1 odd day.\n∴ Last day of third century is Monday.\n\n400 year contain 0 odd days.\n∴ Last day of fourth century is Sunday.\n\nThe cycle is repeated.\n∴ Last day of a century can't be Tuesday or Thursday or Saturday." }, { "code": null, "e": 7494, "s": 7438, "text": "Q 8 - How number of days are present in x weeks x days?" }, { "code": null, "e": 7503, "s": 7494, "text": "A - 7x2 " }, { "code": null, "e": 7510, "s": 7503, "text": "B - 8x" }, { "code": null, "e": 7518, "s": 7510, "text": "C - 14x" }, { "code": null, "e": 7524, "s": 7518, "text": "D - 7" }, { "code": null, "e": 7560, "s": 7524, "text": "x weeks x days=(7x+x) days=8x days." }, { "code": null, "e": 7636, "s": 7560, "text": "Q 9 - It was Sunday on Jan 1, 2006. Discover the week's day on Jan 1, 2010." }, { "code": null, "e": 7647, "s": 7636, "text": "A - Sunday" }, { "code": null, "e": 7660, "s": 7647, "text": "B - Saturday" }, { "code": null, "e": 7671, "s": 7660, "text": "C - Friday" }, { "code": null, "e": 7685, "s": 7671, "text": "D - Wednesday" }, { "code": null, "e": 7888, "s": 7685, "text": "On 31st December,2005 it was Saturday.\nNumber of odd days frame the year 2006 to the year 2009=(1+1+2+1)=5 days.\n\n∴ On 31st December 2009 , it was Thursday.\nIn this way, on first jan, 2010 it is Friday." }, { "code": null, "e": 7924, "s": 7888, "text": "\n 87 Lectures \n 22.5 hours \n" }, { "code": null, "e": 7942, "s": 7924, "text": " Programming Line" }, { "code": null, "e": 7949, "s": 7942, "text": " Print" }, { "code": null, "e": 7960, "s": 7949, "text": " Add Notes" } ]
PHP array_column() Function
The array_column() function returns the values from a single column of the input array and identified by the column_key. Optionally, you can pass index_key to index the values in the returned array by the values from the index_key column of the input array. array array_column( array $input , mixed $column_key [, mixed $index_key = NULL ] ) input (mandatory) A multi-dimensional array or an array of objects from which to pull a column of values from. column_key (mandatory) The column of values to return. This value may be an integer key of the column you wish to retrieve, or it may be a string key name for an associative array or property name. This value can be NULL to return complete arrays or objects index_key (optional) The column to use as the index/keys for the returned array. This value may be the integer key of the column, or it may be the string key name. The function array_column returns an array of values representing a single column from the input array. This function was first introduced in PHP Version 5.5.0. The the ability for the input parameter to be an array of objects was introduced in 7.0.0 Try out following example to get the column of first names from a recordset − <?php $records = array( array( 'id' => 2135, 'first_name' => 'Zara', 'last_name' => 'Ali', ), array( 'id' => 3245, 'first_name' => 'Nuha', 'last_name' => 'Mac', ), array( 'id' => 5342, 'first_name' => 'Shifa', 'last_name' => 'Alam', ), array( 'id' => 5623, 'first_name' => 'Riya', 'last_name' => 'Sweet', ) ); $first_names = array_column($records, 'first_name'); print_r($first_names); ?> This will produce following result − Array ( [0] => Zara [1] => Nuha [2] => Shifa [3] => Riya ) Now let's try one more example to get the column of first names from a recordset but this time we will index recordset using id − <?php $records = array( array( 'id' => 2135, 'first_name' => 'Zara', 'last_name' => 'Ali', ), array( 'id' => 3245, 'first_name' => 'Nuha', 'last_name' => 'Mac', ), array( 'id' => 5342, 'first_name' => 'Shifa', 'last_name' => 'Alam', ), array( 'id' => 5623, 'first_name' => 'Riya', 'last_name' => 'Sweet', ) ); $first_names = array_column($records, 'first_name', 'id'); print_r($first_names); ?> This will produce following result − Array ( [2135] => Zara [3245] => Nuha [5342] => Shifa [5623] => Riya ) 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": 2878, "s": 2757, "text": "The array_column() function returns the values from a single column of the input array and identified by the column_key." }, { "code": null, "e": 3015, "s": 2878, "text": "Optionally, you can pass index_key to index the values in the returned array by the values from the index_key column of the input array." }, { "code": null, "e": 3100, "s": 3015, "text": "array array_column( array $input , mixed $column_key [, mixed $index_key = NULL ] )\n" }, { "code": null, "e": 3118, "s": 3100, "text": "input (mandatory)" }, { "code": null, "e": 3211, "s": 3118, "text": "A multi-dimensional array or an array of objects from which to pull a column of values from." }, { "code": null, "e": 3234, "s": 3211, "text": "column_key (mandatory)" }, { "code": null, "e": 3469, "s": 3234, "text": "The column of values to return. This value may be an integer key of the column you wish to retrieve, or it may be a string key name for an associative array or property name. This value can be NULL to return complete arrays or objects" }, { "code": null, "e": 3490, "s": 3469, "text": "index_key (optional)" }, { "code": null, "e": 3633, "s": 3490, "text": "The column to use as the index/keys for the returned array. This value may be the integer key of the column, or it may be the string key name." }, { "code": null, "e": 3737, "s": 3633, "text": "The function array_column returns an array of values representing a single column from the input array." }, { "code": null, "e": 3884, "s": 3737, "text": "This function was first introduced in PHP Version 5.5.0. The the ability for the input parameter to be an array of objects was introduced in 7.0.0" }, { "code": null, "e": 3962, "s": 3884, "text": "Try out following example to get the column of first names from a recordset −" }, { "code": null, "e": 4486, "s": 3962, "text": "<?php\n\n $records = array(\n array(\n 'id' => 2135,\n 'first_name' => 'Zara',\n 'last_name' => 'Ali',\n ),\n array(\n 'id' => 3245,\n 'first_name' => 'Nuha',\n 'last_name' => 'Mac',\n ),\n array(\n 'id' => 5342,\n 'first_name' => 'Shifa',\n 'last_name' => 'Alam',\n ),\n array(\n 'id' => 5623,\n 'first_name' => 'Riya',\n 'last_name' => 'Sweet',\n )\n );\n\n $first_names = array_column($records, 'first_name');\n print_r($first_names);\n?>" }, { "code": null, "e": 4523, "s": 4486, "text": "This will produce following result −" }, { "code": null, "e": 4599, "s": 4523, "text": "Array\n(\n [0] => Zara\n [1] => Nuha\n [2] => Shifa\n [3] => Riya\n)\n" }, { "code": null, "e": 4729, "s": 4599, "text": "Now let's try one more example to get the column of first names from a recordset but this time we will index recordset using id −" }, { "code": null, "e": 5257, "s": 4729, "text": "<?php\n\n $records = array(\n array(\n 'id' => 2135,\n 'first_name' => 'Zara',\n 'last_name' => 'Ali',\n ),\n array(\n 'id' => 3245,\n 'first_name' => 'Nuha',\n 'last_name' => 'Mac',\n ),\n array(\n 'id' => 5342,\n 'first_name' => 'Shifa',\n 'last_name' => 'Alam',\n ),\n array(\n 'id' => 5623,\n 'first_name' => 'Riya',\n 'last_name' => 'Sweet',\n )\n );\n $first_names = array_column($records, 'first_name', 'id');\n print_r($first_names);\n?>" }, { "code": null, "e": 5294, "s": 5257, "text": "This will produce following result −" }, { "code": null, "e": 5382, "s": 5294, "text": "Array\n(\n [2135] => Zara\n [3245] => Nuha\n [5342] => Shifa\n [5623] => Riya\n)\n" }, { "code": null, "e": 5415, "s": 5382, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 5431, "s": 5415, "text": " Malhar Lathkar" }, { "code": null, "e": 5464, "s": 5431, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 5475, "s": 5464, "text": " Syed Raza" }, { "code": null, "e": 5510, "s": 5475, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5527, "s": 5510, "text": " Frahaan Hussain" }, { "code": null, "e": 5560, "s": 5527, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 5575, "s": 5560, "text": " Nivedita Jain" }, { "code": null, "e": 5610, "s": 5575, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 5622, "s": 5610, "text": " Azaz Patel" }, { "code": null, "e": 5657, "s": 5622, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5685, "s": 5657, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 5692, "s": 5685, "text": " Print" }, { "code": null, "e": 5703, "s": 5692, "text": " Add Notes" } ]
Namespaces and Scope in Python
In python we deal with variables, functions, libraries and modules etc. There is a chance the name of the variable you are going to use is already existing as name of another variable or as the name of another function or another method. In such scenario, we need to learn about how all these names are managed by a python program. This is the concept of namespace. Following are the three categories of namespace Local Namespace: All the names of the functions and variables declared by a program are held in this namespace. This namespace exists as long as the program runs. < /p> Local Namespace: All the names of the functions and variables declared by a program are held in this namespace. This namespace exists as long as the program runs. < /p> Global Namespace: This namespace holds all the names of functions and other variables that are included in the modules being used in the python program. It encompasses all the names that are part of the Local namespace. Global Namespace: This namespace holds all the names of functions and other variables that are included in the modules being used in the python program. It encompasses all the names that are part of the Local namespace. Built-in Namespace: This is the highest level of namespace which is available with default names available as part of the python interpreter that is loaded as the programing environment. It encompasses Global Namespace which in turn encompasses the local namespace. Built-in Namespace: This is the highest level of namespace which is available with default names available as part of the python interpreter that is loaded as the programing environment. It encompasses Global Namespace which in turn encompasses the local namespace. The namespace has a lifetime when it is available. That is also called the scope. Also the scope will depend on the coding region where the variable or object is located. You can see in the below program how the variables declared in an inner loop are available to the outer loop but not vice-versa. Also please note how the name of the outer function also becomes part of a global variable. prog_var = 'Hello' def outer_func(): outer_var = 'x' def inner_func(): inner_var = 'y' print(dir(), ' Local Variable in Inner function') inner_func() print(dir(), 'Local variables in outer function') outer_func() print(dir(), 'Global variables ') Running the above code gives us the following result − ['inner_var'] Local Variable in Inner function ['inner_func', 'outer_var'] Local variables in outer function ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'outer_func', 'prog_var'] Global variables
[ { "code": null, "e": 1428, "s": 1062, "text": "In python we deal with variables, functions, libraries and modules etc. There is a chance the name of the variable you are going to use is already existing as name of another variable or as the name of another function or another method. In such scenario, we need to learn about how all these names are managed by a python program. This is the concept of namespace." }, { "code": null, "e": 1476, "s": 1428, "text": "Following are the three categories of namespace" }, { "code": null, "e": 1645, "s": 1476, "text": "Local Namespace: All the names of the functions and variables declared by a program are held in this namespace. This namespace exists as long as the program runs. < /p>" }, { "code": null, "e": 1814, "s": 1645, "text": "Local Namespace: All the names of the functions and variables declared by a program are held in this namespace. This namespace exists as long as the program runs. < /p>" }, { "code": null, "e": 2034, "s": 1814, "text": "Global Namespace: This namespace holds all the names of functions and other variables that are included in the modules being used in the python program. It encompasses all the names that are part of the Local namespace." }, { "code": null, "e": 2254, "s": 2034, "text": "Global Namespace: This namespace holds all the names of functions and other variables that are included in the modules being used in the python program. It encompasses all the names that are part of the Local namespace." }, { "code": null, "e": 2520, "s": 2254, "text": "Built-in Namespace: This is the highest level of namespace which is available with default names available as part of the python interpreter that is loaded as the programing environment. It encompasses Global Namespace which in turn encompasses the local namespace." }, { "code": null, "e": 2786, "s": 2520, "text": "Built-in Namespace: This is the highest level of namespace which is available with default names available as part of the python interpreter that is loaded as the programing environment. It encompasses Global Namespace which in turn encompasses the local namespace." }, { "code": null, "e": 3178, "s": 2786, "text": "The namespace has a lifetime when it is available. That is also called the scope. Also the scope will depend on the coding region where the variable or object is located. You can see in the below program how the variables declared in an inner loop are available to the outer loop but not vice-versa. Also please note how the name of the outer function also becomes part of a global variable." }, { "code": null, "e": 3469, "s": 3178, "text": "prog_var = 'Hello'\ndef outer_func():\n outer_var = 'x'\n def inner_func():\n inner_var = 'y'\n print(dir(), ' Local Variable in Inner function')\n\n inner_func()\n print(dir(), 'Local variables in outer function')\n\n outer_func()\n print(dir(), 'Global variables ')" }, { "code": null, "e": 3524, "s": 3469, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 3802, "s": 3524, "text": "['inner_var'] Local Variable in Inner function\n['inner_func', 'outer_var'] Local variables in outer function\n['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'outer_func', 'prog_var'] Global variables" } ]
RSpec - Tags
RSpec Tags provide an easy way to run specific tests in your spec files. By default, RSpec will run all tests in the spec files that it runs, but you might only need to run a subset of them. Let’s say that you have some tests that run very quickly and that you’ve just made a change to your application code and you want to just run the quick tests, this code will demonstrate how to do that with RSpec Tags. describe "How to run specific Examples with Tags" do it 'is a slow test', :slow = > true do sleep 10 puts 'This test is slow!' end it 'is a fast test', :fast = > true do puts 'This test is fast!' end end Now, save the above code in a new file called tag_spec.rb. From the command line, run this command: rspec --tag slow tag_spec.rb You will see this output − Run options: include {: slow = >true} This test is slow! . Finished in 10 seconds (files took 0.11601 seconds to load) 1 example, 0 failures Then, run this command: rspec --tag fast tag_spec.rb You will see this output − Run options: include {:fast = >true} This test is fast! . Finished in 0.001 seconds (files took 0.11201 seconds to load) 1 example, 0 failures As you can see, RSpec Tags makes it very easy to a subset of tests! 9 Lectures 37 mins Harshit Srivastava 27 Lectures 7 hours Atul Tiwari Print Add Notes Bookmark this page
[ { "code": null, "e": 2203, "s": 1794, "text": "RSpec Tags provide an easy way to run specific tests in your spec files. By default, RSpec will run all tests in the spec files that it runs, but you might only need to run a subset of them. Let’s say that you have some tests that run very quickly and that you’ve just made a change to your application code and you want to just run the quick tests, this code will demonstrate how to do that with RSpec Tags." }, { "code": null, "e": 2449, "s": 2203, "text": "describe \"How to run specific Examples with Tags\" do \n it 'is a slow test', :slow = > true do \n sleep 10 \n puts 'This test is slow!' \n end \n \n it 'is a fast test', :fast = > true do \n puts 'This test is fast!' \n end \nend" }, { "code": null, "e": 2578, "s": 2449, "text": "Now, save the above code in a new file called tag_spec.rb. From the command line, run this command: rspec --tag slow tag_spec.rb" }, { "code": null, "e": 2605, "s": 2578, "text": "You will see this output −" }, { "code": null, "e": 2643, "s": 2605, "text": "Run options: include {: slow = >true}" }, { "code": null, "e": 2750, "s": 2643, "text": "This test is slow! \n. \nFinished in 10 seconds (files took 0.11601 seconds to load) \n1 example, 0 failures\n" }, { "code": null, "e": 2803, "s": 2750, "text": "Then, run this command: rspec --tag fast tag_spec.rb" }, { "code": null, "e": 2830, "s": 2803, "text": "You will see this output −" }, { "code": null, "e": 2978, "s": 2830, "text": "Run options: include {:fast = >true} \nThis test is fast! \n. \nFinished in 0.001 seconds (files took 0.11201 seconds to load) \n1 example, 0 failures\n" }, { "code": null, "e": 3046, "s": 2978, "text": "As you can see, RSpec Tags makes it very easy to a subset of tests!" }, { "code": null, "e": 3077, "s": 3046, "text": "\n 9 Lectures \n 37 mins\n" }, { "code": null, "e": 3097, "s": 3077, "text": " Harshit Srivastava" }, { "code": null, "e": 3130, "s": 3097, "text": "\n 27 Lectures \n 7 hours \n" }, { "code": null, "e": 3143, "s": 3130, "text": " Atul Tiwari" }, { "code": null, "e": 3150, "s": 3143, "text": " Print" }, { "code": null, "e": 3161, "s": 3150, "text": " Add Notes" } ]
How To Run Commands On Multiple Remote Servers Simultaneously
OpenSSH is a widely used tool to access the remote servers, copy or transfer files, and perform all sorts of system administration tasks. One caution while using OpenSSH is that you can’t run the same command on multiple remote servers in one go. However, Don’t be disappointed! Meet PSSH, Parallel SSH, a simple, and useful alternative to OpenSSH that allows you to run commands on multiple servers from a single terminal. Sounds good? Read on to find more – PSSH consists of the following commands, such as: pssh : SSH to multiple servers at once pscp : Transfer and copy files to multiple remote systems prsync : Copy files to multiple hosts in parallel pnuke : kills processes on multiple remote hosts pslurp : Copies files from multiple remote hosts to a central host In this article, we will discuss on – how to install and use Pssh in real time. The easiest way to install Pssh is to use pip. For those who don’t know already, pip is a package management system used to install and manage software packages written in Python. PSSH is supported on Python 2.4 and greater versions. Pip is available in the default repositories of most Linux distributions. Run the following command to install python-pip in your Linux distribution. Run the following command to install python-pip in your Linux distribution. On Arch Linux and its derivatives: sudo pacman -S python-pip On RHEL, CentOS, Fedora: sudo yum install python-pip Or, sudo dnf install python-pip On Debian, Ubuntu and derivatives: sudo apt-get install python-pip Once you have installed pip, run the following command to install Pssh. This command is same for all Linux distributions. sudo sudo pip install pssh Downloading/unpacking pssh Downloading pssh-2.3.1.tar.gz Running setup.py (path:/tmp/pip_build_root/pssh/setup.py) egg_info for package pssh Installing collected packages: pssh Running setup.py install for pssh changing mode of build/scripts-2.7/pssh from 644 to 755 changing mode of build/scripts-2.7/pnuke from 644 to 755 changing mode of build/scripts-2.7/prsync from 644 to 755 changing mode of build/scripts-2.7/pslurp from 644 to 755 changing mode of build/scripts-2.7/pscp from 644 to 755 changing mode of build/scripts-2.7/pssh-askpass from 644 to 755 changing mode of /usr/local/bin/pssh-askpass to 755 changing mode of /usr/local/bin/pslurp to 755 changing mode of /usr/local/bin/pscp to 755 changing mode of /usr/local/bin/pssh to 755 changing mode of /usr/local/bin/prsync to 755 changing mode of /usr/local/bin/pnuke to 755 Successfully installed pssh Cleaning up... Pssh has been installed on our system. Let us see some practical examples to learn how to use Pssh in real time. Usage of Pssh is fairly easy! You need to create a host file and add your remote server’s IP address with SSH port number. Let us now create a host file: sudo nano hostfile.txt You can use any name of your liking to this file. Then, add the remote server’s details one by one as shown below – 192.168.1.100:22 192.168.1.102:22 Here, 192.168.1.100 and 192.168.1.102 are the IP addresses of my remote Linux hosts. Save and close the file. It’s time to test some commands. Let us check the uptime of both remote servers in one command. To do so, run: pssh -h hostfile.txt -l sk -A -i "uptime" Important note: Here, sk is the username of my remote servers. Please note that you need to have a user called sk with the same password in all remote servers. Otherwise, this command couldn’t help. So it is a must to have a common username with the same password in all your remote servers. Clear? Good. Enter the password of the user “sk”. Warning: do not enter your password if anyone else has superuser privileges or access to your account. Password: [1] 17:02:08 [SUCCESS] 192.168.1.100:22 17:02:23 up 5:10, 1 user, load average: 0.24, 0.38, 0.61 [2] 17:02:08 [SUCCESS] 192.168.1.150:22 17:02:22 up 50 min, 1 user, load average: 0.00, 0.01, 0.05 The command will display the uptime of both remote servers. Warning: You need to be very careful while using Pssh. Since it is meant to be used to run single command on multiple servers at once, one bad command will harm multiple servers simultaneously. So be very cautious while using it. Let us check kernel version in both the servers. To do so, run: pssh -h hostfile.txt -l sk -A -i "uname -r" Warning: do not enter your password if anyone else has superuser privileges or access to your account. Password: [1] 17:06:13 [SUCCESS] 192.168.1.100:22 4.8.13-1-ARCH [2] 17:06:13 [SUCCESS] 192.168.1.150:22 3.10.0-327.22.2.el7.x86_64 Let us send a message to all remote servers. pssh -h hostfile.txt -l sk -A echo "Welcome to Tutroialpoint!!" Can I copy files to all my remote servers at once? Yes, of course, you can! Let us copy a file called test.txt to all remote server with a single command. pscp -h hostfile.txt -l sk -Av -r test.txt /tmp/ Warning: do not enter your password if anyone else has superuser privileges or access to your account. Password: [1] 17:36:59 [SUCCESS] 192.168.1.100:22 [2] 17:37:03 [SUCCESS] 192.168.1.150:22 Now, let us go to the remote server and check the test.txt file is copied in /tmp/ directory. Great! test.txt is there. The same can be applied to the directories. To copy a directory, run: pscp -h hostfile.txt -l sk -Av -r tutorialspoint/ /tmp/ For more details, refer the man pages. man pssh The above command will copy the local directory called tutorialspoint to your remote system’s /tmp/ directory. That’s all for now. Hope this guide helps. For more interesting updates about Linux, please keep reading our articles.
[ { "code": null, "e": 1522, "s": 1062, "text": "OpenSSH is a widely used tool to access the remote servers, copy or transfer files, and perform all sorts of system administration tasks. One caution while using OpenSSH is that you can’t run the same command on multiple remote servers in one go. However, Don’t be disappointed! Meet PSSH, Parallel SSH, a simple, and useful alternative to OpenSSH that allows you to run commands on multiple servers from a single terminal. Sounds good? Read on to find more –" }, { "code": null, "e": 1572, "s": 1522, "text": "PSSH consists of the following commands, such as:" }, { "code": null, "e": 1611, "s": 1572, "text": "pssh : SSH to multiple servers at once" }, { "code": null, "e": 1669, "s": 1611, "text": "pscp : Transfer and copy files to multiple remote systems" }, { "code": null, "e": 1719, "s": 1669, "text": "prsync : Copy files to multiple hosts in parallel" }, { "code": null, "e": 1768, "s": 1719, "text": "pnuke : kills processes on multiple remote hosts" }, { "code": null, "e": 1835, "s": 1768, "text": "pslurp : Copies files from multiple remote hosts to a central host" }, { "code": null, "e": 1915, "s": 1835, "text": "In this article, we will discuss on – how to install and use Pssh in real time." }, { "code": null, "e": 2149, "s": 1915, "text": "The easiest way to install Pssh is to use pip. For those who don’t know already, pip is a package management system used to install and manage software packages written in Python. PSSH is supported on Python 2.4 and greater versions." }, { "code": null, "e": 2299, "s": 2149, "text": "Pip is available in the default repositories of most Linux distributions. Run the following command to install python-pip in your Linux distribution." }, { "code": null, "e": 2375, "s": 2299, "text": "Run the following command to install python-pip in your Linux distribution." }, { "code": null, "e": 2410, "s": 2375, "text": "On Arch Linux and its derivatives:" }, { "code": null, "e": 2436, "s": 2410, "text": "sudo pacman -S python-pip" }, { "code": null, "e": 2461, "s": 2436, "text": "On RHEL, CentOS, Fedora:" }, { "code": null, "e": 2489, "s": 2461, "text": "sudo yum install python-pip" }, { "code": null, "e": 2493, "s": 2489, "text": "Or," }, { "code": null, "e": 2521, "s": 2493, "text": "sudo dnf install python-pip" }, { "code": null, "e": 2556, "s": 2521, "text": "On Debian, Ubuntu and derivatives:" }, { "code": null, "e": 2588, "s": 2556, "text": "sudo apt-get install python-pip" }, { "code": null, "e": 2710, "s": 2588, "text": "Once you have installed pip, run the following command to install Pssh. This command is same for all Linux distributions." }, { "code": null, "e": 2737, "s": 2710, "text": "sudo sudo pip install pssh" }, { "code": null, "e": 3617, "s": 2737, "text": "Downloading/unpacking pssh\nDownloading pssh-2.3.1.tar.gz\nRunning setup.py (path:/tmp/pip_build_root/pssh/setup.py) egg_info for package pssh\nInstalling collected packages: pssh\nRunning setup.py install for pssh\nchanging mode of build/scripts-2.7/pssh from 644 to 755\nchanging mode of build/scripts-2.7/pnuke from 644 to 755\nchanging mode of build/scripts-2.7/prsync from 644 to 755\nchanging mode of build/scripts-2.7/pslurp from 644 to 755\nchanging mode of build/scripts-2.7/pscp from 644 to 755\nchanging mode of build/scripts-2.7/pssh-askpass from 644 to 755\nchanging mode of /usr/local/bin/pssh-askpass to 755\nchanging mode of /usr/local/bin/pslurp to 755\nchanging mode of /usr/local/bin/pscp to 755\nchanging mode of /usr/local/bin/pssh to 755\nchanging mode of /usr/local/bin/prsync to 755\nchanging mode of /usr/local/bin/pnuke to 755\nSuccessfully installed pssh\nCleaning up..." }, { "code": null, "e": 3730, "s": 3617, "text": "Pssh has been installed on our system. Let us see some practical examples to learn how to use Pssh in real time." }, { "code": null, "e": 3853, "s": 3730, "text": "Usage of Pssh is fairly easy! You need to create a host file and add your remote server’s IP address with SSH port number." }, { "code": null, "e": 3884, "s": 3853, "text": "Let us now create a host file:" }, { "code": null, "e": 3907, "s": 3884, "text": "sudo nano hostfile.txt" }, { "code": null, "e": 4023, "s": 3907, "text": "You can use any name of your liking to this file. Then, add the remote server’s details one by one as shown below –" }, { "code": null, "e": 4057, "s": 4023, "text": "192.168.1.100:22\n192.168.1.102:22" }, { "code": null, "e": 4200, "s": 4057, "text": "Here, 192.168.1.100 and 192.168.1.102 are the IP addresses of my remote Linux hosts. Save and close the file. It’s time to test some commands." }, { "code": null, "e": 4278, "s": 4200, "text": "Let us check the uptime of both remote servers in one command. To do so, run:" }, { "code": null, "e": 4320, "s": 4278, "text": "pssh -h hostfile.txt -l sk -A -i \"uptime\"" }, { "code": null, "e": 4625, "s": 4320, "text": "Important note: Here, sk is the username of my remote servers. Please note that you need to have a user called sk with the same password in all remote servers. Otherwise, this command couldn’t help. So it is a must to have a common username with the same password in all your remote servers. Clear? Good." }, { "code": null, "e": 4662, "s": 4625, "text": "Enter the password of the user “sk”." }, { "code": null, "e": 4971, "s": 4662, "text": "Warning: do not enter your password if anyone else has superuser\nprivileges or access to your account.\nPassword:\n[1] 17:02:08 [SUCCESS] 192.168.1.100:22\n17:02:23 up 5:10, 1 user, load average: 0.24, 0.38, 0.61\n[2] 17:02:08 [SUCCESS] 192.168.1.150:22\n17:02:22 up 50 min, 1 user, load average: 0.00, 0.01, 0.05" }, { "code": null, "e": 5031, "s": 4971, "text": "The command will display the uptime of both remote servers." }, { "code": null, "e": 5261, "s": 5031, "text": "Warning: You need to be very careful while using Pssh. Since it is meant to be used to run single command on multiple servers at once, one bad command will harm multiple servers simultaneously. So be very cautious while using it." }, { "code": null, "e": 5325, "s": 5261, "text": "Let us check kernel version in both the servers. To do so, run:" }, { "code": null, "e": 5369, "s": 5325, "text": "pssh -h hostfile.txt -l sk -A -i \"uname -r\"" }, { "code": null, "e": 5603, "s": 5369, "text": "Warning: do not enter your password if anyone else has superuser\nprivileges or access to your account.\nPassword:\n[1] 17:06:13 [SUCCESS] 192.168.1.100:22\n4.8.13-1-ARCH\n[2] 17:06:13 [SUCCESS] 192.168.1.150:22\n3.10.0-327.22.2.el7.x86_64" }, { "code": null, "e": 5648, "s": 5603, "text": "Let us send a message to all remote servers." }, { "code": null, "e": 5712, "s": 5648, "text": "pssh -h hostfile.txt -l sk -A echo \"Welcome to Tutroialpoint!!\"" }, { "code": null, "e": 5788, "s": 5712, "text": "Can I copy files to all my remote servers at once? Yes, of course, you can!" }, { "code": null, "e": 5867, "s": 5788, "text": "Let us copy a file called test.txt to all remote server with a single command." }, { "code": null, "e": 5916, "s": 5867, "text": "pscp -h hostfile.txt -l sk -Av -r test.txt /tmp/" }, { "code": null, "e": 6109, "s": 5916, "text": "Warning: do not enter your password if anyone else has superuser\nprivileges or access to your account.\nPassword:\n[1] 17:36:59 [SUCCESS] 192.168.1.100:22\n[2] 17:37:03 [SUCCESS] 192.168.1.150:22" }, { "code": null, "e": 6203, "s": 6109, "text": "Now, let us go to the remote server and check the test.txt file is copied in /tmp/ directory." }, { "code": null, "e": 6229, "s": 6203, "text": "Great! test.txt is there." }, { "code": null, "e": 6299, "s": 6229, "text": "The same can be applied to the directories. To copy a directory, run:" }, { "code": null, "e": 6355, "s": 6299, "text": "pscp -h hostfile.txt -l sk -Av -r tutorialspoint/ /tmp/" }, { "code": null, "e": 6394, "s": 6355, "text": "For more details, refer the man pages." }, { "code": null, "e": 6403, "s": 6394, "text": "man pssh" }, { "code": null, "e": 6514, "s": 6403, "text": "The above command will copy the local directory called tutorialspoint to your remote system’s /tmp/ directory." }, { "code": null, "e": 6633, "s": 6514, "text": "That’s all for now. Hope this guide helps. For more interesting updates about Linux, please keep reading our articles." } ]
BigIntegerMath sqrt() function | Guava | Java - GeeksforGeeks
03 Aug, 2021 The method sqrt(BigInteger x, RoundingMode mode) of Guava’s BigIntegerMath class returns the square root of x, rounded with the specified rounding mode. Syntax: public static BigInteger sqrt(BigInteger x, RoundingMode mode) Parameters: This method takes the following parameters: x : The BigInteger number whose square-root is to be found. mode : The rounding mode for calculating the square-root. Return Value: This method returns the square root of x, rounded with the specified rounding mode. Exceptions: This method throws following exceptions: IllegalArgumentException: if x < 0. ArithmeticException: if mode is RoundingMode.UNNECESSARY and sqrt(x) is not an integer. Below examples illustrates the BigIntegerMath.sqrt() method: Example 1: // Java code to show implementation of// sqrt(BigInteger x, RoundingMode mode) method// of Guava's BigIntegerMath class import java.math.*;import com.google.common.math.BigIntegerMath; class GFG { // Driver code public static void main(String args[]) { BigInteger x1 = BigInteger.valueOf(226); // Using sqrt(BigInteger x, RoundingMode mode) // method of Guava's BigIntegerMath class // The RoundingMode HALF_EVEN rounds towards // the nearest neighbor unless both neighbors // are equidistant, in which case, round towards // the even neighbor. BigInteger ans1 = BigIntegerMath .sqrt(x1, RoundingMode.HALF_EVEN); System.out.println("Square root of " + x1 + "with HALF_EVEN rounding mode is: " + ans1); BigInteger x2 = BigInteger.valueOf(154); // Using sqrt(BigInteger x, RoundingMode mode) // method of Guava's BigIntegerMath class // The RoundingMode FLOOR rounds towards // negative infinity. BigInteger ans2 = BigIntegerMath .sqrt(x2, RoundingMode.FLOOR); System.out.println("Square root of " + x2 + "with FLOOR rounding mode is: " + ans2); }} Square root of 226with HALF_EVEN rounding mode is: 15 Square root of 154with FLOOR rounding mode is: 12 Example 2: // Java code to show implementation of// sqrt(BigInteger x, RoundingMode mode) method// of Guava's BigIntegerMath class import java.math.*;import com.google.common.math.BigIntegerMath; class GFG { // Driver code public static void main(String args[]) { try { BigInteger x1 = BigInteger.valueOf(-65); // Using sqrt(BigInteger x, RoundingMode mode) // method of Guava's BigIntegerMath class // The RoundingMode HALF_EVEN rounds towards // the nearest neighbor unless both neighbors // are equidistant, in which case, round towards // the even neighbor. BigInteger ans1 = BigIntegerMath .sqrt(x1, RoundingMode.HALF_EVEN); // This should throw "IllegalArgumentException" // as x1 < 0 } catch (Exception e) { System.out.println("Exception: " + e); } }} Exception: java.lang.IllegalArgumentException: x (-65) must be >= 0 Reference: https://google.github.io/guava/releases/21.0/api/docs/com/google/common/math/BigIntegerMath.html#sqrt-java.math.BigInteger-java.math.RoundingMode- manikarora059 Java-BigInteger java-guava Java Java-BigInteger Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Hashtable in Java Constructors in Java Different ways of Reading a text file in Java Comparator Interface in Java with Examples Java Math random() method with Examples HashMap containsKey() Method in Java How to Create Array of Objects in Java? Convert Double to Integer in Java Iterating over ArrayLists in Java Generating random numbers in Java
[ { "code": null, "e": 23557, "s": 23529, "text": "\n03 Aug, 2021" }, { "code": null, "e": 23710, "s": 23557, "text": "The method sqrt(BigInteger x, RoundingMode mode) of Guava’s BigIntegerMath class returns the square root of x, rounded with the specified rounding mode." }, { "code": null, "e": 23718, "s": 23710, "text": "Syntax:" }, { "code": null, "e": 23782, "s": 23718, "text": "public static BigInteger sqrt(BigInteger x, RoundingMode mode)\n" }, { "code": null, "e": 23838, "s": 23782, "text": "Parameters: This method takes the following parameters:" }, { "code": null, "e": 23898, "s": 23838, "text": "x : The BigInteger number whose square-root is to be found." }, { "code": null, "e": 23956, "s": 23898, "text": "mode : The rounding mode for calculating the square-root." }, { "code": null, "e": 24054, "s": 23956, "text": "Return Value: This method returns the square root of x, rounded with the specified rounding mode." }, { "code": null, "e": 24107, "s": 24054, "text": "Exceptions: This method throws following exceptions:" }, { "code": null, "e": 24143, "s": 24107, "text": "IllegalArgumentException: if x < 0." }, { "code": null, "e": 24231, "s": 24143, "text": "ArithmeticException: if mode is RoundingMode.UNNECESSARY and sqrt(x) is not an integer." }, { "code": null, "e": 24292, "s": 24231, "text": "Below examples illustrates the BigIntegerMath.sqrt() method:" }, { "code": null, "e": 24303, "s": 24292, "text": "Example 1:" }, { "code": "// Java code to show implementation of// sqrt(BigInteger x, RoundingMode mode) method// of Guava's BigIntegerMath class import java.math.*;import com.google.common.math.BigIntegerMath; class GFG { // Driver code public static void main(String args[]) { BigInteger x1 = BigInteger.valueOf(226); // Using sqrt(BigInteger x, RoundingMode mode) // method of Guava's BigIntegerMath class // The RoundingMode HALF_EVEN rounds towards // the nearest neighbor unless both neighbors // are equidistant, in which case, round towards // the even neighbor. BigInteger ans1 = BigIntegerMath .sqrt(x1, RoundingMode.HALF_EVEN); System.out.println(\"Square root of \" + x1 + \"with HALF_EVEN rounding mode is: \" + ans1); BigInteger x2 = BigInteger.valueOf(154); // Using sqrt(BigInteger x, RoundingMode mode) // method of Guava's BigIntegerMath class // The RoundingMode FLOOR rounds towards // negative infinity. BigInteger ans2 = BigIntegerMath .sqrt(x2, RoundingMode.FLOOR); System.out.println(\"Square root of \" + x2 + \"with FLOOR rounding mode is: \" + ans2); }}", "e": 25720, "s": 24303, "text": null }, { "code": null, "e": 25825, "s": 25720, "text": "Square root of 226with HALF_EVEN rounding mode is: 15\nSquare root of 154with FLOOR rounding mode is: 12\n" }, { "code": null, "e": 25836, "s": 25825, "text": "Example 2:" }, { "code": "// Java code to show implementation of// sqrt(BigInteger x, RoundingMode mode) method// of Guava's BigIntegerMath class import java.math.*;import com.google.common.math.BigIntegerMath; class GFG { // Driver code public static void main(String args[]) { try { BigInteger x1 = BigInteger.valueOf(-65); // Using sqrt(BigInteger x, RoundingMode mode) // method of Guava's BigIntegerMath class // The RoundingMode HALF_EVEN rounds towards // the nearest neighbor unless both neighbors // are equidistant, in which case, round towards // the even neighbor. BigInteger ans1 = BigIntegerMath .sqrt(x1, RoundingMode.HALF_EVEN); // This should throw \"IllegalArgumentException\" // as x1 < 0 } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}", "e": 26827, "s": 25836, "text": null }, { "code": null, "e": 26896, "s": 26827, "text": "Exception: java.lang.IllegalArgumentException: x (-65) must be >= 0\n" }, { "code": null, "e": 27054, "s": 26896, "text": "Reference: https://google.github.io/guava/releases/21.0/api/docs/com/google/common/math/BigIntegerMath.html#sqrt-java.math.BigInteger-java.math.RoundingMode-" }, { "code": null, "e": 27068, "s": 27054, "text": "manikarora059" }, { "code": null, "e": 27084, "s": 27068, "text": "Java-BigInteger" }, { "code": null, "e": 27095, "s": 27084, "text": "java-guava" }, { "code": null, "e": 27100, "s": 27095, "text": "Java" }, { "code": null, "e": 27116, "s": 27100, "text": "Java-BigInteger" }, { "code": null, "e": 27121, "s": 27116, "text": "Java" }, { "code": null, "e": 27219, "s": 27121, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27228, "s": 27219, "text": "Comments" }, { "code": null, "e": 27241, "s": 27228, "text": "Old Comments" }, { "code": null, "e": 27259, "s": 27241, "text": "Hashtable in Java" }, { "code": null, "e": 27280, "s": 27259, "text": "Constructors in Java" }, { "code": null, "e": 27326, "s": 27280, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27369, "s": 27326, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27409, "s": 27369, "text": "Java Math random() method with Examples" }, { "code": null, "e": 27446, "s": 27409, "text": "HashMap containsKey() Method in Java" }, { "code": null, "e": 27486, "s": 27446, "text": "How to Create Array of Objects in Java?" }, { "code": null, "e": 27520, "s": 27486, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 27554, "s": 27520, "text": "Iterating over ArrayLists in Java" } ]
What are the rules about using an underscore in a C++ identifier?
From MSDN docs − Use of two sequential underscore characters ( __ ) at the beginning of an identifier, or a single leading underscore followed by a capital letter, is reserved for C++ implementations in all scopes. You should avoid using one leading underscore followed by a lowercase letter for names with file scope because of possible conflicts with current or future reserved identifiers. So you should avoid using names like − __foo, __FOO, _FOO And names like the following should not be used in the global namespace − _foo, _bar Other than this, there are some more prefixes like LC_, SIG_, and suffixes like _t should not be used as they're also reserved for the implementation. So you can create variables that contain the underscore between the name or ends with an underscore.
[ { "code": null, "e": 1079, "s": 1062, "text": "From MSDN docs −" }, { "code": null, "e": 1455, "s": 1079, "text": "Use of two sequential underscore characters ( __ ) at the beginning of an identifier, or a single leading underscore followed by a capital letter, is reserved for C++ implementations in all scopes. You should avoid using one leading underscore followed by a lowercase letter for names with file scope because of possible conflicts with current or future reserved identifiers." }, { "code": null, "e": 1494, "s": 1455, "text": "So you should avoid using names like −" }, { "code": null, "e": 1513, "s": 1494, "text": "__foo, __FOO, _FOO" }, { "code": null, "e": 1587, "s": 1513, "text": "And names like the following should not be used in the global namespace −" }, { "code": null, "e": 1598, "s": 1587, "text": "_foo, _bar" }, { "code": null, "e": 1749, "s": 1598, "text": "Other than this, there are some more prefixes like LC_, SIG_, and suffixes like _t should not be used as they're also reserved for the implementation." }, { "code": null, "e": 1850, "s": 1749, "text": "So you can create variables that contain the underscore between the name or ends with an underscore." } ]
Replace Tab with space in SAP ABAP
You just need to make a small change. You need to add an “If condition” for handling the tab as shown below − if <field Name> CO gc_hex_char I think it should sort out your issue and neither it looks like hardcoding or a wrong implementation.
[ { "code": null, "e": 1172, "s": 1062, "text": "You just need to make a small change. You need to add an “If condition” for handling the tab as shown below −" }, { "code": null, "e": 1204, "s": 1172, "text": "if <field Name> CO gc_hex_char\n" }, { "code": null, "e": 1306, "s": 1204, "text": "I think it should sort out your issue and neither it looks like hardcoding or a wrong implementation." } ]
GATE | GATE CS Mock 2018 | Set 2 | Question 64 - GeeksforGeeks
15 Oct, 2019 Consider the given schedule and choose the suitable option. S = T1:R(x), T1:R(y), T1:W(x), T2:R(y), T3:W(y), T1:W(x), T2:R(y) (A) Schedule is view serializable(B) Schedule is conflict serializable but not view serializable(C) Schedule is view serializable but not conflict serializable(D) Neither view serializable nor conflict serializableAnswer: (C)Explanation: Since there is cycle found in precedence graph, it is not Conflict Serializable. Also, there is a blind write in T3 so we need to test further for view serializability using polygraph. From polygraph, we can derive that it is View serializable.Option (C) is Correct.Quiz of this Question shahfenil1998 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2014-(Set-1) | Question 30 GATE | GATE-CS-2015 (Set 1) | Question 65 GATE | GATE CS 2010 | Question 45 GATE | GATE-CS-2015 (Set 3) | Question 65 C++ Program to count Vowels in a string using Pointer GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2015 (Set 1) | Question 42 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 2011 | Question 65 GATE | GATE CS 2012 | Question 65
[ { "code": null, "e": 24075, "s": 24047, "text": "\n15 Oct, 2019" }, { "code": null, "e": 24135, "s": 24075, "text": "Consider the given schedule and choose the suitable option." }, { "code": null, "e": 24202, "s": 24135, "text": "S = T1:R(x), T1:R(y), T1:W(x), T2:R(y), T3:W(y), T1:W(x), T2:R(y) " }, { "code": null, "e": 24728, "s": 24202, "text": "(A) Schedule is view serializable(B) Schedule is conflict serializable but not view serializable(C) Schedule is view serializable but not conflict serializable(D) Neither view serializable nor conflict serializableAnswer: (C)Explanation: Since there is cycle found in precedence graph, it is not Conflict Serializable. Also, there is a blind write in T3 so we need to test further for view serializability using polygraph. From polygraph, we can derive that it is View serializable.Option (C) is Correct.Quiz of this Question" }, { "code": null, "e": 24742, "s": 24728, "text": "shahfenil1998" }, { "code": null, "e": 24747, "s": 24742, "text": "GATE" }, { "code": null, "e": 24845, "s": 24747, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24854, "s": 24845, "text": "Comments" }, { "code": null, "e": 24867, "s": 24854, "text": "Old Comments" }, { "code": null, "e": 24909, "s": 24867, "text": "GATE | GATE-CS-2014-(Set-1) | Question 30" }, { "code": null, "e": 24951, "s": 24909, "text": "GATE | GATE-CS-2015 (Set 1) | Question 65" }, { "code": null, "e": 24985, "s": 24951, "text": "GATE | GATE CS 2010 | Question 45" }, { "code": null, "e": 25027, "s": 24985, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 25081, "s": 25027, "text": "C++ Program to count Vowels in a string using Pointer" }, { "code": null, "e": 25114, "s": 25081, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 25156, "s": 25114, "text": "GATE | GATE-CS-2015 (Set 1) | Question 42" }, { "code": null, "e": 25198, "s": 25156, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 25232, "s": 25198, "text": "GATE | GATE CS 2011 | Question 65" } ]
RSpec - Writing Specs
In this chapter, we will create a new Ruby class, save it in its own file and create a separate spec file to test this class. First, in our new class, it is called StringAnalyzer. It’s a simple class that, you guessed it, analyzes strings. Our class has only one method has_vowels? which as its names suggests, returns true if a string contains vowels and false if it doesn’t. Here’s the implementation for StringAnalyzer − class StringAnalyzer def has_vowels?(str) !!(str =~ /[aeio]+/i) end end If you followed the HelloWorld section, you created a folder called C:\rspec_tutorial\spec. Delete the hello_world.rb file if you have it and save the StringAnalyzer code above to a file called string_analyzer.rb in the C:\rspec_tutorial\spec folder. Here is the source for our spec file to test StringAnalyzer − require 'string_analyzer' describe StringAnalyzer do context "With valid input" do it "should detect when a string contains vowels" do sa = StringAnalyzer.new test_string = 'uuu' expect(sa.has_vowels? test_string).to be true end it "should detect when a string doesn't contain vowels" do sa = StringAnalyzer.new test_string = 'bcdfg' expect(sa.has_vowels? test_string).to be false end end end Save this in the same spec directory, giving it the name string_analyzer_test.rb. In your cmd.exe window, cd to the C:\rspec_tutorial folder and run this command: dir spec You should see the following − Directory of C:\rspec_tutorial\spec 09/13/2015 08:22 AM <DIR> . 09/13/2015 08:22 AM <DIR> .. 09/12/2015 11:44 PM 81 string_analyzer.rb 09/12/2015 11:46 PM 451 string_analyzer_test.rb Now we’re going to run our tests, run this command: rspec spec When you pass the name of a folder to rspec, it runs all of the spec files inside of the folder. You should see this result − No examples found. Finished in 0 seconds (files took 0.068 seconds to load) 0 examples, 0 failures The reason that this happened is that, by default, rspec only runs files whose names end in “_spec.rb”. Rename string_analyzer_test.rb to string_analyzer_spec.rb. You can do that easily by running this command − ren spec\string_analyzer_test.rb string_analyzer_spec.rb Now, run rspec spec again, you should see output that looks like this − F. Failures: 1) StringAnalyzer With valid input should detect when a string contains vowels Failure/Error: expect(sa.has_vowels? test_string).to be true expected true got false # ./spec/string_analyzer_spec.rb:9:in `block (3 levels) in <top (required)>' Finished in 0.015 seconds (files took 0.12201 seconds to load) 2 examples, 1 failure Failed examples: rspec ./spec/string_analyzer_spec.rb:6 # StringAnalyzer With valid input should detect when a string contains vowels Do you see what just happened? Our spec failed because we have a bug in StringAnalyzer. The bug is simple to fix, open up string_analyzer.rb in a text editor and change this line: !!(str =~ /[aeio]+/i) to this: !!(str =~ /[aeiou]+/i) Now, save the changes you just made in string_analyizer.rb and run the rspec spec command again, you should now see output that looks like − .. Finished in 0.002 seconds (files took 0.11401 seconds to load) 2 examples, 0 failures Congratulations, the examples (tests) in your spec file are now passing. We fixed a bug in the regular expression which has vowels method but our tests are far from complete. It would make sense to add more examples that tests various types of input strings with the has vowels method. The following table shows some of the permutations that could be added in new Examples (it blocks) It is up to you to decide, which examples to add to your spec file. There are many conditions to test for, you need to determine what subset of conditions is most important and tests your code the best. The rspec command offers many different options, to see them all, type rspec -help. The following table lists the most popular options and describes what they do. -I PATH Adds PATH to the load (require) path that rspec uses when looking for Ruby source files. -r, --require PATH Adds a specific source file to be required in your spec. file(s). --fail-fast With this option, rspec will stop running specs after the first Example fails. By default, rspec runs all specified spec files, no matter how many failures there are. -f, --format FORMATTER This option allows you to specify different output formats. See the section on Formatters for more details about output formats. -o, --out FILE This option directs rspec to write the test results to the output file FILE instead of to standard out. -c, --color Enables color in rspec’s output. Successful Example results will display in green text, failures will print in red text. -b, --backtrace Displays full error backtraces in rspec’s output. -w, --warnings Displays Ruby warnings in rspec’s output. -P, --pattern PATTERN Load and run spec files that match the pattern PATTERN. For example, if you pass -p “*.rb”, rspec will run all Ruby files, not just the ones that end in “_spec.rb”. -e, --example STRING This option directs rspec to run all Examples that contain the text STRING in their descriptions. -t, --tag TAG With this option, rspec will only run examples that contain the tag TAG. Note that TAG is specified as a Ruby symbol. See the section on RSpec Tags for more details. 9 Lectures 37 mins Harshit Srivastava 27 Lectures 7 hours Atul Tiwari Print Add Notes Bookmark this page
[ { "code": null, "e": 1920, "s": 1794, "text": "In this chapter, we will create a new Ruby class, save it in its own file and create a separate spec file to test this class." }, { "code": null, "e": 2218, "s": 1920, "text": "First, in our new class, it is called StringAnalyzer. It’s a simple class that, you guessed it, analyzes strings. Our class has only one method has_vowels? which as its names suggests, returns true if a string contains vowels and false if it doesn’t. Here’s the implementation for StringAnalyzer −" }, { "code": null, "e": 2306, "s": 2218, "text": "class StringAnalyzer \n def has_vowels?(str) \n !!(str =~ /[aeio]+/i) \n end \nend" }, { "code": null, "e": 2398, "s": 2306, "text": "If you followed the HelloWorld section, you created a folder called C:\\rspec_tutorial\\spec." }, { "code": null, "e": 2557, "s": 2398, "text": "Delete the hello_world.rb file if you have it and save the StringAnalyzer code above to a file called string_analyzer.rb in the C:\\rspec_tutorial\\spec folder." }, { "code": null, "e": 2619, "s": 2557, "text": "Here is the source for our spec file to test StringAnalyzer −" }, { "code": null, "e": 3127, "s": 2619, "text": "require 'string_analyzer' \n\ndescribe StringAnalyzer do \n context \"With valid input\" do \n \n it \"should detect when a string contains vowels\" do \n sa = StringAnalyzer.new \n test_string = 'uuu' \n expect(sa.has_vowels? test_string).to be true \n end \n\t\t\n it \"should detect when a string doesn't contain vowels\" do \n sa = StringAnalyzer.new \n test_string = 'bcdfg' \n expect(sa.has_vowels? test_string).to be false\n end \n \n end \nend" }, { "code": null, "e": 3209, "s": 3127, "text": "Save this in the same spec directory, giving it the name string_analyzer_test.rb." }, { "code": null, "e": 3299, "s": 3209, "text": "In your cmd.exe window, cd to the C:\\rspec_tutorial folder and run this command: dir spec" }, { "code": null, "e": 3330, "s": 3299, "text": "You should see the following −" }, { "code": null, "e": 3366, "s": 3330, "text": "Directory of C:\\rspec_tutorial\\spec" }, { "code": null, "e": 3551, "s": 3366, "text": "09/13/2015 08:22 AM <DIR> .\n09/13/2015 08:22 AM <DIR> ..\n09/12/2015 11:44 PM 81 string_analyzer.rb\n09/12/2015 11:46 PM 451 string_analyzer_test.rb\n" }, { "code": null, "e": 3614, "s": 3551, "text": "Now we’re going to run our tests, run this command: rspec spec" }, { "code": null, "e": 3740, "s": 3614, "text": "When you pass the name of a folder to rspec, it runs all of the spec files inside of the folder. You should see this result −" }, { "code": null, "e": 3841, "s": 3740, "text": "No examples found.\n\nFinished in 0 seconds (files took 0.068 seconds to load)\n0 examples, 0 failures\n" }, { "code": null, "e": 4053, "s": 3841, "text": "The reason that this happened is that, by default, rspec only runs files whose names end in “_spec.rb”. Rename string_analyzer_test.rb to string_analyzer_spec.rb. You can do that easily by running this command −" }, { "code": null, "e": 4111, "s": 4053, "text": "ren spec\\string_analyzer_test.rb string_analyzer_spec.rb\n" }, { "code": null, "e": 4183, "s": 4111, "text": "Now, run rspec spec again, you should see output that looks like this −" }, { "code": null, "e": 4942, "s": 4183, "text": "F.\nFailures:\n\n 1) StringAnalyzer With valid input should detect when a string contains vowels\n Failure/Error: expect(sa.has_vowels? test_string).to be true \n expected true\n got false\n # ./spec/string_analyzer_spec.rb:9:in `block (3 levels) in <top (required)>'\n\nFinished in 0.015 seconds (files took 0.12201 seconds to load)\n2 examples, 1 failure\n\nFailed examples:\nrspec ./spec/string_analyzer_spec.rb:6 # StringAnalyzer With valid \n input should detect when a string contains vowels\nDo you see what just happened? Our spec failed because we have a bug in \n StringAnalyzer. The bug is simple to fix, open up string_analyzer.rb\n in a text editor and change this line:\n!!(str =~ /[aeio]+/i)\nto this:\n!!(str =~ /[aeiou]+/i)\n" }, { "code": null, "e": 5083, "s": 4942, "text": "Now, save the changes you just made in string_analyizer.rb and run the rspec spec command again, you should now see output that looks like −" }, { "code": null, "e": 5173, "s": 5083, "text": "..\nFinished in 0.002 seconds (files took 0.11401 seconds to load)\n2 examples, 0 failures\n" }, { "code": null, "e": 5348, "s": 5173, "text": "Congratulations, the examples (tests) in your spec file are now passing. We fixed a bug in the regular expression which has vowels method but our tests are far from complete." }, { "code": null, "e": 5459, "s": 5348, "text": "It would make sense to add more examples that tests various types of input strings with the has vowels method." }, { "code": null, "e": 5558, "s": 5459, "text": "The following table shows some of the permutations that could be added in new Examples (it blocks)" }, { "code": null, "e": 5761, "s": 5558, "text": "It is up to you to decide, which examples to add to your spec file. There are many conditions to test for, you need to determine what subset of conditions is most important and tests your code the best." }, { "code": null, "e": 5924, "s": 5761, "text": "The rspec command offers many different options, to see them all, type rspec -help. The following table lists the most popular options and describes what they do." }, { "code": null, "e": 5932, "s": 5924, "text": "-I PATH" }, { "code": null, "e": 6021, "s": 5932, "text": "Adds PATH to the load (require) path that rspec uses when looking for Ruby source files." }, { "code": null, "e": 6040, "s": 6021, "text": "-r, --require PATH" }, { "code": null, "e": 6106, "s": 6040, "text": "Adds a specific source file to be required in your spec. file(s)." }, { "code": null, "e": 6118, "s": 6106, "text": "--fail-fast" }, { "code": null, "e": 6285, "s": 6118, "text": "With this option, rspec will stop running specs after the first Example fails. By default, rspec runs all specified spec files, no matter how many failures there are." }, { "code": null, "e": 6308, "s": 6285, "text": "-f, --format FORMATTER" }, { "code": null, "e": 6437, "s": 6308, "text": "This option allows you to specify different output formats. See the section on Formatters for more details about output formats." }, { "code": null, "e": 6452, "s": 6437, "text": "-o, --out FILE" }, { "code": null, "e": 6556, "s": 6452, "text": "This option directs rspec to write the test results to the output file FILE instead of to standard out." }, { "code": null, "e": 6568, "s": 6556, "text": "-c, --color" }, { "code": null, "e": 6689, "s": 6568, "text": "Enables color in rspec’s output. Successful Example results will display in green text, failures will print in red text." }, { "code": null, "e": 6705, "s": 6689, "text": "-b, --backtrace" }, { "code": null, "e": 6755, "s": 6705, "text": "Displays full error backtraces in rspec’s output." }, { "code": null, "e": 6770, "s": 6755, "text": "-w, --warnings" }, { "code": null, "e": 6812, "s": 6770, "text": "Displays Ruby warnings in rspec’s output." }, { "code": null, "e": 6834, "s": 6812, "text": "-P, --pattern PATTERN" }, { "code": null, "e": 6999, "s": 6834, "text": "Load and run spec files that match the pattern PATTERN. For example, if you pass -p “*.rb”, rspec will run all Ruby files, not just the ones that end in “_spec.rb”." }, { "code": null, "e": 7020, "s": 6999, "text": "-e, --example STRING" }, { "code": null, "e": 7118, "s": 7020, "text": "This option directs rspec to run all Examples that contain the text STRING in their descriptions." }, { "code": null, "e": 7132, "s": 7118, "text": "-t, --tag TAG" }, { "code": null, "e": 7298, "s": 7132, "text": "With this option, rspec will only run examples that contain the tag TAG. Note that TAG is specified as a Ruby symbol. See the section on RSpec Tags for more details." }, { "code": null, "e": 7329, "s": 7298, "text": "\n 9 Lectures \n 37 mins\n" }, { "code": null, "e": 7349, "s": 7329, "text": " Harshit Srivastava" }, { "code": null, "e": 7382, "s": 7349, "text": "\n 27 Lectures \n 7 hours \n" }, { "code": null, "e": 7395, "s": 7382, "text": " Atul Tiwari" }, { "code": null, "e": 7402, "s": 7395, "text": " Print" }, { "code": null, "e": 7413, "s": 7402, "text": " Add Notes" } ]
MySQL ALTER column to remove primary key and auto_increment?
You can use ALTER command to remove primary key and auto_increment. The syntax is as follows − ALTER TABLE yourTableName DROP PRIMARY KEY,change yourColumnName yourColumnName data type; To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table removePrimaryKey -> ( -> StudentId int NOT NULL AUTO_INCREMENT, -> StudentFirstName varchar(20), -> StudentLastName varchar(20), -> PRIMARY KEY(StudentId) -> ); Query OK, 0 rows affected (0.47 sec) Check the description of table using DESC command. The syntax is as follows − desc yourTableName; Check the description of the table ‘removePrimaryKey’ using DESC. The query is as follows − mysql> desc removePrimaryKey; The following is the output − +------------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------------+-------------+------+-----+---------+----------------+ | StudentId | int(11) | NO | PRI | NULL | auto_increment | | StudentFirstName | varchar(20) | YES | | NULL | | | StudentLastName | varchar(20) | YES | | NULL | | +------------------+-------------+------+-----+---------+----------------+ 3 rows in set (0.01 sec) Now look at the column Key and Extra above. In the Key column, there is PRI and in the Extra column there is auto_increment. You need to remove both of them, using the ALTER DROP command discussed in the beginning − The query is as follows − mysql> alter table removePrimaryKey DROP PRIMARY KEY,change StudentId StudentId int; Query OK, 0 rows affected (1.79 sec) Records − 0 Duplicates − 0 Warnings − 0 We have successfully removed primary key and auto increment above. Now you check the primary key and auto_increment have been removed from the table or not using the following query − mysql> desc removePrimaryKey; The following is the output − +------------------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +------------------+-------------+------+-----+---------+-------+ | StudentId | int(11) | YES | | NULL | | | StudentFirstName | varchar(20) | YES | | NULL | | | StudentLastName | varchar(20) | YES | | NULL | | +------------------+-------------+------+-----+---------+-------+ 3 rows in set (0.07 sec)
[ { "code": null, "e": 1157, "s": 1062, "text": "You can use ALTER command to remove primary key and auto_increment. The syntax is as follows −" }, { "code": null, "e": 1248, "s": 1157, "text": "ALTER TABLE yourTableName DROP PRIMARY KEY,change yourColumnName yourColumnName data type;" }, { "code": null, "e": 1347, "s": 1248, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1583, "s": 1347, "text": "mysql> create table removePrimaryKey\n -> (\n -> StudentId int NOT NULL AUTO_INCREMENT,\n -> StudentFirstName varchar(20),\n -> StudentLastName varchar(20),\n -> PRIMARY KEY(StudentId)\n -> );\nQuery OK, 0 rows affected (0.47 sec)" }, { "code": null, "e": 1661, "s": 1583, "text": "Check the description of table using DESC command. The syntax is as follows −" }, { "code": null, "e": 1681, "s": 1661, "text": "desc yourTableName;" }, { "code": null, "e": 1773, "s": 1681, "text": "Check the description of the table ‘removePrimaryKey’ using DESC. The query is as follows −" }, { "code": null, "e": 1803, "s": 1773, "text": "mysql> desc removePrimaryKey;" }, { "code": null, "e": 1833, "s": 1803, "text": "The following is the output −" }, { "code": null, "e": 2383, "s": 1833, "text": "+------------------+-------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+------------------+-------------+------+-----+---------+----------------+\n| StudentId | int(11) | NO | PRI | NULL | auto_increment |\n| StudentFirstName | varchar(20) | YES | | NULL | |\n| StudentLastName | varchar(20) | YES | | NULL | |\n+------------------+-------------+------+-----+---------+----------------+\n3 rows in set (0.01 sec)" }, { "code": null, "e": 2599, "s": 2383, "text": "Now look at the column Key and Extra above. In the Key column, there is PRI and in the Extra column there is auto_increment. You need to remove both of them, using the ALTER DROP command discussed in the beginning −" }, { "code": null, "e": 2625, "s": 2599, "text": "The query is as follows −" }, { "code": null, "e": 2787, "s": 2625, "text": "mysql> alter table removePrimaryKey DROP PRIMARY KEY,change StudentId StudentId int;\nQuery OK, 0 rows affected (1.79 sec)\nRecords − 0 Duplicates − 0 Warnings − 0" }, { "code": null, "e": 2971, "s": 2787, "text": "We have successfully removed primary key and auto increment above. Now you check the primary key and auto_increment have been removed from the table or not using the following query −" }, { "code": null, "e": 3001, "s": 2971, "text": "mysql> desc removePrimaryKey;" }, { "code": null, "e": 3031, "s": 3001, "text": "The following is the output −" }, { "code": null, "e": 3518, "s": 3031, "text": "+------------------+-------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+------------------+-------------+------+-----+---------+-------+\n| StudentId | int(11) | YES | | NULL | |\n| StudentFirstName | varchar(20) | YES | | NULL | |\n| StudentLastName | varchar(20) | YES | | NULL | |\n+------------------+-------------+------+-----+---------+-------+\n3 rows in set (0.07 sec)" } ]
Count occurrences of a character in a repeated string in C++
Given a string str, a character and a positive integer N. The string str is repeated indefinitely. The goal is to find the count of occurrences of character in str in first N characters of repetitions. If str is “abac”, character is ch=‘b’ and N is 10. In first 10 characters of “abacabacabacabac.......” b occurs twice. Note − Take str and character ch within the same case. Let us understand with examples. For Example str = "TPTTTT" ch = 'T' n = 12 Count of occurrences of a character in a repeated string are: 10 The number of ‘T’ in str is 5. Length of str is 6. For n=12, str will be fully repeated twice, so count of Ts is 6*2=12. str = "sets" ch = 's' n = 15 Count of occurrences of a character in a repeated string are: 7 The number of ‘s’ in str is 2. Length of str is 4. For n=15, str will be fully repeated 3 times (first 12 characters), so count of s in those will be 3*2=6. For the remaining 3 characters (set) s occurs once. So count is 6+1=7 Approach used in the below program is as follows − In this approach we will first count the number of occurrences of character ch in str. Then we will divide the length of str with N. We will get a number of full repetitions of str within N characters by (N / length of str). So, the number of occurrences of ch in those repetitions will be simple multiplication. For remaining characters (N % length of str) count ch in str again and add to previous count. Take a string str. Take a string str. Take n as integer, ch as character and length of str as integer. Take n as integer, ch as character and length of str as integer. Function occurrences_char(string str, int length, int n, char ch) takes str, ch, n and length of str and returns the count of ch in first n characters in repeated string str. Function occurrences_char(string str, int length, int n, char ch) takes str, ch, n and length of str and returns the count of ch in first n characters in repeated string str. Take the initial count as 0. Take the initial count as 0. Using for loop count occurrences of ch in str. For each str[i]==ch, increment count. Using for loop count occurrences of ch in str. For each str[i]==ch, increment count. No of repetitions of str in n will be occ= n / length. No of repetitions of str in n will be occ= n / length. No. of occurrences of ch in these repetitions will be count * occ. No. of occurrences of ch in these repetitions will be count * occ. For remaining n % length characters of str check if str[i]==ch, if yes increment count. For remaining n % length characters of str check if str[i]==ch, if yes increment count. Return count as result. Return count as result. Live Demo #include <bits/stdc++.h> using namespace std; int occurrences_char(string str, int length, int n, char ch){ int count = 0; for (int i = 0; i < length; i++){ if (str[i] == ch){ count++; } } int occ = n / length; count = count * occ; for (int i = 0; i < n % length; i++){ if (str[i] == ch){ count++; } } return count; } int main(){ string str = "TPTTTT"; char ch = 'T'; int n = 12; int length = str.size(); cout<<"Count of occurrences of a character in a repeated string are: "<<occurrences_char(str, length, n, ch); return 0; } If we run the above code it will generate the following output − Count of occurrences of a character in a repeated string are − 10
[ { "code": null, "e": 1264, "s": 1062, "text": "Given a string str, a character and a positive integer N. The string str is repeated indefinitely. The goal is to find the count of occurrences of character in str in first N characters of repetitions." }, { "code": null, "e": 1315, "s": 1264, "text": "If str is “abac”, character is ch=‘b’ and N is 10." }, { "code": null, "e": 1383, "s": 1315, "text": "In first 10 characters of “abacabacabacabac.......” b occurs twice." }, { "code": null, "e": 1438, "s": 1383, "text": "Note − Take str and character ch within the same case." }, { "code": null, "e": 1471, "s": 1438, "text": "Let us understand with examples." }, { "code": null, "e": 1483, "s": 1471, "text": "For Example" }, { "code": null, "e": 1514, "s": 1483, "text": "str = \"TPTTTT\" ch = 'T' n = 12" }, { "code": null, "e": 1579, "s": 1514, "text": "Count of occurrences of a character in a repeated string are: 10" }, { "code": null, "e": 1700, "s": 1579, "text": "The number of ‘T’ in str is 5. Length of str is 6.\nFor n=12, str will be fully repeated twice, so count of Ts is 6*2=12." }, { "code": null, "e": 1729, "s": 1700, "text": "str = \"sets\" ch = 's' n = 15" }, { "code": null, "e": 1793, "s": 1729, "text": "Count of occurrences of a character in a repeated string are: 7" }, { "code": null, "e": 2020, "s": 1793, "text": "The number of ‘s’ in str is 2. Length of str is 4.\nFor n=15, str will be fully repeated 3 times (first 12 characters), so count of s in those will be 3*2=6. For the remaining 3 characters (set) s occurs once. So count is 6+1=7" }, { "code": null, "e": 2071, "s": 2020, "text": "Approach used in the below program is as follows −" }, { "code": null, "e": 2478, "s": 2071, "text": "In this approach we will first count the number of occurrences of character ch in str. Then we will divide the length of str with N. We will get a number of full repetitions of str within N characters by (N / length of str). So, the number of occurrences of ch in those repetitions will be simple multiplication. For remaining characters (N % length of str) count ch in str again and add to previous count." }, { "code": null, "e": 2497, "s": 2478, "text": "Take a string str." }, { "code": null, "e": 2516, "s": 2497, "text": "Take a string str." }, { "code": null, "e": 2581, "s": 2516, "text": "Take n as integer, ch as character and length of str as integer." }, { "code": null, "e": 2646, "s": 2581, "text": "Take n as integer, ch as character and length of str as integer." }, { "code": null, "e": 2821, "s": 2646, "text": "Function occurrences_char(string str, int length, int n, char ch) takes str, ch, n and length of str and returns the count of ch in first n characters in repeated string str." }, { "code": null, "e": 2996, "s": 2821, "text": "Function occurrences_char(string str, int length, int n, char ch) takes str, ch, n and length of str and returns the count of ch in first n characters in repeated string str." }, { "code": null, "e": 3025, "s": 2996, "text": "Take the initial count as 0." }, { "code": null, "e": 3054, "s": 3025, "text": "Take the initial count as 0." }, { "code": null, "e": 3139, "s": 3054, "text": "Using for loop count occurrences of ch in str. For each str[i]==ch, increment count." }, { "code": null, "e": 3224, "s": 3139, "text": "Using for loop count occurrences of ch in str. For each str[i]==ch, increment count." }, { "code": null, "e": 3279, "s": 3224, "text": "No of repetitions of str in n will be occ= n / length." }, { "code": null, "e": 3334, "s": 3279, "text": "No of repetitions of str in n will be occ= n / length." }, { "code": null, "e": 3401, "s": 3334, "text": "No. of occurrences of ch in these repetitions will be count * occ." }, { "code": null, "e": 3468, "s": 3401, "text": "No. of occurrences of ch in these repetitions will be count * occ." }, { "code": null, "e": 3556, "s": 3468, "text": "For remaining n % length characters of str check if str[i]==ch, if yes increment count." }, { "code": null, "e": 3644, "s": 3556, "text": "For remaining n % length characters of str check if str[i]==ch, if yes increment count." }, { "code": null, "e": 3668, "s": 3644, "text": "Return count as result." }, { "code": null, "e": 3692, "s": 3668, "text": "Return count as result." }, { "code": null, "e": 3703, "s": 3692, "text": " Live Demo" }, { "code": null, "e": 4314, "s": 3703, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint occurrences_char(string str, int length, int n, char ch){\n int count = 0;\n for (int i = 0; i < length; i++){\n if (str[i] == ch){\n count++;\n }\n }\n int occ = n / length;\n count = count * occ;\n for (int i = 0; i < n % length; i++){\n if (str[i] == ch){\n count++;\n }\n }\n return count;\n}\nint main(){\n string str = \"TPTTTT\";\n char ch = 'T';\n int n = 12;\n int length = str.size();\n cout<<\"Count of occurrences of a character in a repeated string are: \"<<occurrences_char(str, length, n, ch);\n return 0;\n}" }, { "code": null, "e": 4379, "s": 4314, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 4445, "s": 4379, "text": "Count of occurrences of a character in a repeated string are − 10" } ]
Java Program to convert Boolean to String
To convert Boolean to String in Java, use the toString() method. For this, firstly, we have declared two booleans. boolean bool1 = false; boolean bool2 = true; Now, convert Boolean to String using the toString() method in Java as shown below − String str1 = new Boolean(bool1).toString(); String str2 = new Boolean(bool2).toString(); Now, when you will display the values “str1” and “str2”, the output would be in String. Let us now see the complete example to convert Boolean to String. Live Demo public class Demo { public static void main(String[] args) { boolean bool1 = false; boolean bool2 = true; String str1 = new Boolean(bool1).toString(); String str2 = new Boolean(bool2).toString(); System.out.println(str1); System.out.println(str2); } } false true
[ { "code": null, "e": 1177, "s": 1062, "text": "To convert Boolean to String in Java, use the toString() method. For this, firstly, we have declared two booleans." }, { "code": null, "e": 1222, "s": 1177, "text": "boolean bool1 = false;\nboolean bool2 = true;" }, { "code": null, "e": 1306, "s": 1222, "text": "Now, convert Boolean to String using the toString() method in Java as shown below −" }, { "code": null, "e": 1396, "s": 1306, "text": "String str1 = new Boolean(bool1).toString();\nString str2 = new Boolean(bool2).toString();" }, { "code": null, "e": 1484, "s": 1396, "text": "Now, when you will display the values “str1” and “str2”, the output would be in String." }, { "code": null, "e": 1550, "s": 1484, "text": "Let us now see the complete example to convert Boolean to String." }, { "code": null, "e": 1561, "s": 1550, "text": " Live Demo" }, { "code": null, "e": 1855, "s": 1561, "text": "public class Demo {\n public static void main(String[] args) {\n boolean bool1 = false;\n boolean bool2 = true;\n String str1 = new Boolean(bool1).toString();\n String str2 = new Boolean(bool2).toString();\n System.out.println(str1);\n System.out.println(str2);\n }\n}" }, { "code": null, "e": 1866, "s": 1855, "text": "false\ntrue" } ]
How to delete multiple ids in MongoDB?
To delete multiple ids in MongoDB, you can use $in operator. Following is the syntax db.yourCollectionName.remove( { _id : { $in: [yourObjectId1, yourObjectId2, yourObjectId3)] } } ); Let us create a collection with documents > db.deleteMultipleIdsDemo.insertOne({"ClientName":"Chris","ClientAge":26}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cd7d6a629b87623db1b19") } > db.deleteMultipleIdsDemo.insertOne({"ClientName":"Robert","ClientAge":28}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cd7dea629b87623db1b1a") } > db.deleteMultipleIdsDemo.insertOne({"ClientName":"Sam","ClientAge":25}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cd7e9a629b87623db1b1b") } > db.deleteMultipleIdsDemo.insertOne({"ClientName":"John","ClientAge":34}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cd7f7a629b87623db1b1c") } > db.deleteMultipleIdsDemo.insertOne({"ClientName":"Carol","ClientAge":36}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cd803a629b87623db1b1d") } Following is the query to display all documents from a collection with the help of find() method > db.deleteMultipleIdsDemo.find().pretty(); This will produce the following output { "_id" : ObjectId("5c9cd7d6a629b87623db1b19"), "ClientName" : "Chris", "ClientAge" : 26 } { "_id" : ObjectId("5c9cd7dea629b87623db1b1a"), "ClientName" : "Robert", "ClientAge" : 28 } { "_id" : ObjectId("5c9cd7e9a629b87623db1b1b"), "ClientName" : "Sam", "ClientAge" : 25 } { "_id" : ObjectId("5c9cd7f7a629b87623db1b1c"), "ClientName" : "John", "ClientAge" : 34 } { "_id" : ObjectId("5c9cd803a629b87623db1b1d"), "ClientName" : "Carol", "ClientAge" : 36 } Following is the query to delete multiple ids in MongoDB > db.deleteMultipleIdsDemo.remove( { _id : { $in: [ObjectId("5c9cd7dea629b87623db1b1a"), ... ObjectId("5c9cd803a629b87623db1b1d"), ... ObjectId("5c9cd7d6a629b87623db1b19") ... ] } } ); WriteResult({ "nRemoved" : 3 }) Let us check the multiple ids have been deleted or not > db.deleteMultipleIdsDemo.find().pretty(); The following is the output displaying we have successfully deleted 3 ids and now only 2 are remaining { "_id" : ObjectId("5c9cd7e9a629b87623db1b1b"), "ClientName" : "Sam", "ClientAge" : 25 } { "_id" : ObjectId("5c9cd7f7a629b87623db1b1c"), "ClientName" : "John", "ClientAge" : 34 }
[ { "code": null, "e": 1147, "s": 1062, "text": "To delete multiple ids in MongoDB, you can use $in operator. Following is the syntax" }, { "code": null, "e": 1246, "s": 1147, "text": "db.yourCollectionName.remove( { _id : { $in: [yourObjectId1, yourObjectId2, yourObjectId3)] } } );" }, { "code": null, "e": 1288, "s": 1246, "text": "Let us create a collection with documents" }, { "code": null, "e": 2096, "s": 1288, "text": "> db.deleteMultipleIdsDemo.insertOne({\"ClientName\":\"Chris\",\"ClientAge\":26});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9cd7d6a629b87623db1b19\")\n}\n> db.deleteMultipleIdsDemo.insertOne({\"ClientName\":\"Robert\",\"ClientAge\":28});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9cd7dea629b87623db1b1a\")\n}\n> db.deleteMultipleIdsDemo.insertOne({\"ClientName\":\"Sam\",\"ClientAge\":25});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9cd7e9a629b87623db1b1b\")\n}\n> db.deleteMultipleIdsDemo.insertOne({\"ClientName\":\"John\",\"ClientAge\":34});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9cd7f7a629b87623db1b1c\")\n}\n> db.deleteMultipleIdsDemo.insertOne({\"ClientName\":\"Carol\",\"ClientAge\":36});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9cd803a629b87623db1b1d\")\n}" }, { "code": null, "e": 2193, "s": 2096, "text": "Following is the query to display all documents from a collection with the help of find() method" }, { "code": null, "e": 2237, "s": 2193, "text": "> db.deleteMultipleIdsDemo.find().pretty();" }, { "code": null, "e": 2276, "s": 2237, "text": "This will produce the following output" }, { "code": null, "e": 2774, "s": 2276, "text": "{\n \"_id\" : ObjectId(\"5c9cd7d6a629b87623db1b19\"),\n \"ClientName\" : \"Chris\",\n \"ClientAge\" : 26\n}\n{\n \"_id\" : ObjectId(\"5c9cd7dea629b87623db1b1a\"),\n \"ClientName\" : \"Robert\",\n \"ClientAge\" : 28\n}\n{\n \"_id\" : ObjectId(\"5c9cd7e9a629b87623db1b1b\"),\n \"ClientName\" : \"Sam\",\n \"ClientAge\" : 25\n}\n{\n \"_id\" : ObjectId(\"5c9cd7f7a629b87623db1b1c\"),\n \"ClientName\" : \"John\",\n \"ClientAge\" : 34\n}\n{\n \"_id\" : ObjectId(\"5c9cd803a629b87623db1b1d\"),\n \"ClientName\" : \"Carol\",\n \"ClientAge\" : 36\n}" }, { "code": null, "e": 2831, "s": 2774, "text": "Following is the query to delete multiple ids in MongoDB" }, { "code": null, "e": 3048, "s": 2831, "text": "> db.deleteMultipleIdsDemo.remove( { _id : { $in: [ObjectId(\"5c9cd7dea629b87623db1b1a\"),\n... ObjectId(\"5c9cd803a629b87623db1b1d\"),\n... ObjectId(\"5c9cd7d6a629b87623db1b19\")\n... ] } } );\nWriteResult({ \"nRemoved\" : 3 })" }, { "code": null, "e": 3103, "s": 3048, "text": "Let us check the multiple ids have been deleted or not" }, { "code": null, "e": 3147, "s": 3103, "text": "> db.deleteMultipleIdsDemo.find().pretty();" }, { "code": null, "e": 3250, "s": 3147, "text": "The following is the output displaying we have successfully deleted 3 ids and now only 2 are remaining" }, { "code": null, "e": 3447, "s": 3250, "text": "{\n \"_id\" : ObjectId(\"5c9cd7e9a629b87623db1b1b\"),\n \"ClientName\" : \"Sam\",\n \"ClientAge\" : 25\n}\n{\n \"_id\" : ObjectId(\"5c9cd7f7a629b87623db1b1c\"),\n \"ClientName\" : \"John\",\n \"ClientAge\" : 34\n}" } ]
Perl while Loop
A while loop statement in Perl programming language repeatedly executes a target statement as long as a given condition is true. The syntax of a while loop in Perl programming language is − while(condition) { statement(s); } Here statement(s) may be a single statement or a block of statements. The condition may be any expression. The loop iterates while the condition is true. When the condition becomes false, program control passes to the line immediately following the loop. The number 0, the strings '0' and "" , the empty list () , and undef are all false in a boolean context and all other values are true. Negation of a true value by ! or not returns a special false value. Here the key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. #!/usr/local/bin/perl $a = 10; # while loop execution while( $a < 20 ) { printf "Value of a: $a\n"; $a = $a + 1; } Here we are using the comparison operator < to compare value of variable $a against 20. So while value of $a is less than 20, while loop continues executing a block of code next to it and as soon as the value of $a becomes equal to 20, it comes out. When executed, above code produces the following result − Value of a: 10 Value of a: 11 Value of a: 12 Value of a: 13 Value of a: 14 Value of a: 15 Value of a: 16 Value of a: 17 Value of a: 18 Value of a: 19 46 Lectures 4.5 hours Devi Killada 11 Lectures 1.5 hours Harshit Srivastava 30 Lectures 6 hours TELCOMA Global 24 Lectures 2 hours Mohammad Nauman 68 Lectures 7 hours Stone River ELearning 58 Lectures 6.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2349, "s": 2220, "text": "A while loop statement in Perl programming language repeatedly executes a target statement as long as a given condition is true." }, { "code": null, "e": 2410, "s": 2349, "text": "The syntax of a while loop in Perl programming language is −" }, { "code": null, "e": 2449, "s": 2410, "text": "while(condition) {\n statement(s);\n}\n" }, { "code": null, "e": 2704, "s": 2449, "text": "Here statement(s) may be a single statement or a block of statements. The condition may be any expression. The loop iterates while the condition is true. When the condition becomes false, program control passes to the line immediately following the loop." }, { "code": null, "e": 2907, "s": 2704, "text": "The number 0, the strings '0' and \"\" , the empty list () , and undef are all false in a boolean context and all other values are true. Negation of a true value by ! or not returns a special false value." }, { "code": null, "e": 3128, "s": 2907, "text": "Here the key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed." }, { "code": null, "e": 3252, "s": 3128, "text": "#!/usr/local/bin/perl\n \n$a = 10;\n\n# while loop execution\nwhile( $a < 20 ) {\n printf \"Value of a: $a\\n\";\n $a = $a + 1;\n}" }, { "code": null, "e": 3560, "s": 3252, "text": "Here we are using the comparison operator < to compare value of variable $a against 20. So while value of $a is less than 20, while loop continues executing a block of code next to it and as soon as the value of $a becomes equal to 20, it comes out. When executed, above code produces the following result −" }, { "code": null, "e": 3711, "s": 3560, "text": "Value of a: 10\nValue of a: 11\nValue of a: 12\nValue of a: 13\nValue of a: 14\nValue of a: 15\nValue of a: 16\nValue of a: 17\nValue of a: 18\nValue of a: 19\n" }, { "code": null, "e": 3746, "s": 3711, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3760, "s": 3746, "text": " Devi Killada" }, { "code": null, "e": 3795, "s": 3760, "text": "\n 11 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3815, "s": 3795, "text": " Harshit Srivastava" }, { "code": null, "e": 3848, "s": 3815, "text": "\n 30 Lectures \n 6 hours \n" }, { "code": null, "e": 3864, "s": 3848, "text": " TELCOMA Global" }, { "code": null, "e": 3897, "s": 3864, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3914, "s": 3897, "text": " Mohammad Nauman" }, { "code": null, "e": 3947, "s": 3914, "text": "\n 68 Lectures \n 7 hours \n" }, { "code": null, "e": 3970, "s": 3947, "text": " Stone River ELearning" }, { "code": null, "e": 4005, "s": 3970, "text": "\n 58 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4028, "s": 4005, "text": " Stone River ELearning" }, { "code": null, "e": 4035, "s": 4028, "text": " Print" }, { "code": null, "e": 4046, "s": 4035, "text": " Add Notes" } ]
Understand and Compare Cloud Functions vs Cloud Run | by Sue Lynn | Towards Data Science
As a data scientist, you will need to decide how to perform model deployment steps, which could involve converting your scripts and deploying them as a microservice. In my case, I was confused about which GCP components should I use to deploy the microservice. Should I deploy on Cloud Run or Cloud Function? Both are GCP serverless products, easy to be deployed and handle HTTP requests/events. So, I decided to perform some research and deploy the same microservice on both cloud functions and cloud run and observe the differences. In this article, I will share the difference between cloud functions and cloud runs and the approach of deploying these two components. Before diving into the difference between these two components, let’s have an understanding of each of these components. The first Beta release of Cloud Function was in March 2017. Cloud Function is an event-driven serverless platform for a lightweight solution to support individual services and can be called via HTTP Request or triggered based on background events. Cloud Function only supports specific languages such as JavaScript, Python, Go, etc. and the code requires to be packaged as a function and the cloud function component will handle the packaging, deployment, and execution of the code. As Cloud Function only handles one request at a time for each instance, it would be suitable only if the use case is a single-purpose workload. Cloud Run Beta release came later than Cloud Function which was first introduced in April 2019 as an addition to other GCP serverless products. Cloud Run is a fully-managed compute platform that is suitable for deploying containerized applications. Cloud Run allows user to write their script based on the user's favorite programming language then push it and package it as a container with Cloud Build. Compare with Cloud Function which only supports one request at a time, Cloud Run is able to be configured to support multiple concurrent requests on a single container instance which allows to save time and save cost. Let’s test deploying a simple service that can be triggered via HTTP endpoints and return a message based on user inputs on both platforms — Cloud Function and Cloud Run. The expected output will return a message based on user input: Steps to Deploy on Cloud Function: We can create an HTTP trigger with a python script that receives user requests and set it up on Cloud Function. (1) Create a function and test it (*The environment I am using is Vertex AI Jupyternotebook on GCP) (2) Go to Cloud Function in Google Cloud Console and select “Create Function” (*Enable Cloud Function API and Cloud Build API If this is your first time) Give your Cloud Function a Name Select a Region Choose HTTP trigger Allow Unauthenticated Invocations if you would like to trigger and call the service from a browser (*Not recommended for production pipeline, but easier while development to see output) (3) Next, Under the code section — select Runtime to “Python 3.9”, Entry Point to the function name “print_message” and add your python function into the main.py file. Note that to pass parameters in a cloud function, you will need to change the function to handle and retrieve parameters using request.args.get() def print_message(request): message = request.args.get('msg') final_message = f"My Name is {message}, Nice meeting you! " return final_message (4) Once the code has been updated, deploy the function by selecting the “Deploy” button at the bottom — The function will then begin deploying on your GCP environment. (5) Test and Call your newly deployed function in the browser You can retrieve your HTTP URL under the trigger tab of the Cloud Function deployed. Call the endpoint from your browser and pass in your input via the URL. Congrats, for walking through with me on the steps required to deploy a microservice to cloud function. Now let’s look at the steps required to create the same microservice on Cloud Run. Steps to Deploy on Cloud Run: The approach to creating a microservice on Cloud Run will require preparing several files — which are: main.py Dockerfile (1) Prepare main.py file & Dockerfile The main.py file consists of the web framework (FastAPI) and python function that receives user input and returns a message. import uvicornfrom fastapi import FastAPIimport osapp = FastAPI()@app.get("/{msg}")async def print_message(msg:str): message = msg final_message = f"My Name is {message}, Nice meeting you! " return final_message Dockerfile: In Cloud run to deploy and create a microservice, a python script is required to be deployed into a Docker Container. A Dockerfile specify how the container will be created and run the web service on container startup. # Use official lightweight Python image as base OS.FROM python:3.7-slim# Copy local code to the container image.ENV APP_HOME /appWORKDIR $APP_HOMECOPY . ./# Install production dependencies.RUN pip install fastapi uvicorn[standard] gunicornENV PORT 8080#Run the web service on container startup using gunicorn webserver.CMD exec gunicorn --bind :$PORT --workers 1 --worker-class uvicorn.workers.UvicornWorker --threads 8 main:app (2) Build and Deploy Docker Image There are different approaches that can be used on Google Cloud Console to build & deploy cloud-run microservice. In my previous articles, I shared the approach to deploy a cloud-run microservice via Cloud Shell Editor. In this article, I will be deploying from the Vertex AI Jupyternotebook environment. In your notebook, create a specific folder and upload the files — main.py & Dockerfile Launch / Open Terminal console in Jupyternotebook In the terminal navigate to the folder that contains the files cd cloud-run-demo Configure and set the region where the microservice will be deployed. gcloud config set run/region asia-southeast1 Run the command to build a new docker image on the selected region. This process will take a few minutes. gcloud builds submit --tag gcr.io/sue-gcp-learn/cloud-run-demo Deploy the newly build image and provide a Cloud Run Service Name. gcloud run deploy --image gcr.io/sue-gcp-learn/cloud-run-demo --platform managed (3) Check & Test deployed Cloud Run Service Microservice URL will be provided upon finished deploying. The service will also be available from the Cloud Run console. Test and call the cloud run endpoint from your browser and pass in your input via the URL. Congrats, for walking through with me on the steps required to deploy a microservice to cloud run. Now you have the knowledge to create a microservice on two different GCP components. Cloud Function allows users to deploy code based on several languages supported whereas Cloud Run does not have this limitation as you will be able to build and deploy container images based on user-selected language. Cloud Functions only supports a single request at a time for each cloud function instance whereas Cloud Run is able to handle multiple requests at the same time and is able to scale up based on demand. Cloud Functions is able to handle specific triggers such as FireStore events and trigger based on changes on Cloud Storage whereas Cloud Run does not come with this additional functionality. Having experience on both component Cloud Function and Cloud Run, I would prefer Cloud Run due to its flexibility and the ability to handle concurrency. As cloud run uses containerization, it is considered portable and can be easily deployed into another environment such as on-prem, on another region, etc. which reduces rework in the future. Nonetheless, I strongly advise you to test creating your microservice on both components if you have the additional time and compare them from your own perspective. Thanks for reading my article and if you enjoyed and would like to support me: Follow me on Medium 🙆🏻 Become a member on Medium through my referral link 🙋 References & Links:
[ { "code": null, "e": 842, "s": 171, "text": "As a data scientist, you will need to decide how to perform model deployment steps, which could involve converting your scripts and deploying them as a microservice. In my case, I was confused about which GCP components should I use to deploy the microservice. Should I deploy on Cloud Run or Cloud Function? Both are GCP serverless products, easy to be deployed and handle HTTP requests/events. So, I decided to perform some research and deploy the same microservice on both cloud functions and cloud run and observe the differences. In this article, I will share the difference between cloud functions and cloud runs and the approach of deploying these two components." }, { "code": null, "e": 963, "s": 842, "text": "Before diving into the difference between these two components, let’s have an understanding of each of these components." }, { "code": null, "e": 1590, "s": 963, "text": "The first Beta release of Cloud Function was in March 2017. Cloud Function is an event-driven serverless platform for a lightweight solution to support individual services and can be called via HTTP Request or triggered based on background events. Cloud Function only supports specific languages such as JavaScript, Python, Go, etc. and the code requires to be packaged as a function and the cloud function component will handle the packaging, deployment, and execution of the code. As Cloud Function only handles one request at a time for each instance, it would be suitable only if the use case is a single-purpose workload." }, { "code": null, "e": 2212, "s": 1590, "text": "Cloud Run Beta release came later than Cloud Function which was first introduced in April 2019 as an addition to other GCP serverless products. Cloud Run is a fully-managed compute platform that is suitable for deploying containerized applications. Cloud Run allows user to write their script based on the user's favorite programming language then push it and package it as a container with Cloud Build. Compare with Cloud Function which only supports one request at a time, Cloud Run is able to be configured to support multiple concurrent requests on a single container instance which allows to save time and save cost." }, { "code": null, "e": 2383, "s": 2212, "text": "Let’s test deploying a simple service that can be triggered via HTTP endpoints and return a message based on user inputs on both platforms — Cloud Function and Cloud Run." }, { "code": null, "e": 2446, "s": 2383, "text": "The expected output will return a message based on user input:" }, { "code": null, "e": 2481, "s": 2446, "text": "Steps to Deploy on Cloud Function:" }, { "code": null, "e": 2593, "s": 2481, "text": "We can create an HTTP trigger with a python script that receives user requests and set it up on Cloud Function." }, { "code": null, "e": 2693, "s": 2593, "text": "(1) Create a function and test it (*The environment I am using is Vertex AI Jupyternotebook on GCP)" }, { "code": null, "e": 2847, "s": 2693, "text": "(2) Go to Cloud Function in Google Cloud Console and select “Create Function” (*Enable Cloud Function API and Cloud Build API If this is your first time)" }, { "code": null, "e": 2879, "s": 2847, "text": "Give your Cloud Function a Name" }, { "code": null, "e": 2895, "s": 2879, "text": "Select a Region" }, { "code": null, "e": 2915, "s": 2895, "text": "Choose HTTP trigger" }, { "code": null, "e": 3101, "s": 2915, "text": "Allow Unauthenticated Invocations if you would like to trigger and call the service from a browser (*Not recommended for production pipeline, but easier while development to see output)" }, { "code": null, "e": 3269, "s": 3101, "text": "(3) Next, Under the code section — select Runtime to “Python 3.9”, Entry Point to the function name “print_message” and add your python function into the main.py file." }, { "code": null, "e": 3415, "s": 3269, "text": "Note that to pass parameters in a cloud function, you will need to change the function to handle and retrieve parameters using request.args.get()" }, { "code": null, "e": 3577, "s": 3415, "text": "def print_message(request): message = request.args.get('msg') final_message = f\"My Name is {message}, Nice meeting you! \" return final_message" }, { "code": null, "e": 3746, "s": 3577, "text": "(4) Once the code has been updated, deploy the function by selecting the “Deploy” button at the bottom — The function will then begin deploying on your GCP environment." }, { "code": null, "e": 3808, "s": 3746, "text": "(5) Test and Call your newly deployed function in the browser" }, { "code": null, "e": 3893, "s": 3808, "text": "You can retrieve your HTTP URL under the trigger tab of the Cloud Function deployed." }, { "code": null, "e": 3965, "s": 3893, "text": "Call the endpoint from your browser and pass in your input via the URL." }, { "code": null, "e": 4152, "s": 3965, "text": "Congrats, for walking through with me on the steps required to deploy a microservice to cloud function. Now let’s look at the steps required to create the same microservice on Cloud Run." }, { "code": null, "e": 4182, "s": 4152, "text": "Steps to Deploy on Cloud Run:" }, { "code": null, "e": 4285, "s": 4182, "text": "The approach to creating a microservice on Cloud Run will require preparing several files — which are:" }, { "code": null, "e": 4293, "s": 4285, "text": "main.py" }, { "code": null, "e": 4304, "s": 4293, "text": "Dockerfile" }, { "code": null, "e": 4342, "s": 4304, "text": "(1) Prepare main.py file & Dockerfile" }, { "code": null, "e": 4467, "s": 4342, "text": "The main.py file consists of the web framework (FastAPI) and python function that receives user input and returns a message." }, { "code": null, "e": 4698, "s": 4467, "text": "import uvicornfrom fastapi import FastAPIimport osapp = FastAPI()@app.get(\"/{msg}\")async def print_message(msg:str): message = msg final_message = f\"My Name is {message}, Nice meeting you! \" return final_message" }, { "code": null, "e": 4710, "s": 4698, "text": "Dockerfile:" }, { "code": null, "e": 4929, "s": 4710, "text": "In Cloud run to deploy and create a microservice, a python script is required to be deployed into a Docker Container. A Dockerfile specify how the container will be created and run the web service on container startup." }, { "code": null, "e": 5359, "s": 4929, "text": "# Use official lightweight Python image as base OS.FROM python:3.7-slim# Copy local code to the container image.ENV APP_HOME /appWORKDIR $APP_HOMECOPY . ./# Install production dependencies.RUN pip install fastapi uvicorn[standard] gunicornENV PORT 8080#Run the web service on container startup using gunicorn webserver.CMD exec gunicorn --bind :$PORT --workers 1 --worker-class uvicorn.workers.UvicornWorker --threads 8 main:app" }, { "code": null, "e": 5393, "s": 5359, "text": "(2) Build and Deploy Docker Image" }, { "code": null, "e": 5698, "s": 5393, "text": "There are different approaches that can be used on Google Cloud Console to build & deploy cloud-run microservice. In my previous articles, I shared the approach to deploy a cloud-run microservice via Cloud Shell Editor. In this article, I will be deploying from the Vertex AI Jupyternotebook environment." }, { "code": null, "e": 5785, "s": 5698, "text": "In your notebook, create a specific folder and upload the files — main.py & Dockerfile" }, { "code": null, "e": 5835, "s": 5785, "text": "Launch / Open Terminal console in Jupyternotebook" }, { "code": null, "e": 5898, "s": 5835, "text": "In the terminal navigate to the folder that contains the files" }, { "code": null, "e": 5916, "s": 5898, "text": "cd cloud-run-demo" }, { "code": null, "e": 5986, "s": 5916, "text": "Configure and set the region where the microservice will be deployed." }, { "code": null, "e": 6031, "s": 5986, "text": "gcloud config set run/region asia-southeast1" }, { "code": null, "e": 6137, "s": 6031, "text": "Run the command to build a new docker image on the selected region. This process will take a few minutes." }, { "code": null, "e": 6200, "s": 6137, "text": "gcloud builds submit --tag gcr.io/sue-gcp-learn/cloud-run-demo" }, { "code": null, "e": 6267, "s": 6200, "text": "Deploy the newly build image and provide a Cloud Run Service Name." }, { "code": null, "e": 6348, "s": 6267, "text": "gcloud run deploy --image gcr.io/sue-gcp-learn/cloud-run-demo --platform managed" }, { "code": null, "e": 6392, "s": 6348, "text": "(3) Check & Test deployed Cloud Run Service" }, { "code": null, "e": 6514, "s": 6392, "text": "Microservice URL will be provided upon finished deploying. The service will also be available from the Cloud Run console." }, { "code": null, "e": 6605, "s": 6514, "text": "Test and call the cloud run endpoint from your browser and pass in your input via the URL." }, { "code": null, "e": 6789, "s": 6605, "text": "Congrats, for walking through with me on the steps required to deploy a microservice to cloud run. Now you have the knowledge to create a microservice on two different GCP components." }, { "code": null, "e": 7007, "s": 6789, "text": "Cloud Function allows users to deploy code based on several languages supported whereas Cloud Run does not have this limitation as you will be able to build and deploy container images based on user-selected language." }, { "code": null, "e": 7209, "s": 7007, "text": "Cloud Functions only supports a single request at a time for each cloud function instance whereas Cloud Run is able to handle multiple requests at the same time and is able to scale up based on demand." }, { "code": null, "e": 7400, "s": 7209, "text": "Cloud Functions is able to handle specific triggers such as FireStore events and trigger based on changes on Cloud Storage whereas Cloud Run does not come with this additional functionality." }, { "code": null, "e": 7744, "s": 7400, "text": "Having experience on both component Cloud Function and Cloud Run, I would prefer Cloud Run due to its flexibility and the ability to handle concurrency. As cloud run uses containerization, it is considered portable and can be easily deployed into another environment such as on-prem, on another region, etc. which reduces rework in the future." }, { "code": null, "e": 7909, "s": 7744, "text": "Nonetheless, I strongly advise you to test creating your microservice on both components if you have the additional time and compare them from your own perspective." }, { "code": null, "e": 7988, "s": 7909, "text": "Thanks for reading my article and if you enjoyed and would like to support me:" }, { "code": null, "e": 8011, "s": 7988, "text": "Follow me on Medium 🙆🏻" }, { "code": null, "e": 8064, "s": 8011, "text": "Become a member on Medium through my referral link 🙋" } ]
What is an alert box in JavaScript?
An alert dialog box is mostly used to give a warning message to the users. For example, if one input field requires to enter some text but the user does not provide any input, then as a part of validation, you can use an alert box to give a warning message. Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one button "OK" to select and proceed. You can try to run the following code to learn how to add an alert box − Live Demo <html> <head> <script> <!-- function Warn() { alert ("This is a warning message!"); document.write ("This is a warning message!"); } //--> </script> </head> <body> <p>Click the following button to see the result: </p> <form> <input type="button" value="Click Me" onclick="Warn();" /> </form> </body> </html>
[ { "code": null, "e": 1320, "s": 1062, "text": "An alert dialog box is mostly used to give a warning message to the users. For example, if one input field requires to enter some text but the user does not provide any input, then as a part of validation, you can use an alert box to give a warning message." }, { "code": null, "e": 1449, "s": 1320, "text": "Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one button \"OK\" to select and proceed." }, { "code": null, "e": 1522, "s": 1449, "text": "You can try to run the following code to learn how to add an alert box −" }, { "code": null, "e": 1532, "s": 1522, "text": "Live Demo" }, { "code": null, "e": 1963, "s": 1532, "text": "<html>\n <head>\n <script>\n <!--\n function Warn() {\n alert (\"This is a warning message!\");\n document.write (\"This is a warning message!\");\n }\n //-->\n </script>\n </head>\n <body>\n <p>Click the following button to see the result: </p>\n <form>\n <input type=\"button\" value=\"Click Me\" onclick=\"Warn();\" />\n </form>\n </body>\n</html>" } ]
Controlling Method Scope In Scala - GeeksforGeeks
06 Nov, 2019 As the name suggests Access Modifiers in scala helps to restrict the scope of a class, variable, method or data member. Controlling Method Scope In Scala helps to restrict the scope of method or data member. There are five types of controlling method scope in Scala: Public ScopePrivate ScopeProtected ScopeObject-private ScopePackage Specific Public Scope Private Scope Protected Scope Object-private Scope Package Specific When no access modifier is specified for a class, method or data member, it is said to be having the default access modifier by default. The data members, class or methods which are not declared using any access modifiers i.e. having default access modifier are accessible anywhere using package & imports or by creating new instances.Example :// Scala program of Public Scope// package testAclass classA{ def method1(): Unit= { println("method1") }} // Creating objectobject GfG{ // Main method def main(args: Array[String]) { // classA in the same package // as the main method var x = new classA x.method1() }}Output :method1 Example : // Scala program of Public Scope// package testAclass classA{ def method1(): Unit= { println("method1") }} // Creating objectobject GfG{ // Main method def main(args: Array[String]) { // classA in the same package // as the main method var x = new classA x.method1() }} Output : method1 Example : Private modifier is same as private in java. By marking a method or variable private it is available to the current class and its members and any of instances of the same class. Any other object/class of same package will not be able to access the private members. This is done by using the private access modifier.Example :// Scala program of Private Scope// package testAclass classA { var x = 1 private def method1: Unit = { println("method1") }} // Creating objectobject GfG{ // Main method def main(arg: Array[String]) { var obj1 = new classA printf("x = "+obj1.x) // println(obj1.method1) error: method // method1 in class classA cannot // be accessed in classA }}Output:x = 1 Example : // Scala program of Private Scope// package testAclass classA { var x = 1 private def method1: Unit = { println("method1") }} // Creating objectobject GfG{ // Main method def main(arg: Array[String]) { var obj1 = new classA printf("x = "+obj1.x) // println(obj1.method1) error: method // method1 in class classA cannot // be accessed in classA }} Output: x = 1 Scala protected is different from protected in java. To mark a member protected, use the keyword protected before a class or variable. Protected members can be accessed only by the sub classes in the same package.Example :// Scala program of Protected Scope// package testclass classab{ protected var ab: Int=4 var ad: Int =1} // Creating objectobject GfG extends classab{ // sub class // Main method def main(args: Array[String]) { println(ab) //can be accessed println(ad) //can be accessed }}Output:4 1 // Scala program of Protected Scope// package testclass classab{ protected var ab: Int=4 var ad: Int =1} // Creating objectobject GfG extends classab{ // sub class // Main method def main(args: Array[String]) { println(ab) //can be accessed println(ad) //can be accessed }} Output: 4 1 Protected members cannot be accessed by other members in other packages even with imports.Example :// Scala program of Protected Scope// package testApackage testA{ class classA { protected var ab: Int=4 var ad: Int =1 }} // another package testBpackage testB{ // importing all the members // from testA package import testA._ // Creating object object GfG { // Main method def main(args: Array[String]) { var ta= new classA ta.ad ta.ab //error } }}Output:error: variable ab in class classA cannot be accessed in testA.classAAccess to protected method ab not permitted becauseenclosing object GfG in package testB is not a subclass ofclass classA in package testA where target is definedta.ab //error^one error found // Scala program of Protected Scope// package testApackage testA{ class classA { protected var ab: Int=4 var ad: Int =1 }} // another package testBpackage testB{ // importing all the members // from testA package import testA._ // Creating object object GfG { // Main method def main(args: Array[String]) { var ta= new classA ta.ad ta.ab //error } }} Output: error: variable ab in class classA cannot be accessed in testA.classAAccess to protected method ab not permitted becauseenclosing object GfG in package testB is not a subclass ofclass classA in package testA where target is definedta.ab //error^one error found Object private is same as private the only difference is that the member declared object private will available only from in which the member is defined, i.e. no object can access it hence therefore named object private. Object protected is same as protected the only difference is that the member will be only available in which it is defined or to the sub classes and not available to the objects. To mark an member object private use the keywords private[this]. To mark an member object protected use the keywords protected[this], where this refers or points to the current object.Example :// Scala program of Object Private/Protected Scope// package test1.test11class class11 { private[this] var x = 1 private var t = 2 var z = 3 def method11(other: class11): Unit = { println(x) println(t) println(z) // println(other.x) println(other.t) println(other.z) }}// here on line14 x can only be// accessed from inside in which // it is defined // Creating objectobject GfG{ // Main method def main(arg: Array[String]) { var obj11 = new class11() //current instance created var y = 2 println(obj11.method11(obj11)) println(obj11.z) //println(obj11.t) //error: t cannot be accessed //println(obj11.x) //error: x is not a member of class11 //according to obj11 x is not a member }}Output :1 2 3 2 3 () 3 Example : // Scala program of Object Private/Protected Scope// package test1.test11class class11 { private[this] var x = 1 private var t = 2 var z = 3 def method11(other: class11): Unit = { println(x) println(t) println(z) // println(other.x) println(other.t) println(other.z) }}// here on line14 x can only be// accessed from inside in which // it is defined // Creating objectobject GfG{ // Main method def main(arg: Array[String]) { var obj11 = new class11() //current instance created var y = 2 println(obj11.method11(obj11)) println(obj11.z) //println(obj11.t) //error: t cannot be accessed //println(obj11.x) //error: x is not a member of class11 //according to obj11 x is not a member }} Output : 1 2 3 2 3 () 3 When we want a member to be available to a whole package. It comes to declare that member as private[package_name]. All the member inside the package can access that member. Member can be accessed by any other package whose name is being qualified to.Example :// Scala program of Package Specific// Scala program of Package Specificpackage aaclass geek{ class g1 { // inner class // private to class g1 private var a = 0 // available to package aa private[aa] var b = 0 def method() { a = a + 1 b = b + 1 println("welcome to inner class g1") println("a= "+a) } }} // Creating objectobject Main{ // Driver code def main(args: Array[String]) { val obj = new geek() val o = new obj.g1 o.method(); println("b= "+o.b); }} // Scala program of Package Specific// Scala program of Package Specificpackage aaclass geek{ class g1 { // inner class // private to class g1 private var a = 0 // available to package aa private[aa] var b = 0 def method() { a = a + 1 b = b + 1 println("welcome to inner class g1") println("a= "+a) } }} // Creating objectobject Main{ // Driver code def main(args: Array[String]) { val obj = new geek() val o = new obj.g1 o.method(); println("b= "+o.b); }} Output : welcome to inner class g1 a= 1 b= 1 Akanksha_Rai Picked Scala Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Scala List filter() method with example Scala Tutorial – Learn Scala with Step By Step Guide Type Casting in Scala Scala Map How to get the first element of List in Scala Class and Object in Scala Scala Lists Scala List contains() method with example Operators in Scala Inheritance in Scala
[ { "code": null, "e": 24014, "s": 23986, "text": "\n06 Nov, 2019" }, { "code": null, "e": 24281, "s": 24014, "text": "As the name suggests Access Modifiers in scala helps to restrict the scope of a class, variable, method or data member. Controlling Method Scope In Scala helps to restrict the scope of method or data member. There are five types of controlling method scope in Scala:" }, { "code": null, "e": 24358, "s": 24281, "text": "Public ScopePrivate ScopeProtected ScopeObject-private ScopePackage Specific" }, { "code": null, "e": 24371, "s": 24358, "text": "Public Scope" }, { "code": null, "e": 24385, "s": 24371, "text": "Private Scope" }, { "code": null, "e": 24401, "s": 24385, "text": "Protected Scope" }, { "code": null, "e": 24422, "s": 24401, "text": "Object-private Scope" }, { "code": null, "e": 24439, "s": 24422, "text": "Package Specific" }, { "code": null, "e": 24576, "s": 24439, "text": "When no access modifier is specified for a class, method or data member, it is said to be having the default access modifier by default." }, { "code": null, "e": 25138, "s": 24576, "text": "The data members, class or methods which are not declared using any access modifiers i.e. having default access modifier are accessible anywhere using package & imports or by creating new instances.Example :// Scala program of Public Scope// package testAclass classA{ def method1(): Unit= { println(\"method1\") }} // Creating objectobject GfG{ // Main method def main(args: Array[String]) { // classA in the same package // as the main method var x = new classA x.method1() }}Output :method1\nExample :" }, { "code": "// Scala program of Public Scope// package testAclass classA{ def method1(): Unit= { println(\"method1\") }} // Creating objectobject GfG{ // Main method def main(args: Array[String]) { // classA in the same package // as the main method var x = new classA x.method1() }}", "e": 25468, "s": 25138, "text": null }, { "code": null, "e": 25477, "s": 25468, "text": "Output :" }, { "code": null, "e": 25486, "s": 25477, "text": "method1\n" }, { "code": null, "e": 25496, "s": 25486, "text": "Example :" }, { "code": null, "e": 25674, "s": 25496, "text": "Private modifier is same as private in java. By marking a method or variable private it is available to the current class and its members and any of instances of the same class." }, { "code": null, "e": 25761, "s": 25674, "text": "Any other object/class of same package will not be able to access the private members." }, { "code": null, "e": 26249, "s": 25761, "text": "This is done by using the private access modifier.Example :// Scala program of Private Scope// package testAclass classA { var x = 1 private def method1: Unit = { println(\"method1\") }} // Creating objectobject GfG{ // Main method def main(arg: Array[String]) { var obj1 = new classA printf(\"x = \"+obj1.x) // println(obj1.method1) error: method // method1 in class classA cannot // be accessed in classA }}Output:x = 1\n" }, { "code": null, "e": 26259, "s": 26249, "text": "Example :" }, { "code": "// Scala program of Private Scope// package testAclass classA { var x = 1 private def method1: Unit = { println(\"method1\") }} // Creating objectobject GfG{ // Main method def main(arg: Array[String]) { var obj1 = new classA printf(\"x = \"+obj1.x) // println(obj1.method1) error: method // method1 in class classA cannot // be accessed in classA }}", "e": 26675, "s": 26259, "text": null }, { "code": null, "e": 26683, "s": 26675, "text": "Output:" }, { "code": null, "e": 26690, "s": 26683, "text": "x = 1\n" }, { "code": null, "e": 26825, "s": 26690, "text": "Scala protected is different from protected in java. To mark a member protected, use the keyword protected before a class or variable." }, { "code": null, "e": 27234, "s": 26825, "text": "Protected members can be accessed only by the sub classes in the same package.Example :// Scala program of Protected Scope// package testclass classab{ protected var ab: Int=4 var ad: Int =1} // Creating objectobject GfG extends classab{ // sub class // Main method def main(args: Array[String]) { println(ab) //can be accessed println(ad) //can be accessed }}Output:4\n1\n" }, { "code": "// Scala program of Protected Scope// package testclass classab{ protected var ab: Int=4 var ad: Int =1} // Creating objectobject GfG extends classab{ // sub class // Main method def main(args: Array[String]) { println(ab) //can be accessed println(ad) //can be accessed }}", "e": 27545, "s": 27234, "text": null }, { "code": null, "e": 27553, "s": 27545, "text": "Output:" }, { "code": null, "e": 27558, "s": 27553, "text": "4\n1\n" }, { "code": null, "e": 28389, "s": 27558, "text": "Protected members cannot be accessed by other members in other packages even with imports.Example :// Scala program of Protected Scope// package testApackage testA{ class classA { protected var ab: Int=4 var ad: Int =1 }} // another package testBpackage testB{ // importing all the members // from testA package import testA._ // Creating object object GfG { // Main method def main(args: Array[String]) { var ta= new classA ta.ad ta.ab //error } }}Output:error: variable ab in class classA cannot be accessed in testA.classAAccess to protected method ab not permitted becauseenclosing object GfG in package testB is not a subclass ofclass classA in package testA where target is definedta.ab //error^one error found" }, { "code": "// Scala program of Protected Scope// package testApackage testA{ class classA { protected var ab: Int=4 var ad: Int =1 }} // another package testBpackage testB{ // importing all the members // from testA package import testA._ // Creating object object GfG { // Main method def main(args: Array[String]) { var ta= new classA ta.ad ta.ab //error } }}", "e": 28854, "s": 28389, "text": null }, { "code": null, "e": 28862, "s": 28854, "text": "Output:" }, { "code": null, "e": 29123, "s": 28862, "text": "error: variable ab in class classA cannot be accessed in testA.classAAccess to protected method ab not permitted becauseenclosing object GfG in package testB is not a subclass ofclass classA in package testA where target is definedta.ab //error^one error found" }, { "code": null, "e": 29344, "s": 29123, "text": "Object private is same as private the only difference is that the member declared object private will available only from in which the member is defined, i.e. no object can access it hence therefore named object private." }, { "code": null, "e": 29523, "s": 29344, "text": "Object protected is same as protected the only difference is that the member will be only available in which it is defined or to the sub classes and not available to the objects." }, { "code": null, "e": 29588, "s": 29523, "text": "To mark an member object private use the keywords private[this]." }, { "code": null, "e": 30556, "s": 29588, "text": "To mark an member object protected use the keywords protected[this], where this refers or points to the current object.Example :// Scala program of Object Private/Protected Scope// package test1.test11class class11 { private[this] var x = 1 private var t = 2 var z = 3 def method11(other: class11): Unit = { println(x) println(t) println(z) // println(other.x) println(other.t) println(other.z) }}// here on line14 x can only be// accessed from inside in which // it is defined // Creating objectobject GfG{ // Main method def main(arg: Array[String]) { var obj11 = new class11() //current instance created var y = 2 println(obj11.method11(obj11)) println(obj11.z) //println(obj11.t) //error: t cannot be accessed //println(obj11.x) //error: x is not a member of class11 //according to obj11 x is not a member }}Output :1\n2\n3\n2\n3\n()\n3\n" }, { "code": null, "e": 30566, "s": 30556, "text": "Example :" }, { "code": "// Scala program of Object Private/Protected Scope// package test1.test11class class11 { private[this] var x = 1 private var t = 2 var z = 3 def method11(other: class11): Unit = { println(x) println(t) println(z) // println(other.x) println(other.t) println(other.z) }}// here on line14 x can only be// accessed from inside in which // it is defined // Creating objectobject GfG{ // Main method def main(arg: Array[String]) { var obj11 = new class11() //current instance created var y = 2 println(obj11.method11(obj11)) println(obj11.z) //println(obj11.t) //error: t cannot be accessed //println(obj11.x) //error: x is not a member of class11 //according to obj11 x is not a member }}", "e": 31383, "s": 30566, "text": null }, { "code": null, "e": 31392, "s": 31383, "text": "Output :" }, { "code": null, "e": 31408, "s": 31392, "text": "1\n2\n3\n2\n3\n()\n3\n" }, { "code": null, "e": 31524, "s": 31408, "text": "When we want a member to be available to a whole package. It comes to declare that member as private[package_name]." }, { "code": null, "e": 31582, "s": 31524, "text": "All the member inside the package can access that member." }, { "code": null, "e": 32290, "s": 31582, "text": "Member can be accessed by any other package whose name is being qualified to.Example :// Scala program of Package Specific// Scala program of Package Specificpackage aaclass geek{ class g1 { // inner class // private to class g1 private var a = 0 // available to package aa private[aa] var b = 0 def method() { a = a + 1 b = b + 1 println(\"welcome to inner class g1\") println(\"a= \"+a) } }} // Creating objectobject Main{ // Driver code def main(args: Array[String]) { val obj = new geek() val o = new obj.g1 o.method(); println(\"b= \"+o.b); }}" }, { "code": "// Scala program of Package Specific// Scala program of Package Specificpackage aaclass geek{ class g1 { // inner class // private to class g1 private var a = 0 // available to package aa private[aa] var b = 0 def method() { a = a + 1 b = b + 1 println(\"welcome to inner class g1\") println(\"a= \"+a) } }} // Creating objectobject Main{ // Driver code def main(args: Array[String]) { val obj = new geek() val o = new obj.g1 o.method(); println(\"b= \"+o.b); }}", "e": 32912, "s": 32290, "text": null }, { "code": null, "e": 32921, "s": 32912, "text": "Output :" }, { "code": null, "e": 32958, "s": 32921, "text": "welcome to inner class g1\na= 1\nb= 1\n" }, { "code": null, "e": 32971, "s": 32958, "text": "Akanksha_Rai" }, { "code": null, "e": 32978, "s": 32971, "text": "Picked" }, { "code": null, "e": 32984, "s": 32978, "text": "Scala" }, { "code": null, "e": 32997, "s": 32984, "text": "Scala-Method" }, { "code": null, "e": 33003, "s": 32997, "text": "Scala" }, { "code": null, "e": 33101, "s": 33003, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33141, "s": 33101, "text": "Scala List filter() method with example" }, { "code": null, "e": 33194, "s": 33141, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 33216, "s": 33194, "text": "Type Casting in Scala" }, { "code": null, "e": 33226, "s": 33216, "text": "Scala Map" }, { "code": null, "e": 33272, "s": 33226, "text": "How to get the first element of List in Scala" }, { "code": null, "e": 33298, "s": 33272, "text": "Class and Object in Scala" }, { "code": null, "e": 33310, "s": 33298, "text": "Scala Lists" }, { "code": null, "e": 33352, "s": 33310, "text": "Scala List contains() method with example" }, { "code": null, "e": 33371, "s": 33352, "text": "Operators in Scala" } ]
MongoDB - ObjectId
We have been using MongoDB Object Id in all the previous chapters. In this chapter, we will understand the structure of ObjectId. An ObjectId is a 12-byte BSON type having the following structure − The first 4 bytes representing the seconds since the unix epoch The next 3 bytes are the machine identifier The next 2 bytes consists of process id The last 3 bytes are a random counter value MongoDB uses ObjectIds as the default value of _id field of each document, which is generated while the creation of any document. The complex combination of ObjectId makes all the _id fields unique. To generate a new ObjectId use the following code − >newObjectId = ObjectId() The above statement returned the following uniquely generated id − ObjectId("5349b4ddd2781d08c09890f3") Instead of MongoDB generating the ObjectId, you can also provide a 12-byte id − >myObjectId = ObjectId("5349b4ddd2781d08c09890f4") Since the _id ObjectId by default stores the 4-byte timestamp, in most cases you do not need to store the creation time of any document. You can fetch the creation time of a document using getTimestamp method − >ObjectId("5349b4ddd2781d08c09890f4").getTimestamp() This will return the creation time of this document in ISO date format − ISODate("2014-04-12T21:49:17Z") In some cases, you may need the value of ObjectId in a string format. To convert the ObjectId in string, use the following code − >newObjectId.str The above code will return the string format of the Guid − 5349b4ddd2781d08c09890f3 44 Lectures 3 hours Arnab Chakraborty 54 Lectures 5.5 hours Eduonix Learning Solutions 44 Lectures 4.5 hours Kaushik Roy Chowdhury 40 Lectures 2.5 hours University Code 26 Lectures 8 hours Bassir Jafarzadeh 70 Lectures 2.5 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2683, "s": 2553, "text": "We have been using MongoDB Object Id in all the previous chapters. In this chapter, we will understand the structure of ObjectId." }, { "code": null, "e": 2751, "s": 2683, "text": "An ObjectId is a 12-byte BSON type having the following structure −" }, { "code": null, "e": 2815, "s": 2751, "text": "The first 4 bytes representing the seconds since the unix epoch" }, { "code": null, "e": 2859, "s": 2815, "text": "The next 3 bytes are the machine identifier" }, { "code": null, "e": 2899, "s": 2859, "text": "The next 2 bytes consists of process id" }, { "code": null, "e": 2943, "s": 2899, "text": "The last 3 bytes are a random counter value" }, { "code": null, "e": 3142, "s": 2943, "text": "MongoDB uses ObjectIds as the default value of _id field of each document, which is generated while the creation of any document. The complex combination of ObjectId makes all the _id fields unique." }, { "code": null, "e": 3194, "s": 3142, "text": "To generate a new ObjectId use the following code −" }, { "code": null, "e": 3220, "s": 3194, "text": ">newObjectId = ObjectId()" }, { "code": null, "e": 3287, "s": 3220, "text": "The above statement returned the following uniquely generated id −" }, { "code": null, "e": 3324, "s": 3287, "text": "ObjectId(\"5349b4ddd2781d08c09890f3\")" }, { "code": null, "e": 3404, "s": 3324, "text": "Instead of MongoDB generating the ObjectId, you can also provide a 12-byte id −" }, { "code": null, "e": 3455, "s": 3404, "text": ">myObjectId = ObjectId(\"5349b4ddd2781d08c09890f4\")" }, { "code": null, "e": 3666, "s": 3455, "text": "Since the _id ObjectId by default stores the 4-byte timestamp, in most cases you do not need to store the creation time of any document. You can fetch the creation time of a document using getTimestamp method −" }, { "code": null, "e": 3719, "s": 3666, "text": ">ObjectId(\"5349b4ddd2781d08c09890f4\").getTimestamp()" }, { "code": null, "e": 3792, "s": 3719, "text": "This will return the creation time of this document in ISO date format −" }, { "code": null, "e": 3824, "s": 3792, "text": "ISODate(\"2014-04-12T21:49:17Z\")" }, { "code": null, "e": 3954, "s": 3824, "text": "In some cases, you may need the value of ObjectId in a string format. To convert the ObjectId in string, use the following code −" }, { "code": null, "e": 3971, "s": 3954, "text": ">newObjectId.str" }, { "code": null, "e": 4030, "s": 3971, "text": "The above code will return the string format of the Guid −" }, { "code": null, "e": 4056, "s": 4030, "text": "5349b4ddd2781d08c09890f3\n" }, { "code": null, "e": 4089, "s": 4056, "text": "\n 44 Lectures \n 3 hours \n" }, { "code": null, "e": 4108, "s": 4089, "text": " Arnab Chakraborty" }, { "code": null, "e": 4143, "s": 4108, "text": "\n 54 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4171, "s": 4143, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4206, "s": 4171, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4229, "s": 4206, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 4264, "s": 4229, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4281, "s": 4264, "text": " University Code" }, { "code": null, "e": 4314, "s": 4281, "text": "\n 26 Lectures \n 8 hours \n" }, { "code": null, "e": 4333, "s": 4314, "text": " Bassir Jafarzadeh" }, { "code": null, "e": 4368, "s": 4333, "text": "\n 70 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4388, "s": 4368, "text": " Skillbakerystudios" }, { "code": null, "e": 4395, "s": 4388, "text": " Print" }, { "code": null, "e": 4406, "s": 4395, "text": " Add Notes" } ]
Bokeh - Circle Glyphs
The figure object has many methods using which vectorised glyphs of different shapes such as circle, rectangle, polygon, etc. can, be drawn. Following methods are available for drawing circle glyphs − The circle() method adds a circle glyph to the figure and needs x and y coordinates of its center. Additionally, it can be configured with the help of parameters such as fill_color, line-color, line_width etc. The circle_cross() method adds circle glyph with a ‘+’ cross through the center. The circle_x() method adds circle with an ‘X’ cross through the center. Following example shows use of various circle glyphs added to Bokeh figure − from bokeh.plotting import figure, output_file, show plot = figure(plot_width = 300, plot_height = 300) plot.circle(x = [1, 2, 3], y = [3,7,5], size = 20, fill_color = 'red') plot.circle_cross(x = [2,4,6], y = [5,8,9], size = 20, fill_color = 'blue',fill_alpha = 0.2, line_width = 2) plot.circle_x(x = [5,7,2], y = [2,4,9], size = 20, fill_color = 'green',fill_alpha = 0.6, line_width = 2) show(plot) Print Add Notes Bookmark this page
[ { "code": null, "e": 2411, "s": 2270, "text": "The figure object has many methods using which vectorised glyphs of different shapes such as circle, rectangle, polygon, etc. can, be drawn." }, { "code": null, "e": 2471, "s": 2411, "text": "Following methods are available for drawing circle glyphs −" }, { "code": null, "e": 2681, "s": 2471, "text": "The circle() method adds a circle glyph to the figure and needs x and y coordinates of its center. Additionally, it can be configured with the help of parameters such as fill_color, line-color, line_width etc." }, { "code": null, "e": 2762, "s": 2681, "text": "The circle_cross() method adds circle glyph with a ‘+’ cross through the center." }, { "code": null, "e": 2834, "s": 2762, "text": "The circle_x() method adds circle with an ‘X’ cross through the center." }, { "code": null, "e": 2911, "s": 2834, "text": "Following example shows use of various circle glyphs added to Bokeh figure −" }, { "code": null, "e": 3312, "s": 2911, "text": "from bokeh.plotting import figure, output_file, show\nplot = figure(plot_width = 300, plot_height = 300)\nplot.circle(x = [1, 2, 3], y = [3,7,5], size = 20, fill_color = 'red')\nplot.circle_cross(x = [2,4,6], y = [5,8,9], size = 20, fill_color = 'blue',fill_alpha = 0.2, line_width = 2)\nplot.circle_x(x = [5,7,2], y = [2,4,9], size = 20, fill_color = 'green',fill_alpha = 0.6, line_width = 2)\nshow(plot)" }, { "code": null, "e": 3319, "s": 3312, "text": " Print" }, { "code": null, "e": 3330, "s": 3319, "text": " Add Notes" } ]
How to delete last element from a List in C++ STL
Suppose we have one STL list in C++. There are few elements. We have to delete the last element from that list. So if the elements are like [10, 41, 54, 20, 23, 69, 84, 75], then last element is 75. We will see the C++ code to delete last element from list. Live Demo #include<iostream> #include<list> using namespace std; void display(list<int> my_list){ for (auto it = my_list.begin(); it != my_list.end(); ++it) cout << *it << " "; } int main() { int arr[] = {10, 41, 54, 20, 23, 69, 84, 75}; int n = sizeof(arr)/sizeof(arr[0]); list<int> my_list; for(int i = 0; i<n; i++){ my_list.push_back(arr[i]); } cout << "List before delete: "; display(my_list); my_list.pop_back();//delete last element cout << "\nList after delete: "; display(my_list); } List before delete: 10 41 54 20 23 69 84 75 List after delete: 10 41 54 20 23 69 84
[ { "code": null, "e": 1320, "s": 1062, "text": "Suppose we have one STL list in C++. There are few elements. We have to delete the last element from that list. So if the elements are like [10, 41, 54, 20, 23, 69, 84, 75], then last element is 75. We will see the C++ code to delete last element from list." }, { "code": null, "e": 1331, "s": 1320, "text": " Live Demo" }, { "code": null, "e": 1855, "s": 1331, "text": "#include<iostream>\n#include<list>\nusing namespace std;\nvoid display(list<int> my_list){\n for (auto it = my_list.begin(); it != my_list.end(); ++it)\n cout << *it << \" \";\n}\nint main() {\n int arr[] = {10, 41, 54, 20, 23, 69, 84, 75};\n int n = sizeof(arr)/sizeof(arr[0]);\n list<int> my_list;\n for(int i = 0; i<n; i++){\n my_list.push_back(arr[i]);\n }\n cout << \"List before delete: \";\n display(my_list);\n my_list.pop_back();//delete last element\n cout << \"\\nList after delete: \";\n display(my_list);\n}" }, { "code": null, "e": 1939, "s": 1855, "text": "List before delete: 10 41 54 20 23 69 84 75\nList after delete: 10 41 54 20 23 69 84" } ]
How to compute a growth rate in BigQuery using SQL | by Romain Granger | Towards Data Science
For some use cases, it’s important to monitor the change of a specific variable over a period of time. A common example would be to monitor revenue month-over-month to understand the growth of a business and measure the impact of, for example, special marketing efforts, a limited time offer, giveaways, changes in pricing, etc... Besides, it does not only apply to revenue. A long list of potential variables exists: Stock price Revenue/Transactions Users/Active or Churn Users From experience, it’s not easy to find a good and easy method in SQL. Lots of them are using exhaustive grouping and joining clauses, complex date filtering or indexing, and even sometimes, methods or functions that are not present in all SQL dialects. So if you are interested in understanding an efficient and easy method to achieve this calculation, you are definitely in the right place! 😎 In this article, we will be computing a month-over-month revenue growth rate, based on the Google Merchandise shop data. It’s one of the most common examples we pick here, but the method can work for any variable other than revenue. It can be used for understanding user growth or price changes and more... It is the same for the time period, we are executing our example over a monthly period but it can be days, weeks, or years. Our solution will be using navigation functions. They are functions that allow us to compute or get a value over a group of rows and return a single result for each row. It’s like traveling or browsing over a single table without performing joins or grouping over dimensions. To know more about navigation functions, you can have a look here 👇🏼 https://cloud.google.com/bigquery/docs/reference/standard-sql/navigation_functions For this experiment, we are using Google Analytics sample data from the public BigQuery data set. You can get more information and access it by following this link 👇🏼 https://support.google.com/analytics/answer/7586738?hl=en You can try the following queries assuming that you have already: A project and dataset configured in BigQuery (You’ll need your project ID) Access to the BigQuery public data set and the google analytics sample table (google_analytics_sample) Here is the full code below on gist, that we will explain step by step: First, we would like to get our specific variable (in this case revenue) aggregated by our desire time period (in this case on a monthly basis). The above query returns a table with the revenue generated by the online shop every month. By using the “EXPLORE DATA” button between the query editor and the result table, we can display nicely on Data Studio the monthly revenue as follow: That’s only the first step, but it’s a good start, hang on 😅 To compute the growth rates, we will use navigation functions and more precisely the LAG() function. If you know it already you can jump directly to step #3, if you are not familiar with these functions, we will explain its mechanism in the next step to fully understand our process. Hints and explanations about the query We are using PARSE_DATE() to change the format of the date because the original Google Analytics format is YYYYMMDD. In this case, the function will return a DATE type with a standard YYYY-MM-DD format. We then apply a DATE_TRUNC(), to extract the monthly part of the date, like a %Y-%m format, and get the revenue per month. We are converting the revenue because this field is expressed as the value passed to Analytics multiplied by 106 (e.g., 2.40 would be given as 2400000), we need then to divide it by 1000000. Note that this format is really specific to google analytics data in BigQuery. Grouping by 1 means that we actually perform the grouping by the first column regardless of its name. To compute the growth rate, we are using the relative change formula which is defined by the following: ((final value — initial value) / initial value) * 100 But what does it mean for us? In our case, the final value is therevenue from our current month, and the initial value is therevenue from the previous month (or previous row), and that’s why windowing functions will be really helpful in this case. The LAG() function is not that hard, I promise 😎 It is a function, that returns the value of the wanted variable from a preceding row. It is a function that requires an ORDER BY clause in the OVER() statement. It is usually used as LAG(variable,offset) where: variable can be any data type. (in our case a FLOAT) offset must be a non-negative integer. Hints and explanations about the query For readability, we write the previous query inside a WITH clause, we also remove the first ORDER BY which was just to nicely display the previous table. After running this query, we obtain the following output: As you can see on the output, on the same row, we have the revenue for the current month and the last_month_revenue which is the revenue value from the previous month (which is our preceding row here). As said, the LAG() function use as input the column containing our desire variable (revenue), and an OFFSET that you can define (by default 1, meaning the first previous row) LAG(revenue,1) OVER(ORDER BY months ASC) Changing the offset value changes which preceding row is returned. The default value is 1, indicating that it will pick the previous row. This is why we write it without filling an offset in our example. BigQuery LAG() documentation 👉🏼 here Now that we have our relative change formula, and understood the use of the LAG() function, we need to write our final query expressing the formula in SQL: The first WITH clause doesn’t change. Under the “ — Main Query” comment, we only replace our previous last_month_revenue by the relative change formula. This gives us pretty much the same output: That’s how we get the month-over-month growth rate! 🍻 It is then ready to be displayed on Data studio. Hints and explanations about the query As a reminder, we use ((final value — initial value) / initial value) * 100 revenue = Final value, which is the value of our current month. LAG(revenue)OVER(ORDER BY months ASC) = Initial value, the value of our previous month. Here, we just convert the formula using our SQL syntax and fields. To have a cleaner result, we round the output applying ROUND(value,2) to limit the number to two decimals. We can then use Datastudio to display our results, which gives us a nice overview of our revenue changes month-over-month: This method can be used on any kind of time series and variable. The interesting part is the use of navigation functions. They make this exercise a lot easier even if they are not that easy to understand at first. I hope you’ll like this method and the article will help you save some time and maybe even understand navigation functions better if you are new to it! But more importantly, I hope this will help you get more at ease using SQL and BigQuery! It’s a good use case to practice your skills! Time to dive into some data! 🤓
[ { "code": null, "e": 503, "s": 172, "text": "For some use cases, it’s important to monitor the change of a specific variable over a period of time. A common example would be to monitor revenue month-over-month to understand the growth of a business and measure the impact of, for example, special marketing efforts, a limited time offer, giveaways, changes in pricing, etc..." }, { "code": null, "e": 590, "s": 503, "text": "Besides, it does not only apply to revenue. A long list of potential variables exists:" }, { "code": null, "e": 602, "s": 590, "text": "Stock price" }, { "code": null, "e": 623, "s": 602, "text": "Revenue/Transactions" }, { "code": null, "e": 651, "s": 623, "text": "Users/Active or Churn Users" }, { "code": null, "e": 904, "s": 651, "text": "From experience, it’s not easy to find a good and easy method in SQL. Lots of them are using exhaustive grouping and joining clauses, complex date filtering or indexing, and even sometimes, methods or functions that are not present in all SQL dialects." }, { "code": null, "e": 1045, "s": 904, "text": "So if you are interested in understanding an efficient and easy method to achieve this calculation, you are definitely in the right place! 😎" }, { "code": null, "e": 1352, "s": 1045, "text": "In this article, we will be computing a month-over-month revenue growth rate, based on the Google Merchandise shop data. It’s one of the most common examples we pick here, but the method can work for any variable other than revenue. It can be used for understanding user growth or price changes and more..." }, { "code": null, "e": 1476, "s": 1352, "text": "It is the same for the time period, we are executing our example over a monthly period but it can be days, weeks, or years." }, { "code": null, "e": 1752, "s": 1476, "text": "Our solution will be using navigation functions. They are functions that allow us to compute or get a value over a group of rows and return a single result for each row. It’s like traveling or browsing over a single table without performing joins or grouping over dimensions." }, { "code": null, "e": 1821, "s": 1752, "text": "To know more about navigation functions, you can have a look here 👇🏼" }, { "code": null, "e": 1904, "s": 1821, "text": "https://cloud.google.com/bigquery/docs/reference/standard-sql/navigation_functions" }, { "code": null, "e": 2071, "s": 1904, "text": "For this experiment, we are using Google Analytics sample data from the public BigQuery data set. You can get more information and access it by following this link 👇🏼" }, { "code": null, "e": 2129, "s": 2071, "text": "https://support.google.com/analytics/answer/7586738?hl=en" }, { "code": null, "e": 2195, "s": 2129, "text": "You can try the following queries assuming that you have already:" }, { "code": null, "e": 2270, "s": 2195, "text": "A project and dataset configured in BigQuery (You’ll need your project ID)" }, { "code": null, "e": 2373, "s": 2270, "text": "Access to the BigQuery public data set and the google analytics sample table (google_analytics_sample)" }, { "code": null, "e": 2445, "s": 2373, "text": "Here is the full code below on gist, that we will explain step by step:" }, { "code": null, "e": 2590, "s": 2445, "text": "First, we would like to get our specific variable (in this case revenue) aggregated by our desire time period (in this case on a monthly basis)." }, { "code": null, "e": 2681, "s": 2590, "text": "The above query returns a table with the revenue generated by the online shop every month." }, { "code": null, "e": 2831, "s": 2681, "text": "By using the “EXPLORE DATA” button between the query editor and the result table, we can display nicely on Data Studio the monthly revenue as follow:" }, { "code": null, "e": 2892, "s": 2831, "text": "That’s only the first step, but it’s a good start, hang on 😅" }, { "code": null, "e": 3176, "s": 2892, "text": "To compute the growth rates, we will use navigation functions and more precisely the LAG() function. If you know it already you can jump directly to step #3, if you are not familiar with these functions, we will explain its mechanism in the next step to fully understand our process." }, { "code": null, "e": 3215, "s": 3176, "text": "Hints and explanations about the query" }, { "code": null, "e": 3418, "s": 3215, "text": "We are using PARSE_DATE() to change the format of the date because the original Google Analytics format is YYYYMMDD. In this case, the function will return a DATE type with a standard YYYY-MM-DD format." }, { "code": null, "e": 3541, "s": 3418, "text": "We then apply a DATE_TRUNC(), to extract the monthly part of the date, like a %Y-%m format, and get the revenue per month." }, { "code": null, "e": 3811, "s": 3541, "text": "We are converting the revenue because this field is expressed as the value passed to Analytics multiplied by 106 (e.g., 2.40 would be given as 2400000), we need then to divide it by 1000000. Note that this format is really specific to google analytics data in BigQuery." }, { "code": null, "e": 3913, "s": 3811, "text": "Grouping by 1 means that we actually perform the grouping by the first column regardless of its name." }, { "code": null, "e": 4017, "s": 3913, "text": "To compute the growth rate, we are using the relative change formula which is defined by the following:" }, { "code": null, "e": 4071, "s": 4017, "text": "((final value — initial value) / initial value) * 100" }, { "code": null, "e": 4101, "s": 4071, "text": "But what does it mean for us?" }, { "code": null, "e": 4319, "s": 4101, "text": "In our case, the final value is therevenue from our current month, and the initial value is therevenue from the previous month (or previous row), and that’s why windowing functions will be really helpful in this case." }, { "code": null, "e": 4368, "s": 4319, "text": "The LAG() function is not that hard, I promise 😎" }, { "code": null, "e": 4454, "s": 4368, "text": "It is a function, that returns the value of the wanted variable from a preceding row." }, { "code": null, "e": 4579, "s": 4454, "text": "It is a function that requires an ORDER BY clause in the OVER() statement. It is usually used as LAG(variable,offset) where:" }, { "code": null, "e": 4632, "s": 4579, "text": "variable can be any data type. (in our case a FLOAT)" }, { "code": null, "e": 4671, "s": 4632, "text": "offset must be a non-negative integer." }, { "code": null, "e": 4710, "s": 4671, "text": "Hints and explanations about the query" }, { "code": null, "e": 4864, "s": 4710, "text": "For readability, we write the previous query inside a WITH clause, we also remove the first ORDER BY which was just to nicely display the previous table." }, { "code": null, "e": 4922, "s": 4864, "text": "After running this query, we obtain the following output:" }, { "code": null, "e": 5124, "s": 4922, "text": "As you can see on the output, on the same row, we have the revenue for the current month and the last_month_revenue which is the revenue value from the previous month (which is our preceding row here)." }, { "code": null, "e": 5299, "s": 5124, "text": "As said, the LAG() function use as input the column containing our desire variable (revenue), and an OFFSET that you can define (by default 1, meaning the first previous row)" }, { "code": null, "e": 5340, "s": 5299, "text": "LAG(revenue,1) OVER(ORDER BY months ASC)" }, { "code": null, "e": 5544, "s": 5340, "text": "Changing the offset value changes which preceding row is returned. The default value is 1, indicating that it will pick the previous row. This is why we write it without filling an offset in our example." }, { "code": null, "e": 5581, "s": 5544, "text": "BigQuery LAG() documentation 👉🏼 here" }, { "code": null, "e": 5737, "s": 5581, "text": "Now that we have our relative change formula, and understood the use of the LAG() function, we need to write our final query expressing the formula in SQL:" }, { "code": null, "e": 5933, "s": 5737, "text": "The first WITH clause doesn’t change. Under the “ — Main Query” comment, we only replace our previous last_month_revenue by the relative change formula. This gives us pretty much the same output:" }, { "code": null, "e": 6036, "s": 5933, "text": "That’s how we get the month-over-month growth rate! 🍻 It is then ready to be displayed on Data studio." }, { "code": null, "e": 6075, "s": 6036, "text": "Hints and explanations about the query" }, { "code": null, "e": 6151, "s": 6075, "text": "As a reminder, we use ((final value — initial value) / initial value) * 100" }, { "code": null, "e": 6215, "s": 6151, "text": "revenue = Final value, which is the value of our current month." }, { "code": null, "e": 6303, "s": 6215, "text": "LAG(revenue)OVER(ORDER BY months ASC) = Initial value, the value of our previous month." }, { "code": null, "e": 6370, "s": 6303, "text": "Here, we just convert the formula using our SQL syntax and fields." }, { "code": null, "e": 6477, "s": 6370, "text": "To have a cleaner result, we round the output applying ROUND(value,2) to limit the number to two decimals." }, { "code": null, "e": 6600, "s": 6477, "text": "We can then use Datastudio to display our results, which gives us a nice overview of our revenue changes month-over-month:" }, { "code": null, "e": 6814, "s": 6600, "text": "This method can be used on any kind of time series and variable. The interesting part is the use of navigation functions. They make this exercise a lot easier even if they are not that easy to understand at first." }, { "code": null, "e": 6966, "s": 6814, "text": "I hope you’ll like this method and the article will help you save some time and maybe even understand navigation functions better if you are new to it!" }, { "code": null, "e": 7101, "s": 6966, "text": "But more importantly, I hope this will help you get more at ease using SQL and BigQuery! It’s a good use case to practice your skills!" } ]
How to add 1 day to the date in MySQL?
We can add 1 day to the date with the help of DATE_ADD() function. Creating a table. mysql> create table Add1DayDemo -> ( -> id int, -> MyDate datetime not null -> ); Query OK, 0 rows affected (1.06 sec) Insert some records. mysql> insert into Add1DayDemo values(1,now()); Query OK, 1 row affected (0.08 sec) mysql> insert into Add1DayDemo values(2,date_add(now(),interval 5 day)); Query OK, 1 row affected (0.16 sec) To display all records. mysql> select *from Add1DayDemo; The following is the output. +------+---------------------+ | id | MyDate | +------+---------------------+ | 1 | 2018-10-30 10:51:21 | | 2 | 2018-11-04 10:51:30 | +------+---------------------+ 2 rows in set (0.00 sec) To add 1 day in field “MyDate”, use the SELECT mysql> SELECT DATE_ADD(`MyDate`, INTERVAL 1 DAY) from Add1DayDemo -> where id=2; The following is the output that shows the day, which was 4th November, increments by one, since we added a day. +------------------------------------+ | DATE_ADD(`MyDate`, INTERVAL 1 DAY) | +------------------------------------+ | 2018-11-05 10:51:30 | +------------------------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1129, "s": 1062, "text": "We can add 1 day to the date with the help of DATE_ADD() function." }, { "code": null, "e": 1147, "s": 1129, "text": "Creating a table." }, { "code": null, "e": 1278, "s": 1147, "text": "mysql> create table Add1DayDemo\n -> (\n -> id int,\n -> MyDate datetime not null\n -> );\nQuery OK, 0 rows affected (1.06 sec)" }, { "code": null, "e": 1299, "s": 1278, "text": "Insert some records." }, { "code": null, "e": 1495, "s": 1299, "text": "mysql> insert into Add1DayDemo values(1,now());\nQuery OK, 1 row affected (0.08 sec)\n\nmysql> insert into Add1DayDemo values(2,date_add(now(),interval 5 day));\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 1519, "s": 1495, "text": "To display all records." }, { "code": null, "e": 1552, "s": 1519, "text": "mysql> select *from Add1DayDemo;" }, { "code": null, "e": 1581, "s": 1552, "text": "The following is the output." }, { "code": null, "e": 1793, "s": 1581, "text": "+------+---------------------+\n| id | MyDate |\n+------+---------------------+\n| 1 | 2018-10-30 10:51:21 |\n| 2 | 2018-11-04 10:51:30 |\n+------+---------------------+\n2 rows in set (0.00 sec)\n" }, { "code": null, "e": 1840, "s": 1793, "text": "To add 1 day in field “MyDate”, use the SELECT" }, { "code": null, "e": 1926, "s": 1840, "text": "mysql> SELECT DATE_ADD(`MyDate`, INTERVAL 1 DAY) from Add1DayDemo\n -> where id=2;" }, { "code": null, "e": 2039, "s": 1926, "text": "The following is the output that shows the day, which was 4th November, increments by one, since we added a day." }, { "code": null, "e": 2259, "s": 2039, "text": "+------------------------------------+\n| DATE_ADD(`MyDate`, INTERVAL 1 DAY) |\n+------------------------------------+\n| 2018-11-05 10:51:30 |\n+------------------------------------+\n1 row in set (0.00 sec)\n" } ]
Object Detector Android App Using PyTorch Mobile Neural Network | by Tushar Chand Kapoor | Towards Data Science
Tushar Kapoor: (https://www.tusharck.com/) Running Machine Learning code on mobile devices is the next big thing. PyTorch, in the latest release PyTorch 1.3, added PyTorch Mobile for deploying machine learning models on Android and iOS devices. Here we will look into creating an Android Application for object detection inside an image; like the GIF shown below. We will be using a pre-trained ResNet18 model for this tutorial. ResNet18 is the state of the art computer vision model with 1000 classes for classification. Install Torchvision library Install Torchvision library pip install torchvision 2. Download and trace the ResNet18 model. We trace the model because we need an executable ScriptModule for just-in-time compilation. import torchimport torchvisionresnet18 = torchvision.models.resnet18(pretrained=True)resnet18.eval()example_inputs = torch.rand(1, 3, 224, 224)resnet18_traced = torch.jit.trace(resnet18, example_inputs = example_inputs)resnet18_traced.save("resnet18_traced.pt") Note: Store resnet18_traced.pt in a known location we will be requiring this in the later steps of the tutorial.In torch.rand we have taken 224,224 sizes because ResNet18 accepts the sizes of 224*224. Store resnet18_traced.pt in a known location we will be requiring this in the later steps of the tutorial. In torch.rand we have taken 224,224 sizes because ResNet18 accepts the sizes of 224*224. Download and install Android Studio if you haven’t already while installing say YES to download and installation of SDK.Link: https://developer.android.com/studioOpen Android Studio and click on:+ Start a new Android Studio ProjectSelect the Empty Activity. Download and install Android Studio if you haven’t already while installing say YES to download and installation of SDK.Link: https://developer.android.com/studio Open Android Studio and click on:+ Start a new Android Studio Project Select the Empty Activity. 4. Enter the application Name: ObjectDetectorDemo. Then Press Finish. 5. Install NDK to run native code inside Android: Go to Tools > SDK Manager. Click on SDK Tools. Check the box next to NDK (Side by side). 6. Add the dependencies. Inside build.gradle(Module:app). Add the following inside the dependencies. dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.0.2' implementation 'androidx.constraintlayout:constraintlayout:1.1.3'implementation 'org.pytorch:pytorch_android:1.3.0' implementation 'org.pytorch:pytorch_android_torchvision:1.3.0'} 7. Add a basic layout to load the image and display the results. Go to app>res> layout> activity_main.xml and add the code below. <ImageView android:id="@+id/image" app:layout_constraintTop_toTopOf="parent" android:layout_width="match_parent" android:layout_height="400dp" android:layout_marginBottom="20dp" android:scaleType="fitCenter" /><TextView android:id="@+id/result_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="top" android:text="" android:textSize="20dp" android:textStyle="bold" android:textAllCaps="true" android:textAlignment="center" app:layout_constraintTop_toTopOf="@id/button" app:layout_constraintBottom_toBottomOf="@+id/image" /><Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Load Image" app:layout_constraintBottom_toBottomOf="@+id/result_text" app:layout_constraintTop_toTopOf="@+id/detect" /><Button android:id="@+id/detect" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Detect" android:layout_marginBottom="50dp" app:layout_constraintBottom_toBottomOf="parent" /> Your layout should look like in the image below. 8. We need to set permissions to read the images stores on the device. Go to app> manifests> AndroidManifest.xml and add the code below inside the manifest tag. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> Get permission on application load (This is only asked until you give the permission). — Go to MainActivity java. Add the code below inside onCreate() method. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[] {android.Manifest.permission.READ_EXTERNAL_STORAGE}, 1);} 9. Copy Model. Now is the time we copy the model we created using the python script. Open your application from File Explorer/Finder. Go to app > src > main. Create a folder the named assets Copy your model in this folder. When you open you see in your Android Studio you should see like in the image below. (If not right-click on app folder and click on Synchronize App). 10. We need to list the output classes of the model. Go to app > java. Inside the first folder make a new Java class name as ModelClasses. Define a list of classes as (Full list is 1000 classes so, it possible to copy all here check Json or check Git. for the full list and copy inside the list below): public static String[] MODEL_CLASSES = new String[]{ "tench, Tinca tinca", "goldfish, Carassius auratus" . . .} 11. Main Activity Java, here will define the button actions, reading the image and calling the PyTorch model. See the comments inside the code for explanation. 12. Now it is time to test the application. There are two ways two do it: Running on Emulator [click here]. Use an Android Device. (For this you need to enable USB Debugging [click here]). After you run your application it should look behave like the GIF on top of the page. Link to Git repository: https://github.com/tusharck/Object-Detector-Android-App-Using-PyTorch-Mobile-Neural-Network Disclaimer: The “Android” name, the Android logo, the “Google Play” brand, and other Google trademarks, are property of Google LLC and not part of the assets available through the Android Open Source Project.PyTorch, PyTorch, the PyTorch logo, and all other trademarks, service marks, graphics and logos used in connection with PyTorch, or the Website are trademarks or registered trademarks of PyTorch or PyTorch’s licensors. The “Android” name, the Android logo, the “Google Play” brand, and other Google trademarks, are property of Google LLC and not part of the assets available through the Android Open Source Project. PyTorch, PyTorch, the PyTorch logo, and all other trademarks, service marks, graphics and logos used in connection with PyTorch, or the Website are trademarks or registered trademarks of PyTorch or PyTorch’s licensors.
[ { "code": null, "e": 215, "s": 172, "text": "Tushar Kapoor: (https://www.tusharck.com/)" }, { "code": null, "e": 417, "s": 215, "text": "Running Machine Learning code on mobile devices is the next big thing. PyTorch, in the latest release PyTorch 1.3, added PyTorch Mobile for deploying machine learning models on Android and iOS devices." }, { "code": null, "e": 536, "s": 417, "text": "Here we will look into creating an Android Application for object detection inside an image; like the GIF shown below." }, { "code": null, "e": 694, "s": 536, "text": "We will be using a pre-trained ResNet18 model for this tutorial. ResNet18 is the state of the art computer vision model with 1000 classes for classification." }, { "code": null, "e": 722, "s": 694, "text": "Install Torchvision library" }, { "code": null, "e": 750, "s": 722, "text": "Install Torchvision library" }, { "code": null, "e": 774, "s": 750, "text": "pip install torchvision" }, { "code": null, "e": 816, "s": 774, "text": "2. Download and trace the ResNet18 model." }, { "code": null, "e": 908, "s": 816, "text": "We trace the model because we need an executable ScriptModule for just-in-time compilation." }, { "code": null, "e": 1170, "s": 908, "text": "import torchimport torchvisionresnet18 = torchvision.models.resnet18(pretrained=True)resnet18.eval()example_inputs = torch.rand(1, 3, 224, 224)resnet18_traced = torch.jit.trace(resnet18, example_inputs = example_inputs)resnet18_traced.save(\"resnet18_traced.pt\")" }, { "code": null, "e": 1176, "s": 1170, "text": "Note:" }, { "code": null, "e": 1371, "s": 1176, "text": "Store resnet18_traced.pt in a known location we will be requiring this in the later steps of the tutorial.In torch.rand we have taken 224,224 sizes because ResNet18 accepts the sizes of 224*224." }, { "code": null, "e": 1478, "s": 1371, "text": "Store resnet18_traced.pt in a known location we will be requiring this in the later steps of the tutorial." }, { "code": null, "e": 1567, "s": 1478, "text": "In torch.rand we have taken 224,224 sizes because ResNet18 accepts the sizes of 224*224." }, { "code": null, "e": 1825, "s": 1567, "text": "Download and install Android Studio if you haven’t already while installing say YES to download and installation of SDK.Link: https://developer.android.com/studioOpen Android Studio and click on:+ Start a new Android Studio ProjectSelect the Empty Activity." }, { "code": null, "e": 1988, "s": 1825, "text": "Download and install Android Studio if you haven’t already while installing say YES to download and installation of SDK.Link: https://developer.android.com/studio" }, { "code": null, "e": 2058, "s": 1988, "text": "Open Android Studio and click on:+ Start a new Android Studio Project" }, { "code": null, "e": 2085, "s": 2058, "text": "Select the Empty Activity." }, { "code": null, "e": 2155, "s": 2085, "text": "4. Enter the application Name: ObjectDetectorDemo. Then Press Finish." }, { "code": null, "e": 2205, "s": 2155, "text": "5. Install NDK to run native code inside Android:" }, { "code": null, "e": 2232, "s": 2205, "text": "Go to Tools > SDK Manager." }, { "code": null, "e": 2252, "s": 2232, "text": "Click on SDK Tools." }, { "code": null, "e": 2294, "s": 2252, "text": "Check the box next to NDK (Side by side)." }, { "code": null, "e": 2319, "s": 2294, "text": "6. Add the dependencies." }, { "code": null, "e": 2395, "s": 2319, "text": "Inside build.gradle(Module:app). Add the following inside the dependencies." }, { "code": null, "e": 2711, "s": 2395, "text": "dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.0.2' implementation 'androidx.constraintlayout:constraintlayout:1.1.3'implementation 'org.pytorch:pytorch_android:1.3.0' implementation 'org.pytorch:pytorch_android_torchvision:1.3.0'}" }, { "code": null, "e": 2776, "s": 2711, "text": "7. Add a basic layout to load the image and display the results." }, { "code": null, "e": 2841, "s": 2776, "text": "Go to app>res> layout> activity_main.xml and add the code below." }, { "code": null, "e": 3956, "s": 2841, "text": "<ImageView android:id=\"@+id/image\" app:layout_constraintTop_toTopOf=\"parent\" android:layout_width=\"match_parent\" android:layout_height=\"400dp\" android:layout_marginBottom=\"20dp\" android:scaleType=\"fitCenter\" /><TextView android:id=\"@+id/result_text\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_gravity=\"top\" android:text=\"\" android:textSize=\"20dp\" android:textStyle=\"bold\" android:textAllCaps=\"true\" android:textAlignment=\"center\" app:layout_constraintTop_toTopOf=\"@id/button\" app:layout_constraintBottom_toBottomOf=\"@+id/image\" /><Button android:id=\"@+id/button\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Load Image\" app:layout_constraintBottom_toBottomOf=\"@+id/result_text\" app:layout_constraintTop_toTopOf=\"@+id/detect\" /><Button android:id=\"@+id/detect\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Detect\" android:layout_marginBottom=\"50dp\" app:layout_constraintBottom_toBottomOf=\"parent\" />" }, { "code": null, "e": 4005, "s": 3956, "text": "Your layout should look like in the image below." }, { "code": null, "e": 4076, "s": 4005, "text": "8. We need to set permissions to read the images stores on the device." }, { "code": null, "e": 4166, "s": 4076, "text": "Go to app> manifests> AndroidManifest.xml and add the code below inside the manifest tag." }, { "code": null, "e": 4241, "s": 4166, "text": "<uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\"/>" }, { "code": null, "e": 4328, "s": 4241, "text": "Get permission on application load (This is only asked until you give the permission)." }, { "code": null, "e": 4400, "s": 4328, "text": "— Go to MainActivity java. Add the code below inside onCreate() method." }, { "code": null, "e": 4548, "s": 4400, "text": "if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[] {android.Manifest.permission.READ_EXTERNAL_STORAGE}, 1);}" }, { "code": null, "e": 4633, "s": 4548, "text": "9. Copy Model. Now is the time we copy the model we created using the python script." }, { "code": null, "e": 4682, "s": 4633, "text": "Open your application from File Explorer/Finder." }, { "code": null, "e": 4706, "s": 4682, "text": "Go to app > src > main." }, { "code": null, "e": 4739, "s": 4706, "text": "Create a folder the named assets" }, { "code": null, "e": 4771, "s": 4739, "text": "Copy your model in this folder." }, { "code": null, "e": 4921, "s": 4771, "text": "When you open you see in your Android Studio you should see like in the image below. (If not right-click on app folder and click on Synchronize App)." }, { "code": null, "e": 4974, "s": 4921, "text": "10. We need to list the output classes of the model." }, { "code": null, "e": 4992, "s": 4974, "text": "Go to app > java." }, { "code": null, "e": 5060, "s": 4992, "text": "Inside the first folder make a new Java class name as ModelClasses." }, { "code": null, "e": 5224, "s": 5060, "text": "Define a list of classes as (Full list is 1000 classes so, it possible to copy all here check Json or check Git. for the full list and copy inside the list below):" }, { "code": null, "e": 5371, "s": 5224, "text": "public static String[] MODEL_CLASSES = new String[]{ \"tench, Tinca tinca\", \"goldfish, Carassius auratus\" . . .}" }, { "code": null, "e": 5531, "s": 5371, "text": "11. Main Activity Java, here will define the button actions, reading the image and calling the PyTorch model. See the comments inside the code for explanation." }, { "code": null, "e": 5605, "s": 5531, "text": "12. Now it is time to test the application. There are two ways two do it:" }, { "code": null, "e": 5639, "s": 5605, "text": "Running on Emulator [click here]." }, { "code": null, "e": 5720, "s": 5639, "text": "Use an Android Device. (For this you need to enable USB Debugging [click here])." }, { "code": null, "e": 5806, "s": 5720, "text": "After you run your application it should look behave like the GIF on top of the page." }, { "code": null, "e": 5922, "s": 5806, "text": "Link to Git repository: https://github.com/tusharck/Object-Detector-Android-App-Using-PyTorch-Mobile-Neural-Network" }, { "code": null, "e": 5934, "s": 5922, "text": "Disclaimer:" }, { "code": null, "e": 6349, "s": 5934, "text": "The “Android” name, the Android logo, the “Google Play” brand, and other Google trademarks, are property of Google LLC and not part of the assets available through the Android Open Source Project.PyTorch, PyTorch, the PyTorch logo, and all other trademarks, service marks, graphics and logos used in connection with PyTorch, or the Website are trademarks or registered trademarks of PyTorch or PyTorch’s licensors." }, { "code": null, "e": 6546, "s": 6349, "text": "The “Android” name, the Android logo, the “Google Play” brand, and other Google trademarks, are property of Google LLC and not part of the assets available through the Android Open Source Project." } ]
Explaining Python Classes in a simple way | by Eugenia Anello | Towards Data Science
When I studied the Python Classes the first time, I found it really complicated and I didn’t grasp the reason why they needed to be known. In a university lesson, the professor started to explain directly the syntax to build the classes without explaining the real sense of doing this particular topic and used very boring examples that made me lose in the way. In this post, I want to explain Python Classes in a different way. I’ll start explaining why the classes need to be known and show some of the many cases of already-built classes. Once the external context is clear, the next step is to show step by step how to define classes using some examples and illustrations. Table of Contents: Intro to ClassesCreate a ClassConstructor MethodMagical MethodInstance Method Intro to Classes Create a Class Constructor Method Magical Method Instance Method When you started to study Python, you have surely met the sentence: Python is an object-oriented programming language It means that programming in Python leads to being surrounded by objects everywhere. In the instant we assign a value to a variable, we are creating an object. This object belongs to a particular class already pre-built, like numbers, strings, lists, dictionaries and so on. Depending on the class, the object will have different properties and methods. Let’s see some classic examples of objects and classes: a = 28print(type(a))#<class 'int'> We defined an object a, which belongs to the Integer class. l = [1,2,3]print(type(l))#<class 'list'> This time, the new object belongs to the List class. From the object, we can call methods, already pre-built in Python. To see all the methods allowed in the object, we use the dir function: dir(l) From the output, we can notice that the class can provide three types of methods: Initializer method __init__, called in this way because it’s the method that initializes the attributes of the object. Moreover, it is automatically called once the object is created. Magical methods are special methods with double underscores on both sides. For example, __add__ and __mul__ are used to respectively sum and multiplicate objects of the same class, while __repr__ returns a representation of the object as a string. Instance methods are methods that belong to the object created. For example, l.append(4) adds an element at the end of the list. Now, we will create an empty class and we’ll progressively add parts of code within the tutorial. class Dog: pass We created a class with the name Dog, where pass is used to indicate that nothing is defined. jack = Dog()print(type(jack))#<class '__main__.Dog'> Once we defined the Dog class, we can create an object of the class, which is assigned to the variable jack. It’s built using a similar notation we use to call a function: Dog(). The object can also be called instance. Don’t be confused if you find the words “instance” or “object” written somewhere, they always refer to the same thing. Like before, we check the type of object. The output clearly points out that the object belongs to the Dog class. In addition to the code shown previously, the initializer method __init__ is used to initialize the attributes of the Dog class. class Dog: def __init__(self,name,breed,age): self.Name = name self.Breed = breed self.Age = age print("Name: {}, Breed: {}, Age: {}".format(self.Name, self.Breed,self.Age)) We can observe that the method has different arguments: self is a standard notation used as the first argument and refers to the object, which will be created later. It’s also useful to access the attributes that belong to the class. name, breed and age are the remaining arguments. Each argument is used to store the specific attribute’s value of the object. Name, Breed and Age are the defined attributes. Note the attributes are typically not capitalized. In this post, they are UpperCase to highlight the difference between the attributes and their corresponding values. jack = Dog('Jack','Husky',5)#Name: Jack, Breed: Husky, Age: 5print(jack)#<__main__.Dog object at 0x000002551DCEFFD0>print(jack.Age)#5 We create again the object, but we also specify the values that correspond to the attributes. If you try to run the code, you’ll obtain automatically the line of text shown in the second row of the grey window. It’s a good way to check if the class defined is working well. It’s also worth noticing that the initializer method is called automatically after creating the object. This aspect can be demonstrated by printing the value of attribute “Age”. You can do the same for the remaining attributes. There is also the possibility to print the same information in a more sophisticated way. For this purpose, we use the magical method __repr__: class Dog: def __init__(self,name,breed,age): self.Name = name self.Breed = breed self.Age = age def __repr__(self): return "Name: {}, Breed: {}, Age: {}".format(self.Name, self.Breed,self.Age) The method __repr__ takes a unique parameter selffrom which it can access the attributes of the object. jack = Dog('Jack','Husky',5)print(jack)#Name: Jack, Breed: Husky, Age: 5 If we display the new instance created, we can look at the attributes and their respective values. The instance methods are methods that belong to the class. As the magical methods, they take an input the parameter self to access the attributes of the class. Let’s see an example: class Dog: def __init__(self,name,breed,age,tired): self.Name = name self.Breed = breed self.Age = age self.Tired = tired def __repr__(self): return "Name: {}, Breed: {}, Age: {}".format(self.Name, self.Breed,self.Age) def Sleep(self): if self.Tired==True: return 'I will sleep' else: return "I don't want to sleep" In the initializer method, we added a new argument tired and, consequently, a new attribute Tired. After, we define a new method called Sleep: if the attribute’s value is equal to True, the dog will sleep, otherwise, it won’t. jack = Dog('Jack','Husky',5,tired=False)print(jack.Sleep())#I don't want to sleep The dog is not tired, so it won’t sleep. In this post, I provided a fast summary of the Python classes. I hope you found it useful to consolidate your basis about the classes. I didn't explain other types of methods, Static and Class Methods, since I want to focus on the most common ones. Moreover, another interesting topic is Class Inheritance, which is covered in another post I wrote. Thanks for reading. Have a nice day! Did you appreciate the article? Become a member and get unlimited access to new data science posts every day!
[ { "code": null, "e": 534, "s": 172, "text": "When I studied the Python Classes the first time, I found it really complicated and I didn’t grasp the reason why they needed to be known. In a university lesson, the professor started to explain directly the syntax to build the classes without explaining the real sense of doing this particular topic and used very boring examples that made me lose in the way." }, { "code": null, "e": 849, "s": 534, "text": "In this post, I want to explain Python Classes in a different way. I’ll start explaining why the classes need to be known and show some of the many cases of already-built classes. Once the external context is clear, the next step is to show step by step how to define classes using some examples and illustrations." }, { "code": null, "e": 868, "s": 849, "text": "Table of Contents:" }, { "code": null, "e": 946, "s": 868, "text": "Intro to ClassesCreate a ClassConstructor MethodMagical MethodInstance Method" }, { "code": null, "e": 963, "s": 946, "text": "Intro to Classes" }, { "code": null, "e": 978, "s": 963, "text": "Create a Class" }, { "code": null, "e": 997, "s": 978, "text": "Constructor Method" }, { "code": null, "e": 1012, "s": 997, "text": "Magical Method" }, { "code": null, "e": 1028, "s": 1012, "text": "Instance Method" }, { "code": null, "e": 1096, "s": 1028, "text": "When you started to study Python, you have surely met the sentence:" }, { "code": null, "e": 1146, "s": 1096, "text": "Python is an object-oriented programming language" }, { "code": null, "e": 1246, "s": 1146, "text": "It means that programming in Python leads to being surrounded by objects everywhere. In the instant" }, { "code": null, "e": 1500, "s": 1246, "text": "we assign a value to a variable, we are creating an object. This object belongs to a particular class already pre-built, like numbers, strings, lists, dictionaries and so on. Depending on the class, the object will have different properties and methods." }, { "code": null, "e": 1556, "s": 1500, "text": "Let’s see some classic examples of objects and classes:" }, { "code": null, "e": 1591, "s": 1556, "text": "a = 28print(type(a))#<class 'int'>" }, { "code": null, "e": 1651, "s": 1591, "text": "We defined an object a, which belongs to the Integer class." }, { "code": null, "e": 1692, "s": 1651, "text": "l = [1,2,3]print(type(l))#<class 'list'>" }, { "code": null, "e": 1883, "s": 1692, "text": "This time, the new object belongs to the List class. From the object, we can call methods, already pre-built in Python. To see all the methods allowed in the object, we use the dir function:" }, { "code": null, "e": 1890, "s": 1883, "text": "dir(l)" }, { "code": null, "e": 1972, "s": 1890, "text": "From the output, we can notice that the class can provide three types of methods:" }, { "code": null, "e": 2156, "s": 1972, "text": "Initializer method __init__, called in this way because it’s the method that initializes the attributes of the object. Moreover, it is automatically called once the object is created." }, { "code": null, "e": 2404, "s": 2156, "text": "Magical methods are special methods with double underscores on both sides. For example, __add__ and __mul__ are used to respectively sum and multiplicate objects of the same class, while __repr__ returns a representation of the object as a string." }, { "code": null, "e": 2533, "s": 2404, "text": "Instance methods are methods that belong to the object created. For example, l.append(4) adds an element at the end of the list." }, { "code": null, "e": 2631, "s": 2533, "text": "Now, we will create an empty class and we’ll progressively add parts of code within the tutorial." }, { "code": null, "e": 2649, "s": 2631, "text": "class Dog: pass" }, { "code": null, "e": 2743, "s": 2649, "text": "We created a class with the name Dog, where pass is used to indicate that nothing is defined." }, { "code": null, "e": 2796, "s": 2743, "text": "jack = Dog()print(type(jack))#<class '__main__.Dog'>" }, { "code": null, "e": 2975, "s": 2796, "text": "Once we defined the Dog class, we can create an object of the class, which is assigned to the variable jack. It’s built using a similar notation we use to call a function: Dog()." }, { "code": null, "e": 3134, "s": 2975, "text": "The object can also be called instance. Don’t be confused if you find the words “instance” or “object” written somewhere, they always refer to the same thing." }, { "code": null, "e": 3248, "s": 3134, "text": "Like before, we check the type of object. The output clearly points out that the object belongs to the Dog class." }, { "code": null, "e": 3377, "s": 3248, "text": "In addition to the code shown previously, the initializer method __init__ is used to initialize the attributes of the Dog class." }, { "code": null, "e": 3608, "s": 3377, "text": "class Dog: def __init__(self,name,breed,age): self.Name = name self.Breed = breed self.Age = age print(\"Name: {}, Breed: {}, Age: {}\".format(self.Name, self.Breed,self.Age))" }, { "code": null, "e": 3664, "s": 3608, "text": "We can observe that the method has different arguments:" }, { "code": null, "e": 3842, "s": 3664, "text": "self is a standard notation used as the first argument and refers to the object, which will be created later. It’s also useful to access the attributes that belong to the class." }, { "code": null, "e": 3968, "s": 3842, "text": "name, breed and age are the remaining arguments. Each argument is used to store the specific attribute’s value of the object." }, { "code": null, "e": 4183, "s": 3968, "text": "Name, Breed and Age are the defined attributes. Note the attributes are typically not capitalized. In this post, they are UpperCase to highlight the difference between the attributes and their corresponding values." }, { "code": null, "e": 4317, "s": 4183, "text": "jack = Dog('Jack','Husky',5)#Name: Jack, Breed: Husky, Age: 5print(jack)#<__main__.Dog object at 0x000002551DCEFFD0>print(jack.Age)#5" }, { "code": null, "e": 4591, "s": 4317, "text": "We create again the object, but we also specify the values that correspond to the attributes. If you try to run the code, you’ll obtain automatically the line of text shown in the second row of the grey window. It’s a good way to check if the class defined is working well." }, { "code": null, "e": 4819, "s": 4591, "text": "It’s also worth noticing that the initializer method is called automatically after creating the object. This aspect can be demonstrated by printing the value of attribute “Age”. You can do the same for the remaining attributes." }, { "code": null, "e": 4962, "s": 4819, "text": "There is also the possibility to print the same information in a more sophisticated way. For this purpose, we use the magical method __repr__:" }, { "code": null, "e": 5232, "s": 4962, "text": "class Dog: def __init__(self,name,breed,age): self.Name = name self.Breed = breed self.Age = age def __repr__(self): return \"Name: {}, Breed: {}, Age: {}\".format(self.Name, self.Breed,self.Age)" }, { "code": null, "e": 5336, "s": 5232, "text": "The method __repr__ takes a unique parameter selffrom which it can access the attributes of the object." }, { "code": null, "e": 5409, "s": 5336, "text": "jack = Dog('Jack','Husky',5)print(jack)#Name: Jack, Breed: Husky, Age: 5" }, { "code": null, "e": 5508, "s": 5409, "text": "If we display the new instance created, we can look at the attributes and their respective values." }, { "code": null, "e": 5690, "s": 5508, "text": "The instance methods are methods that belong to the class. As the magical methods, they take an input the parameter self to access the attributes of the class. Let’s see an example:" }, { "code": null, "e": 6129, "s": 5690, "text": "class Dog: def __init__(self,name,breed,age,tired): self.Name = name self.Breed = breed self.Age = age self.Tired = tired def __repr__(self): return \"Name: {}, Breed: {}, Age: {}\".format(self.Name, self.Breed,self.Age) def Sleep(self): if self.Tired==True: return 'I will sleep' else: return \"I don't want to sleep\"" }, { "code": null, "e": 6356, "s": 6129, "text": "In the initializer method, we added a new argument tired and, consequently, a new attribute Tired. After, we define a new method called Sleep: if the attribute’s value is equal to True, the dog will sleep, otherwise, it won’t." }, { "code": null, "e": 6438, "s": 6356, "text": "jack = Dog('Jack','Husky',5,tired=False)print(jack.Sleep())#I don't want to sleep" }, { "code": null, "e": 6479, "s": 6438, "text": "The dog is not tired, so it won’t sleep." }, { "code": null, "e": 6865, "s": 6479, "text": "In this post, I provided a fast summary of the Python classes. I hope you found it useful to consolidate your basis about the classes. I didn't explain other types of methods, Static and Class Methods, since I want to focus on the most common ones. Moreover, another interesting topic is Class Inheritance, which is covered in another post I wrote. Thanks for reading. Have a nice day!" } ]
How to match beginning of a particular string/line using Java RegEx
The meta character “^” matches the beginning of a particular string i.e. it matches the first character of the string. For example, The expression “^\\d” matches the string/line starting with a digit. The expression “^\\d” matches the string/line starting with a digit. The expression “^[a-z]” matches the string/line starting with a lower case alphabet. The expression “^[a-z]” matches the string/line starting with a lower case alphabet. import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { public static void main(String args[]) { //Reading String from user System.out.println("Enter a String"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); String regex = "^[^a-zA-Z0-9//s].*"; //Compiling the regular expression Pattern pattern = Pattern.compile(regex); //Retrieving the matcher object Matcher matcher = pattern.matcher(input); if(matcher.matches()) { System.out.println("Match occurred"); } else { System.out.println("Match not occurred"); } } } Enter a String #starting with a special character Match occurred import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main( String args[] ) { String regex = "\\.$"; Scanner sc = new Scanner(System.in); System.out.println("Enter 5 input strings: "); String input[] = new String[5]; for (int i=0; i<5; i++) { input[i] = sc.nextLine(); } //Creating a Pattern object Pattern p = Pattern.compile(regex); for(int i=0; i<5;i++) { //Creating a Matcher object Matcher m = p.matcher(input[i]); if(m.find()) { System.out.println("String "+i+" ends with '.'"); } } } } Enter 5 input strings: hello how are you. where do you live what is your name. welcome to tutorialspoint The Biggest Online Tutorials Library. String 0 ends with '.' String 2 ends with '.' String 4 ends with '.' import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main( String args[] ) { String regex = "^[A-Z]"; Scanner sc = new Scanner(System.in); System.out.println("Enter 5 input strings: "); String input[] = new String[5]; for (int i=0; i<5; i++) { input[i] = sc.nextLine(); } //Creating a Pattern object Pattern p = Pattern.compile(regex); for(int i=0; i<5;i++) { //Creating a Matcher object Matcher m = p.matcher(input[i]); if(m.find()) { System.out.println("String "+i+" starts with a capital letter"); } } } } Enter 5 input strings: Sample text1 sample text2 hello how are you Welcome to tutorialspoint Good morning String 0 starts with a capital letter String 3 starts with a capital letter String 4 starts with a capital letter
[ { "code": null, "e": 1194, "s": 1062, "text": "The meta character “^” matches the beginning of a particular string i.e. it matches the first character of the string. For example," }, { "code": null, "e": 1263, "s": 1194, "text": "The expression “^\\\\d” matches the string/line starting with a digit." }, { "code": null, "e": 1332, "s": 1263, "text": "The expression “^\\\\d” matches the string/line starting with a digit." }, { "code": null, "e": 1417, "s": 1332, "text": "The expression “^[a-z]” matches the string/line starting with a lower case alphabet." }, { "code": null, "e": 1502, "s": 1417, "text": "The expression “^[a-z]” matches the string/line starting with a lower case alphabet." }, { "code": null, "e": 2192, "s": 1502, "text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class Example {\n public static void main(String args[]) {\n //Reading String from user\n System.out.println(\"Enter a String\");\n Scanner sc = new Scanner(System.in);\n String input = sc.nextLine();\n String regex = \"^[^a-zA-Z0-9//s].*\";\n //Compiling the regular expression\n Pattern pattern = Pattern.compile(regex);\n //Retrieving the matcher object\n Matcher matcher = pattern.matcher(input);\n if(matcher.matches()) {\n System.out.println(\"Match occurred\");\n } else { \n System.out.println(\"Match not occurred\");\n }\n }\n}" }, { "code": null, "e": 2257, "s": 2192, "text": "Enter a String\n#starting with a special character\nMatch occurred" }, { "code": null, "e": 2956, "s": 2257, "text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class RegexExample {\n public static void main( String args[] ) {\n String regex = \"\\\\.$\";\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter 5 input strings: \");\n String input[] = new String[5];\n for (int i=0; i<5; i++) {\n input[i] = sc.nextLine();\n }\n //Creating a Pattern object\n Pattern p = Pattern.compile(regex);\n for(int i=0; i<5;i++) {\n //Creating a Matcher object\n Matcher m = p.matcher(input[i]);\n if(m.find()) {\n System.out.println(\"String \"+i+\" ends with '.'\");\n }\n }\n }\n}" }, { "code": null, "e": 3168, "s": 2956, "text": "Enter 5 input strings:\nhello how are you.\nwhere do you live\nwhat is your name.\nwelcome to tutorialspoint\nThe Biggest Online Tutorials Library.\nString 0 ends with '.'\nString 2 ends with '.'\nString 4 ends with '.'" }, { "code": null, "e": 3884, "s": 3168, "text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class RegexExample {\n public static void main( String args[] ) {\n String regex = \"^[A-Z]\";\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter 5 input strings: \");\n String input[] = new String[5];\n for (int i=0; i<5; i++) {\n input[i] = sc.nextLine();\n }\n //Creating a Pattern object\n Pattern p = Pattern.compile(regex);\n for(int i=0; i<5;i++) {\n //Creating a Matcher object\n Matcher m = p.matcher(input[i]);\n if(m.find()) {\n System.out.println(\"String \"+i+\" starts with a capital letter\");\n }\n }\n }\n}" }, { "code": null, "e": 4104, "s": 3884, "text": "Enter 5 input strings:\nSample text1\nsample text2\nhello how are you\nWelcome to tutorialspoint\nGood morning\nString 0 starts with a capital letter\nString 3 starts with a capital letter\nString 4 starts with a capital letter" } ]
How Do You Implement AdaBoost with Python? | by Rukshan Pramoditha | Towards Data Science
We’re continuing from Part 1 of Boosting algorithms in machine learning article series. Have you read Part 1? It gives you a short introduction to boosting and definitions of some key technical terms that are all important to understand today’s content. Today, we’re going to learn one of the most popular boosting algorithms: AdaBoost (Adaptive Boosting). More emphasis will be given to the implementation part of the algorithm under the following topics. Scikit-learn classes for AdaBoost Train and evaluate an AdaBoost classification model on Wine data Compare the AdaBoost model with a decision tree stump Important hyperparameters in AdaBoost Measure the effect of hyperparameter n_estimators Measure the effect of hyperparameter learning_rate Find the optimal hyperparameter values using Grid Search All code samples will be included as GitHub gists so that you can easily work with them! At the end of the article, you will be able to implement the AdaBoost algorithm on a given dataset with optimal hyperparameter values. Let’s get started! The Python implementation of AdaBoost is fulfilled by two Scikit-learn classes: AdaBoostClassifier() for classification (both binary and multi-class) and AdaBoostRegressor() for regression. The import conventions are: from sklearn.ensemble import AdaBoostClassifierfrom sklearn.ensemble import AdaBoostRegressor By early stopping the tree growth with max_depth=1, we’ll build a decision stump on Wine data. This is to compare the decision stump with the AdaBoost model. We also use this stump model as the base learner for AdaBoost. The following Python code creates a decision tree stump on Wine data and evaluates its performance. The model’s performance is poor. This is not a surprise as we strictly regulated the tree growth by setting max_depth=1. Now, we’re going to build an AdaBoost classification model on Wine data. Ohh that score! The AdaBoost model is performing really well compared to the decision tree stump. The following are the most important hyperparameters in both AdaBoostClassifier() and AdaBoostRegressor(). base_estimator: This is the base learner used in AdaBoost algorithms. The default and most common learner is a decision tree stump (a decision tree with max_depth=1) as we discussed earlier. n_estimators: The maximum number of estimators (models) to train sequentially. The default is 50. We’ll measure the effect of this hyperparameter soon. learning_rate: This determines the weight applied to each estimator in the boosting process. The default is 1. Smaller values such as 0.05, 0.1 force the algorithm to train slower but with high-performance scores. We’ll measure the effect of this hyperparameter soon. We’ll manually measure the effect of the hyperparameter n_estimators by varying its values from 2 to 100 and plot the test scores given by the AdaBoost model. After about 30 estimators, the accuracy score is constant at 0.972 that we obtained earlier. You can use any integer above 30. But keep in mind that if you increase the value, the algorithm will take much time for training. So, in this case, it is better to use the default value, 50. We’ll manually measure the effect of the hyperparameter learning_rate by varying its values from 0.1 to 1 and plot the test scores given by the AdaBoost model. The highest accuracy is given at 0.4, 0.5, 0.7 and 0.8. We’ve used 0.5 in the above model. Both measurements were done manually. There is an easier way to find the optimal values for n_estimators and learning_rate. Here, we automatically tune (find optimal values) both hyperparameters at the same time by using Grid Search. In contrast, in the previous steps, we tuned one hyperparameter at a time. We can use these values to get the highest accuracy of the AdaBoost model. Some other possible combinations that give the same accuracy are: learning_rate=0.5, n_estimators=50 learning_rate=0.8, n_estimators=50 learning_rate=0.8, n_estimators=100 learning_rate=0.4, n_estimators=50 Building AdaBoost models in Python is straightforward. All you have to do is to determine the type of problem (regression/classification) you want to solve and select the suitable AdaBoost class provided in Scikit-learn. However, the hyperparameter tuning procedure is a real challenge. You need to make some visualizations, do parallel computations for hyperparameter tuning. Actually, you’ll create thousands of models. Luckily, we can automate the tuning process using advanced methods as we discussed in this post. The model’s outputs can be largely affected by random data splitting. You may get different accuracy scores depending on the integer specified in the random_state. It is always recommended to specify an integer to get static results at different executions. Compared to other tree-based methods such as decision trees and random forests, boosting algorithms like AdaBoost perform really well. This is because tress in boosting are sequentially trained considering the errors created by initial tress in previous rounds. In Part 3, we’ll discuss Gradient Boosting, another popular boosting algorithm. See you in the next story. Happy learning to everyone! My readers can sign up for a membership through the following link to get full access to every story I write and I will receive a portion of your membership fee. rukshanpramoditha.medium.com Thank you so much for your continuous support! Special credit goes to John Price on Unsplash, who provides me with a nice cover image for this post.
[ { "code": null, "e": 426, "s": 172, "text": "We’re continuing from Part 1 of Boosting algorithms in machine learning article series. Have you read Part 1? It gives you a short introduction to boosting and definitions of some key technical terms that are all important to understand today’s content." }, { "code": null, "e": 629, "s": 426, "text": "Today, we’re going to learn one of the most popular boosting algorithms: AdaBoost (Adaptive Boosting). More emphasis will be given to the implementation part of the algorithm under the following topics." }, { "code": null, "e": 663, "s": 629, "text": "Scikit-learn classes for AdaBoost" }, { "code": null, "e": 728, "s": 663, "text": "Train and evaluate an AdaBoost classification model on Wine data" }, { "code": null, "e": 782, "s": 728, "text": "Compare the AdaBoost model with a decision tree stump" }, { "code": null, "e": 820, "s": 782, "text": "Important hyperparameters in AdaBoost" }, { "code": null, "e": 870, "s": 820, "text": "Measure the effect of hyperparameter n_estimators" }, { "code": null, "e": 921, "s": 870, "text": "Measure the effect of hyperparameter learning_rate" }, { "code": null, "e": 978, "s": 921, "text": "Find the optimal hyperparameter values using Grid Search" }, { "code": null, "e": 1202, "s": 978, "text": "All code samples will be included as GitHub gists so that you can easily work with them! At the end of the article, you will be able to implement the AdaBoost algorithm on a given dataset with optimal hyperparameter values." }, { "code": null, "e": 1221, "s": 1202, "text": "Let’s get started!" }, { "code": null, "e": 1439, "s": 1221, "text": "The Python implementation of AdaBoost is fulfilled by two Scikit-learn classes: AdaBoostClassifier() for classification (both binary and multi-class) and AdaBoostRegressor() for regression. The import conventions are:" }, { "code": null, "e": 1533, "s": 1439, "text": "from sklearn.ensemble import AdaBoostClassifierfrom sklearn.ensemble import AdaBoostRegressor" }, { "code": null, "e": 1754, "s": 1533, "text": "By early stopping the tree growth with max_depth=1, we’ll build a decision stump on Wine data. This is to compare the decision stump with the AdaBoost model. We also use this stump model as the base learner for AdaBoost." }, { "code": null, "e": 1854, "s": 1754, "text": "The following Python code creates a decision tree stump on Wine data and evaluates its performance." }, { "code": null, "e": 1975, "s": 1854, "text": "The model’s performance is poor. This is not a surprise as we strictly regulated the tree growth by setting max_depth=1." }, { "code": null, "e": 2048, "s": 1975, "text": "Now, we’re going to build an AdaBoost classification model on Wine data." }, { "code": null, "e": 2146, "s": 2048, "text": "Ohh that score! The AdaBoost model is performing really well compared to the decision tree stump." }, { "code": null, "e": 2253, "s": 2146, "text": "The following are the most important hyperparameters in both AdaBoostClassifier() and AdaBoostRegressor()." }, { "code": null, "e": 2444, "s": 2253, "text": "base_estimator: This is the base learner used in AdaBoost algorithms. The default and most common learner is a decision tree stump (a decision tree with max_depth=1) as we discussed earlier." }, { "code": null, "e": 2596, "s": 2444, "text": "n_estimators: The maximum number of estimators (models) to train sequentially. The default is 50. We’ll measure the effect of this hyperparameter soon." }, { "code": null, "e": 2864, "s": 2596, "text": "learning_rate: This determines the weight applied to each estimator in the boosting process. The default is 1. Smaller values such as 0.05, 0.1 force the algorithm to train slower but with high-performance scores. We’ll measure the effect of this hyperparameter soon." }, { "code": null, "e": 3023, "s": 2864, "text": "We’ll manually measure the effect of the hyperparameter n_estimators by varying its values from 2 to 100 and plot the test scores given by the AdaBoost model." }, { "code": null, "e": 3308, "s": 3023, "text": "After about 30 estimators, the accuracy score is constant at 0.972 that we obtained earlier. You can use any integer above 30. But keep in mind that if you increase the value, the algorithm will take much time for training. So, in this case, it is better to use the default value, 50." }, { "code": null, "e": 3468, "s": 3308, "text": "We’ll manually measure the effect of the hyperparameter learning_rate by varying its values from 0.1 to 1 and plot the test scores given by the AdaBoost model." }, { "code": null, "e": 3559, "s": 3468, "text": "The highest accuracy is given at 0.4, 0.5, 0.7 and 0.8. We’ve used 0.5 in the above model." }, { "code": null, "e": 3683, "s": 3559, "text": "Both measurements were done manually. There is an easier way to find the optimal values for n_estimators and learning_rate." }, { "code": null, "e": 3868, "s": 3683, "text": "Here, we automatically tune (find optimal values) both hyperparameters at the same time by using Grid Search. In contrast, in the previous steps, we tuned one hyperparameter at a time." }, { "code": null, "e": 4009, "s": 3868, "text": "We can use these values to get the highest accuracy of the AdaBoost model. Some other possible combinations that give the same accuracy are:" }, { "code": null, "e": 4044, "s": 4009, "text": "learning_rate=0.5, n_estimators=50" }, { "code": null, "e": 4079, "s": 4044, "text": "learning_rate=0.8, n_estimators=50" }, { "code": null, "e": 4115, "s": 4079, "text": "learning_rate=0.8, n_estimators=100" }, { "code": null, "e": 4150, "s": 4115, "text": "learning_rate=0.4, n_estimators=50" }, { "code": null, "e": 4669, "s": 4150, "text": "Building AdaBoost models in Python is straightforward. All you have to do is to determine the type of problem (regression/classification) you want to solve and select the suitable AdaBoost class provided in Scikit-learn. However, the hyperparameter tuning procedure is a real challenge. You need to make some visualizations, do parallel computations for hyperparameter tuning. Actually, you’ll create thousands of models. Luckily, we can automate the tuning process using advanced methods as we discussed in this post." }, { "code": null, "e": 4927, "s": 4669, "text": "The model’s outputs can be largely affected by random data splitting. You may get different accuracy scores depending on the integer specified in the random_state. It is always recommended to specify an integer to get static results at different executions." }, { "code": null, "e": 5189, "s": 4927, "text": "Compared to other tree-based methods such as decision trees and random forests, boosting algorithms like AdaBoost perform really well. This is because tress in boosting are sequentially trained considering the errors created by initial tress in previous rounds." }, { "code": null, "e": 5324, "s": 5189, "text": "In Part 3, we’ll discuss Gradient Boosting, another popular boosting algorithm. See you in the next story. Happy learning to everyone!" }, { "code": null, "e": 5486, "s": 5324, "text": "My readers can sign up for a membership through the following link to get full access to every story I write and I will receive a portion of your membership fee." }, { "code": null, "e": 5515, "s": 5486, "text": "rukshanpramoditha.medium.com" }, { "code": null, "e": 5562, "s": 5515, "text": "Thank you so much for your continuous support!" } ]
C++ Environment Setup
If you are still willing to set up your environment for C++, you need to have the following two softwares on your computer. This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows and vim or vi can be used on windows as well as Linux, or UNIX. The files you create with your editor are called source files and for C++ they typically are named with the extension .cpp, .cp, or .c. A text editor should be in place to start your C++ programming. This is an actual C++ compiler, which will be used to compile your source code into final executable program. Most C++ compilers don't care what extension you give to your source code, but if you don't specify otherwise, many will use .cpp by default. Most frequently used and free available compiler is GNU C/C++ compiler, otherwise you can have compilers either from HP or Solaris if you have the respective Operating Systems. If you are using Linux or UNIX then check whether GCC is installed on your system by entering the following command from the command line − $ g++ -v If you have installed GCC, then it should print a message such as the following − Using built-in specs. Target: i386-redhat-linux Configured with: ../configure --prefix=/usr ....... Thread model: posix gcc version 4.1.2 20080704 (Red Hat 4.1.2-46) If GCC is not installed, then you will have to install it yourself using the detailed instructions available at https://gcc.gnu.org/install/ If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from Apple's website and follow the simple installation instructions. Xcode is currently available at developer.apple.com/technologies/tools/. To install GCC at Windows you need to install MinGW. To install MinGW, go to the MinGW homepage, www.mingw.org, and follow the link to the MinGW download page. Download the latest version of the MinGW installation program which should be named MinGW-<version>.exe. While installing MinGW, at a minimum, you must install gcc-core, gcc-g++, binutils, and the MinGW runtime, but you may wish to install more. Add the bin subdirectory of your MinGW installation to your PATH environment variable so that you can specify these tools on the command line by their simple names. When the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and several other GNU tools from the Windows command line. 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2442, "s": 2318, "text": "If you are still willing to set up your environment for C++, you need to have the following two softwares on your computer." }, { "code": null, "e": 2586, "s": 2442, "text": "This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi." }, { "code": null, "e": 2769, "s": 2586, "text": "Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows and vim or vi can be used on windows as well as Linux, or UNIX." }, { "code": null, "e": 2905, "s": 2769, "text": "The files you create with your editor are called source files and for C++ they typically are named with the extension .cpp, .cp, or .c." }, { "code": null, "e": 2969, "s": 2905, "text": "A text editor should be in place to start your C++ programming." }, { "code": null, "e": 3079, "s": 2969, "text": "This is an actual C++ compiler, which will be used to compile your source code into final executable program." }, { "code": null, "e": 3221, "s": 3079, "text": "Most C++ compilers don't care what extension you give to your source code, but if you don't specify otherwise, many will use .cpp by default." }, { "code": null, "e": 3398, "s": 3221, "text": "Most frequently used and free available compiler is GNU C/C++ compiler, otherwise you can have compilers either from HP or Solaris if you have the respective Operating Systems." }, { "code": null, "e": 3538, "s": 3398, "text": "If you are using Linux or UNIX then check whether GCC is installed on your system by entering the following command from the command line −" }, { "code": null, "e": 3548, "s": 3538, "text": "$ g++ -v\n" }, { "code": null, "e": 3630, "s": 3548, "text": "If you have installed GCC, then it should print a message such as the following −" }, { "code": null, "e": 3797, "s": 3630, "text": "Using built-in specs.\nTarget: i386-redhat-linux\nConfigured with: ../configure --prefix=/usr .......\nThread model: posix\ngcc version 4.1.2 20080704 (Red Hat 4.1.2-46)\n" }, { "code": null, "e": 3938, "s": 3797, "text": "If GCC is not installed, then you will have to install it yourself using the detailed instructions available at https://gcc.gnu.org/install/" }, { "code": null, "e": 4108, "s": 3938, "text": "If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from Apple's website and follow the simple installation instructions." }, { "code": null, "e": 4181, "s": 4108, "text": "Xcode is currently available at developer.apple.com/technologies/tools/." }, { "code": null, "e": 4446, "s": 4181, "text": "To install GCC at Windows you need to install MinGW. To install MinGW, go to the MinGW homepage, www.mingw.org, and follow the link to the MinGW download page. Download the latest version of the MinGW installation program which should be named MinGW-<version>.exe." }, { "code": null, "e": 4587, "s": 4446, "text": "While installing MinGW, at a minimum, you must install gcc-core, gcc-g++, binutils, and the MinGW runtime, but you may wish to install more." }, { "code": null, "e": 4752, "s": 4587, "text": "Add the bin subdirectory of your MinGW installation to your PATH environment variable so that you can specify these tools on the command line by their simple names." }, { "code": null, "e": 4901, "s": 4752, "text": "When the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and several other GNU tools from the Windows command line." }, { "code": null, "e": 4938, "s": 4901, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 4957, "s": 4938, "text": " Arnab Chakraborty" }, { "code": null, "e": 4989, "s": 4957, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 5012, "s": 4989, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 5048, "s": 5012, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 5065, "s": 5048, "text": " Frahaan Hussain" }, { "code": null, "e": 5100, "s": 5065, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5117, "s": 5100, "text": " Frahaan Hussain" }, { "code": null, "e": 5152, "s": 5117, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5169, "s": 5152, "text": " Frahaan Hussain" }, { "code": null, "e": 5204, "s": 5169, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5221, "s": 5204, "text": " Frahaan Hussain" }, { "code": null, "e": 5228, "s": 5221, "text": " Print" }, { "code": null, "e": 5239, "s": 5228, "text": " Add Notes" } ]
Swap two variables in one line in Java
In order to swap two variable using single expression or in single line we could use bitwise XOR operator of Java. As we now that in Java XOR functions as XOR of two numbers a and b returns a number which has all the bits as 1 wherever bits of a and b differs. So for swapping of two variable we would use this operator as Live Demo public class SwapUsingBitwise { public static void main(String[] args) { int a = 8 ; int b = 10; System.out.println("Before swaping : a = " + a + " b = "+b); a = a^b^(b = a); System.out.println("After swaping : a = "+ a + " b = " + b); } } Before swaping : a = 8 b = 10 After swaping : a = 10 b = 8
[ { "code": null, "e": 1177, "s": 1062, "text": "In order to swap two variable using single expression or in single line we could use bitwise XOR operator of Java." }, { "code": null, "e": 1323, "s": 1177, "text": "As we now that in Java XOR functions as XOR of two numbers a and b returns a number which has all the bits as 1 wherever bits of a and b differs." }, { "code": null, "e": 1385, "s": 1323, "text": "So for swapping of two variable we would use this operator as" }, { "code": null, "e": 1396, "s": 1385, "text": " Live Demo" }, { "code": null, "e": 1667, "s": 1396, "text": "public class SwapUsingBitwise {\n public static void main(String[] args) {\n int a = 8 ; int b = 10;\n System.out.println(\"Before swaping : a = \" + a + \" b = \"+b);\n a = a^b^(b = a);\n System.out.println(\"After swaping : a = \"+ a + \" b = \" + b);\n }\n}" }, { "code": null, "e": 1727, "s": 1667, "text": "Before swaping : a = 8 b = 10\nAfter swaping : a = 10 b = 8\n" } ]
Square every digit of a number - JavaScript
We are required to write a JavaScript function that takes in a number and returns a new number in which all the digits of the original number are squared and concatenated For example: If the number is − 9119 Then the output should be − 811181 because 9^2 is 81 and 1^2 is 1. Following is the code − const num = 9119; const squared = num => { const numStr = String(num); let res = ''; for(let i = 0; i < numStr.length; i++){ const square = Math.pow(+numStr[i], 2); res += square; }; return res; }; console.log(squared(num)); This will produce the following output in console − 811181
[ { "code": null, "e": 1233, "s": 1062, "text": "We are required to write a JavaScript function that takes in a number and returns a new number in which all the digits of the original number are squared and concatenated" }, { "code": null, "e": 1265, "s": 1233, "text": "For example: If the number is −" }, { "code": null, "e": 1270, "s": 1265, "text": "9119" }, { "code": null, "e": 1298, "s": 1270, "text": "Then the output should be −" }, { "code": null, "e": 1305, "s": 1298, "text": "811181" }, { "code": null, "e": 1337, "s": 1305, "text": "because 9^2 is 81 and 1^2 is 1." }, { "code": null, "e": 1361, "s": 1337, "text": "Following is the code −" }, { "code": null, "e": 1613, "s": 1361, "text": "const num = 9119;\nconst squared = num => {\n const numStr = String(num);\n let res = '';\n for(let i = 0; i < numStr.length; i++){\n const square = Math.pow(+numStr[i], 2);\n res += square;\n };\n return res;\n};\nconsole.log(squared(num));" }, { "code": null, "e": 1665, "s": 1613, "text": "This will produce the following output in console −" }, { "code": null, "e": 1672, "s": 1665, "text": "811181" } ]
wprintf() and wscanf in C Library - GeeksforGeeks
19 Dec, 2017 If you are dealing with the wide characters then printf() and scanf() function cannot be used. There are different functions for input and output C wide string. wprintf() : The wprintf() function writes the wide string pointed to by format to stdout. The wide string format may contain format specifiers starting with % which are replaced by the values of variables that are passed to the wprintf() function as additional arguments.Syntax :int wprintf (const wchar_t* format, ...);Parameters :format : A pointer to a null terminated wide string that is written to stdout. It consists of wide characters along with optional format specifiers starting with %. The format specifiers are replaced by the values of respective variables that follows format.... : Other additional arguments specifying the data to be printed. They occur in a sequence according to the format specifier.There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.Return Value :If successful, the wprintf() function returns number of characters written. On failure it returns a negative value. If successful, the wprintf() function returns number of characters written.On failure it returns a negative value.// C Program to show the wprintf () function.#include <stdio.h>#include <wchar.h> // Header file containing wprintf function// Driver codeint main(){ wint_t x = 5; wchar_t name[] = L"GEEKS"; wprintf(L"x = %d \n", x); wprintf(L"HELLO %ls \n", name); return 0;}Output:x = 5 HELLO GEEKS wscanf() : The wscanf() function reads the data from stdin and stores the values into the respective variables. The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier within the format string.Syntax :int wscanf (const wchar_t* format, ...);Parameters :format : Pointer to a null-terminated character string that specifies how to read the input. It consists of format specifiers starting with %. Notice though, that all format specifiers have the same meaning as in scanf; therefore, %lc shall be used to read a wide character (and not %c), as well as %ls shall be used for wide strings (and not %s).... : Other additional arguments for receiving data. They occur in a sequence according to the format specifier.There should be at least as many of these arguments as the number of values stored by the format specifiers. Additional arguments are ignored by the function.Return Value : The wscanf() function returns the number of receiving arguments successfully assigned. We can count and match the expected number of items or be less due to a matching failure, a reading error is occured, or the reach of the end-of-file causes an error.If failure occurs before the first receiving argument was assigned, EOF is returned.// Program to show the wprintf () function.#include <stdio.h>#include <wchar.h> // Header file containing wscanf() functionint main(){ wchar_t str[80]; int i; wscanf(L"%ls", str); wscanf(L"%d", &i); wprintf(L"I am a %ls of CSE in %d year.\n", str, i); return 0;}Input:GEEK 2 Output:I am a GEEK of CSE in 2 year. wprintf() : The wprintf() function writes the wide string pointed to by format to stdout. The wide string format may contain format specifiers starting with % which are replaced by the values of variables that are passed to the wprintf() function as additional arguments.Syntax :int wprintf (const wchar_t* format, ...);Parameters :format : A pointer to a null terminated wide string that is written to stdout. It consists of wide characters along with optional format specifiers starting with %. The format specifiers are replaced by the values of respective variables that follows format.... : Other additional arguments specifying the data to be printed. They occur in a sequence according to the format specifier.There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.Return Value :If successful, the wprintf() function returns number of characters written. On failure it returns a negative value. If successful, the wprintf() function returns number of characters written.On failure it returns a negative value.// C Program to show the wprintf () function.#include <stdio.h>#include <wchar.h> // Header file containing wprintf function// Driver codeint main(){ wint_t x = 5; wchar_t name[] = L"GEEKS"; wprintf(L"x = %d \n", x); wprintf(L"HELLO %ls \n", name); return 0;}Output:x = 5 HELLO GEEKS Syntax : int wprintf (const wchar_t* format, ...); Parameters : format : A pointer to a null terminated wide string that is written to stdout. It consists of wide characters along with optional format specifiers starting with %. The format specifiers are replaced by the values of respective variables that follows format. ... : Other additional arguments specifying the data to be printed. They occur in a sequence according to the format specifier.There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function. Return Value :If successful, the wprintf() function returns number of characters written. On failure it returns a negative value. If successful, the wprintf() function returns number of characters written.On failure it returns a negative value. // C Program to show the wprintf () function.#include <stdio.h>#include <wchar.h> // Header file containing wprintf function// Driver codeint main(){ wint_t x = 5; wchar_t name[] = L"GEEKS"; wprintf(L"x = %d \n", x); wprintf(L"HELLO %ls \n", name); return 0;} Output: x = 5 HELLO GEEKS wscanf() : The wscanf() function reads the data from stdin and stores the values into the respective variables. The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier within the format string.Syntax :int wscanf (const wchar_t* format, ...);Parameters :format : Pointer to a null-terminated character string that specifies how to read the input. It consists of format specifiers starting with %. Notice though, that all format specifiers have the same meaning as in scanf; therefore, %lc shall be used to read a wide character (and not %c), as well as %ls shall be used for wide strings (and not %s).... : Other additional arguments for receiving data. They occur in a sequence according to the format specifier.There should be at least as many of these arguments as the number of values stored by the format specifiers. Additional arguments are ignored by the function.Return Value : The wscanf() function returns the number of receiving arguments successfully assigned. We can count and match the expected number of items or be less due to a matching failure, a reading error is occured, or the reach of the end-of-file causes an error.If failure occurs before the first receiving argument was assigned, EOF is returned.// Program to show the wprintf () function.#include <stdio.h>#include <wchar.h> // Header file containing wscanf() functionint main(){ wchar_t str[80]; int i; wscanf(L"%ls", str); wscanf(L"%d", &i); wprintf(L"I am a %ls of CSE in %d year.\n", str, i); return 0;}Input:GEEK 2 Output:I am a GEEK of CSE in 2 year. Syntax : int wscanf (const wchar_t* format, ...); Parameters : format : Pointer to a null-terminated character string that specifies how to read the input. It consists of format specifiers starting with %. Notice though, that all format specifiers have the same meaning as in scanf; therefore, %lc shall be used to read a wide character (and not %c), as well as %ls shall be used for wide strings (and not %s). ... : Other additional arguments for receiving data. They occur in a sequence according to the format specifier.There should be at least as many of these arguments as the number of values stored by the format specifiers. Additional arguments are ignored by the function. Return Value : The wscanf() function returns the number of receiving arguments successfully assigned. We can count and match the expected number of items or be less due to a matching failure, a reading error is occured, or the reach of the end-of-file causes an error.If failure occurs before the first receiving argument was assigned, EOF is returned. // Program to show the wprintf () function.#include <stdio.h>#include <wchar.h> // Header file containing wscanf() functionint main(){ wchar_t str[80]; int i; wscanf(L"%ls", str); wscanf(L"%d", &i); wprintf(L"I am a %ls of CSE in %d year.\n", str, i); return 0;} Input: GEEK 2 Output: I am a GEEK of CSE in 2 year. C-Library C-String C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C Arrow operator -> in C/C++ with Examples 'this' pointer in C++ How to split a string in C/C++, Python and Java? Smart Pointers in C++ and How to Use Them UDP Server-Client implementation in C How to dynamically allocate a 2D array in C? Unordered Sets in C++ Standard Template Library
[ { "code": null, "e": 23817, "s": 23789, "text": "\n19 Dec, 2017" }, { "code": null, "e": 23978, "s": 23817, "text": "If you are dealing with the wide characters then printf() and scanf() function cannot be used. There are different functions for input and output C wide string." }, { "code": null, "e": 27028, "s": 23978, "text": "wprintf() : The wprintf() function writes the wide string pointed to by format to stdout. The wide string format may contain format specifiers starting with % which are replaced by the values of variables that are passed to the wprintf() function as additional arguments.Syntax :int wprintf (const wchar_t* format, ...);Parameters :format : A pointer to a null terminated wide string that is written to stdout. It consists of wide characters along with optional format specifiers starting with %. The format specifiers are replaced by the values of respective variables that follows format.... : Other additional arguments specifying the data to be printed. They occur in a sequence according to the format specifier.There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.Return Value :If successful, the wprintf() function returns number of characters written. On failure it returns a negative value. If successful, the wprintf() function returns number of characters written.On failure it returns a negative value.// C Program to show the wprintf () function.#include <stdio.h>#include <wchar.h> // Header file containing wprintf function// Driver codeint main(){ wint_t x = 5; wchar_t name[] = L\"GEEKS\"; wprintf(L\"x = %d \\n\", x); wprintf(L\"HELLO %ls \\n\", name); return 0;}Output:x = 5 \nHELLO GEEKS\nwscanf() : The wscanf() function reads the data from stdin and stores the values into the respective variables. The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier within the format string.Syntax :int wscanf (const wchar_t* format, ...);Parameters :format : Pointer to a null-terminated character string that specifies how to read the input. It consists of format specifiers starting with %. Notice though, that all format specifiers have the same meaning as in scanf; therefore, %lc shall be used to read a wide character (and not %c), as well as %ls shall be used for wide strings (and not %s).... : Other additional arguments for receiving data. They occur in a sequence according to the format specifier.There should be at least as many of these arguments as the number of values stored by the format specifiers. Additional arguments are ignored by the function.Return Value : The wscanf() function returns the number of receiving arguments successfully assigned. We can count and match the expected number of items or be less due to a matching failure, a reading error is occured, or the reach of the end-of-file causes an error.If failure occurs before the first receiving argument was assigned, EOF is returned.// Program to show the wprintf () function.#include <stdio.h>#include <wchar.h> // Header file containing wscanf() functionint main(){ wchar_t str[80]; int i; wscanf(L\"%ls\", str); wscanf(L\"%d\", &i); wprintf(L\"I am a %ls of CSE in %d year.\\n\", str, i); return 0;}Input:GEEK\n2\nOutput:I am a GEEK of CSE in 2 year.\n" }, { "code": null, "e": 28451, "s": 27028, "text": "wprintf() : The wprintf() function writes the wide string pointed to by format to stdout. The wide string format may contain format specifiers starting with % which are replaced by the values of variables that are passed to the wprintf() function as additional arguments.Syntax :int wprintf (const wchar_t* format, ...);Parameters :format : A pointer to a null terminated wide string that is written to stdout. It consists of wide characters along with optional format specifiers starting with %. The format specifiers are replaced by the values of respective variables that follows format.... : Other additional arguments specifying the data to be printed. They occur in a sequence according to the format specifier.There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.Return Value :If successful, the wprintf() function returns number of characters written. On failure it returns a negative value. If successful, the wprintf() function returns number of characters written.On failure it returns a negative value.// C Program to show the wprintf () function.#include <stdio.h>#include <wchar.h> // Header file containing wprintf function// Driver codeint main(){ wint_t x = 5; wchar_t name[] = L\"GEEKS\"; wprintf(L\"x = %d \\n\", x); wprintf(L\"HELLO %ls \\n\", name); return 0;}Output:x = 5 \nHELLO GEEKS\n" }, { "code": null, "e": 28460, "s": 28451, "text": "Syntax :" }, { "code": null, "e": 28502, "s": 28460, "text": "int wprintf (const wchar_t* format, ...);" }, { "code": null, "e": 28515, "s": 28502, "text": "Parameters :" }, { "code": null, "e": 28774, "s": 28515, "text": "format : A pointer to a null terminated wide string that is written to stdout. It consists of wide characters along with optional format specifiers starting with %. The format specifiers are replaced by the values of respective variables that follows format." }, { "code": null, "e": 29063, "s": 28774, "text": "... : Other additional arguments specifying the data to be printed. They occur in a sequence according to the format specifier.There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function." }, { "code": null, "e": 29308, "s": 29063, "text": "Return Value :If successful, the wprintf() function returns number of characters written. On failure it returns a negative value. If successful, the wprintf() function returns number of characters written.On failure it returns a negative value." }, { "code": "// C Program to show the wprintf () function.#include <stdio.h>#include <wchar.h> // Header file containing wprintf function// Driver codeint main(){ wint_t x = 5; wchar_t name[] = L\"GEEKS\"; wprintf(L\"x = %d \\n\", x); wprintf(L\"HELLO %ls \\n\", name); return 0;}", "e": 29583, "s": 29308, "text": null }, { "code": null, "e": 29591, "s": 29583, "text": "Output:" }, { "code": null, "e": 29611, "s": 29591, "text": "x = 5 \nHELLO GEEKS\n" }, { "code": null, "e": 31239, "s": 29611, "text": "wscanf() : The wscanf() function reads the data from stdin and stores the values into the respective variables. The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier within the format string.Syntax :int wscanf (const wchar_t* format, ...);Parameters :format : Pointer to a null-terminated character string that specifies how to read the input. It consists of format specifiers starting with %. Notice though, that all format specifiers have the same meaning as in scanf; therefore, %lc shall be used to read a wide character (and not %c), as well as %ls shall be used for wide strings (and not %s).... : Other additional arguments for receiving data. They occur in a sequence according to the format specifier.There should be at least as many of these arguments as the number of values stored by the format specifiers. Additional arguments are ignored by the function.Return Value : The wscanf() function returns the number of receiving arguments successfully assigned. We can count and match the expected number of items or be less due to a matching failure, a reading error is occured, or the reach of the end-of-file causes an error.If failure occurs before the first receiving argument was assigned, EOF is returned.// Program to show the wprintf () function.#include <stdio.h>#include <wchar.h> // Header file containing wscanf() functionint main(){ wchar_t str[80]; int i; wscanf(L\"%ls\", str); wscanf(L\"%d\", &i); wprintf(L\"I am a %ls of CSE in %d year.\\n\", str, i); return 0;}Input:GEEK\n2\nOutput:I am a GEEK of CSE in 2 year.\n" }, { "code": null, "e": 31248, "s": 31239, "text": "Syntax :" }, { "code": null, "e": 31289, "s": 31248, "text": "int wscanf (const wchar_t* format, ...);" }, { "code": null, "e": 31302, "s": 31289, "text": "Parameters :" }, { "code": null, "e": 31650, "s": 31302, "text": "format : Pointer to a null-terminated character string that specifies how to read the input. It consists of format specifiers starting with %. Notice though, that all format specifiers have the same meaning as in scanf; therefore, %lc shall be used to read a wide character (and not %c), as well as %ls shall be used for wide strings (and not %s)." }, { "code": null, "e": 31921, "s": 31650, "text": "... : Other additional arguments for receiving data. They occur in a sequence according to the format specifier.There should be at least as many of these arguments as the number of values stored by the format specifiers. Additional arguments are ignored by the function." }, { "code": null, "e": 32274, "s": 31921, "text": "Return Value : The wscanf() function returns the number of receiving arguments successfully assigned. We can count and match the expected number of items or be less due to a matching failure, a reading error is occured, or the reach of the end-of-file causes an error.If failure occurs before the first receiving argument was assigned, EOF is returned." }, { "code": "// Program to show the wprintf () function.#include <stdio.h>#include <wchar.h> // Header file containing wscanf() functionint main(){ wchar_t str[80]; int i; wscanf(L\"%ls\", str); wscanf(L\"%d\", &i); wprintf(L\"I am a %ls of CSE in %d year.\\n\", str, i); return 0;}", "e": 32557, "s": 32274, "text": null }, { "code": null, "e": 32564, "s": 32557, "text": "Input:" }, { "code": null, "e": 32572, "s": 32564, "text": "GEEK\n2\n" }, { "code": null, "e": 32580, "s": 32572, "text": "Output:" }, { "code": null, "e": 32611, "s": 32580, "text": "I am a GEEK of CSE in 2 year.\n" }, { "code": null, "e": 32621, "s": 32611, "text": "C-Library" }, { "code": null, "e": 32630, "s": 32621, "text": "C-String" }, { "code": null, "e": 32641, "s": 32630, "text": "C Language" }, { "code": null, "e": 32739, "s": 32641, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32748, "s": 32739, "text": "Comments" }, { "code": null, "e": 32761, "s": 32748, "text": "Old Comments" }, { "code": null, "e": 32799, "s": 32761, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 32825, "s": 32799, "text": "Exception Handling in C++" }, { "code": null, "e": 32845, "s": 32825, "text": "Multithreading in C" }, { "code": null, "e": 32886, "s": 32845, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 32908, "s": 32886, "text": "'this' pointer in C++" }, { "code": null, "e": 32957, "s": 32908, "text": "How to split a string in C/C++, Python and Java?" }, { "code": null, "e": 32999, "s": 32957, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 33037, "s": 32999, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 33082, "s": 33037, "text": "How to dynamically allocate a 2D array in C?" } ]