title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to Insert Records to a Table using JDBC Connection? - GeeksforGeeks
20 Nov, 2020 Before inserting contents in a table we need to connect our java application to our database. Java has its own API which JDBC API which uses JDBC drivers for database connections. Before JDBC, ODBC API was used but it was written in C which means it was platform-dependent. JDBC API provides the applications-to-JDBC connection and JDBC driver provides a manager-to-driver connection. Steps for connectivity between Java program and database 1. Loading the Driver: To begin with, you first need to load the driver or register it before using it in the program. Registration is to be done once in your program. You can register a driver in one of the two ways mentioned below: Class.forName(): Here we load the driver’s class file into memory at the runtime. No need of using new or creation of an object. The following example uses Class.forName() to load the Oracle driver – Class.forName(“oracle.jdbc.driver.OracleDriver”); DriverManager.registerDriver(): DriverManager is a Java inbuilt class with a static member register. Here we call the constructor of the driver class at compile time. The following example uses DriverManager.registerDriver()to register the Oracle driver – DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()) 2. Create the connections: After loading the driver, establish connections using: Connection con = DriverManager.getConnection(url,user,password) User: username from which your SQL command prompt can be accessed.Password: password from which your SQL command prompt can be accessed. con: is a reference to Connection interface.url : Uniform Resource Locator. It can be created as follows: String url = “ jdbc:oracle:thin:@localhost:1521:xe” Where oracle is the database used, thin is the driver used, @localhost is the IP Address where the database is stored, 1521 is the port number and xe is the service provider. All 3 parameters above are of String type and are to be declared by the programmer before calling the function. Use of this can be referred from the final code. 3. Create a statement: Once a connection is established you can interact with the database. The JDBCStatement, CallableStatement, and PreparedStatement interfaces define the methods that enable you to send SQL commands and receive data from your database. Use of JDBC Statement is as follows: Statement st = con.createStatement(); Here, con is a reference to Connection interface used in the previous step. 4. Execute the query: Now comes the most important part of executing the query. The query here is an SQL Query. Now we know we can have multiple types of queries. Some of them are as follows: Query for updating/inserting table in a database. Query for retrieving data. The executeQuery() method of Statement interface is used to execute queries of retrieving values from the database. This method returns the object of ResultSet that can be used to get all the records of a table.The executeUpdate(SQL query) method of statement interface is used to execute queries of updating/inserting. Example: int m = st.executeUpdate(sql); if (m==1) System.out.println("inserted successfully : "+sql); else System.out.println("insertion failed"); Here SQL is SQL query of the type String 5. Close the connections: So finally we have sent the data to the specified location and now we are on the verge of completion of our task. By closing the connection, objects of Statement and ResultSet will be closed automatically. The close() method of the Connection interface is used to close the connection. Example: con.close(); Java // Java program to insert records to a table using JDBC import java.io.*;import java.sql.*; public class Database { // url that points to mysql database, 'db' is database // name static final String url = "jdbc:mysql://localhost:3306/db"; public static void main(String[] args) throws ClassNotFoundException { try { // this Class.forName() method is user for // driver registration with name of the driver // as argument // we have used MySQL driver Class.forName("com.mysql.jdbc.Driver"); // getConnection() establishes a connection. It // takes url that points to your database, // username and password of MySQL connections as // arguments Connection conn = DriverManager.getConnection( url, "root", "1234"); // create.Statement() creates statement object // which is responsible for executing queries on // table Statement stmt = conn.createStatement(); // executeUpdate() is used for INSERT, UPDATE, // DELETE statements.It returns number of rows // affected by the execution of the statement int result = stmt.executeUpdate( "insert into student(Id,name,number) values('1','rachel','45')"); // if result is greater than 0, it means values // has been added if (result > 0) System.out.println("successfully inserted"); else System.out.println( "unsucessful insertion "); // closing connection conn.close(); } catch (SQLException e) { System.out.println(e); } }} Driver, DriverManager(), Connection(), Statement(), Resultset() are classes provided by JDBC API. If insertion is successful output will be: Successfully inserted If insertion is not successful output will be: unsuccessful insertion JDBC Picked Technical Scripter 2020 Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java
[ { "code": null, "e": 26017, "s": 25989, "text": "\n20 Nov, 2020" }, { "code": null, "e": 26402, "s": 26017, "text": "Before inserting contents in a table we need to connect our java application to our database. Java has its own API which JDBC API which uses JDBC drivers for database connections. Before JDBC, ODBC API was used but it was written in C which means it was platform-dependent. JDBC API provides the applications-to-JDBC connection and JDBC driver provides a manager-to-driver connection." }, { "code": null, "e": 26459, "s": 26402, "text": "Steps for connectivity between Java program and database" }, { "code": null, "e": 26693, "s": 26459, "text": "1. Loading the Driver: To begin with, you first need to load the driver or register it before using it in the program. Registration is to be done once in your program. You can register a driver in one of the two ways mentioned below:" }, { "code": null, "e": 26893, "s": 26693, "text": "Class.forName(): Here we load the driver’s class file into memory at the runtime. No need of using new or creation of an object. The following example uses Class.forName() to load the Oracle driver –" }, { "code": null, "e": 26944, "s": 26893, "text": "Class.forName(“oracle.jdbc.driver.OracleDriver”);\n" }, { "code": null, "e": 27200, "s": 26944, "text": "DriverManager.registerDriver(): DriverManager is a Java inbuilt class with a static member register. Here we call the constructor of the driver class at compile time. The following example uses DriverManager.registerDriver()to register the Oracle driver –" }, { "code": null, "e": 27269, "s": 27200, "text": "DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())\n" }, { "code": null, "e": 27351, "s": 27269, "text": "2. Create the connections: After loading the driver, establish connections using:" }, { "code": null, "e": 27416, "s": 27351, "text": "Connection con = DriverManager.getConnection(url,user,password)\n" }, { "code": null, "e": 27553, "s": 27416, "text": "User: username from which your SQL command prompt can be accessed.Password: password from which your SQL command prompt can be accessed." }, { "code": null, "e": 27659, "s": 27553, "text": "con: is a reference to Connection interface.url : Uniform Resource Locator. It can be created as follows:" }, { "code": null, "e": 27712, "s": 27659, "text": "String url = “ jdbc:oracle:thin:@localhost:1521:xe”\n" }, { "code": null, "e": 28048, "s": 27712, "text": "Where oracle is the database used, thin is the driver used, @localhost is the IP Address where the database is stored, 1521 is the port number and xe is the service provider. All 3 parameters above are of String type and are to be declared by the programmer before calling the function. Use of this can be referred from the final code." }, { "code": null, "e": 28304, "s": 28048, "text": "3. Create a statement: Once a connection is established you can interact with the database. The JDBCStatement, CallableStatement, and PreparedStatement interfaces define the methods that enable you to send SQL commands and receive data from your database." }, { "code": null, "e": 28341, "s": 28304, "text": "Use of JDBC Statement is as follows:" }, { "code": null, "e": 28380, "s": 28341, "text": "Statement st = con.createStatement();\n" }, { "code": null, "e": 28456, "s": 28380, "text": "Here, con is a reference to Connection interface used in the previous step." }, { "code": null, "e": 28648, "s": 28456, "text": "4. Execute the query: Now comes the most important part of executing the query. The query here is an SQL Query. Now we know we can have multiple types of queries. Some of them are as follows:" }, { "code": null, "e": 28698, "s": 28648, "text": "Query for updating/inserting table in a database." }, { "code": null, "e": 28725, "s": 28698, "text": "Query for retrieving data." }, { "code": null, "e": 29045, "s": 28725, "text": "The executeQuery() method of Statement interface is used to execute queries of retrieving values from the database. This method returns the object of ResultSet that can be used to get all the records of a table.The executeUpdate(SQL query) method of statement interface is used to execute queries of updating/inserting." }, { "code": null, "e": 29054, "s": 29045, "text": "Example:" }, { "code": null, "e": 29201, "s": 29054, "text": "int m = st.executeUpdate(sql);\nif (m==1)\n System.out.println(\"inserted successfully : \"+sql);\nelse\n System.out.println(\"insertion failed\");\n" }, { "code": null, "e": 29242, "s": 29201, "text": "Here SQL is SQL query of the type String" }, { "code": null, "e": 29554, "s": 29242, "text": "5. Close the connections: So finally we have sent the data to the specified location and now we are on the verge of completion of our task. By closing the connection, objects of Statement and ResultSet will be closed automatically. The close() method of the Connection interface is used to close the connection." }, { "code": null, "e": 29563, "s": 29554, "text": "Example:" }, { "code": null, "e": 29577, "s": 29563, "text": "con.close();\n" }, { "code": null, "e": 29582, "s": 29577, "text": "Java" }, { "code": "// Java program to insert records to a table using JDBC import java.io.*;import java.sql.*; public class Database { // url that points to mysql database, 'db' is database // name static final String url = \"jdbc:mysql://localhost:3306/db\"; public static void main(String[] args) throws ClassNotFoundException { try { // this Class.forName() method is user for // driver registration with name of the driver // as argument // we have used MySQL driver Class.forName(\"com.mysql.jdbc.Driver\"); // getConnection() establishes a connection. It // takes url that points to your database, // username and password of MySQL connections as // arguments Connection conn = DriverManager.getConnection( url, \"root\", \"1234\"); // create.Statement() creates statement object // which is responsible for executing queries on // table Statement stmt = conn.createStatement(); // executeUpdate() is used for INSERT, UPDATE, // DELETE statements.It returns number of rows // affected by the execution of the statement int result = stmt.executeUpdate( \"insert into student(Id,name,number) values('1','rachel','45')\"); // if result is greater than 0, it means values // has been added if (result > 0) System.out.println(\"successfully inserted\"); else System.out.println( \"unsucessful insertion \"); // closing connection conn.close(); } catch (SQLException e) { System.out.println(e); } }}", "e": 31385, "s": 29582, "text": null }, { "code": null, "e": 31485, "s": 31385, "text": "Driver, DriverManager(), Connection(), Statement(), Resultset() are classes provided by JDBC API. " }, { "code": null, "e": 31551, "s": 31485, "text": "If insertion is successful output will be: Successfully inserted " }, { "code": null, "e": 31621, "s": 31551, "text": "If insertion is not successful output will be: unsuccessful insertion" }, { "code": null, "e": 31626, "s": 31621, "text": "JDBC" }, { "code": null, "e": 31633, "s": 31626, "text": "Picked" }, { "code": null, "e": 31657, "s": 31633, "text": "Technical Scripter 2020" }, { "code": null, "e": 31662, "s": 31657, "text": "Java" }, { "code": null, "e": 31681, "s": 31662, "text": "Technical Scripter" }, { "code": null, "e": 31686, "s": 31681, "text": "Java" }, { "code": null, "e": 31784, "s": 31686, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31835, "s": 31784, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 31865, "s": 31835, "text": "HashMap in Java with Examples" }, { "code": null, "e": 31880, "s": 31865, "text": "Stream In Java" }, { "code": null, "e": 31899, "s": 31880, "text": "Interfaces in Java" }, { "code": null, "e": 31930, "s": 31899, "text": "How to iterate any Map in Java" }, { "code": null, "e": 31948, "s": 31930, "text": "ArrayList in Java" }, { "code": null, "e": 31980, "s": 31948, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 32000, "s": 31980, "text": "Stack Class in Java" }, { "code": null, "e": 32024, "s": 32000, "text": "Singleton Class in Java" } ]
TCS Digital Interview Experience (On-Campus) - GeeksforGeeks
13 Jan, 2022 Company – TCS (Digital Profile) Job Profile – System Engineer Eligibility: All Branches B.Tech, M.Tech % in X and XII – 60% or 6.0 CGPA In Pursuing Degree – 70% or 7.0 CGPA In UG (for PGs) – 60% or 6.0 CGPA Round 1(Aptitude Test): It was divided into two parts and was held in two days. First day it was Aptitude test which consisted of Quantitative Aptitude and Verbal Ability (Easy-Medium Level questions in both sections) Next day was Coding Round. It consisted of two easy-medium level questions to be done in 60 minutes on TCS Platform Description: Given 3 mechanical gears that are connected to each other Find out how many times Gear3 will rotate given the radius of all 3 gears and the number of times Gear1 is rotated Time Limit: 1sec Sample Test Case: Input: 1 10 1 100 Output: 100 Explanation: Given R1=1, R2=10, R3=1 So, if we rotate Gear1 100 times, Gear3 will rotate 100 times Description: A security Company sends and receives the location coordinates in an encrypted manner. The encrypted coordinates will be in form of two strings, one will be the latitude and other longitudes Decryption rules as follows: The last character of encrypted string denotes the direction latitude string(only two [n-North, s-South]) longitude string(other two [e-East, w-West])Except last character the string denotes integer value irrespective of whether it is a latitude string or longitude string The Integer part of the coordinate can be decoded as (Count of letter with maximum occurrences – Count of letter with minimum occurrences in string)All letters are in lower case The last character of encrypted string denotes the direction latitude string(only two [n-North, s-South]) longitude string(other two [e-East, w-West]) Except last character the string denotes integer value irrespective of whether it is a latitude string or longitude string The Integer part of the coordinate can be decoded as (Count of letter with maximum occurrences – Count of letter with minimum occurrences in string) All letters are in lower case Time Limit: 1sec Constraints : 4 <length of string <= 1000 Sample Test case : Input: babbeddcs aeeaecacw Output: 2 South 1 West Around 610 students shortlisted for Interview round from 5010 students from our college Round 2(Interview): There was only 1 round of interview which is comprised of Technical+Managerial+HR and 3 different members were in the panel . Firstly they asked to introduce myself and explain about my projects. First person(Technical Interviewer) asked me which language I am comfortable with and I replied “JAVA” Asked why JAVA and asked to explain OOP’s Concepts in java, asked to explain Fibonacci series code using different approaches. Then Asked about SQL (types of Joins, types of Normalizations, ACID properties) and then asked me to share the screen and given 2 SQL queries which are related to JOINS concepts asked to write the code for them and I have written both. Then Second Person(Managerial Interviewer) asked about recent project I have done and I have explained about one of the Machine Learning project I have done then he asked some basic questions related to ML. Then asked some basic questions related to Python (key features of python, list vs tuple, Why it is Interpreted Language). Then Started asking Situation and Behavioural type of questions like how do you handle pressure(Explain with situation), If one of your teammates dumps all of his work on you how would you react to that situation, how do you handle conflicts with coworkers, What makes you different from all other people in this panel for hiring you. Then third person asked some standard HR type questions like: Are you comfortable working with shifts? Are you comfortable with relocation? Do you have any history of arrears/backlogs? Do you have any education gap? Have you maintained 7.0 CGPA and above in all Semesters Why would you like to join TCS? INTERVIEW ENDS The Interview lasted for 45-50 minutes After 20 days the results were announced, 160 students out of 610 from our college got selected and I was one of them. Tips: Keep your basics strong Try to be confident and keep smiling The interviewer focuses on whatever written in the Resume, so try to be honest with it. As it is a Digital Profile, Interviewer expects basic knowledge on any Latest Technologies like ML/AI, IoT, Cloud Computing etc, so please be prepared for that. Marketing On-Campus TCS TCS Digital TCS-interview-experience Interview Experiences TCS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE-1 (Off-Campus) Amazon AWS Interview Experience for SDE-1 Difference between ANN, CNN and RNN Amazon Interview Experience for SDE-1 (Off-Campus) 2022 Amazon Interview Experience Amazon Interview Experience for SDE-1 EPAM Interview Experience (Off-Campus) Amazon Interview Experience (Off-Campus) 2022 JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021 Amazon Interview Experience for SDE-1 (On-Campus)
[ { "code": null, "e": 26125, "s": 26097, "text": "\n13 Jan, 2022" }, { "code": null, "e": 26157, "s": 26125, "text": "Company – TCS (Digital Profile)" }, { "code": null, "e": 26187, "s": 26157, "text": "Job Profile – System Engineer" }, { "code": null, "e": 26203, "s": 26187, "text": "Eligibility: " }, { "code": null, "e": 26232, "s": 26203, "text": "All Branches B.Tech, M.Tech " }, { "code": null, "e": 26265, "s": 26232, "text": "% in X and XII – 60% or 6.0 CGPA" }, { "code": null, "e": 26302, "s": 26265, "text": "In Pursuing Degree – 70% or 7.0 CGPA" }, { "code": null, "e": 26336, "s": 26302, "text": "In UG (for PGs) – 60% or 6.0 CGPA" }, { "code": null, "e": 26360, "s": 26336, "text": "Round 1(Aptitude Test):" }, { "code": null, "e": 26555, "s": 26360, "text": "It was divided into two parts and was held in two days. First day it was Aptitude test which consisted of Quantitative Aptitude and Verbal Ability (Easy-Medium Level questions in both sections)" }, { "code": null, "e": 26671, "s": 26555, "text": "Next day was Coding Round. It consisted of two easy-medium level questions to be done in 60 minutes on TCS Platform" }, { "code": null, "e": 26861, "s": 26671, "text": "Description: Given 3 mechanical gears that are connected to each other Find out how many times Gear3 will rotate given the radius of all 3 gears and the number of times Gear1 is rotated " }, { "code": null, "e": 26878, "s": 26861, "text": "Time Limit: 1sec" }, { "code": null, "e": 26897, "s": 26878, "text": "Sample Test Case: " }, { "code": null, "e": 27032, "s": 26897, "text": "Input: \n1 10 1\n100\nOutput: \n100\nExplanation: \nGiven R1=1, R2=10, R3=1 \nSo, if we rotate Gear1 100 times, \nGear3 will rotate 100 times" }, { "code": null, "e": 27236, "s": 27032, "text": "Description: A security Company sends and receives the location coordinates in an encrypted manner. The encrypted coordinates will be in form of two strings, one will be the latitude and other longitudes" }, { "code": null, "e": 27265, "s": 27236, "text": "Decryption rules as follows:" }, { "code": null, "e": 27719, "s": 27265, "text": "The last character of encrypted string denotes the direction latitude string(only two [n-North, s-South]) longitude string(other two [e-East, w-West])Except last character the string denotes integer value irrespective of whether it is a latitude string or longitude string The Integer part of the coordinate can be decoded as (Count of letter with maximum occurrences – Count of letter with minimum occurrences in string)All letters are in lower case" }, { "code": null, "e": 27871, "s": 27719, "text": "The last character of encrypted string denotes the direction latitude string(only two [n-North, s-South]) longitude string(other two [e-East, w-West])" }, { "code": null, "e": 27997, "s": 27871, "text": "Except last character the string denotes integer value irrespective of whether it is a latitude string or longitude string " }, { "code": null, "e": 28146, "s": 27997, "text": "The Integer part of the coordinate can be decoded as (Count of letter with maximum occurrences – Count of letter with minimum occurrences in string)" }, { "code": null, "e": 28176, "s": 28146, "text": "All letters are in lower case" }, { "code": null, "e": 28193, "s": 28176, "text": "Time Limit: 1sec" }, { "code": null, "e": 28235, "s": 28193, "text": "Constraints : 4 <length of string <= 1000" }, { "code": null, "e": 28255, "s": 28235, "text": "Sample Test case : " }, { "code": null, "e": 28309, "s": 28255, "text": "Input: \nbabbeddcs\naeeaecacw\nOutput: \n2 South 1 West" }, { "code": null, "e": 28397, "s": 28309, "text": "Around 610 students shortlisted for Interview round from 5010 students from our college" }, { "code": null, "e": 28544, "s": 28397, "text": "Round 2(Interview): There was only 1 round of interview which is comprised of Technical+Managerial+HR and 3 different members were in the panel ." }, { "code": null, "e": 28614, "s": 28544, "text": "Firstly they asked to introduce myself and explain about my projects." }, { "code": null, "e": 28845, "s": 28614, "text": "First person(Technical Interviewer) asked me which language I am comfortable with and I replied “JAVA” Asked why JAVA and asked to explain OOP’s Concepts in java, asked to explain Fibonacci series code using different approaches. " }, { "code": null, "e": 29081, "s": 28845, "text": "Then Asked about SQL (types of Joins, types of Normalizations, ACID properties) and then asked me to share the screen and given 2 SQL queries which are related to JOINS concepts asked to write the code for them and I have written both." }, { "code": null, "e": 29289, "s": 29081, "text": "Then Second Person(Managerial Interviewer) asked about recent project I have done and I have explained about one of the Machine Learning project I have done then he asked some basic questions related to ML. " }, { "code": null, "e": 29413, "s": 29289, "text": "Then asked some basic questions related to Python (key features of python, list vs tuple, Why it is Interpreted Language). " }, { "code": null, "e": 29748, "s": 29413, "text": "Then Started asking Situation and Behavioural type of questions like how do you handle pressure(Explain with situation), If one of your teammates dumps all of his work on you how would you react to that situation, how do you handle conflicts with coworkers, What makes you different from all other people in this panel for hiring you." }, { "code": null, "e": 29810, "s": 29748, "text": "Then third person asked some standard HR type questions like:" }, { "code": null, "e": 29851, "s": 29810, "text": "Are you comfortable working with shifts?" }, { "code": null, "e": 29888, "s": 29851, "text": "Are you comfortable with relocation?" }, { "code": null, "e": 29933, "s": 29888, "text": "Do you have any history of arrears/backlogs?" }, { "code": null, "e": 29964, "s": 29933, "text": "Do you have any education gap?" }, { "code": null, "e": 30020, "s": 29964, "text": "Have you maintained 7.0 CGPA and above in all Semesters" }, { "code": null, "e": 30053, "s": 30020, "text": "Why would you like to join TCS? " }, { "code": null, "e": 30068, "s": 30053, "text": "INTERVIEW ENDS" }, { "code": null, "e": 30107, "s": 30068, "text": "The Interview lasted for 45-50 minutes" }, { "code": null, "e": 30226, "s": 30107, "text": "After 20 days the results were announced, 160 students out of 610 from our college got selected and I was one of them." }, { "code": null, "e": 30232, "s": 30226, "text": "Tips:" }, { "code": null, "e": 30256, "s": 30232, "text": "Keep your basics strong" }, { "code": null, "e": 30293, "s": 30256, "text": "Try to be confident and keep smiling" }, { "code": null, "e": 30381, "s": 30293, "text": "The interviewer focuses on whatever written in the Resume, so try to be honest with it." }, { "code": null, "e": 30542, "s": 30381, "text": "As it is a Digital Profile, Interviewer expects basic knowledge on any Latest Technologies like ML/AI, IoT, Cloud Computing etc, so please be prepared for that." }, { "code": null, "e": 30569, "s": 30559, "text": "Marketing" }, { "code": null, "e": 30579, "s": 30569, "text": "On-Campus" }, { "code": null, "e": 30583, "s": 30579, "text": "TCS" }, { "code": null, "e": 30595, "s": 30583, "text": "TCS Digital" }, { "code": null, "e": 30620, "s": 30595, "text": "TCS-interview-experience" }, { "code": null, "e": 30642, "s": 30620, "text": "Interview Experiences" }, { "code": null, "e": 30646, "s": 30642, "text": "TCS" }, { "code": null, "e": 30744, "s": 30646, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30795, "s": 30744, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 30837, "s": 30795, "text": "Amazon AWS Interview Experience for SDE-1" }, { "code": null, "e": 30873, "s": 30837, "text": "Difference between ANN, CNN and RNN" }, { "code": null, "e": 30929, "s": 30873, "text": "Amazon Interview Experience for SDE-1 (Off-Campus) 2022" }, { "code": null, "e": 30957, "s": 30929, "text": "Amazon Interview Experience" }, { "code": null, "e": 30995, "s": 30957, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 31034, "s": 30995, "text": "EPAM Interview Experience (Off-Campus)" }, { "code": null, "e": 31080, "s": 31034, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 31152, "s": 31080, "text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021" } ]
How to use useMediaQuery Component in ReactJS ? - GeeksforGeeks
13 Apr, 2021 The useMediaQuery Component is a CSS media query hook for React. Using this functionality, we can write our own CSS media query for which this function looks for a match, and it renders if the query matches. Material UI for React has this component available for us, and it is very easy to integrate. We can use the following approach in ReactJS to use useMediaQuery Component. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the material-ui module using the following command:npm install @material-ui/core/useMediaQueryProject Structure: It will look like the following.Project StructureExample: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.App.jsApp.jsimport React from 'react';import useMediaQuery from '@material-ui/core/useMediaQuery'; export default function App() { const ourMediaQuery = useMediaQuery('(min-width:400px)'); return ( <div style={{ display: 'block'}}> <h4>How to use useMediaQuery Component in ReactJS?</h4> <span>{`Is Screen at Minimum 400px: ${ourMediaQuery}`}</span> </div> );}Step to Run Application: Run the application using the following command from the root directory of the project:npm startOutput: Now open your browser and go to http://localhost:3000/, you will see the following output:Reference: https://material-ui.com/components/use-media-query/My Personal Notes arrow_drop_upSave Step 3: After creating the ReactJS application, Install the material-ui module using the following command: npm install @material-ui/core/useMediaQuery Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react';import useMediaQuery from '@material-ui/core/useMediaQuery'; export default function App() { const ourMediaQuery = useMediaQuery('(min-width:400px)'); return ( <div style={{ display: 'block'}}> <h4>How to use useMediaQuery Component in ReactJS?</h4> <span>{`Is Screen at Minimum 400px: ${ourMediaQuery}`}</span> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://material-ui.com/components/use-media-query/ Material-UI ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ReactJS useNavigate() Hook How to set background images in ReactJS ? Axios in React: A Guide for Beginners How to create a table in ReactJS ? How to navigate on path by button click in react router ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26071, "s": 26043, "text": "\n13 Apr, 2021" }, { "code": null, "e": 26449, "s": 26071, "text": "The useMediaQuery Component is a CSS media query hook for React. Using this functionality, we can write our own CSS media query for which this function looks for a match, and it renders if the query matches. Material UI for React has this component available for us, and it is very easy to integrate. We can use the following approach in ReactJS to use useMediaQuery Component." }, { "code": null, "e": 26499, "s": 26449, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 26594, "s": 26499, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 26658, "s": 26594, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 26690, "s": 26658, "text": "npx create-react-app foldername" }, { "code": null, "e": 26803, "s": 26690, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 26903, "s": 26803, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 26917, "s": 26903, "text": "cd foldername" }, { "code": null, "e": 27961, "s": 26917, "text": "Step 3: After creating the ReactJS application, Install the material-ui module using the following command:npm install @material-ui/core/useMediaQueryProject Structure: It will look like the following.Project StructureExample: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.App.jsApp.jsimport React from 'react';import useMediaQuery from '@material-ui/core/useMediaQuery'; export default function App() { const ourMediaQuery = useMediaQuery('(min-width:400px)'); return ( <div style={{ display: 'block'}}> <h4>How to use useMediaQuery Component in ReactJS?</h4> <span>{`Is Screen at Minimum 400px: ${ourMediaQuery}`}</span> </div> );}Step to Run Application: Run the application using the following command from the root directory of the project:npm startOutput: Now open your browser and go to http://localhost:3000/, you will see the following output:Reference: https://material-ui.com/components/use-media-query/My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 28069, "s": 27961, "text": "Step 3: After creating the ReactJS application, Install the material-ui module using the following command:" }, { "code": null, "e": 28113, "s": 28069, "text": "npm install @material-ui/core/useMediaQuery" }, { "code": null, "e": 28165, "s": 28113, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 28183, "s": 28165, "text": "Project Structure" }, { "code": null, "e": 28313, "s": 28183, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 28320, "s": 28313, "text": "App.js" }, { "code": "import React from 'react';import useMediaQuery from '@material-ui/core/useMediaQuery'; export default function App() { const ourMediaQuery = useMediaQuery('(min-width:400px)'); return ( <div style={{ display: 'block'}}> <h4>How to use useMediaQuery Component in ReactJS?</h4> <span>{`Is Screen at Minimum 400px: ${ourMediaQuery}`}</span> </div> );}", "e": 28689, "s": 28320, "text": null }, { "code": null, "e": 28802, "s": 28689, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 28812, "s": 28802, "text": "npm start" }, { "code": null, "e": 28911, "s": 28812, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 28974, "s": 28911, "text": "Reference: https://material-ui.com/components/use-media-query/" }, { "code": null, "e": 28986, "s": 28974, "text": "Material-UI" }, { "code": null, "e": 28994, "s": 28986, "text": "ReactJS" }, { "code": null, "e": 29011, "s": 28994, "text": "Web Technologies" }, { "code": null, "e": 29109, "s": 29011, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29136, "s": 29109, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 29178, "s": 29136, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 29216, "s": 29178, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 29251, "s": 29216, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 29309, "s": 29251, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 29349, "s": 29309, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29382, "s": 29349, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29427, "s": 29382, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29477, "s": 29427, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to detect operating system on the client machine using JavaScript ? - GeeksforGeeks
16 Aug, 2019 To detect the operating system on the client machine, one can simply use navigator.appVersion or navigator.userAgent property.The Navigator appVersion property is a read-only property and it returns a string which represents the version information of the browser. Syntax navigator.appVersion Example 1: This example uses navigator.appVersion property to display the operating system name. <!DOCTYPE html> <html> <head> <title> How to detect operating system on the client machine using JavaScript ? </title></head> <body style="text-align:center;"> <h1 style="color:green;">GeeksforGeeks</h1> <button ondblclick="operatingSytem()"> Return Operating System Name </button> <p id="OS"></p> <!-- Script to display the OS name --> <script> function operatingSytem() { var OSName="Unknown OS"; if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows"; if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS"; if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX"; if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux"; // Display the OS name document.getElementById("OS").innerHTML = OSName; } </script> </body> </html> Output: Before Click on the Button: After Click on the Button: Example 2: This example uses navigator.appVersion property to display all the properties of the client machine. <!DOCTYPE html> <html> <head> <title> How to detect operating system on the client machine using JavaScript ? </title></head> <body style="text-align:center;"> <h1 style="color:green;">GeeksforGeeks</h1> <button ondblclick="version()"> Return OS Version </button> <p id="OS"></p> <!-- Script to return OS details --> <script> function version() { var os = navigator.appVersion; // Display the OS details document.getElementById("OS").innerHTML = os; } </script> </body> </html> Output: Before Click on the Button: After Click on the Button: JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26102, "s": 26074, "text": "\n16 Aug, 2019" }, { "code": null, "e": 26367, "s": 26102, "text": "To detect the operating system on the client machine, one can simply use navigator.appVersion or navigator.userAgent property.The Navigator appVersion property is a read-only property and it returns a string which represents the version information of the browser." }, { "code": null, "e": 26374, "s": 26367, "text": "Syntax" }, { "code": null, "e": 26395, "s": 26374, "text": "navigator.appVersion" }, { "code": null, "e": 26492, "s": 26395, "text": "Example 1: This example uses navigator.appVersion property to display the operating system name." }, { "code": "<!DOCTYPE html> <html> <head> <title> How to detect operating system on the client machine using JavaScript ? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\">GeeksforGeeks</h1> <button ondblclick=\"operatingSytem()\"> Return Operating System Name </button> <p id=\"OS\"></p> <!-- Script to display the OS name --> <script> function operatingSytem() { var OSName=\"Unknown OS\"; if (navigator.appVersion.indexOf(\"Win\")!=-1) OSName=\"Windows\"; if (navigator.appVersion.indexOf(\"Mac\")!=-1) OSName=\"MacOS\"; if (navigator.appVersion.indexOf(\"X11\")!=-1) OSName=\"UNIX\"; if (navigator.appVersion.indexOf(\"Linux\")!=-1) OSName=\"Linux\"; // Display the OS name document.getElementById(\"OS\").innerHTML = OSName; } </script> </body> </html>", "e": 27422, "s": 26492, "text": null }, { "code": null, "e": 27430, "s": 27422, "text": "Output:" }, { "code": null, "e": 27458, "s": 27430, "text": "Before Click on the Button:" }, { "code": null, "e": 27485, "s": 27458, "text": "After Click on the Button:" }, { "code": null, "e": 27597, "s": 27485, "text": "Example 2: This example uses navigator.appVersion property to display all the properties of the client machine." }, { "code": "<!DOCTYPE html> <html> <head> <title> How to detect operating system on the client machine using JavaScript ? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\">GeeksforGeeks</h1> <button ondblclick=\"version()\"> Return OS Version </button> <p id=\"OS\"></p> <!-- Script to return OS details --> <script> function version() { var os = navigator.appVersion; // Display the OS details document.getElementById(\"OS\").innerHTML = os; } </script> </body> </html> ", "e": 28230, "s": 27597, "text": null }, { "code": null, "e": 28238, "s": 28230, "text": "Output:" }, { "code": null, "e": 28266, "s": 28238, "text": "Before Click on the Button:" }, { "code": null, "e": 28293, "s": 28266, "text": "After Click on the Button:" }, { "code": null, "e": 28309, "s": 28293, "text": "JavaScript-Misc" }, { "code": null, "e": 28316, "s": 28309, "text": "Picked" }, { "code": null, "e": 28327, "s": 28316, "text": "JavaScript" }, { "code": null, "e": 28344, "s": 28327, "text": "Web Technologies" }, { "code": null, "e": 28371, "s": 28344, "text": "Web technologies Questions" }, { "code": null, "e": 28469, "s": 28371, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28509, "s": 28469, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28554, "s": 28509, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28615, "s": 28554, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28687, "s": 28615, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28739, "s": 28687, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 28779, "s": 28739, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28812, "s": 28779, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28857, "s": 28812, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28900, "s": 28857, "text": "How to fetch data from an API in ReactJS ?" } ]
Python - Convert Key-Value list Dictionary to List of Lists - GeeksforGeeks
22 Apr, 2020 Sometimes, while working with Python dictionary, we can have a problem in which we need to perform the flattening a key value pair of dictionary to a list and convert to lists of list. This can have applications in domains in which we have data. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop + items()This brute force way in which we can perform this task. In this, we loop through all the pairs and extract list value elements using items() and render in a new list. # Python3 code to demonstrate working of # Convert Key-Value list Dictionary to Lists of List# Using loop + items() # initializing Dictionarytest_dict = {'gfg' : [1, 3, 4], 'is' : [7, 6], 'best' : [4, 5]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Convert Key-Value list Dictionary to Lists of List# Using loop + items()res = []for key, val in test_dict.items(): res.append([key] + val) # printing result print("The converted list is : " + str(res)) The original dictionary is : {‘gfg’: [1, 3, 4], ‘is’: [7, 6], ‘best’: [4, 5]}The converted list is : [[‘gfg’, 1, 3, 4], [‘is’, 7, 6], [‘best’, 4, 5]] Method #2 : Using list comprehensionThis task can also be performed using list comprehension. In this, we perform the task similar to above method just in one-liner shorter way. # Python3 code to demonstrate working of # Convert Key-Value list Dictionary to Lists of List# Using list comprehension # initializing Dictionarytest_dict = {'gfg' : [1, 3, 4], 'is' : [7, 6], 'best' : [4, 5]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Convert Key-Value list Dictionary to Lists of List# Using list comprehensionres = [[key] + val for key, val in test_dict.items()] # printing result print("The converted list is : " + str(res)) The original dictionary is : {‘gfg’: [1, 3, 4], ‘is’: [7, 6], ‘best’: [4, 5]}The converted list is : [[‘gfg’, 1, 3, 4], [‘is’, 7, 6], [‘best’, 4, 5]] Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25533, "s": 25505, "text": "\n22 Apr, 2020" }, { "code": null, "e": 25842, "s": 25533, "text": "Sometimes, while working with Python dictionary, we can have a problem in which we need to perform the flattening a key value pair of dictionary to a list and convert to lists of list. This can have applications in domains in which we have data. Lets discuss certain ways in which this task can be performed." }, { "code": null, "e": 26041, "s": 25842, "text": "Method #1 : Using loop + items()This brute force way in which we can perform this task. In this, we loop through all the pairs and extract list value elements using items() and render in a new list." }, { "code": "# Python3 code to demonstrate working of # Convert Key-Value list Dictionary to Lists of List# Using loop + items() # initializing Dictionarytest_dict = {'gfg' : [1, 3, 4], 'is' : [7, 6], 'best' : [4, 5]} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Convert Key-Value list Dictionary to Lists of List# Using loop + items()res = []for key, val in test_dict.items(): res.append([key] + val) # printing result print(\"The converted list is : \" + str(res)) ", "e": 26544, "s": 26041, "text": null }, { "code": null, "e": 26694, "s": 26544, "text": "The original dictionary is : {‘gfg’: [1, 3, 4], ‘is’: [7, 6], ‘best’: [4, 5]}The converted list is : [[‘gfg’, 1, 3, 4], [‘is’, 7, 6], [‘best’, 4, 5]]" }, { "code": null, "e": 26874, "s": 26696, "text": "Method #2 : Using list comprehensionThis task can also be performed using list comprehension. In this, we perform the task similar to above method just in one-liner shorter way." }, { "code": "# Python3 code to demonstrate working of # Convert Key-Value list Dictionary to Lists of List# Using list comprehension # initializing Dictionarytest_dict = {'gfg' : [1, 3, 4], 'is' : [7, 6], 'best' : [4, 5]} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Convert Key-Value list Dictionary to Lists of List# Using list comprehensionres = [[key] + val for key, val in test_dict.items()] # printing result print(\"The converted list is : \" + str(res)) ", "e": 27369, "s": 26874, "text": null }, { "code": null, "e": 27519, "s": 27369, "text": "The original dictionary is : {‘gfg’: [1, 3, 4], ‘is’: [7, 6], ‘best’: [4, 5]}The converted list is : [[‘gfg’, 1, 3, 4], [‘is’, 7, 6], [‘best’, 4, 5]]" }, { "code": null, "e": 27546, "s": 27519, "text": "Python dictionary-programs" }, { "code": null, "e": 27553, "s": 27546, "text": "Python" }, { "code": null, "e": 27569, "s": 27553, "text": "Python Programs" }, { "code": null, "e": 27667, "s": 27569, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27699, "s": 27667, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27721, "s": 27699, "text": "Enumerate() in Python" }, { "code": null, "e": 27763, "s": 27721, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27789, "s": 27763, "text": "Python String | replace()" }, { "code": null, "e": 27818, "s": 27789, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27840, "s": 27818, "text": "Defaultdict in Python" }, { "code": null, "e": 27879, "s": 27840, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27925, "s": 27879, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27963, "s": 27925, "text": "Python | Convert a list to dictionary" } ]
How to Get directory of Current Script in Python? - GeeksforGeeks
26 Nov, 2020 A Parent directory is a directory above another file/directory in a hierarchical file system. Getting the Parent directory is essential in performing certain tasks related to filesystem management. In this article, we will take a look at methods used for obtaining the Parent directory of the currently running python script, and would learn about various uses/demerits of each. For performing the aforementioned task we would be using two libraries named os and inspect, both of which are built-in and therefore does not require any installation. For demonstration purposes, we would be using the following file, which is located at C:\suga\Lpath.py. The file’s content (code) will be changed according to the context in which it is being referenced. We would be utilizing the dirname() function found within the os.path module extensively within the following examples. And therefore it would be better if we get acquainted about it beforehand. Syntax: os.path.dirname(path) Parameter: path: A path-like object representing a file system path. Return Type: This method returns a string which represents the absolute path to the parent directory for the specified path Methods 1#: Using __file__ module object. In this method, we would be using the __file__ (file keyword surrounded by double underscores (dunder)). This predefined attribute is present in most python files. This attribute is used for obtaining the filename of the currently executing python file. We would be passing the path obtained by __file__, to os.path.dirname() function in order to get the parent directory of the python file. Python3 import os # Displaying the script pathprint(__file__) # Displaying the parent directory of the scriptprint(os.path.dirname(__file__)) OUTPUT: C:\suga\Lpath.py C:\suga Drawbacks: The above method would only work if it is used inside a python script. Therefore, if run from an interactive environment (stdin) or line by line interpreter (debugging) it would not work. __file__ would not be present in statically linked C modules (libraries written originally in C but ported over to python) __file__ would not be defined in a built-in module Methods 2#: Using sys.argv[0] command-line argument sys.argv is a list that contains the command line arguments passed to the python program. In this method we would be using the 0th argument of sys.argv list, that is the path to the current executing python file, to get the parent directory of the python script. Python3 import sys print(os.path.dirname(sys.argv[0])) OUTPUT: C:\suga Drawbacks: The above method would only work if sys.argv[0] is used inside a python script. It won’t work for raw stdin, ex. running the command from the python command-line interpreter (IDLE). The above method is argument based, therefore if the python script is run in a particular way such that the first argument (at index 0) is not the filename of the executable, the method won’t work. Ex. if the Lpath.py file is ran using the command ‘py Lpath.py‘ it would result in no output being displayed. Methods 3#: Using getsourcefile() function In this method we would be using the getsourcefile() method found inside the inspect library, to obtain the absolute path of the currently executing python script. Then we would be passing it to os.path.dirname() function to get the parent directory of the filename. This method is generally the most optimal and compatible one of the aforementioned methods as it is cross-platform, small scale (fewer code lines), and works under variable execution environments. Syntax: getsourcefile(object) Parameters: object: A Referenceable object within the python script Return Type: Returns the full path to the file within whom the object was found. Returns None if the object could not be identified within the source. Python3 from inspect import getsourcefile import os print(os.path.dirname(getsourcefile(lambda:0))) OUTPUT: C:\suga Explanation: Firstly, we imported the getsourcefile() function found inside the inspect library. After which we imported the os library for using the os.path.dirname() function found within, which would be used for extracting the parent directory out of the script filename. We provided lambda:0 as the argument to the getsourcefile() function, as it required a reference object within the python script, therefore we created a dummy function using lambda, just to enable it to be referenced within the python script. NOTE: The above code might have to be altered a bit (using a self-tailored function, rather than dirname()) if it is to be executed within line-by-line interpreters (ex. IDLE). But that is outside the scope of this article. Python file-handling-programs Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n26 Nov, 2020" }, { "code": null, "e": 26085, "s": 25537, "text": "A Parent directory is a directory above another file/directory in a hierarchical file system. Getting the Parent directory is essential in performing certain tasks related to filesystem management. In this article, we will take a look at methods used for obtaining the Parent directory of the currently running python script, and would learn about various uses/demerits of each. For performing the aforementioned task we would be using two libraries named os and inspect, both of which are built-in and therefore does not require any installation." }, { "code": null, "e": 26291, "s": 26085, "text": "For demonstration purposes, we would be using the following file, which is located at C:\\suga\\Lpath.py. The file’s content (code) will be changed according to the context in which it is being referenced. " }, { "code": null, "e": 26486, "s": 26291, "text": "We would be utilizing the dirname() function found within the os.path module extensively within the following examples. And therefore it would be better if we get acquainted about it beforehand." }, { "code": null, "e": 26516, "s": 26486, "text": "Syntax: os.path.dirname(path)" }, { "code": null, "e": 26527, "s": 26516, "text": "Parameter:" }, { "code": null, "e": 26585, "s": 26527, "text": "path: A path-like object representing a file system path." }, { "code": null, "e": 26599, "s": 26585, "text": "Return Type: " }, { "code": null, "e": 26710, "s": 26599, "text": "This method returns a string which represents the absolute path to the parent directory for the specified path" }, { "code": null, "e": 26752, "s": 26710, "text": "Methods 1#: Using __file__ module object." }, { "code": null, "e": 27144, "s": 26752, "text": "In this method, we would be using the __file__ (file keyword surrounded by double underscores (dunder)). This predefined attribute is present in most python files. This attribute is used for obtaining the filename of the currently executing python file. We would be passing the path obtained by __file__, to os.path.dirname() function in order to get the parent directory of the python file." }, { "code": null, "e": 27152, "s": 27144, "text": "Python3" }, { "code": "import os # Displaying the script pathprint(__file__) # Displaying the parent directory of the scriptprint(os.path.dirname(__file__))", "e": 27288, "s": 27152, "text": null }, { "code": null, "e": 27296, "s": 27288, "text": "OUTPUT:" }, { "code": null, "e": 27322, "s": 27296, "text": "C:\\suga\\Lpath.py\nC:\\suga\n" }, { "code": null, "e": 27335, "s": 27322, "text": "Drawbacks: " }, { "code": null, "e": 27523, "s": 27335, "text": "The above method would only work if it is used inside a python script. Therefore, if run from an interactive environment (stdin) or line by line interpreter (debugging) it would not work." }, { "code": null, "e": 27646, "s": 27523, "text": "__file__ would not be present in statically linked C modules (libraries written originally in C but ported over to python)" }, { "code": null, "e": 27697, "s": 27646, "text": "__file__ would not be defined in a built-in module" }, { "code": null, "e": 27749, "s": 27697, "text": "Methods 2#: Using sys.argv[0] command-line argument" }, { "code": null, "e": 28012, "s": 27749, "text": "sys.argv is a list that contains the command line arguments passed to the python program. In this method we would be using the 0th argument of sys.argv list, that is the path to the current executing python file, to get the parent directory of the python script." }, { "code": null, "e": 28020, "s": 28012, "text": "Python3" }, { "code": "import sys print(os.path.dirname(sys.argv[0]))", "e": 28068, "s": 28020, "text": null }, { "code": null, "e": 28076, "s": 28068, "text": "OUTPUT:" }, { "code": null, "e": 28085, "s": 28076, "text": "C:\\suga\n" }, { "code": null, "e": 28096, "s": 28085, "text": "Drawbacks:" }, { "code": null, "e": 28278, "s": 28096, "text": "The above method would only work if sys.argv[0] is used inside a python script. It won’t work for raw stdin, ex. running the command from the python command-line interpreter (IDLE)." }, { "code": null, "e": 28587, "s": 28278, "text": "The above method is argument based, therefore if the python script is run in a particular way such that the first argument (at index 0) is not the filename of the executable, the method won’t work. Ex. if the Lpath.py file is ran using the command ‘py Lpath.py‘ it would result in no output being displayed." }, { "code": null, "e": 28632, "s": 28587, "text": "Methods 3#: Using getsourcefile() function " }, { "code": null, "e": 29098, "s": 28632, "text": "In this method we would be using the getsourcefile() method found inside the inspect library, to obtain the absolute path of the currently executing python script. Then we would be passing it to os.path.dirname() function to get the parent directory of the filename. This method is generally the most optimal and compatible one of the aforementioned methods as it is cross-platform, small scale (fewer code lines), and works under variable execution environments. " }, { "code": null, "e": 29128, "s": 29098, "text": "Syntax: getsourcefile(object)" }, { "code": null, "e": 29140, "s": 29128, "text": "Parameters:" }, { "code": null, "e": 29196, "s": 29140, "text": "object: A Referenceable object within the python script" }, { "code": null, "e": 29210, "s": 29196, "text": "Return Type: " }, { "code": null, "e": 29348, "s": 29210, "text": "Returns the full path to the file within whom the object was found. Returns None if the object could not be identified within the source." }, { "code": null, "e": 29356, "s": 29348, "text": "Python3" }, { "code": "from inspect import getsourcefile import os print(os.path.dirname(getsourcefile(lambda:0)))", "e": 29452, "s": 29356, "text": null }, { "code": null, "e": 29460, "s": 29452, "text": "OUTPUT:" }, { "code": null, "e": 29469, "s": 29460, "text": "C:\\suga\n" }, { "code": null, "e": 29482, "s": 29469, "text": "Explanation:" }, { "code": null, "e": 29989, "s": 29482, "text": "Firstly, we imported the getsourcefile() function found inside the inspect library. After which we imported the os library for using the os.path.dirname() function found within, which would be used for extracting the parent directory out of the script filename. We provided lambda:0 as the argument to the getsourcefile() function, as it required a reference object within the python script, therefore we created a dummy function using lambda, just to enable it to be referenced within the python script. " }, { "code": null, "e": 30214, "s": 29989, "text": "NOTE: The above code might have to be altered a bit (using a self-tailored function, rather than dirname()) if it is to be executed within line-by-line interpreters (ex. IDLE). But that is outside the scope of this article. " }, { "code": null, "e": 30244, "s": 30214, "text": "Python file-handling-programs" }, { "code": null, "e": 30251, "s": 30244, "text": "Python" }, { "code": null, "e": 30349, "s": 30251, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30381, "s": 30349, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30423, "s": 30381, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30465, "s": 30423, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30521, "s": 30465, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30548, "s": 30521, "text": "Python Classes and Objects" }, { "code": null, "e": 30587, "s": 30548, "text": "Python | Get unique values from a list" }, { "code": null, "e": 30618, "s": 30587, "text": "Python | os.path.join() method" }, { "code": null, "e": 30640, "s": 30618, "text": "Defaultdict in Python" }, { "code": null, "e": 30669, "s": 30640, "text": "Create a directory in Python" } ]
How to hide div element by default and show it on click using JavaScript and Bootstrap ? - GeeksforGeeks
31 Dec, 2019 The task is to show a hidden div on click using Bootstrap. There are two methods to solve this problem which are discussed below: Approach 1: Set display: none property of the div that needs to be displayed. Use .show() method to display the div element. Example: This example implements the above approach. <!DOCTYPE HTML><html> <head> <title> How to hide div element by default and show it on click using JavaScript and Bootstrap ? </title> <style> #div { display: none; background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"></p> <div id="div"> This is Div box. </div> <br> <button onClick="GFG_Fun()"> click here </button> <br> <p id="GFG_DOWN" style="color: green;"></p> <script> $('#GFG_UP').text( "Click on button to toggle the DIV Box using Bootstrap."); function show(divId) { $("#" + divId).show(); } function GFG_Fun() { show('div'); $('#GFG_DOWN').text("DIV Box is visible."); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Approach 2: Set display: none property of the div that needs to be displayed. Use .toggle() method to display the Div. However, this method can be used to again hide the div. Example: This example implements the above approach. <!DOCTYPE HTML><html> <head> <title> How to hide div element by default and show it on click using JavaScript and Bootstrap ? </title> <style> #div { display: none; background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style= "font-size: 19px;font-weight: bold;"> </p> <div id="div"> This is Div box. </div> <br> <button onClick="GFG_Fun()"> click here </button> <br> <p id="GFG_DOWN" style="color: green;"> </p> <script> $('#GFG_UP').text("Click on button to toggle the DIV Box using Bootstrap."); function toggler(divId) { $("#" + divId).toggle(); } function GFG_Fun() { toggler('div'); $('#GFG_DOWN').text("DIV Box is toggling."); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Bootstrap-Misc JavaScript-Misc Bootstrap JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to pass data into a bootstrap modal? How to Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ? How to Use Bootstrap with React? How to change the background color of the active nav-item? Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 26502, "s": 26474, "text": "\n31 Dec, 2019" }, { "code": null, "e": 26632, "s": 26502, "text": "The task is to show a hidden div on click using Bootstrap. There are two methods to solve this problem which are discussed below:" }, { "code": null, "e": 26644, "s": 26632, "text": "Approach 1:" }, { "code": null, "e": 26710, "s": 26644, "text": "Set display: none property of the div that needs to be displayed." }, { "code": null, "e": 26757, "s": 26710, "text": "Use .show() method to display the div element." }, { "code": null, "e": 26810, "s": 26757, "text": "Example: This example implements the above approach." }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to hide div element by default and show it on click using JavaScript and Bootstrap ? </title> <style> #div { display: none; background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> <div id=\"div\"> This is Div box. </div> <br> <button onClick=\"GFG_Fun()\"> click here </button> <br> <p id=\"GFG_DOWN\" style=\"color: green;\"></p> <script> $('#GFG_UP').text( \"Click on button to toggle the DIV Box using Bootstrap.\"); function show(divId) { $(\"#\" + divId).show(); } function GFG_Fun() { show('div'); $('#GFG_DOWN').text(\"DIV Box is visible.\"); } </script></body> </html>", "e": 28063, "s": 26810, "text": null }, { "code": null, "e": 28071, "s": 28063, "text": "Output:" }, { "code": null, "e": 28102, "s": 28071, "text": "Before clicking on the button:" }, { "code": null, "e": 28132, "s": 28102, "text": "After clicking on the button:" }, { "code": null, "e": 28144, "s": 28132, "text": "Approach 2:" }, { "code": null, "e": 28210, "s": 28144, "text": "Set display: none property of the div that needs to be displayed." }, { "code": null, "e": 28307, "s": 28210, "text": "Use .toggle() method to display the Div. However, this method can be used to again hide the div." }, { "code": null, "e": 28360, "s": 28307, "text": "Example: This example implements the above approach." }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to hide div element by default and show it on click using JavaScript and Bootstrap ? </title> <style> #div { display: none; background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style= \"font-size: 19px;font-weight: bold;\"> </p> <div id=\"div\"> This is Div box. </div> <br> <button onClick=\"GFG_Fun()\"> click here </button> <br> <p id=\"GFG_DOWN\" style=\"color: green;\"> </p> <script> $('#GFG_UP').text(\"Click on button to toggle the DIV Box using Bootstrap.\"); function toggler(divId) { $(\"#\" + divId).toggle(); } function GFG_Fun() { toggler('div'); $('#GFG_DOWN').text(\"DIV Box is toggling.\"); } </script></body> </html>", "e": 29679, "s": 28360, "text": null }, { "code": null, "e": 29687, "s": 29679, "text": "Output:" }, { "code": null, "e": 29718, "s": 29687, "text": "Before clicking on the button:" }, { "code": null, "e": 29748, "s": 29718, "text": "After clicking on the button:" }, { "code": null, "e": 29763, "s": 29748, "text": "Bootstrap-Misc" }, { "code": null, "e": 29779, "s": 29763, "text": "JavaScript-Misc" }, { "code": null, "e": 29789, "s": 29779, "text": "Bootstrap" }, { "code": null, "e": 29800, "s": 29789, "text": "JavaScript" }, { "code": null, "e": 29817, "s": 29800, "text": "Web Technologies" }, { "code": null, "e": 29915, "s": 29817, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29956, "s": 29915, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 29997, "s": 29956, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 30060, "s": 29997, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 30093, "s": 30060, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 30152, "s": 30093, "text": "How to change the background color of the active nav-item?" }, { "code": null, "e": 30192, "s": 30152, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30237, "s": 30192, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30298, "s": 30237, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30370, "s": 30298, "text": "Differences between Functional Components and Class Components in React" } ]
Flutter - A Simple Multi-Player Dice Game - GeeksforGeeks
16 Aug, 2021 Here, we are going to create a dice game. As the name suggests there will be two dice and either player one or player two rolls the dice and according to the result the winner is decided. Flutter is Google’s UI toolkit for building beautiful, natively compiled applications for mobile, web, desktop, and embedded devices from a single codebase. Guide on installation of flutter can be found on their documentation. When installing flutter you might have selected your preferred editor. Just go on the editor and create a new flutter project. If you wish to create the project via command line or if you are using VS Code enter the following command in terminal $ flutter create dice Before we start with flutter let’s first take a look at the approach to building our game. We’ll add 6 images of dice each having numbers (1-6). At first, both dice will show 1 and no result. When either player 1 or player 2 rolls the dice we’ll randomly select one of the 6 images we added and based on the outcome we’ll declare the result whether it is player 1 who won or player 2 or it is a draw. To add assets in the flutter project you can create a folder that contains all your assets at the root of the project. Now that we only have image assets we’ll create a folder called “images” and add the images to that folder. Typically you would create a folder called assets then inside it a folder called images this is due to the fact that many times apps have different assets such as audio, video, etc. You can find images with dice on the internet. To let flutter know that we have added these images we’ll go to pubspec.yaml file and uncomment the assets line and added the image folder. XML name: dicedescription: A new Flutter project. # The following line prevents the package from being accidentally published to# pub.dev using `pub publish`. This is preferred for private packages.publish_to: 'none' # Remove this line if you wish to publish to pub.dev # The following defines the version and build number for your application.# A version number is three numbers separated by dots, like 1.2.43# followed by an optional build number separated by a +.# Both the version and the builder number may be overridden in flutter# build by specifying --build-name and --build-number, respectively.# In Android, build-name is used as versionName while build-number used as versionCode.# Read more about Android versioning at https://developer.android.com/studio/publish/versioning# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.# Read more about iOS versioning at# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.htmlversion: 1.0.0+1 environment: sdk: ">=2.12.0 <3.0.0" dependencies: flutter: sdk: flutter # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.2 dev_dependencies: flutter_test: sdk: flutter # For information on the generic Dart part of this file, see the# following page: https://dart.dev/tools/pub/pubspec # The following section is specific to Flutter.flutter: # The following line ensures that the Material Icons font is # included with your application, so that you can use the icons in # the material Icons class. uses-material-design: true # To add assets to your application, add an assets section, like this: assets: - images/ # An image asset can refer to one or more resolution-specific "variants", see # https://flutter.dev/assets-and-images/#resolution-aware. # For details regarding adding assets from package dependencies, see # https://flutter.dev/assets-and-images/#from-packages # To add custom fonts to your application, add a fonts section here, # in this "flutter" section. Each entry in this list should have a # "family" key with the font family name, and a "fonts" key with a # list giving the asset and other descriptors for the font. For # example: # fonts: # - family: Schyler # fonts: # - asset: fonts/Schyler-Regular.ttf # - asset: fonts/Schyler-Italic.ttf # style: italic # - family: Trajan Pro # fonts: # - asset: fonts/TrajanPro.ttf # - asset: fonts/TrajanPro_Bold.ttf # weight: 700 # # For details regarding fonts from package dependencies, # see https://flutter.dev/custom-fonts/#from-packages First, make sure that you delete all the code inside the main.dart file and delete the file inside the test folder. Dart import 'package:flutter/material.dart';// The main function from where the execution starts //void main() { // runApp function which starts the application // runApp(MaterialApp( // Disables debug tag which are in the flutter apps // debugShowCheckedModeBanner: false, // Scaffold is like canvas it is generally // in the root of screen widget // home: Scaffold( backgroundColor: Colors.green, appBar: AppBar( backgroundColor: Colors.green, title: Text("GeeksForGeeks"), centerTitle: true, ), body: Container(), ), ));} After running the app you’ll see the app bar with a title on your screen. Dart import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( // Disables debug tag which are in the flutter apps // debugShowCheckedModeBanner: false, home: Scaffold( backgroundColor: Colors.green, appBar: AppBar( backgroundColor: Colors.green, title: Text("GeeksForGeeks"), centerTitle: true, ), body: Dice(), ), ));} class Dice extends StatefulWidget { const Dice({Key? key}) : super(key: key); @override _DiceState createState() => _DiceState();} class _DiceState extends State<Dice> { @override Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Column( children: [ MaterialButton( child: Image.asset('images/dice1.png', height: 150, width: 150), onPressed: () {}, ), Text( "Player 1", style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 10, ), ), ], ), Column( children: [ MaterialButton( child: Image.asset( 'images/dice1.png', height: 150, width: 150, ), onPressed: () {}, ), Text( "Player 2", style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 10, ), ), ], ) ], ), // To create space between dice and result // SizedBox( height: 20, ), Text( "result", style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 20, ), ), ], ); }} Dart import 'dart:math';import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( // Disables debug tag which are in the flutter apps // debugShowCheckedModeBanner: false, home: Scaffold( backgroundColor: Colors.green, appBar: AppBar( backgroundColor: Colors.green, title: Text("GeeksForGeeks"), centerTitle: true, ), body: Dice(), ), ));} class Dice extends StatefulWidget { const Dice({Key? key}) : super(key: key); @override _DiceState createState() => _DiceState();} class _DiceState extends State<Dice> { // Initialize the dice to 1 // int playerOne = 1; int playerTwo = 1; String result = ""; // Function to roll the dice and decide the winner// void rollDice() { setState(() { // Randomise the dice // playerOne = Random().nextInt(6) + 1; playerTwo = Random().nextInt(6) + 1; // Check which player won // if (playerOne > playerTwo) { result = "Player 1 Wins"; } else if (playerTwo > playerOne) { result = "Player 2 Wins"; } else { result = "Draw"; } }); } @override Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Column( children: [ MaterialButton( child: Image.asset('images/dice$playerOne.png', height: 150, width: 150), onPressed: () { rollDice(); }, ), Text( "Player 1", style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 10, ), ), ], ), Column( children: [ MaterialButton( child: Image.asset( 'images/dice$playerTwo.png', height: 150, width: 150, ), onPressed: () { rollDice(); }, ), Text( "Player 2", style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 10, ), ), ], ) ], ), // To create space between dice and result // SizedBox( height: 20, ), Text( result, style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 20, ), ), ], ); }} Output: Flutter Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Checkbox Widget Flutter - Flexible Widget Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Flutter Tutorial Flutter - Checkbox Widget Flutter - Flexible Widget
[ { "code": null, "e": 25209, "s": 25181, "text": "\n16 Aug, 2021" }, { "code": null, "e": 25397, "s": 25209, "text": "Here, we are going to create a dice game. As the name suggests there will be two dice and either player one or player two rolls the dice and according to the result the winner is decided." }, { "code": null, "e": 25624, "s": 25397, "text": "Flutter is Google’s UI toolkit for building beautiful, natively compiled applications for mobile, web, desktop, and embedded devices from a single codebase. Guide on installation of flutter can be found on their documentation." }, { "code": null, "e": 25870, "s": 25624, "text": "When installing flutter you might have selected your preferred editor. Just go on the editor and create a new flutter project. If you wish to create the project via command line or if you are using VS Code enter the following command in terminal" }, { "code": null, "e": 25892, "s": 25870, "text": "$ flutter create dice" }, { "code": null, "e": 26295, "s": 25892, "text": "Before we start with flutter let’s first take a look at the approach to building our game. We’ll add 6 images of dice each having numbers (1-6). At first, both dice will show 1 and no result. When either player 1 or player 2 rolls the dice we’ll randomly select one of the 6 images we added and based on the outcome we’ll declare the result whether it is player 1 who won or player 2 or it is a draw. " }, { "code": null, "e": 26751, "s": 26295, "text": "To add assets in the flutter project you can create a folder that contains all your assets at the root of the project. Now that we only have image assets we’ll create a folder called “images” and add the images to that folder. Typically you would create a folder called assets then inside it a folder called images this is due to the fact that many times apps have different assets such as audio, video, etc. You can find images with dice on the internet." }, { "code": null, "e": 26891, "s": 26751, "text": "To let flutter know that we have added these images we’ll go to pubspec.yaml file and uncomment the assets line and added the image folder." }, { "code": null, "e": 26895, "s": 26891, "text": "XML" }, { "code": "name: dicedescription: A new Flutter project. # The following line prevents the package from being accidentally published to# pub.dev using `pub publish`. This is preferred for private packages.publish_to: 'none' # Remove this line if you wish to publish to pub.dev # The following defines the version and build number for your application.# A version number is three numbers separated by dots, like 1.2.43# followed by an optional build number separated by a +.# Both the version and the builder number may be overridden in flutter# build by specifying --build-name and --build-number, respectively.# In Android, build-name is used as versionName while build-number used as versionCode.# Read more about Android versioning at https://developer.android.com/studio/publish/versioning# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.# Read more about iOS versioning at# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.htmlversion: 1.0.0+1 environment: sdk: \">=2.12.0 <3.0.0\" dependencies: flutter: sdk: flutter # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.2 dev_dependencies: flutter_test: sdk: flutter # For information on the generic Dart part of this file, see the# following page: https://dart.dev/tools/pub/pubspec # The following section is specific to Flutter.flutter: # The following line ensures that the Material Icons font is # included with your application, so that you can use the icons in # the material Icons class. uses-material-design: true # To add assets to your application, add an assets section, like this: assets: - images/ # An image asset can refer to one or more resolution-specific \"variants\", see # https://flutter.dev/assets-and-images/#resolution-aware. # For details regarding adding assets from package dependencies, see # https://flutter.dev/assets-and-images/#from-packages # To add custom fonts to your application, add a fonts section here, # in this \"flutter\" section. Each entry in this list should have a # \"family\" key with the font family name, and a \"fonts\" key with a # list giving the asset and other descriptors for the font. For # example: # fonts: # - family: Schyler # fonts: # - asset: fonts/Schyler-Regular.ttf # - asset: fonts/Schyler-Italic.ttf # style: italic # - family: Trajan Pro # fonts: # - asset: fonts/TrajanPro.ttf # - asset: fonts/TrajanPro_Bold.ttf # weight: 700 # # For details regarding fonts from package dependencies, # see https://flutter.dev/custom-fonts/#from-packages", "e": 29682, "s": 26895, "text": null }, { "code": null, "e": 29798, "s": 29682, "text": "First, make sure that you delete all the code inside the main.dart file and delete the file inside the test folder." }, { "code": null, "e": 29803, "s": 29798, "text": "Dart" }, { "code": "import 'package:flutter/material.dart';// The main function from where the execution starts //void main() { // runApp function which starts the application // runApp(MaterialApp( // Disables debug tag which are in the flutter apps // debugShowCheckedModeBanner: false, // Scaffold is like canvas it is generally // in the root of screen widget // home: Scaffold( backgroundColor: Colors.green, appBar: AppBar( backgroundColor: Colors.green, title: Text(\"GeeksForGeeks\"), centerTitle: true, ), body: Container(), ), ));}", "e": 30385, "s": 29803, "text": null }, { "code": null, "e": 30459, "s": 30385, "text": "After running the app you’ll see the app bar with a title on your screen." }, { "code": null, "e": 30464, "s": 30459, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( // Disables debug tag which are in the flutter apps // debugShowCheckedModeBanner: false, home: Scaffold( backgroundColor: Colors.green, appBar: AppBar( backgroundColor: Colors.green, title: Text(\"GeeksForGeeks\"), centerTitle: true, ), body: Dice(), ), ));} class Dice extends StatefulWidget { const Dice({Key? key}) : super(key: key); @override _DiceState createState() => _DiceState();} class _DiceState extends State<Dice> { @override Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Column( children: [ MaterialButton( child: Image.asset('images/dice1.png', height: 150, width: 150), onPressed: () {}, ), Text( \"Player 1\", style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 10, ), ), ], ), Column( children: [ MaterialButton( child: Image.asset( 'images/dice1.png', height: 150, width: 150, ), onPressed: () {}, ), Text( \"Player 2\", style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 10, ), ), ], ) ], ), // To create space between dice and result // SizedBox( height: 20, ), Text( \"result\", style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 20, ), ), ], ); }}", "e": 32633, "s": 30464, "text": null }, { "code": null, "e": 32638, "s": 32633, "text": "Dart" }, { "code": "import 'dart:math';import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( // Disables debug tag which are in the flutter apps // debugShowCheckedModeBanner: false, home: Scaffold( backgroundColor: Colors.green, appBar: AppBar( backgroundColor: Colors.green, title: Text(\"GeeksForGeeks\"), centerTitle: true, ), body: Dice(), ), ));} class Dice extends StatefulWidget { const Dice({Key? key}) : super(key: key); @override _DiceState createState() => _DiceState();} class _DiceState extends State<Dice> { // Initialize the dice to 1 // int playerOne = 1; int playerTwo = 1; String result = \"\"; // Function to roll the dice and decide the winner// void rollDice() { setState(() { // Randomise the dice // playerOne = Random().nextInt(6) + 1; playerTwo = Random().nextInt(6) + 1; // Check which player won // if (playerOne > playerTwo) { result = \"Player 1 Wins\"; } else if (playerTwo > playerOne) { result = \"Player 2 Wins\"; } else { result = \"Draw\"; } }); } @override Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Column( children: [ MaterialButton( child: Image.asset('images/dice$playerOne.png', height: 150, width: 150), onPressed: () { rollDice(); }, ), Text( \"Player 1\", style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 10, ), ), ], ), Column( children: [ MaterialButton( child: Image.asset( 'images/dice$playerTwo.png', height: 150, width: 150, ), onPressed: () { rollDice(); }, ), Text( \"Player 2\", style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 10, ), ), ], ) ], ), // To create space between dice and result // SizedBox( height: 20, ), Text( result, style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 20, ), ), ], ); }}", "e": 35470, "s": 32638, "text": null }, { "code": null, "e": 35478, "s": 35470, "text": "Output:" }, { "code": null, "e": 35486, "s": 35478, "text": "Flutter" }, { "code": null, "e": 35491, "s": 35486, "text": "Dart" }, { "code": null, "e": 35499, "s": 35491, "text": "Flutter" }, { "code": null, "e": 35597, "s": 35499, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35629, "s": 35597, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 35668, "s": 35629, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 35694, "s": 35668, "text": "ListView Class in Flutter" }, { "code": null, "e": 35720, "s": 35694, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 35746, "s": 35720, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 35778, "s": 35746, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 35817, "s": 35778, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 35834, "s": 35817, "text": "Flutter Tutorial" }, { "code": null, "e": 35860, "s": 35834, "text": "Flutter - Checkbox Widget" } ]
Angular PrimeNG Tooltip Component - GeeksforGeeks
11 Sep, 2021 Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Tooltip component in Angular PrimeNG. We will also learn about the properties, styling along with their syntaxes that will be used in the code. Tooltip component: It is used to make an element that provides advisory information for a component. Properties: pTooltip: It is the text of the tooltip. It is of string data type & the default value is null. tooltipPosition: It is the position of the tooltip. It is of string data type & the default value is right. tooltipEvent: It is the event to show the tooltip. It is of string data type & the default value is hover. positionStyle: It is the text representing the type of CSS position. It is of string data type & the default value is absolute. tooltipDisabled: It is used to specify whether the component should be disabled. It is of boolean data type & the default value is false. appendTo: It is used to specify the target element to attach the overlay. It is of string data type & the default value is any. hideDelay: It is the delay to hide the tooltip in milliseconds. It is of number data type & the default value is null. showDelay: It is the delay to show the tooltip in milliseconds. It is of number data type & the default value is null. life: It is the time to wait in milliseconds to hide the tooltip even it is active. It is of number data type & the default value is null. tooltipStyleClass: It is the style class of the tooltip. It is of string data type & the default value is null. escape: it is used to specify whether the content is rendered as text. It is of boolean data type & the default value is true. tooltipZIndex: It is used to specify whether the z-index should be managed automatically. It is of string data type & the default value is auto. Styling: p-tooltip: It is the container element. p-tooltip-arrow: It is the arrow of the tooltip. p-tooltip-text: It is the text of the tooltip. Creating Angular application & module installation: Step 1: Create an Angular application using the following command. ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command. cd appname Step 3: Install PrimeNG in your given directory. npm install primeng --save npm install primeicons --save Project Structure: It will look like the following: Example 1: This is the basic example that illustrates how to implement a focus event to display and blur to hide in the Tooltip component. app.component.html <h2>GeeksforGeeeks</h2><h5>PrimeNG Tooltip Component</h5><div class="p-grid p-fluid"> <div class="p-col-12 p-md-3"> <input type="text" pInputText pTooltip="It is a tooltip" placeholder="Hover Here" tooltipEvent="focus"/> </div> <div class="p-col-12 p-md-3"> <input type="text" pInputText pTooltip="It is a tooltip" placeholder="Hover Here" tooltipPosition="bottom" tooltipEvent="focus"/> </div></div> app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'mt-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { TooltipModule } from "primeng/tooltip";import { InputTextModule } from "primeng/inputtext"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, TooltipModule, InputTextModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Example 2: In this example, we are going to use the tooltip component in a button. app.component.html <h2>GeeksforGeeeks</h2><h5>PrimeNG Tooltip Component</h5><div class="p-grid p-fluid"> <div class="p-col-12 p-md-3"> <p-button label="Hover Here" pTooltip="It is a tooltip"></p-button> </div> <div class="p-col-12 p-md-3"> <p-button label="Hover Here" pTooltip="It is a tooltip" tooltipPosition="bottom"> </p-button> </div></div> app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'mt-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { TooltipModule } from "primeng/tooltip";import { ButtonModule } from "primeng/button"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, TooltipModule, ButtonModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Reference: https://primefaces.org/primeng/showcase/#/tooltip Angular-PrimeNG AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Angular PrimeNG Dropdown Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular 10 (blur) Event How to create module with Routing in Angular 9 ? How to setup 404 page in angular routing ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24718, "s": 24690, "text": "\n11 Sep, 2021" }, { "code": null, "e": 25108, "s": 24718, "text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Tooltip component in Angular PrimeNG. We will also learn about the properties, styling along with their syntaxes that will be used in the code. " }, { "code": null, "e": 25209, "s": 25108, "text": "Tooltip component: It is used to make an element that provides advisory information for a component." }, { "code": null, "e": 25221, "s": 25209, "text": "Properties:" }, { "code": null, "e": 25317, "s": 25221, "text": "pTooltip: It is the text of the tooltip. It is of string data type & the default value is null." }, { "code": null, "e": 25425, "s": 25317, "text": "tooltipPosition: It is the position of the tooltip. It is of string data type & the default value is right." }, { "code": null, "e": 25532, "s": 25425, "text": "tooltipEvent: It is the event to show the tooltip. It is of string data type & the default value is hover." }, { "code": null, "e": 25660, "s": 25532, "text": "positionStyle: It is the text representing the type of CSS position. It is of string data type & the default value is absolute." }, { "code": null, "e": 25798, "s": 25660, "text": "tooltipDisabled: It is used to specify whether the component should be disabled. It is of boolean data type & the default value is false." }, { "code": null, "e": 25926, "s": 25798, "text": "appendTo: It is used to specify the target element to attach the overlay. It is of string data type & the default value is any." }, { "code": null, "e": 26045, "s": 25926, "text": "hideDelay: It is the delay to hide the tooltip in milliseconds. It is of number data type & the default value is null." }, { "code": null, "e": 26164, "s": 26045, "text": "showDelay: It is the delay to show the tooltip in milliseconds. It is of number data type & the default value is null." }, { "code": null, "e": 26303, "s": 26164, "text": "life: It is the time to wait in milliseconds to hide the tooltip even it is active. It is of number data type & the default value is null." }, { "code": null, "e": 26415, "s": 26303, "text": "tooltipStyleClass: It is the style class of the tooltip. It is of string data type & the default value is null." }, { "code": null, "e": 26542, "s": 26415, "text": "escape: it is used to specify whether the content is rendered as text. It is of boolean data type & the default value is true." }, { "code": null, "e": 26687, "s": 26542, "text": "tooltipZIndex: It is used to specify whether the z-index should be managed automatically. It is of string data type & the default value is auto." }, { "code": null, "e": 26696, "s": 26687, "text": "Styling:" }, { "code": null, "e": 26736, "s": 26696, "text": "p-tooltip: It is the container element." }, { "code": null, "e": 26785, "s": 26736, "text": "p-tooltip-arrow: It is the arrow of the tooltip." }, { "code": null, "e": 26832, "s": 26785, "text": "p-tooltip-text: It is the text of the tooltip." }, { "code": null, "e": 26886, "s": 26834, "text": "Creating Angular application & module installation:" }, { "code": null, "e": 26953, "s": 26886, "text": "Step 1: Create an Angular application using the following command." }, { "code": null, "e": 26968, "s": 26953, "text": "ng new appname" }, { "code": null, "e": 27065, "s": 26968, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command." }, { "code": null, "e": 27076, "s": 27065, "text": "cd appname" }, { "code": null, "e": 27125, "s": 27076, "text": "Step 3: Install PrimeNG in your given directory." }, { "code": null, "e": 27182, "s": 27125, "text": "npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 27234, "s": 27182, "text": "Project Structure: It will look like the following:" }, { "code": null, "e": 27373, "s": 27234, "text": "Example 1: This is the basic example that illustrates how to implement a focus event to display and blur to hide in the Tooltip component." }, { "code": null, "e": 27392, "s": 27373, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeeks</h2><h5>PrimeNG Tooltip Component</h5><div class=\"p-grid p-fluid\"> <div class=\"p-col-12 p-md-3\"> <input type=\"text\" pInputText pTooltip=\"It is a tooltip\" placeholder=\"Hover Here\" tooltipEvent=\"focus\"/> </div> <div class=\"p-col-12 p-md-3\"> <input type=\"text\" pInputText pTooltip=\"It is a tooltip\" placeholder=\"Hover Here\" tooltipPosition=\"bottom\" tooltipEvent=\"focus\"/> </div></div>", "e": 27858, "s": 27392, "text": null }, { "code": null, "e": 27875, "s": 27858, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'mt-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {}", "e": 28058, "s": 27875, "text": null }, { "code": null, "e": 28072, "s": 28058, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { TooltipModule } from \"primeng/tooltip\";import { InputTextModule } from \"primeng/inputtext\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, TooltipModule, InputTextModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 28603, "s": 28072, "text": null }, { "code": null, "e": 28613, "s": 28605, "text": "Output:" }, { "code": null, "e": 28696, "s": 28613, "text": "Example 2: In this example, we are going to use the tooltip component in a button." }, { "code": null, "e": 28715, "s": 28696, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeeks</h2><h5>PrimeNG Tooltip Component</h5><div class=\"p-grid p-fluid\"> <div class=\"p-col-12 p-md-3\"> <p-button label=\"Hover Here\" pTooltip=\"It is a tooltip\"></p-button> </div> <div class=\"p-col-12 p-md-3\"> <p-button label=\"Hover Here\" pTooltip=\"It is a tooltip\" tooltipPosition=\"bottom\"> </p-button> </div></div>", "e": 29071, "s": 28715, "text": null }, { "code": null, "e": 29088, "s": 29071, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'mt-app', templateUrl: './app.component.html', styleUrls: ['./app.component.scss']})export class AppComponent {}", "e": 29271, "s": 29088, "text": null }, { "code": null, "e": 29285, "s": 29271, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { TooltipModule } from \"primeng/tooltip\";import { ButtonModule } from \"primeng/button\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, TooltipModule, ButtonModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 29807, "s": 29285, "text": null }, { "code": null, "e": 29815, "s": 29807, "text": "Output:" }, { "code": null, "e": 29876, "s": 29815, "text": "Reference: https://primefaces.org/primeng/showcase/#/tooltip" }, { "code": null, "e": 29892, "s": 29876, "text": "Angular-PrimeNG" }, { "code": null, "e": 29902, "s": 29892, "text": "AngularJS" }, { "code": null, "e": 29919, "s": 29902, "text": "Web Technologies" }, { "code": null, "e": 30017, "s": 29919, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30026, "s": 30017, "text": "Comments" }, { "code": null, "e": 30039, "s": 30026, "text": "Old Comments" }, { "code": null, "e": 30074, "s": 30039, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 30127, "s": 30074, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 30151, "s": 30127, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 30200, "s": 30151, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 30243, "s": 30200, "text": "How to setup 404 page in angular routing ?" }, { "code": null, "e": 30299, "s": 30243, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 30332, "s": 30299, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30394, "s": 30332, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 30437, "s": 30394, "text": "How to fetch data from an API in ReactJS ?" } ]
Currying Functions in Scala with Examples - GeeksforGeeks
13 Feb, 2019 Currying in Scala is simply a technique or a process of transforming a function. This function takes multiple arguments into a function that takes single argument. It is applied widely in multiple functional languages. Syntax def function name(argument1, argument2) = operation Let’s understand with a simple example,Example: // Scala program add two numbers// using currying Functionobject Curry{ // Define currying function def add(x: Int, y: Int) = x + y; def main(args: Array[String]) { println(add(20, 19)); }} Output: 39 Here, we have define add function which takes two arguments (x and y) and the function simply adds x and y and gives us the result, calling it in the main function. Another way to declare currying functionSuppose, we have to transform this add function into a Curried function, that is transforming the function that takes two(multiple) arguments into a function that takes one(single) argument. Syntax def function name(argument1) = (argument2) => operation Example // Scala program add two numbers// using Currying function object Curry{ // transforming the function that // takes two(multiple) arguments into // a function that takes one(single) argument. def add2(a: Int) = (b: Int) => a + b; // Main method def main(args: Array[String]) { println(add2(20)(19)); }} Output: 39 Here, we have define add2 function which takes only one argument a and we are going to return a second function which will have the value of add2. The second function will also take an argument let say b and this function when called in main, takes two parenthesis(add2()()), where the first parenthesis is of the function add2 and second parenthesis is of the second function. It will return the addition of two numbers, that is a+b. Therefore, we have curried the add function, which means we have transformed the function that takes two arguments into a function that takes one argument and the function itself returns the result. Example // Scala program add two numbers// using Currying functionobject Curry{ def add2(a: Int) = (b: Int) => a + b; // Main function def main(args: Array[String]) { // Partially Applied function. val sum = add2(29); println(sum(5)); }} Output: 34 Here, only one argument is passed while assigning the function to the value. The second argument is passed with the value and these arguments are added and result is printed. Also, another way(syntax) to write the currying function. Syntax def function name(argument1) (argument2) = operation Example // Scala program add two numbers// using Currying functionobject Curry{ // Curring function declaration def add2(a: Int) (b: Int) = a + b; def main(args: Array[String]) { println(add2(29)(5)); }} Output: 34 For this syntax, the Partial Application function also changes.Example // Scala program add two numbers// using Currying functionobject Curry{ // Curring function declaration def add2(a: Int) (b: Int) = a + b; def main(args: Array[String]) { // Partially Applied function. val sum=add2(29)_; println(sum(5)); }} Output: 34 Here, only the ‘_’ is added after the calling the function add2 for value of sum. Scala Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Scala List filter() method with example Scala Map Type Casting in Scala Scala List contains() method with example Scala Lists Scala Tutorial – Learn Scala with Step By Step Guide Operators in Scala Class and Object in Scala Inheritance in Scala Scala | Arrays
[ { "code": null, "e": 23990, "s": 23962, "text": "\n13 Feb, 2019" }, { "code": null, "e": 24216, "s": 23990, "text": "Currying in Scala is simply a technique or a process of transforming a function. This function takes multiple arguments into a function that takes single argument. It is applied widely in multiple functional languages. Syntax" }, { "code": null, "e": 24268, "s": 24216, "text": "def function name(argument1, argument2) = operation" }, { "code": null, "e": 24316, "s": 24268, "text": "Let’s understand with a simple example,Example:" }, { "code": "// Scala program add two numbers// using currying Functionobject Curry{ // Define currying function def add(x: Int, y: Int) = x + y; def main(args: Array[String]) { println(add(20, 19)); }}", "e": 24530, "s": 24316, "text": null }, { "code": null, "e": 24538, "s": 24530, "text": "Output:" }, { "code": null, "e": 24541, "s": 24538, "text": "39" }, { "code": null, "e": 24706, "s": 24541, "text": "Here, we have define add function which takes two arguments (x and y) and the function simply adds x and y and gives us the result, calling it in the main function." }, { "code": null, "e": 24944, "s": 24706, "text": "Another way to declare currying functionSuppose, we have to transform this add function into a Curried function, that is transforming the function that takes two(multiple) arguments into a function that takes one(single) argument. Syntax" }, { "code": null, "e": 25000, "s": 24944, "text": "def function name(argument1) = (argument2) => operation" }, { "code": null, "e": 25008, "s": 25000, "text": "Example" }, { "code": "// Scala program add two numbers// using Currying function object Curry{ // transforming the function that // takes two(multiple) arguments into // a function that takes one(single) argument. def add2(a: Int) = (b: Int) => a + b; // Main method def main(args: Array[String]) { println(add2(20)(19)); }}", "e": 25347, "s": 25008, "text": null }, { "code": null, "e": 25355, "s": 25347, "text": "Output:" }, { "code": null, "e": 25358, "s": 25355, "text": "39" }, { "code": null, "e": 25992, "s": 25358, "text": "Here, we have define add2 function which takes only one argument a and we are going to return a second function which will have the value of add2. The second function will also take an argument let say b and this function when called in main, takes two parenthesis(add2()()), where the first parenthesis is of the function add2 and second parenthesis is of the second function. It will return the addition of two numbers, that is a+b. Therefore, we have curried the add function, which means we have transformed the function that takes two arguments into a function that takes one argument and the function itself returns the result." }, { "code": null, "e": 26000, "s": 25992, "text": "Example" }, { "code": "// Scala program add two numbers// using Currying functionobject Curry{ def add2(a: Int) = (b: Int) => a + b; // Main function def main(args: Array[String]) { // Partially Applied function. val sum = add2(29); println(sum(5)); }}", "e": 26268, "s": 26000, "text": null }, { "code": null, "e": 26276, "s": 26268, "text": "Output:" }, { "code": null, "e": 26279, "s": 26276, "text": "34" }, { "code": null, "e": 26454, "s": 26279, "text": "Here, only one argument is passed while assigning the function to the value. The second argument is passed with the value and these arguments are added and result is printed." }, { "code": null, "e": 26519, "s": 26454, "text": "Also, another way(syntax) to write the currying function. Syntax" }, { "code": null, "e": 26572, "s": 26519, "text": "def function name(argument1) (argument2) = operation" }, { "code": null, "e": 26580, "s": 26572, "text": "Example" }, { "code": "// Scala program add two numbers// using Currying functionobject Curry{ // Curring function declaration def add2(a: Int) (b: Int) = a + b; def main(args: Array[String]) { println(add2(29)(5)); }}", "e": 26800, "s": 26580, "text": null }, { "code": null, "e": 26808, "s": 26800, "text": "Output:" }, { "code": null, "e": 26811, "s": 26808, "text": "34" }, { "code": null, "e": 26882, "s": 26811, "text": "For this syntax, the Partial Application function also changes.Example" }, { "code": "// Scala program add two numbers// using Currying functionobject Curry{ // Curring function declaration def add2(a: Int) (b: Int) = a + b; def main(args: Array[String]) { // Partially Applied function. val sum=add2(29)_; println(sum(5)); }}", "e": 27160, "s": 26882, "text": null }, { "code": null, "e": 27168, "s": 27160, "text": "Output:" }, { "code": null, "e": 27171, "s": 27168, "text": "34" }, { "code": null, "e": 27253, "s": 27171, "text": "Here, only the ‘_’ is added after the calling the function add2 for value of sum." }, { "code": null, "e": 27259, "s": 27253, "text": "Scala" }, { "code": null, "e": 27272, "s": 27259, "text": "Scala-Method" }, { "code": null, "e": 27278, "s": 27272, "text": "Scala" }, { "code": null, "e": 27376, "s": 27278, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27385, "s": 27376, "text": "Comments" }, { "code": null, "e": 27398, "s": 27385, "text": "Old Comments" }, { "code": null, "e": 27438, "s": 27398, "text": "Scala List filter() method with example" }, { "code": null, "e": 27448, "s": 27438, "text": "Scala Map" }, { "code": null, "e": 27470, "s": 27448, "text": "Type Casting in Scala" }, { "code": null, "e": 27512, "s": 27470, "text": "Scala List contains() method with example" }, { "code": null, "e": 27524, "s": 27512, "text": "Scala Lists" }, { "code": null, "e": 27577, "s": 27524, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 27596, "s": 27577, "text": "Operators in Scala" }, { "code": null, "e": 27622, "s": 27596, "text": "Class and Object in Scala" }, { "code": null, "e": 27643, "s": 27622, "text": "Inheritance in Scala" } ]
How do we create an image map in HTML?
To add an image map, use the <map> tag in HTML. The HTML <map> tag is used for defining an image map along with <img> tag. The following is the attribute − You can try to run the following code to learn how to create an image map in HTML − <!DOCTYPE html> <html> <head> <title>HTML map Tag</title> </head> <body> <img src = "/images/html.gif" alt = "HTML Map" border = "0" usemap = "#html"/> <!-- Create Mappings --> <map name = "html"> <area shape = "circle" coords = "154,150,59" href = "about/about_team.htm" alt = "Team" target = "_self" /> </map> </body> </html>
[ { "code": null, "e": 1185, "s": 1062, "text": "To add an image map, use the <map> tag in HTML. The HTML <map> tag is used for defining an image map along with <img> tag." }, { "code": null, "e": 1218, "s": 1185, "text": "The following is the attribute −" }, { "code": null, "e": 1302, "s": 1218, "text": "You can try to run the following code to learn how to create an image map in HTML −" }, { "code": null, "e": 1690, "s": 1302, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML map Tag</title>\n </head>\n <body>\n <img src = \"/images/html.gif\" alt = \"HTML Map\" border = \"0\" usemap = \"#html\"/>\n <!-- Create Mappings -->\n <map name = \"html\">\n <area shape = \"circle\" coords = \"154,150,59\" href = \"about/about_team.htm\"\n alt = \"Team\" target = \"_self\" />\n </map>\n </body>\n</html>" } ]
Python | Numpy numpy.matrix.H() - GeeksforGeeks
08 Apr, 2019 With the help of Numpy numpy.matrix.H() method, we can make a conjugate Transpose of any complex matrix either having dimension one or more than more. Syntax : numpy.matrix.H() Return : Return conjugate transpose of every complex matrix Example #1 :In this example we can see that with the help of matrix.H() method, we are able to transform any type of complex matrix. # import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix([1-2j, 3-4j]) # applying matrix.H() methodgeeks = gfg.getH() print(geeks) [[ 1.+2.j] [ 3.+4.j]] Example #2 : # import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix([[1-5j, 2 + 5j, 3-3j], [4 + 6j, 5-8j, 6-2j], [7 + 6j, 8-6j, 9 + 1.j]]) # applying matrix.H() methodgeeks = gfg.getH() print(geeks) [[ 1.+5.j 4.-6.j 7.-6.j] [ 2.-5.j 5.+8.j 8.+6.j] [ 3.+3.j 6.+2.j 9.-1.j]] Python numpy-Matrix Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24420, "s": 24392, "text": "\n08 Apr, 2019" }, { "code": null, "e": 24571, "s": 24420, "text": "With the help of Numpy numpy.matrix.H() method, we can make a conjugate Transpose of any complex matrix either having dimension one or more than more." }, { "code": null, "e": 24597, "s": 24571, "text": "Syntax : numpy.matrix.H()" }, { "code": null, "e": 24657, "s": 24597, "text": "Return : Return conjugate transpose of every complex matrix" }, { "code": null, "e": 24790, "s": 24657, "text": "Example #1 :In this example we can see that with the help of matrix.H() method, we are able to transform any type of complex matrix." }, { "code": "# import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix([1-2j, 3-4j]) # applying matrix.H() methodgeeks = gfg.getH() print(geeks)", "e": 24985, "s": 24790, "text": null }, { "code": null, "e": 25009, "s": 24985, "text": "[[ 1.+2.j]\n [ 3.+4.j]]\n" }, { "code": null, "e": 25022, "s": 25009, "text": "Example #2 :" }, { "code": "# import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix([[1-5j, 2 + 5j, 3-3j], [4 + 6j, 5-8j, 6-2j], [7 + 6j, 8-6j, 9 + 1.j]]) # applying matrix.H() methodgeeks = gfg.getH() print(geeks)", "e": 25274, "s": 25022, "text": null }, { "code": null, "e": 25357, "s": 25274, "text": "[[ 1.+5.j 4.-6.j 7.-6.j]\n [ 2.-5.j 5.+8.j 8.+6.j]\n [ 3.+3.j 6.+2.j 9.-1.j]]\n" }, { "code": null, "e": 25386, "s": 25357, "text": "Python numpy-Matrix Function" }, { "code": null, "e": 25399, "s": 25386, "text": "Python-numpy" }, { "code": null, "e": 25406, "s": 25399, "text": "Python" }, { "code": null, "e": 25504, "s": 25406, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25522, "s": 25504, "text": "Python Dictionary" }, { "code": null, "e": 25557, "s": 25522, "text": "Read a file line by line in Python" }, { "code": null, "e": 25579, "s": 25557, "text": "Enumerate() in Python" }, { "code": null, "e": 25611, "s": 25579, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25641, "s": 25611, "text": "Iterate over a list in Python" }, { "code": null, "e": 25683, "s": 25641, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 25709, "s": 25683, "text": "Python String | replace()" }, { "code": null, "e": 25746, "s": 25709, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 25789, "s": 25746, "text": "Python program to convert a list to string" } ]
How to set "step" on axis X in my figure in Matplotlib Python 2.6.6?
To set Step on X-axis in a figure in Matplotlib Python, we can take the following Steps − Create a list of data points, x. Add a subplot to the current figure using subplot() method. Set xticks and ticklabels with rotation=45. To display the figure, use show() method. import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True x = [1, 2, 3, 4] y = [1.2, 1.9, 3.1, 4.2] plt.plot(x,y) ax1 = plt.subplot() ax1.set_xticks(x) ax1.set_xticklabels(["one", "two", "three", "four"], rotation=45) plt.show()
[ { "code": null, "e": 1152, "s": 1062, "text": "To set Step on X-axis in a figure in Matplotlib Python, we can take the following Steps −" }, { "code": null, "e": 1185, "s": 1152, "text": "Create a list of data points, x." }, { "code": null, "e": 1245, "s": 1185, "text": "Add a subplot to the current figure using subplot() method." }, { "code": null, "e": 1289, "s": 1245, "text": "Set xticks and ticklabels with rotation=45." }, { "code": null, "e": 1331, "s": 1289, "text": "To display the figure, use show() method." }, { "code": null, "e": 1621, "s": 1331, "text": "import matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = [1, 2, 3, 4]\ny = [1.2, 1.9, 3.1, 4.2]\nplt.plot(x,y)\nax1 = plt.subplot()\nax1.set_xticks(x)\nax1.set_xticklabels([\"one\", \"two\", \"three\", \"four\"], rotation=45)\nplt.show()" } ]
Convex Hull | Practice | GeeksforGeeks
Convex Hull of a set of points, in 2D plane, is a convex polygon with minimum area such that each point lies either on the boundary of polygon or inside it. Now given a set of points the task is to find the convex hull of points. Example 1: Input: points_list = {{1,2},{3,1},{5,6}} Output: {{1,2},{3,1},{5,6}} Example 2: Input : points_list = {{5,1},{4,4},{1,2}} Output: {{1,2},{4,4},{5,1}} Your Task: You don't need to read or print anything. Your task is to complete the function FindConvexHull() which takes points_list as input parameter and returns Convex Hull of given points in a list. If not possible returns a list containing -1. Expected Time Complexity: O(nlog(n)) Expected Space Complexity: O(n) where n = total no. of points Constraints: 1 <= n <= 104 -105 <= x, y <= 105 0 Mozammel Hossen1 year ago Mozammel Hossen Why it is giving WA? My Code: https://paste.ubuntu.com/p/... Input:12941 1 23 32 46 26 36 41 15 36 39 40 7 48 14 12 12 39 34 37 38 9 16 47 37 9 32 31 26 35 40 16 37 40 44 1 48 22 34 39 49 10 41 16 49 36 45 44 43 25 21 48 7 37 3 30 15 1 Correct Output:3 30, 7 48, 15 1, 21 48, 44 1, 45 44, 49 10, 49 36 My Output:3 30, 7 48, 15 1, 21 48, 41 1, 44 1, 45 44, 49 10, 49 36 0 rahul sharma2 years ago rahul sharma for sample test case161 1 2 2 2 0 2 4 3 3 4 2 The accepted solutions i tried ere does not consider 3,3 as part of output and those are accepted but 3,3 must be part of solution.what did i miss 0 anand verma2 years ago anand verma Input:14778 887 794 916 387 336 650 493 363 422 691 28 764 60 541 927 173 427 212 737 568 369 783 430 863 531 68 124 Its Correct output is:68 124, 212 737, 541 927, 691 28, 764 60, 794 916, 863 531 And Your Code's output is:68 124, 212 737, 541 927, 794 916, 863 531, 764 60, 691 28what's the problem here i'm using graham scan please helpthnx in advance 0 shivam kumar2 years ago shivam kumar https://practice.geeksforge... if it can help, considered co-linear case. 0 Sunil Aditya2 years ago Sunil Aditya my pyhton 3 code https://ide.geeksforgeeks.o...there are two wrong test acse31 11 2 1 1and 41 1 1 23 43 4so use try except to handle it 0 Prashant Singh2 years ago Prashant Singh What wrong in my output,I did run this input to geeks provided code which is giving output similar to my codeInput:2529 23 33 47 16 20 9 25 49 40 40 23 8 23 15 38 10 30 39 48 18 44 10 13 7 31 10 47 48 48 6 15 46 30 45 3 30 48 36 30 25 22 23 21 38 45 26 43 5 27 Its Correct output is:5 27, 6 15, 10 13, 10 47, 30 48, 45 3, 48 48, 49 40 And Your Code's output is:5 27, 6 15, 10 13, 10 47, 30 48, 39 48, 45 3, 48 48, 49 40@shameek_agarwal:disqus 0 aniket poddar2 years ago aniket poddar https://ide.geeksforgeeks.o... Here why are we not considering co-linear points 0 Vidit Gupta2 years ago Vidit Gupta Code working fine while compiling, but getting the below error while submitting code. Plz help @quandray:disqus. Runtime Error:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2 at GFG.main(File.java:35) https://ide.geeksforgeeks.o... -1 Shameek Agarwal2 years ago Shameek Agarwal Graham scan workingmy code->https://ideone.com/yeCEga 0 yash2 years ago yash https://ide.geeksforgeeks.o... getting segmentation fault We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 470, "s": 238, "text": "Convex Hull of a set of points, in 2D plane, is a convex polygon with minimum area such that each point lies either on the boundary of polygon or inside it. Now given a set of points the task is to find the convex hull of points.\n " }, { "code": null, "e": 481, "s": 470, "text": "Example 1:" }, { "code": null, "e": 551, "s": 481, "text": "Input: points_list = {{1,2},{3,1},{5,6}}\nOutput: {{1,2},{3,1},{5,6}}\n" }, { "code": null, "e": 562, "s": 551, "text": "Example 2:" }, { "code": null, "e": 633, "s": 562, "text": "Input : points_list = {{5,1},{4,4},{1,2}}\nOutput: {{1,2},{4,4},{5,1}}\n" }, { "code": null, "e": 885, "s": 635, "text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function FindConvexHull() which takes points_list as input parameter and returns Convex Hull of given points in a list. If not possible returns a list containing -1.\n " }, { "code": null, "e": 986, "s": 885, "text": "Expected Time Complexity: O(nlog(n))\nExpected Space Complexity: O(n) where n = total no. of points\n " }, { "code": null, "e": 1033, "s": 986, "text": "Constraints:\n1 <= n <= 104\n-105 <= x, y <= 105" }, { "code": null, "e": 1035, "s": 1033, "text": "0" }, { "code": null, "e": 1061, "s": 1035, "text": "Mozammel Hossen1 year ago" }, { "code": null, "e": 1077, "s": 1061, "text": "Mozammel Hossen" }, { "code": null, "e": 1098, "s": 1077, "text": "Why it is giving WA?" }, { "code": null, "e": 1138, "s": 1098, "text": "My Code: https://paste.ubuntu.com/p/..." }, { "code": null, "e": 1313, "s": 1138, "text": "Input:12941 1 23 32 46 26 36 41 15 36 39 40 7 48 14 12 12 39 34 37 38 9 16 47 37 9 32 31 26 35 40 16 37 40 44 1 48 22 34 39 49 10 41 16 49 36 45 44 43 25 21 48 7 37 3 30 15 1" }, { "code": null, "e": 1379, "s": 1313, "text": "Correct Output:3 30, 7 48, 15 1, 21 48, 44 1, 45 44, 49 10, 49 36" }, { "code": null, "e": 1446, "s": 1379, "text": "My Output:3 30, 7 48, 15 1, 21 48, 41 1, 44 1, 45 44, 49 10, 49 36" }, { "code": null, "e": 1448, "s": 1446, "text": "0" }, { "code": null, "e": 1472, "s": 1448, "text": "rahul sharma2 years ago" }, { "code": null, "e": 1485, "s": 1472, "text": "rahul sharma" }, { "code": null, "e": 1531, "s": 1485, "text": "for sample test case161 1 2 2 2 0 2 4 3 3 4 2" }, { "code": null, "e": 1678, "s": 1531, "text": "The accepted solutions i tried ere does not consider 3,3 as part of output and those are accepted but 3,3 must be part of solution.what did i miss" }, { "code": null, "e": 1680, "s": 1678, "text": "0" }, { "code": null, "e": 1703, "s": 1680, "text": "anand verma2 years ago" }, { "code": null, "e": 1715, "s": 1703, "text": "anand verma" }, { "code": null, "e": 1832, "s": 1715, "text": "Input:14778 887 794 916 387 336 650 493 363 422 691 28 764 60 541 927 173 427 212 737 568 369 783 430 863 531 68 124" }, { "code": null, "e": 1913, "s": 1832, "text": "Its Correct output is:68 124, 212 737, 541 927, 691 28, 764 60, 794 916, 863 531" }, { "code": null, "e": 2070, "s": 1913, "text": "And Your Code's output is:68 124, 212 737, 541 927, 794 916, 863 531, 764 60, 691 28what's the problem here i'm using graham scan please helpthnx in advance" }, { "code": null, "e": 2072, "s": 2070, "text": "0" }, { "code": null, "e": 2096, "s": 2072, "text": "shivam kumar2 years ago" }, { "code": null, "e": 2109, "s": 2096, "text": "shivam kumar" }, { "code": null, "e": 2140, "s": 2109, "text": "https://practice.geeksforge..." }, { "code": null, "e": 2183, "s": 2140, "text": "if it can help, considered co-linear case." }, { "code": null, "e": 2185, "s": 2183, "text": "0" }, { "code": null, "e": 2209, "s": 2185, "text": "Sunil Aditya2 years ago" }, { "code": null, "e": 2222, "s": 2209, "text": "Sunil Aditya" }, { "code": null, "e": 2358, "s": 2222, "text": "my pyhton 3 code https://ide.geeksforgeeks.o...there are two wrong test acse31 11 2 1 1and 41 1 1 23 43 4so use try except to handle it" }, { "code": null, "e": 2360, "s": 2358, "text": "0" }, { "code": null, "e": 2386, "s": 2360, "text": "Prashant Singh2 years ago" }, { "code": null, "e": 2401, "s": 2386, "text": "Prashant Singh" }, { "code": null, "e": 2662, "s": 2401, "text": "What wrong in my output,I did run this input to geeks provided code which is giving output similar to my codeInput:2529 23 33 47 16 20 9 25 49 40 40 23 8 23 15 38 10 30 39 48 18 44 10 13 7 31 10 47 48 48 6 15 46 30 45 3 30 48 36 30 25 22 23 21 38 45 26 43 5 27" }, { "code": null, "e": 2736, "s": 2662, "text": "Its Correct output is:5 27, 6 15, 10 13, 10 47, 30 48, 45 3, 48 48, 49 40" }, { "code": null, "e": 2844, "s": 2736, "text": "And Your Code's output is:5 27, 6 15, 10 13, 10 47, 30 48, 39 48, 45 3, 48 48, 49 40@shameek_agarwal:disqus" }, { "code": null, "e": 2846, "s": 2844, "text": "0" }, { "code": null, "e": 2871, "s": 2846, "text": "aniket poddar2 years ago" }, { "code": null, "e": 2885, "s": 2871, "text": "aniket poddar" }, { "code": null, "e": 2916, "s": 2885, "text": "https://ide.geeksforgeeks.o..." }, { "code": null, "e": 2965, "s": 2916, "text": "Here why are we not considering co-linear points" }, { "code": null, "e": 2967, "s": 2965, "text": "0" }, { "code": null, "e": 2990, "s": 2967, "text": "Vidit Gupta2 years ago" }, { "code": null, "e": 3002, "s": 2990, "text": "Vidit Gupta" }, { "code": null, "e": 3115, "s": 3002, "text": "Code working fine while compiling, but getting the below error while submitting code. Plz help @quandray:disqus." }, { "code": null, "e": 3259, "s": 3115, "text": "Runtime Error:Exception in thread \"main\" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2 at GFG.main(File.java:35)" }, { "code": null, "e": 3290, "s": 3259, "text": "https://ide.geeksforgeeks.o..." }, { "code": null, "e": 3293, "s": 3290, "text": "-1" }, { "code": null, "e": 3320, "s": 3293, "text": "Shameek Agarwal2 years ago" }, { "code": null, "e": 3336, "s": 3320, "text": "Shameek Agarwal" }, { "code": null, "e": 3390, "s": 3336, "text": "Graham scan workingmy code->https://ideone.com/yeCEga" }, { "code": null, "e": 3392, "s": 3390, "text": "0" }, { "code": null, "e": 3408, "s": 3392, "text": "yash2 years ago" }, { "code": null, "e": 3413, "s": 3408, "text": "yash" }, { "code": null, "e": 3444, "s": 3413, "text": "https://ide.geeksforgeeks.o..." }, { "code": null, "e": 3471, "s": 3444, "text": "getting segmentation fault" }, { "code": null, "e": 3617, "s": 3471, "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": 3653, "s": 3617, "text": " Login to access your submissions. " }, { "code": null, "e": 3663, "s": 3653, "text": "\nProblem\n" }, { "code": null, "e": 3673, "s": 3663, "text": "\nContest\n" }, { "code": null, "e": 3736, "s": 3673, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3884, "s": 3736, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 4092, "s": 3884, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 4198, "s": 4092, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How set AWS Access Keys in Windows or Mac Environment - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws It is important to know how to set AWS Access keys in Windows or Mac when we are connecting to AWS using AWS CLI. AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are the programmatic credentials, which helps us to connect with the AWS using the AWS command-line interface. In Windows, we can add these secrets using the set, setx commands. set AWS_ACCESS_KEY_ID=Your_Access_Key set AWS_SECRET_ACCESS_KEY=Your_Secred_Access_Key set AWS_DEFAULT_REGION=Your_AWS_Region set modifies the current shell’s (the window’s) environment values, and the change is available immediately, but it is temporary. setx AWS_ACCESS_KEY_ID=Your_Access_Key setx AWS_SECRET_ACCESS_KEY=Your_Secred_Access_Key setx AWS_DEFAULT_REGION=Your_AWS_Region setx modifies the value permanently, which affects all future shells, but does not modify the environment of the shells already running. You have to exit the shell and reopen it before the change will be available, but the value will remain modified until you change it again. $env:AWS_ACCESS_KEY_ID="Your_Access_Key" $env:AWS_SECRET_ACCESS_KEY="Your_Secred_Access_Key" In Mac or Linux flavours, you can set the values using the export keyword. export AWS_ACCESS_KEY_ID=Your_Access_Key export AWS_SECRET_ACCESS_KEY=Your_Secred_Access_Key export AWS_DEFAULT_REGION=Your_AWS_Region export also just like set in windows, it modifies the current shell’s environment values, and the change is available immediately, but it is temporary. If you want to have permanent values in Mac or Linux environments, add the values into bash_profile.sh like below export AWS_ACCESS_KEY_ID=Your_Access_Key export AWS_SECRET_ACCESS_KEY=Your_Secred_Access_Key export AWS_DEFAULT_REGION=Your_AWS_Region Apply the source command to save the bash_profile. $source ~/.bash_profile [default] aws_access_key_id=Your_Access_Key aws_secret_access_key= Your_Secred_Access_Key AWS CLI install Happy Learning 🙂 How to install AWS CLI on Windows 10 How to Copy Local Files to AWS EC2 instance Manually ? Python – AWS SAM Lambda Example How to connect AWS EC2 Instance using PuTTY C Structures – Access the members of a Struct How add files to S3 Bucket using Shell Script How to access for loop index in Python [Fixed] – Error: No changes to deploy. Stack is up to date How to install PuTTY on windows 10 How to install Java on Mac OS How to install Elasticsearch on Windows 10 Install Docker Desktop on Windows 10 How to install Docker Toolbox on Windows 10 How to install SOAPUI on Windows 10 Spring Boot Environment Properties reading based on activeprofile How to install AWS CLI on Windows 10 How to Copy Local Files to AWS EC2 instance Manually ? Python – AWS SAM Lambda Example How to connect AWS EC2 Instance using PuTTY C Structures – Access the members of a Struct How add files to S3 Bucket using Shell Script How to access for loop index in Python [Fixed] – Error: No changes to deploy. Stack is up to date How to install PuTTY on windows 10 How to install Java on Mac OS How to install Elasticsearch on Windows 10 Install Docker Desktop on Windows 10 How to install Docker Toolbox on Windows 10 How to install SOAPUI on Windows 10 Spring Boot Environment Properties reading based on activeprofile Δ Install Java on Mac OS Install AWS CLI on Windows Install Minikube on Windows Install Docker Toolbox on Windows Install SOAPUI on Windows Install Gradle on Windows Install RabbitMQ on Windows Install PuTTY on windows Install Mysql on Windows Install Hibernate Tools in Eclipse Install Elasticsearch on Windows Install Maven on Windows Install Maven on Ubuntu Install Maven on Windows Command Add OJDBC jar to Maven Repository Install Ant on Windows Install RabbitMQ on Windows Install Apache Kafka on Ubuntu Install Apache Kafka on Windows
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 512, "s": 398, "text": "It is important to know how to set AWS Access keys in Windows or Mac when we are connecting to AWS using AWS CLI." }, { "code": null, "e": 734, "s": 512, "text": "AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are the programmatic credentials, which helps us to connect with the AWS using the AWS command-line interface. In Windows, we can add these secrets using the set, setx commands." }, { "code": null, "e": 860, "s": 734, "text": "set AWS_ACCESS_KEY_ID=Your_Access_Key\nset AWS_SECRET_ACCESS_KEY=Your_Secred_Access_Key\nset AWS_DEFAULT_REGION=Your_AWS_Region" }, { "code": null, "e": 990, "s": 860, "text": "set modifies the current shell’s (the window’s) environment values, and the change is available immediately, but it is temporary." }, { "code": null, "e": 1121, "s": 990, "text": "setx AWS_ACCESS_KEY_ID=Your_Access_Key \nsetx AWS_SECRET_ACCESS_KEY=Your_Secred_Access_Key \nsetx AWS_DEFAULT_REGION=Your_AWS_Region" }, { "code": null, "e": 1398, "s": 1121, "text": "setx modifies the value permanently, which affects all future shells, but does not modify the environment of the shells already running. You have to exit the shell and reopen it before the change will be available, but the value will remain modified until you change it again." }, { "code": null, "e": 1491, "s": 1398, "text": "$env:AWS_ACCESS_KEY_ID=\"Your_Access_Key\"\n$env:AWS_SECRET_ACCESS_KEY=\"Your_Secred_Access_Key\"" }, { "code": null, "e": 1566, "s": 1491, "text": "In Mac or Linux flavours, you can set the values using the export keyword." }, { "code": null, "e": 1703, "s": 1566, "text": "export AWS_ACCESS_KEY_ID=Your_Access_Key \nexport AWS_SECRET_ACCESS_KEY=Your_Secred_Access_Key \nexport AWS_DEFAULT_REGION=Your_AWS_Region" }, { "code": null, "e": 1855, "s": 1703, "text": "export also just like set in windows, it modifies the current shell’s environment values, and the change is available immediately, but it is temporary." }, { "code": null, "e": 1969, "s": 1855, "text": "If you want to have permanent values in Mac or Linux environments, add the values into bash_profile.sh like below" }, { "code": null, "e": 2106, "s": 1969, "text": "export AWS_ACCESS_KEY_ID=Your_Access_Key \nexport AWS_SECRET_ACCESS_KEY=Your_Secred_Access_Key \nexport AWS_DEFAULT_REGION=Your_AWS_Region" }, { "code": null, "e": 2157, "s": 2106, "text": "Apply the source command to save the bash_profile." }, { "code": null, "e": 2181, "s": 2157, "text": "$source ~/.bash_profile" }, { "code": null, "e": 2272, "s": 2181, "text": "[default]\naws_access_key_id=Your_Access_Key\naws_secret_access_key= Your_Secred_Access_Key " }, { "code": null, "e": 2288, "s": 2272, "text": "AWS CLI install" }, { "code": null, "e": 2305, "s": 2288, "text": "Happy Learning 🙂" }, { "code": null, "e": 2956, "s": 2305, "text": "\nHow to install AWS CLI on Windows 10\nHow to Copy Local Files to AWS EC2 instance Manually ?\nPython – AWS SAM Lambda Example\nHow to connect AWS EC2 Instance using PuTTY\nC Structures – Access the members of a Struct\nHow add files to S3 Bucket using Shell Script\nHow to access for loop index in Python\n[Fixed] – Error: No changes to deploy. Stack is up to date\nHow to install PuTTY on windows 10\nHow to install Java on Mac OS\nHow to install Elasticsearch on Windows 10\nInstall Docker Desktop on Windows 10\nHow to install Docker Toolbox on Windows 10\nHow to install SOAPUI on Windows 10\nSpring Boot Environment Properties reading based on activeprofile\n" }, { "code": null, "e": 2993, "s": 2956, "text": "How to install AWS CLI on Windows 10" }, { "code": null, "e": 3048, "s": 2993, "text": "How to Copy Local Files to AWS EC2 instance Manually ?" }, { "code": null, "e": 3080, "s": 3048, "text": "Python – AWS SAM Lambda Example" }, { "code": null, "e": 3124, "s": 3080, "text": "How to connect AWS EC2 Instance using PuTTY" }, { "code": null, "e": 3170, "s": 3124, "text": "C Structures – Access the members of a Struct" }, { "code": null, "e": 3216, "s": 3170, "text": "How add files to S3 Bucket using Shell Script" }, { "code": null, "e": 3255, "s": 3216, "text": "How to access for loop index in Python" }, { "code": null, "e": 3314, "s": 3255, "text": "[Fixed] – Error: No changes to deploy. Stack is up to date" }, { "code": null, "e": 3349, "s": 3314, "text": "How to install PuTTY on windows 10" }, { "code": null, "e": 3379, "s": 3349, "text": "How to install Java on Mac OS" }, { "code": null, "e": 3422, "s": 3379, "text": "How to install Elasticsearch on Windows 10" }, { "code": null, "e": 3459, "s": 3422, "text": "Install Docker Desktop on Windows 10" }, { "code": null, "e": 3503, "s": 3459, "text": "How to install Docker Toolbox on Windows 10" }, { "code": null, "e": 3539, "s": 3503, "text": "How to install SOAPUI on Windows 10" }, { "code": null, "e": 3605, "s": 3539, "text": "Spring Boot Environment Properties reading based on activeprofile" }, { "code": null, "e": 3611, "s": 3609, "text": "Δ" }, { "code": null, "e": 3635, "s": 3611, "text": " Install Java on Mac OS" }, { "code": null, "e": 3663, "s": 3635, "text": " Install AWS CLI on Windows" }, { "code": null, "e": 3692, "s": 3663, "text": " Install Minikube on Windows" }, { "code": null, "e": 3727, "s": 3692, "text": " Install Docker Toolbox on Windows" }, { "code": null, "e": 3754, "s": 3727, "text": " Install SOAPUI on Windows" }, { "code": null, "e": 3781, "s": 3754, "text": " Install Gradle on Windows" }, { "code": null, "e": 3810, "s": 3781, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 3836, "s": 3810, "text": " Install PuTTY on windows" }, { "code": null, "e": 3862, "s": 3836, "text": " Install Mysql on Windows" }, { "code": null, "e": 3898, "s": 3862, "text": " Install Hibernate Tools in Eclipse" }, { "code": null, "e": 3932, "s": 3898, "text": " Install Elasticsearch on Windows" }, { "code": null, "e": 3958, "s": 3932, "text": " Install Maven on Windows" }, { "code": null, "e": 3983, "s": 3958, "text": " Install Maven on Ubuntu" }, { "code": null, "e": 4017, "s": 3983, "text": " Install Maven on Windows Command" }, { "code": null, "e": 4052, "s": 4017, "text": " Add OJDBC jar to Maven Repository" }, { "code": null, "e": 4076, "s": 4052, "text": " Install Ant on Windows" }, { "code": null, "e": 4105, "s": 4076, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 4137, "s": 4105, "text": " Install Apache Kafka on Ubuntu" } ]
Static Members of a C++ Class
We can define class members static using static keyword. When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member. A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present. We can't put it in the class definition but it can be initialized outside the class as done in the following example by redeclaring the static variable, using the scope resolution operator :: to identify which class it belongs to. Let us try the following example to understand the concept of static data members − #include <iostream> using namespace std; class Box { public: static int objectCount; // Constructor definition Box(double l = 2.0, double b = 2.0, double h = 2.0) { cout <<"Constructor called." << endl; length = l; breadth = b; height = h; // Increase every time object is created objectCount++; } double Volume() { return length * breadth * height; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; // Initialize static member of class Box int Box::objectCount = 0; int main(void) { Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2 // Print total number of objects. cout << "Total objects: " << Box::objectCount << endl; return 0; } When the above code is compiled and executed, it produces the following result − Constructor called. Constructor called. Total objects: 2 By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::. A static member function can only access static data member, other static member functions and any other functions from outside the class. Static member functions have a class scope and they do not have access to the this pointer of the class. You could use a static member function to determine whether some objects of the class have been created or not. Let us try the following example to understand the concept of static function members − #include <iostream> using namespace std; class Box { public: static int objectCount; // Constructor definition Box(double l = 2.0, double b = 2.0, double h = 2.0) { cout <<"Constructor called." << endl; length = l; breadth = b; height = h; // Increase every time object is created objectCount++; } double Volume() { return length * breadth * height; } static int getCount() { return objectCount; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; // Initialize static member of class Box int Box::objectCount = 0; int main(void) { // Print total number of objects before creating object. cout << "Inital Stage Count: " << Box::getCount() << endl; Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2 // Print total number of objects after creating object. cout << "Final Stage Count: " << Box::getCount() << endl; return 0; } When the above code is compiled and executed, it produces the following result − Inital Stage Count: 0 Constructor called. Constructor called. Final Stage Count: 2 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": 2528, "s": 2318, "text": "We can define class members static using static keyword. When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member." }, { "code": null, "e": 2926, "s": 2528, "text": "A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present. We can't put it in the class definition but it can be initialized outside the class as done in the following example by redeclaring the static variable, using the scope resolution operator :: to identify which class it belongs to." }, { "code": null, "e": 3010, "s": 2926, "text": "Let us try the following example to understand the concept of static data members −" }, { "code": null, "e": 3931, "s": 3010, "text": "#include <iostream>\n \nusing namespace std;\n\nclass Box {\n public:\n static int objectCount;\n \n // Constructor definition\n Box(double l = 2.0, double b = 2.0, double h = 2.0) {\n cout <<\"Constructor called.\" << endl;\n length = l;\n breadth = b;\n height = h;\n \n // Increase every time object is created\n objectCount++;\n }\n double Volume() {\n return length * breadth * height;\n }\n \n private:\n double length; // Length of a box\n double breadth; // Breadth of a box\n double height; // Height of a box\n};\n\n// Initialize static member of class Box\nint Box::objectCount = 0;\n\nint main(void) {\n Box Box1(3.3, 1.2, 1.5); // Declare box1\n Box Box2(8.5, 6.0, 2.0); // Declare box2\n\n // Print total number of objects.\n cout << \"Total objects: \" << Box::objectCount << endl;\n\n return 0;\n}" }, { "code": null, "e": 4012, "s": 3931, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4070, "s": 4012, "text": "Constructor called.\nConstructor called.\nTotal objects: 2\n" }, { "code": null, "e": 4354, "s": 4070, "text": "By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::." }, { "code": null, "e": 4493, "s": 4354, "text": "A static member function can only access static data member, other static member functions and any other functions from outside the class." }, { "code": null, "e": 4710, "s": 4493, "text": "Static member functions have a class scope and they do not have access to the this pointer of the class. You could use a static member function to determine whether some objects of the class have been created or not." }, { "code": null, "e": 4798, "s": 4710, "text": "Let us try the following example to understand the concept of static function members −" }, { "code": null, "e": 5925, "s": 4798, "text": "#include <iostream>\n \nusing namespace std;\n\nclass Box {\n public:\n static int objectCount;\n \n // Constructor definition\n Box(double l = 2.0, double b = 2.0, double h = 2.0) {\n cout <<\"Constructor called.\" << endl;\n length = l;\n breadth = b;\n height = h;\n\n // Increase every time object is created\n objectCount++;\n }\n double Volume() {\n return length * breadth * height;\n }\n static int getCount() {\n return objectCount;\n }\n \n private:\n double length; // Length of a box\n double breadth; // Breadth of a box\n double height; // Height of a box\n};\n\n// Initialize static member of class Box\nint Box::objectCount = 0;\n\nint main(void) {\n // Print total number of objects before creating object.\n cout << \"Inital Stage Count: \" << Box::getCount() << endl;\n\n Box Box1(3.3, 1.2, 1.5); // Declare box1\n Box Box2(8.5, 6.0, 2.0); // Declare box2\n\n // Print total number of objects after creating object.\n cout << \"Final Stage Count: \" << Box::getCount() << endl;\n\n return 0;\n}" }, { "code": null, "e": 6006, "s": 5925, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 6090, "s": 6006, "text": "Inital Stage Count: 0\nConstructor called.\nConstructor called.\nFinal Stage Count: 2\n" }, { "code": null, "e": 6127, "s": 6090, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 6146, "s": 6127, "text": " Arnab Chakraborty" }, { "code": null, "e": 6178, "s": 6146, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 6201, "s": 6178, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 6237, "s": 6201, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 6254, "s": 6237, "text": " Frahaan Hussain" }, { "code": null, "e": 6289, "s": 6254, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6306, "s": 6289, "text": " Frahaan Hussain" }, { "code": null, "e": 6341, "s": 6306, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6358, "s": 6341, "text": " Frahaan Hussain" }, { "code": null, "e": 6393, "s": 6358, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6410, "s": 6393, "text": " Frahaan Hussain" }, { "code": null, "e": 6417, "s": 6410, "text": " Print" }, { "code": null, "e": 6428, "s": 6417, "text": " Add Notes" } ]
Java AWT | Ellipse2D - GeeksforGeeks
31 Oct, 2019 Ellipse2D class is present in java.awt.geom package and it is used to define an ellipse by stating its framing rectangle. This class is only the abstract superclass for all objects which store a 2D ellipse. Ellipse2D.Double defines an ellipse with double precision. Ellipse2D.Float defines an ellipse with float precision. Constructor of the class are: Ellipse2D.Double() : creates an ellipse at location 0, 0 and size 0, 0.Ellipse2D.Double(double x, double y, double w, double h) : creates an ellipse at location x, y and width w and height h.Ellipse2D.Float() : creates an ellipse at location 0, 0 and size 0, 0.Ellipse2D.Float(Float x, Float y, Float w, Float h) : creates an ellipse at location x, y and width w and height h. Ellipse2D.Double() : creates an ellipse at location 0, 0 and size 0, 0. Ellipse2D.Double(double x, double y, double w, double h) : creates an ellipse at location x, y and width w and height h. Ellipse2D.Float() : creates an ellipse at location 0, 0 and size 0, 0. Ellipse2D.Float(Float x, Float y, Float w, Float h) : creates an ellipse at location x, y and width w and height h. Commonly used methods: Below programs illustrate the Ellipse2D class: Java program to create two ellipses and draw them to a java applet: To create ellipse shape on Java applet, we will initialize Ellipse2d class objects named “ed” and “ed1”. The 4 parameters passed in the constructor of the “ed” object are the X coordinate of the upper-left corner of the framing rectangle, the Y coordinate of the upper-left corner of the framing rectangle, the width of the framing rectangle and the height of the framing rectangle. In the constructor of “ed”, we pass nothing, which means the ellipse is initialized to location (0, 0) and size (0, 0). To show them on screen, we create an object of Graphics2d class “g1” and call g1.draw() method.// java program to create two ellipse and // draw them to a java appletimport java.awt.*;import javax.swing.*;import java.awt.geom.*;public class solve1 extends JApplet { public void init() { setSize(300, 300); } // paint the applet public void paint(Graphics g) { // create a ellipse2d Ellipse2D ed = new Ellipse2D.Double(100.0d, 100.0d, 120.0d, 80.0d); // create another ellipse2d Ellipse2D ed1 = new Ellipse2D.Double(); // set framing rectangle of ellipse ed1.setFrame(100.0d, 100.0d, 80.0d, 120.0d); Graphics2D g1 = (Graphics2D)g; g1.setColor(Color.red); // draw the first ellipse g1.draw(ed); g1.setColor(Color.blue); // draw the first ellipse g1.draw(ed1); }}Output:Java program to create two ellipse and check whether a point or a rectangle is contained in that ellipse or intersected by it: To check whether a point or a rectangle is contained in that ellipse or intersected by the 2 ellipses, we first create the 2 ellipses in the similar way we created above. Then we create 2 rectangles, by calling the method drawRect() on Graphics2d object “g1”. The parameters in drawRect() method specify the x coordinate of the rectangle to be drawn, the y coordinate of the rectangle to be drawn, the width of the rectangle to be drawn and the height of the rectangle to be drawn. To check whether they contain it or not, we call ed.contains() method and pass the coordinate of the point or rectangle in it, and show the results on a message dialog.// java program to create two ellipse and check whether// a point or a rectangle is contained in that ellipse// or intersected by itimport java.awt.*;import javax.swing.*;import java.awt.geom.*;public class solve2 extends JApplet { public void init() { setSize(300, 300); } // paint the applet public void paint(Graphics g) { // create a ellipse2d Ellipse2D ed = new Ellipse2D.Double(100.0d, 100.0d, 120.0d, 80.0d); // create another ellipse2d Ellipse2D ed1 = new Ellipse2D.Double(); // set framing rectangle of ellipse ed1.setFrame(100.0d, 100.0d, 80.0d, 120.0d); Graphics2D g1 = (Graphics2D)g; g1.setColor(Color.red); // draw the first ellipse g1.draw(ed); g1.setColor(Color.blue); // draw the first ellipse g1.draw(ed1); g1.setColor(Color.black); // draw a rectangle g.drawRect(100, 100, 80, 100); g1.setColor(Color.orange); // draw a rectangle g.drawRect(150, 150, 10, 10); // does it contain point JOptionPane.showMessageDialog(this, "ellipse 1 contains point 150, 150 " + ed.contains(150, 150)); // does it contain rectangle JOptionPane.showMessageDialog(this, "ellipse 1 contains rectangle at" + " 150, 150 of width 10 and height 10 " + ed.contains(150, 150, 10, 10)); // does it contain rectangle JOptionPane.showMessageDialog(this, "ellipse 1 contains rectangle at "+ " 150, 150 of width 80 and height 100 " + ed.contains(150, 150, 80, 100)); // does it intersect rectangle JOptionPane.showMessageDialog(this, "ellipse 1 intersect rectangle at "+ " 150, 150 of width 80 and height 100 " + ed.intersects(150, 150, 80, 100)); }}Output: Java program to create two ellipses and draw them to a java applet: To create ellipse shape on Java applet, we will initialize Ellipse2d class objects named “ed” and “ed1”. The 4 parameters passed in the constructor of the “ed” object are the X coordinate of the upper-left corner of the framing rectangle, the Y coordinate of the upper-left corner of the framing rectangle, the width of the framing rectangle and the height of the framing rectangle. In the constructor of “ed”, we pass nothing, which means the ellipse is initialized to location (0, 0) and size (0, 0). To show them on screen, we create an object of Graphics2d class “g1” and call g1.draw() method.// java program to create two ellipse and // draw them to a java appletimport java.awt.*;import javax.swing.*;import java.awt.geom.*;public class solve1 extends JApplet { public void init() { setSize(300, 300); } // paint the applet public void paint(Graphics g) { // create a ellipse2d Ellipse2D ed = new Ellipse2D.Double(100.0d, 100.0d, 120.0d, 80.0d); // create another ellipse2d Ellipse2D ed1 = new Ellipse2D.Double(); // set framing rectangle of ellipse ed1.setFrame(100.0d, 100.0d, 80.0d, 120.0d); Graphics2D g1 = (Graphics2D)g; g1.setColor(Color.red); // draw the first ellipse g1.draw(ed); g1.setColor(Color.blue); // draw the first ellipse g1.draw(ed1); }}Output: // java program to create two ellipse and // draw them to a java appletimport java.awt.*;import javax.swing.*;import java.awt.geom.*;public class solve1 extends JApplet { public void init() { setSize(300, 300); } // paint the applet public void paint(Graphics g) { // create a ellipse2d Ellipse2D ed = new Ellipse2D.Double(100.0d, 100.0d, 120.0d, 80.0d); // create another ellipse2d Ellipse2D ed1 = new Ellipse2D.Double(); // set framing rectangle of ellipse ed1.setFrame(100.0d, 100.0d, 80.0d, 120.0d); Graphics2D g1 = (Graphics2D)g; g1.setColor(Color.red); // draw the first ellipse g1.draw(ed); g1.setColor(Color.blue); // draw the first ellipse g1.draw(ed1); }} Output: Java program to create two ellipse and check whether a point or a rectangle is contained in that ellipse or intersected by it: To check whether a point or a rectangle is contained in that ellipse or intersected by the 2 ellipses, we first create the 2 ellipses in the similar way we created above. Then we create 2 rectangles, by calling the method drawRect() on Graphics2d object “g1”. The parameters in drawRect() method specify the x coordinate of the rectangle to be drawn, the y coordinate of the rectangle to be drawn, the width of the rectangle to be drawn and the height of the rectangle to be drawn. To check whether they contain it or not, we call ed.contains() method and pass the coordinate of the point or rectangle in it, and show the results on a message dialog.// java program to create two ellipse and check whether// a point or a rectangle is contained in that ellipse// or intersected by itimport java.awt.*;import javax.swing.*;import java.awt.geom.*;public class solve2 extends JApplet { public void init() { setSize(300, 300); } // paint the applet public void paint(Graphics g) { // create a ellipse2d Ellipse2D ed = new Ellipse2D.Double(100.0d, 100.0d, 120.0d, 80.0d); // create another ellipse2d Ellipse2D ed1 = new Ellipse2D.Double(); // set framing rectangle of ellipse ed1.setFrame(100.0d, 100.0d, 80.0d, 120.0d); Graphics2D g1 = (Graphics2D)g; g1.setColor(Color.red); // draw the first ellipse g1.draw(ed); g1.setColor(Color.blue); // draw the first ellipse g1.draw(ed1); g1.setColor(Color.black); // draw a rectangle g.drawRect(100, 100, 80, 100); g1.setColor(Color.orange); // draw a rectangle g.drawRect(150, 150, 10, 10); // does it contain point JOptionPane.showMessageDialog(this, "ellipse 1 contains point 150, 150 " + ed.contains(150, 150)); // does it contain rectangle JOptionPane.showMessageDialog(this, "ellipse 1 contains rectangle at" + " 150, 150 of width 10 and height 10 " + ed.contains(150, 150, 10, 10)); // does it contain rectangle JOptionPane.showMessageDialog(this, "ellipse 1 contains rectangle at "+ " 150, 150 of width 80 and height 100 " + ed.contains(150, 150, 80, 100)); // does it intersect rectangle JOptionPane.showMessageDialog(this, "ellipse 1 intersect rectangle at "+ " 150, 150 of width 80 and height 100 " + ed.intersects(150, 150, 80, 100)); }}Output: // java program to create two ellipse and check whether// a point or a rectangle is contained in that ellipse// or intersected by itimport java.awt.*;import javax.swing.*;import java.awt.geom.*;public class solve2 extends JApplet { public void init() { setSize(300, 300); } // paint the applet public void paint(Graphics g) { // create a ellipse2d Ellipse2D ed = new Ellipse2D.Double(100.0d, 100.0d, 120.0d, 80.0d); // create another ellipse2d Ellipse2D ed1 = new Ellipse2D.Double(); // set framing rectangle of ellipse ed1.setFrame(100.0d, 100.0d, 80.0d, 120.0d); Graphics2D g1 = (Graphics2D)g; g1.setColor(Color.red); // draw the first ellipse g1.draw(ed); g1.setColor(Color.blue); // draw the first ellipse g1.draw(ed1); g1.setColor(Color.black); // draw a rectangle g.drawRect(100, 100, 80, 100); g1.setColor(Color.orange); // draw a rectangle g.drawRect(150, 150, 10, 10); // does it contain point JOptionPane.showMessageDialog(this, "ellipse 1 contains point 150, 150 " + ed.contains(150, 150)); // does it contain rectangle JOptionPane.showMessageDialog(this, "ellipse 1 contains rectangle at" + " 150, 150 of width 10 and height 10 " + ed.contains(150, 150, 10, 10)); // does it contain rectangle JOptionPane.showMessageDialog(this, "ellipse 1 contains rectangle at "+ " 150, 150 of width 80 and height 100 " + ed.contains(150, 150, 80, 100)); // does it intersect rectangle JOptionPane.showMessageDialog(this, "ellipse 1 intersect rectangle at "+ " 150, 150 of width 80 and height 100 " + ed.intersects(150, 150, 80, 100)); }} Output: Note: The above programs might not run in an online IDE please use an Offline compiler. Reference: https://docs.oracle.com/javase/7/docs/api/java/awt/geom/Ellipse2D.html ManasChhabra2 Java-AWT Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Functional Interfaces in Java Generics in Java Comparator Interface in Java with Examples Introduction to Java HashMap get() Method in Java Strings in Java
[ { "code": null, "e": 23948, "s": 23920, "text": "\n31 Oct, 2019" }, { "code": null, "e": 24155, "s": 23948, "text": "Ellipse2D class is present in java.awt.geom package and it is used to define an ellipse by stating its framing rectangle. This class is only the abstract superclass for all objects which store a 2D ellipse." }, { "code": null, "e": 24214, "s": 24155, "text": "Ellipse2D.Double defines an ellipse with double precision." }, { "code": null, "e": 24271, "s": 24214, "text": "Ellipse2D.Float defines an ellipse with float precision." }, { "code": null, "e": 24301, "s": 24271, "text": "Constructor of the class are:" }, { "code": null, "e": 24678, "s": 24301, "text": "Ellipse2D.Double() : creates an ellipse at location 0, 0 and size 0, 0.Ellipse2D.Double(double x, double y, double w, double h) : creates an ellipse at location x, y and width w and height h.Ellipse2D.Float() : creates an ellipse at location 0, 0 and size 0, 0.Ellipse2D.Float(Float x, Float y, Float w, Float h) : creates an ellipse at location x, y and width w and height h." }, { "code": null, "e": 24750, "s": 24678, "text": "Ellipse2D.Double() : creates an ellipse at location 0, 0 and size 0, 0." }, { "code": null, "e": 24871, "s": 24750, "text": "Ellipse2D.Double(double x, double y, double w, double h) : creates an ellipse at location x, y and width w and height h." }, { "code": null, "e": 24942, "s": 24871, "text": "Ellipse2D.Float() : creates an ellipse at location 0, 0 and size 0, 0." }, { "code": null, "e": 25058, "s": 24942, "text": "Ellipse2D.Float(Float x, Float y, Float w, Float h) : creates an ellipse at location x, y and width w and height h." }, { "code": null, "e": 25081, "s": 25058, "text": "Commonly used methods:" }, { "code": null, "e": 25128, "s": 25081, "text": "Below programs illustrate the Ellipse2D class:" }, { "code": null, "e": 29340, "s": 25128, "text": "Java program to create two ellipses and draw them to a java applet: To create ellipse shape on Java applet, we will initialize Ellipse2d class objects named “ed” and “ed1”. The 4 parameters passed in the constructor of the “ed” object are the X coordinate of the upper-left corner of the framing rectangle, the Y coordinate of the upper-left corner of the framing rectangle, the width of the framing rectangle and the height of the framing rectangle. In the constructor of “ed”, we pass nothing, which means the ellipse is initialized to location (0, 0) and size (0, 0). To show them on screen, we create an object of Graphics2d class “g1” and call g1.draw() method.// java program to create two ellipse and // draw them to a java appletimport java.awt.*;import javax.swing.*;import java.awt.geom.*;public class solve1 extends JApplet { public void init() { setSize(300, 300); } // paint the applet public void paint(Graphics g) { // create a ellipse2d Ellipse2D ed = new Ellipse2D.Double(100.0d, 100.0d, 120.0d, 80.0d); // create another ellipse2d Ellipse2D ed1 = new Ellipse2D.Double(); // set framing rectangle of ellipse ed1.setFrame(100.0d, 100.0d, 80.0d, 120.0d); Graphics2D g1 = (Graphics2D)g; g1.setColor(Color.red); // draw the first ellipse g1.draw(ed); g1.setColor(Color.blue); // draw the first ellipse g1.draw(ed1); }}Output:Java program to create two ellipse and check whether a point or a rectangle is contained in that ellipse or intersected by it: To check whether a point or a rectangle is contained in that ellipse or intersected by the 2 ellipses, we first create the 2 ellipses in the similar way we created above. Then we create 2 rectangles, by calling the method drawRect() on Graphics2d object “g1”. The parameters in drawRect() method specify the x coordinate of the rectangle to be drawn, the y coordinate of the rectangle to be drawn, the width of the rectangle to be drawn and the height of the rectangle to be drawn. To check whether they contain it or not, we call ed.contains() method and pass the coordinate of the point or rectangle in it, and show the results on a message dialog.// java program to create two ellipse and check whether// a point or a rectangle is contained in that ellipse// or intersected by itimport java.awt.*;import javax.swing.*;import java.awt.geom.*;public class solve2 extends JApplet { public void init() { setSize(300, 300); } // paint the applet public void paint(Graphics g) { // create a ellipse2d Ellipse2D ed = new Ellipse2D.Double(100.0d, 100.0d, 120.0d, 80.0d); // create another ellipse2d Ellipse2D ed1 = new Ellipse2D.Double(); // set framing rectangle of ellipse ed1.setFrame(100.0d, 100.0d, 80.0d, 120.0d); Graphics2D g1 = (Graphics2D)g; g1.setColor(Color.red); // draw the first ellipse g1.draw(ed); g1.setColor(Color.blue); // draw the first ellipse g1.draw(ed1); g1.setColor(Color.black); // draw a rectangle g.drawRect(100, 100, 80, 100); g1.setColor(Color.orange); // draw a rectangle g.drawRect(150, 150, 10, 10); // does it contain point JOptionPane.showMessageDialog(this, \"ellipse 1 contains point 150, 150 \" + ed.contains(150, 150)); // does it contain rectangle JOptionPane.showMessageDialog(this, \"ellipse 1 contains rectangle at\" + \" 150, 150 of width 10 and height 10 \" + ed.contains(150, 150, 10, 10)); // does it contain rectangle JOptionPane.showMessageDialog(this, \"ellipse 1 contains rectangle at \"+ \" 150, 150 of width 80 and height 100 \" + ed.contains(150, 150, 80, 100)); // does it intersect rectangle JOptionPane.showMessageDialog(this, \"ellipse 1 intersect rectangle at \"+ \" 150, 150 of width 80 and height 100 \" + ed.intersects(150, 150, 80, 100)); }}Output:" }, { "code": null, "e": 30859, "s": 29340, "text": "Java program to create two ellipses and draw them to a java applet: To create ellipse shape on Java applet, we will initialize Ellipse2d class objects named “ed” and “ed1”. The 4 parameters passed in the constructor of the “ed” object are the X coordinate of the upper-left corner of the framing rectangle, the Y coordinate of the upper-left corner of the framing rectangle, the width of the framing rectangle and the height of the framing rectangle. In the constructor of “ed”, we pass nothing, which means the ellipse is initialized to location (0, 0) and size (0, 0). To show them on screen, we create an object of Graphics2d class “g1” and call g1.draw() method.// java program to create two ellipse and // draw them to a java appletimport java.awt.*;import javax.swing.*;import java.awt.geom.*;public class solve1 extends JApplet { public void init() { setSize(300, 300); } // paint the applet public void paint(Graphics g) { // create a ellipse2d Ellipse2D ed = new Ellipse2D.Double(100.0d, 100.0d, 120.0d, 80.0d); // create another ellipse2d Ellipse2D ed1 = new Ellipse2D.Double(); // set framing rectangle of ellipse ed1.setFrame(100.0d, 100.0d, 80.0d, 120.0d); Graphics2D g1 = (Graphics2D)g; g1.setColor(Color.red); // draw the first ellipse g1.draw(ed); g1.setColor(Color.blue); // draw the first ellipse g1.draw(ed1); }}Output:" }, { "code": "// java program to create two ellipse and // draw them to a java appletimport java.awt.*;import javax.swing.*;import java.awt.geom.*;public class solve1 extends JApplet { public void init() { setSize(300, 300); } // paint the applet public void paint(Graphics g) { // create a ellipse2d Ellipse2D ed = new Ellipse2D.Double(100.0d, 100.0d, 120.0d, 80.0d); // create another ellipse2d Ellipse2D ed1 = new Ellipse2D.Double(); // set framing rectangle of ellipse ed1.setFrame(100.0d, 100.0d, 80.0d, 120.0d); Graphics2D g1 = (Graphics2D)g; g1.setColor(Color.red); // draw the first ellipse g1.draw(ed); g1.setColor(Color.blue); // draw the first ellipse g1.draw(ed1); }}", "e": 31705, "s": 30859, "text": null }, { "code": null, "e": 31713, "s": 31705, "text": "Output:" }, { "code": null, "e": 34407, "s": 31713, "text": "Java program to create two ellipse and check whether a point or a rectangle is contained in that ellipse or intersected by it: To check whether a point or a rectangle is contained in that ellipse or intersected by the 2 ellipses, we first create the 2 ellipses in the similar way we created above. Then we create 2 rectangles, by calling the method drawRect() on Graphics2d object “g1”. The parameters in drawRect() method specify the x coordinate of the rectangle to be drawn, the y coordinate of the rectangle to be drawn, the width of the rectangle to be drawn and the height of the rectangle to be drawn. To check whether they contain it or not, we call ed.contains() method and pass the coordinate of the point or rectangle in it, and show the results on a message dialog.// java program to create two ellipse and check whether// a point or a rectangle is contained in that ellipse// or intersected by itimport java.awt.*;import javax.swing.*;import java.awt.geom.*;public class solve2 extends JApplet { public void init() { setSize(300, 300); } // paint the applet public void paint(Graphics g) { // create a ellipse2d Ellipse2D ed = new Ellipse2D.Double(100.0d, 100.0d, 120.0d, 80.0d); // create another ellipse2d Ellipse2D ed1 = new Ellipse2D.Double(); // set framing rectangle of ellipse ed1.setFrame(100.0d, 100.0d, 80.0d, 120.0d); Graphics2D g1 = (Graphics2D)g; g1.setColor(Color.red); // draw the first ellipse g1.draw(ed); g1.setColor(Color.blue); // draw the first ellipse g1.draw(ed1); g1.setColor(Color.black); // draw a rectangle g.drawRect(100, 100, 80, 100); g1.setColor(Color.orange); // draw a rectangle g.drawRect(150, 150, 10, 10); // does it contain point JOptionPane.showMessageDialog(this, \"ellipse 1 contains point 150, 150 \" + ed.contains(150, 150)); // does it contain rectangle JOptionPane.showMessageDialog(this, \"ellipse 1 contains rectangle at\" + \" 150, 150 of width 10 and height 10 \" + ed.contains(150, 150, 10, 10)); // does it contain rectangle JOptionPane.showMessageDialog(this, \"ellipse 1 contains rectangle at \"+ \" 150, 150 of width 80 and height 100 \" + ed.contains(150, 150, 80, 100)); // does it intersect rectangle JOptionPane.showMessageDialog(this, \"ellipse 1 intersect rectangle at \"+ \" 150, 150 of width 80 and height 100 \" + ed.intersects(150, 150, 80, 100)); }}Output:" }, { "code": "// java program to create two ellipse and check whether// a point or a rectangle is contained in that ellipse// or intersected by itimport java.awt.*;import javax.swing.*;import java.awt.geom.*;public class solve2 extends JApplet { public void init() { setSize(300, 300); } // paint the applet public void paint(Graphics g) { // create a ellipse2d Ellipse2D ed = new Ellipse2D.Double(100.0d, 100.0d, 120.0d, 80.0d); // create another ellipse2d Ellipse2D ed1 = new Ellipse2D.Double(); // set framing rectangle of ellipse ed1.setFrame(100.0d, 100.0d, 80.0d, 120.0d); Graphics2D g1 = (Graphics2D)g; g1.setColor(Color.red); // draw the first ellipse g1.draw(ed); g1.setColor(Color.blue); // draw the first ellipse g1.draw(ed1); g1.setColor(Color.black); // draw a rectangle g.drawRect(100, 100, 80, 100); g1.setColor(Color.orange); // draw a rectangle g.drawRect(150, 150, 10, 10); // does it contain point JOptionPane.showMessageDialog(this, \"ellipse 1 contains point 150, 150 \" + ed.contains(150, 150)); // does it contain rectangle JOptionPane.showMessageDialog(this, \"ellipse 1 contains rectangle at\" + \" 150, 150 of width 10 and height 10 \" + ed.contains(150, 150, 10, 10)); // does it contain rectangle JOptionPane.showMessageDialog(this, \"ellipse 1 contains rectangle at \"+ \" 150, 150 of width 80 and height 100 \" + ed.contains(150, 150, 80, 100)); // does it intersect rectangle JOptionPane.showMessageDialog(this, \"ellipse 1 intersect rectangle at \"+ \" 150, 150 of width 80 and height 100 \" + ed.intersects(150, 150, 80, 100)); }}", "e": 36317, "s": 34407, "text": null }, { "code": null, "e": 36325, "s": 36317, "text": "Output:" }, { "code": null, "e": 36413, "s": 36325, "text": "Note: The above programs might not run in an online IDE please use an Offline compiler." }, { "code": null, "e": 36495, "s": 36413, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/awt/geom/Ellipse2D.html" }, { "code": null, "e": 36509, "s": 36495, "text": "ManasChhabra2" }, { "code": null, "e": 36518, "s": 36509, "text": "Java-AWT" }, { "code": null, "e": 36523, "s": 36518, "text": "Java" }, { "code": null, "e": 36528, "s": 36523, "text": "Java" }, { "code": null, "e": 36626, "s": 36528, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36641, "s": 36626, "text": "Stream In Java" }, { "code": null, "e": 36662, "s": 36641, "text": "Constructors in Java" }, { "code": null, "e": 36708, "s": 36662, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 36727, "s": 36708, "text": "Exceptions in Java" }, { "code": null, "e": 36757, "s": 36727, "text": "Functional Interfaces in Java" }, { "code": null, "e": 36774, "s": 36757, "text": "Generics in Java" }, { "code": null, "e": 36817, "s": 36774, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 36838, "s": 36817, "text": "Introduction to Java" }, { "code": null, "e": 36867, "s": 36838, "text": "HashMap get() Method in Java" } ]
0/1 Knapsack using Least Cost Branch and Bound - GeeksforGeeks
01 Feb, 2022 Given N items with weights W[0..n-1], values V[0..n-1] and a knapsack with capacity C, select the items such that: The sum of weights taken into the knapsack is less than or equal to C.The sum of values of the items in the knapsack is maximum among all the possible combinations. The sum of weights taken into the knapsack is less than or equal to C. The sum of values of the items in the knapsack is maximum among all the possible combinations. Examples: Input: N = 4, C = 15, V[]= {10, 10, 12, 18}, W[]= {2, 4, 6, 9} Output: Items taken into the knapsack are 1 1 0 1 Maximum profit is 38 Explanation: 1 in the output indicates that the item is included in the knapsack while 0 indicates that the item is excluded. Since the maximum possible cost allowed is 15, the ways to select items are: (1 1 0 1) -> Cost = 2 + 4 + 9 = 15, Profit = 10 + 10 + 18 = 38. (0 0 1 1) -> Cost = 6 + 9 = 15, Profit = 12 + 18 = 30 (1 1 1 0) -> Cost = 2 + 4 + 6 = 12, Profit = 32 Hence, maximum profit possible within a cost of 15 is 38.Input: N = 4, C = 21, V[]= {18, 20, 14, 18}, W[]= {6, 3, 5, 9} Output: Items taken into the knapsack are 1 1 0 1 Maximum profit is 56 Explanation: Cost = 6 + 3 + 9 = 18 Profit = 18 + 20 + 18 = 56 Approach: In this post, the implementation of Branch and Bound method using Least cost(LC) for 0/1 Knapsack Problem is discussed.Branch and Bound can be solved using FIFO, LIFO and LC strategies. The least cost(LC) is considered the most intelligent as it selects the next node based on a Heuristic Cost Function. It picks the one with the least cost. As 0/1 Knapsack is about maximizing the total value, we cannot directly use the LC Branch and Bound technique to solve this. Instead, we convert this into a minimization problem by taking negative of the given values. Follow the steps below to solve the problem: Sort the items based on their value/weight(V/W) ratio.Insert a dummy node into the priority queue.Repeat the following steps until the priority queue is empty:Extract the peek element from the priority queue and assign it to the current node.If the upper bound of the current node is less than minLB, the minimum lower bound of all the nodes explored, then there is no point of exploration. So, continue with the next element. The reason for not considering the nodes whose upper bound is greater than minLB is that, the upper bound stores the best value that might be achieved. If the best value itself is not optimal than minLB, then exploring that path is of no use. Update the path array.If the current node’s level is N, then check whether the lower bound of the current node is less than finalLB, minimum lower bound of all the paths that reached the final level. If it is true, update the finalPath and finalLB. Otherwise, continue with the next element.Calculate the lower and upper bounds of the right child of the current node.If the current item can be inserted into the knapsack, then calculate the lower and upper bound of the left child of the current node.Update the minLB and insert the children if their upper bound is less than minLB. Sort the items based on their value/weight(V/W) ratio. Insert a dummy node into the priority queue. Repeat the following steps until the priority queue is empty:Extract the peek element from the priority queue and assign it to the current node.If the upper bound of the current node is less than minLB, the minimum lower bound of all the nodes explored, then there is no point of exploration. So, continue with the next element. The reason for not considering the nodes whose upper bound is greater than minLB is that, the upper bound stores the best value that might be achieved. If the best value itself is not optimal than minLB, then exploring that path is of no use. Update the path array.If the current node’s level is N, then check whether the lower bound of the current node is less than finalLB, minimum lower bound of all the paths that reached the final level. If it is true, update the finalPath and finalLB. Otherwise, continue with the next element.Calculate the lower and upper bounds of the right child of the current node.If the current item can be inserted into the knapsack, then calculate the lower and upper bound of the left child of the current node.Update the minLB and insert the children if their upper bound is less than minLB. Extract the peek element from the priority queue and assign it to the current node. If the upper bound of the current node is less than minLB, the minimum lower bound of all the nodes explored, then there is no point of exploration. So, continue with the next element. The reason for not considering the nodes whose upper bound is greater than minLB is that, the upper bound stores the best value that might be achieved. If the best value itself is not optimal than minLB, then exploring that path is of no use. Update the path array. If the current node’s level is N, then check whether the lower bound of the current node is less than finalLB, minimum lower bound of all the paths that reached the final level. If it is true, update the finalPath and finalLB. Otherwise, continue with the next element. Calculate the lower and upper bounds of the right child of the current node. If the current item can be inserted into the knapsack, then calculate the lower and upper bound of the left child of the current node. Update the minLB and insert the children if their upper bound is less than minLB. Illustration: N = 4, C = 15, V[]= {10 10 12 18}, W[]= {2 4 6 9} Left branch and right branch at ith level stores the maximum obtained including and excluding the ith element.Below image shows the state of the priority queue after every step: Below is the implementation of the above approach: C++ Java // C++ Program to implement 0/1// knapsack using LC Branch and Bound #include <bits/stdc++.h>using namespace std; // Stores the number of itemsint size; // Stores the knapsack capacityfloat capacity; typedef struct Item { // Stores the weight of items float weight; // Stores the value of items int value; // Stores the index of items int idx;} Item; typedef struct Node { // Upper Bound: Best case // (Fractional Knapsack) float ub; // Lower Bound: Worst case (0/1) float lb; // Level of the node // in the decision tree int level; // Stores if the current item is // selected or not bool flag; // Total Value: Stores the sum of the // values of the items included float tv; // Total Weight: Stores the sum of the // weights of the items included float tw;} Node; // Function to calculate upper bound// (includes fractional part of the items)float upper_bound(float tv, float tw, int idx, vector<Item>& arr){ float value = tv; float weight = tw; for (int i = idx; i < size; i++) { if (weight + arr[i].weight <= capacity) { weight += arr[i].weight; value -= arr[i].value; } else { value -= (float)(capacity - weight) / arr[i].weight * arr[i].value; break; } } return value;} // Function to calculate lower bound (doesn't// include fractional part of the items)float lower_bound(float tv, float tw, int idx, vector<Item>& arr){ float value = tv; float weight = tw; for (int i = idx; i < size; i++) { if (weight + arr[i].weight <= capacity) { weight += arr[i].weight; value -= arr[i].value; } else { break; } } return value;} class comp {public: bool operator()(Node a, Node b) { return a.lb > b.lb; }}; void assign(Node& a, float ub, float lb, int level, bool flag, float tv, float tw){ a.ub = ub; a.lb = lb; a.level = level; a.flag = flag; a.tv = tv; a.tw = tw;} void knapsack(vector<Item>& arr){ // Sort the items based on the // profit/weight ratio sort(arr.begin(), arr.end(), [&](Item& a, Item& b) { return a.value / a.weight > b.value / b.weight; }); // min_lb -> Minimum lower bound // of all the nodes explored // final_lb -> Minimum lower bound // of all the paths that reached // the final level float min_lb = 0, final_lb = INT_MAX; // curr_path -> Boolean array to store // at every index if the element is // included or not // final_path -> Boolean array to store // the result of selection array when // it reached the last level bool curr_path[size], final_path[size]; // Priority queue to store the nodes // based on lower bounds priority_queue<Node, vector<Node>, comp> pq; Node current, left, right; current.lb = current.ub = current.tw = current.tv = current.level = current.flag = 0; // Insert a dummy node pq.push(current); for (int i = 0; i < size; i++) curr_path[i] = final_path[i] = false; while (!pq.empty()) { current = pq.top(); pq.pop(); if (current.ub > min_lb || current.ub >= final_lb) { // If the current node's best case // value is not optimal than min_lb, // then there is no reason to explore // that path including final_lb // eliminates all those paths whose // best values is equal to final_lb continue; } // update the path if (current.level != 0) curr_path[current.level - 1] = current.flag; if (current.level == size) { // Reached last level if (current.lb < final_lb) for (int i = 0; i < size; i++) final_path[arr[i].idx] = curr_path[i]; final_lb = min(current.lb, final_lb); continue; } int level = current.level; // right node -> Excludes current item // Hence, cp, cw will obtain the value // of that of parent assign(right, upper_bound(current.tv, current.tw, level + 1, arr), lower_bound(current.tv, current.tw, level + 1, arr), level + 1, false, current.tv, current.tw); // Check whether adding the current // item will not exceed the knapsack weight if (current.tw + arr[current.level].weight <= capacity) { // left node -> includes current item // c and lb should be calculated // including the current item. left.ub = upper_bound( current.tv - arr[level].value, current.tw + arr[level].weight, level + 1, arr); left.lb = lower_bound( current.tv - arr[level].value, current.tw + arr[level].weight, level + 1, arr); assign(left, left.ub, left.lb, level + 1, true, current.tv - arr[level].value, current.tw + arr[level].weight); } // If Left node cannot be inserted else { // Stop the left node from // getting added to the // priority queue left.ub = left.lb = 1; } // Update the lower bound min_lb = min(min_lb, left.lb); min_lb = min(min_lb, right.lb); // Exploring nodes whose // upper bound is greater than // min_lb will never give // the optimal result if (min_lb >= left.ub) pq.push(left); if (min_lb >= right.ub) pq.push(right); } cout << "Items taken into the" << " knapsack are : \n"; if (final_lb == INT_MAX) final_lb = 0; for (int i = 0; i < size; i++) cout << final_path[i] << " "; cout << "\n"; cout << "Maximum profit is : " << (-final_lb) << "\n";} // Driver Codeint main(){ size = 4; capacity = 15; vector<Item> arr; arr.push_back({ 2, 10, 0 }); arr.push_back({ 4, 10, 1 }); arr.push_back({ 6, 12, 2 }); arr.push_back({ 9, 18, 3 }); knapsack(arr); return 0;} // Java Program to implement// 0/1 knapsack using LC// Branch and Bound import java.util.*;class Item { // Stores the weight // of items float weight; // Stores the values // of items int value; // Stores the index // of items int idx; public Item() {} public Item(int value, float weight, int idx) { this.value = value; this.weight = weight; this.idx = idx; }} class Node { // Upper Bound: Best case // (Fractional Knapsack) float ub; // Lower Bound: Worst case // (0/1) float lb; // Level of the node in // the decision tree int level; // Stores if the current // item is selected or not boolean flag; // Total Value: Stores the // sum of the values of the // items included float tv; // Total Weight: Stores the sum of // the weights of included items float tw; public Node() {} public Node(Node cpy) { this.tv = cpy.tv; this.tw = cpy.tw; this.ub = cpy.ub; this.lb = cpy.lb; this.level = cpy.level; this.flag = cpy.flag; }} // Comparator to sort based on lower boundclass sortByC implements Comparator<Node> { public int compare(Node a, Node b) { boolean temp = a.lb > b.lb; return temp ? 1 : -1; }} class sortByRatio implements Comparator<Item> { public int compare(Item a, Item b) { boolean temp = (float)a.value / a.weight > (float)b.value / b.weight; return temp ? -1 : 1; }} class knapsack { private static int size; private static float capacity; // Function to calculate upper bound // (includes fractional part of the items) static float upperBound(float tv, float tw, int idx, Item arr[]) { float value = tv; float weight = tw; for (int i = idx; i < size; i++) { if (weight + arr[i].weight <= capacity) { weight += arr[i].weight; value -= arr[i].value; } else { value -= (float)(capacity - weight) / arr[i].weight * arr[i].value; break; } } return value; } // Calculate lower bound (doesn't // include fractional part of items) static float lowerBound(float tv, float tw, int idx, Item arr[]) { float value = tv; float weight = tw; for (int i = idx; i < size; i++) { if (weight + arr[i].weight <= capacity) { weight += arr[i].weight; value -= arr[i].value; } else { break; } } return value; } static void assign(Node a, float ub, float lb, int level, boolean flag, float tv, float tw) { a.ub = ub; a.lb = lb; a.level = level; a.flag = flag; a.tv = tv; a.tw = tw; } public static void solve(Item arr[]) { // Sort the items based on the // profit/weight ratio Arrays.sort(arr, new sortByRatio()); Node current, left, right; current = new Node(); left = new Node(); right = new Node(); // min_lb -> Minimum lower bound // of all the nodes explored // final_lb -> Minimum lower bound // of all the paths that reached // the final level float minLB = 0, finalLB = Integer.MAX_VALUE; current.tv = current.tw = current.ub = current.lb = 0; current.level = 0; current.flag = false; // Priority queue to store elements // based on lower bounds PriorityQueue<Node> pq = new PriorityQueue<Node>( new sortByC()); // Insert a dummy node pq.add(current); // curr_path -> Boolean array to store // at every index if the element is // included or not // final_path -> Boolean array to store // the result of selection array when // it reached the last level boolean currPath[] = new boolean[size]; boolean finalPath[] = new boolean[size]; while (!pq.isEmpty()) { current = pq.poll(); if (current.ub > minLB || current.ub >= finalLB) { // if the current node's best case // value is not optimal than minLB, // then there is no reason to // explore that node. Including // finalLB eliminates all those // paths whose best values is equal // to the finalLB continue; } if (current.level != 0) currPath[current.level - 1] = current.flag; if (current.level == size) { if (current.lb < finalLB) { // Reached last level for (int i = 0; i < size; i++) finalPath[arr[i].idx] = currPath[i]; finalLB = current.lb; } continue; } int level = current.level; // right node -> Excludes current item // Hence, cp, cw will obtain the value // of that of parent assign(right, upperBound(current.tv, current.tw, level + 1, arr), lowerBound(current.tv, current.tw, level + 1, arr), level + 1, false, current.tv, current.tw); if (current.tw + arr[current.level].weight <= capacity) { // left node -> includes current item // c and lb should be calculated // including the current item. left.ub = upperBound( current.tv - arr[level].value, current.tw + arr[level].weight, level + 1, arr); left.lb = lowerBound( current.tv - arr[level].value, current.tw + arr[level].weight, level + 1, arr); assign(left, left.ub, left.lb, level + 1, true, current.tv - arr[level].value, current.tw + arr[level].weight); } // If the left node cannot // be inserted else { // Stop the left node from // getting added to the // priority queue left.ub = left.lb = 1; } // Update minLB minLB = Math.min(minLB, left.lb); minLB = Math.min(minLB, right.lb); if (minLB >= left.ub) pq.add(new Node(left)); if (minLB >= right.ub) pq.add(new Node(right)); } System.out.println("Items taken" + "into the knapsack are"); for (int i = 0; i < size; i++) { if (finalPath[i]) System.out.print("1 "); else System.out.print("0 "); } System.out.println("\nMaximum profit" + " is " + (-finalLB)); } // Driver code public static void main(String args[]) { size = 4; capacity = 15; Item arr[] = new Item[size]; arr[0] = new Item(10, 2, 0); arr[1] = new Item(10, 4, 1); arr[2] = new Item(12, 6, 2); arr[3] = new Item(18, 9, 3); solve(arr); }} Items taken into the knapsack are : 1 1 0 1 Maximum profit is : 38 udaykumar12381 singghakshay sumitgumber28 knapsack priority-queue Algorithms Branch and Bound Dynamic Programming Heap Sorting Dynamic Programming Sorting Heap priority-queue Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SCAN (Elevator) Disk Scheduling Algorithms Program for SSTF disk scheduling algorithm Rail Fence Cipher - Encryption and Decryption Quadratic Probing in Hashing Backtracking | Introduction 8 puzzle Problem using Branch And Bound 0/1 Knapsack using Branch and Bound Traveling Salesman Problem using Branch And Bound N Queen Problem using Branch And Bound
[ { "code": null, "e": 24700, "s": 24672, "text": "\n01 Feb, 2022" }, { "code": null, "e": 24817, "s": 24700, "text": "Given N items with weights W[0..n-1], values V[0..n-1] and a knapsack with capacity C, select the items such that: " }, { "code": null, "e": 24982, "s": 24817, "text": "The sum of weights taken into the knapsack is less than or equal to C.The sum of values of the items in the knapsack is maximum among all the possible combinations." }, { "code": null, "e": 25053, "s": 24982, "text": "The sum of weights taken into the knapsack is less than or equal to C." }, { "code": null, "e": 25148, "s": 25053, "text": "The sum of values of the items in the knapsack is maximum among all the possible combinations." }, { "code": null, "e": 25160, "s": 25148, "text": "Examples: " }, { "code": null, "e": 25918, "s": 25160, "text": "Input: N = 4, C = 15, V[]= {10, 10, 12, 18}, W[]= {2, 4, 6, 9} Output: Items taken into the knapsack are 1 1 0 1 Maximum profit is 38 Explanation: 1 in the output indicates that the item is included in the knapsack while 0 indicates that the item is excluded. Since the maximum possible cost allowed is 15, the ways to select items are: (1 1 0 1) -> Cost = 2 + 4 + 9 = 15, Profit = 10 + 10 + 18 = 38. (0 0 1 1) -> Cost = 6 + 9 = 15, Profit = 12 + 18 = 30 (1 1 1 0) -> Cost = 2 + 4 + 6 = 12, Profit = 32 Hence, maximum profit possible within a cost of 15 is 38.Input: N = 4, C = 21, V[]= {18, 20, 14, 18}, W[]= {6, 3, 5, 9} Output: Items taken into the knapsack are 1 1 0 1 Maximum profit is 56 Explanation: Cost = 6 + 3 + 9 = 18 Profit = 18 + 20 + 18 = 56 " }, { "code": null, "e": 26537, "s": 25920, "text": "Approach: In this post, the implementation of Branch and Bound method using Least cost(LC) for 0/1 Knapsack Problem is discussed.Branch and Bound can be solved using FIFO, LIFO and LC strategies. The least cost(LC) is considered the most intelligent as it selects the next node based on a Heuristic Cost Function. It picks the one with the least cost. As 0/1 Knapsack is about maximizing the total value, we cannot directly use the LC Branch and Bound technique to solve this. Instead, we convert this into a minimization problem by taking negative of the given values. Follow the steps below to solve the problem: " }, { "code": null, "e": 27791, "s": 26537, "text": "Sort the items based on their value/weight(V/W) ratio.Insert a dummy node into the priority queue.Repeat the following steps until the priority queue is empty:Extract the peek element from the priority queue and assign it to the current node.If the upper bound of the current node is less than minLB, the minimum lower bound of all the nodes explored, then there is no point of exploration. So, continue with the next element. The reason for not considering the nodes whose upper bound is greater than minLB is that, the upper bound stores the best value that might be achieved. If the best value itself is not optimal than minLB, then exploring that path is of no use. Update the path array.If the current node’s level is N, then check whether the lower bound of the current node is less than finalLB, minimum lower bound of all the paths that reached the final level. If it is true, update the finalPath and finalLB. Otherwise, continue with the next element.Calculate the lower and upper bounds of the right child of the current node.If the current item can be inserted into the knapsack, then calculate the lower and upper bound of the left child of the current node.Update the minLB and insert the children if their upper bound is less than minLB." }, { "code": null, "e": 27846, "s": 27791, "text": "Sort the items based on their value/weight(V/W) ratio." }, { "code": null, "e": 27891, "s": 27846, "text": "Insert a dummy node into the priority queue." }, { "code": null, "e": 29047, "s": 27891, "text": "Repeat the following steps until the priority queue is empty:Extract the peek element from the priority queue and assign it to the current node.If the upper bound of the current node is less than minLB, the minimum lower bound of all the nodes explored, then there is no point of exploration. So, continue with the next element. The reason for not considering the nodes whose upper bound is greater than minLB is that, the upper bound stores the best value that might be achieved. If the best value itself is not optimal than minLB, then exploring that path is of no use. Update the path array.If the current node’s level is N, then check whether the lower bound of the current node is less than finalLB, minimum lower bound of all the paths that reached the final level. If it is true, update the finalPath and finalLB. Otherwise, continue with the next element.Calculate the lower and upper bounds of the right child of the current node.If the current item can be inserted into the knapsack, then calculate the lower and upper bound of the left child of the current node.Update the minLB and insert the children if their upper bound is less than minLB." }, { "code": null, "e": 29131, "s": 29047, "text": "Extract the peek element from the priority queue and assign it to the current node." }, { "code": null, "e": 29561, "s": 29131, "text": "If the upper bound of the current node is less than minLB, the minimum lower bound of all the nodes explored, then there is no point of exploration. So, continue with the next element. The reason for not considering the nodes whose upper bound is greater than minLB is that, the upper bound stores the best value that might be achieved. If the best value itself is not optimal than minLB, then exploring that path is of no use. " }, { "code": null, "e": 29584, "s": 29561, "text": "Update the path array." }, { "code": null, "e": 29854, "s": 29584, "text": "If the current node’s level is N, then check whether the lower bound of the current node is less than finalLB, minimum lower bound of all the paths that reached the final level. If it is true, update the finalPath and finalLB. Otherwise, continue with the next element." }, { "code": null, "e": 29931, "s": 29854, "text": "Calculate the lower and upper bounds of the right child of the current node." }, { "code": null, "e": 30066, "s": 29931, "text": "If the current item can be inserted into the knapsack, then calculate the lower and upper bound of the left child of the current node." }, { "code": null, "e": 30148, "s": 30066, "text": "Update the minLB and insert the children if their upper bound is less than minLB." }, { "code": null, "e": 30216, "s": 30150, "text": "Illustration: N = 4, C = 15, V[]= {10 10 12 18}, W[]= {2 4 6 9} " }, { "code": null, "e": 30396, "s": 30216, "text": "Left branch and right branch at ith level stores the maximum obtained including and excluding the ith element.Below image shows the state of the priority queue after every step: " }, { "code": null, "e": 30450, "s": 30398, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 30454, "s": 30450, "text": "C++" }, { "code": null, "e": 30459, "s": 30454, "text": "Java" }, { "code": "// C++ Program to implement 0/1// knapsack using LC Branch and Bound #include <bits/stdc++.h>using namespace std; // Stores the number of itemsint size; // Stores the knapsack capacityfloat capacity; typedef struct Item { // Stores the weight of items float weight; // Stores the value of items int value; // Stores the index of items int idx;} Item; typedef struct Node { // Upper Bound: Best case // (Fractional Knapsack) float ub; // Lower Bound: Worst case (0/1) float lb; // Level of the node // in the decision tree int level; // Stores if the current item is // selected or not bool flag; // Total Value: Stores the sum of the // values of the items included float tv; // Total Weight: Stores the sum of the // weights of the items included float tw;} Node; // Function to calculate upper bound// (includes fractional part of the items)float upper_bound(float tv, float tw, int idx, vector<Item>& arr){ float value = tv; float weight = tw; for (int i = idx; i < size; i++) { if (weight + arr[i].weight <= capacity) { weight += arr[i].weight; value -= arr[i].value; } else { value -= (float)(capacity - weight) / arr[i].weight * arr[i].value; break; } } return value;} // Function to calculate lower bound (doesn't// include fractional part of the items)float lower_bound(float tv, float tw, int idx, vector<Item>& arr){ float value = tv; float weight = tw; for (int i = idx; i < size; i++) { if (weight + arr[i].weight <= capacity) { weight += arr[i].weight; value -= arr[i].value; } else { break; } } return value;} class comp {public: bool operator()(Node a, Node b) { return a.lb > b.lb; }}; void assign(Node& a, float ub, float lb, int level, bool flag, float tv, float tw){ a.ub = ub; a.lb = lb; a.level = level; a.flag = flag; a.tv = tv; a.tw = tw;} void knapsack(vector<Item>& arr){ // Sort the items based on the // profit/weight ratio sort(arr.begin(), arr.end(), [&](Item& a, Item& b) { return a.value / a.weight > b.value / b.weight; }); // min_lb -> Minimum lower bound // of all the nodes explored // final_lb -> Minimum lower bound // of all the paths that reached // the final level float min_lb = 0, final_lb = INT_MAX; // curr_path -> Boolean array to store // at every index if the element is // included or not // final_path -> Boolean array to store // the result of selection array when // it reached the last level bool curr_path[size], final_path[size]; // Priority queue to store the nodes // based on lower bounds priority_queue<Node, vector<Node>, comp> pq; Node current, left, right; current.lb = current.ub = current.tw = current.tv = current.level = current.flag = 0; // Insert a dummy node pq.push(current); for (int i = 0; i < size; i++) curr_path[i] = final_path[i] = false; while (!pq.empty()) { current = pq.top(); pq.pop(); if (current.ub > min_lb || current.ub >= final_lb) { // If the current node's best case // value is not optimal than min_lb, // then there is no reason to explore // that path including final_lb // eliminates all those paths whose // best values is equal to final_lb continue; } // update the path if (current.level != 0) curr_path[current.level - 1] = current.flag; if (current.level == size) { // Reached last level if (current.lb < final_lb) for (int i = 0; i < size; i++) final_path[arr[i].idx] = curr_path[i]; final_lb = min(current.lb, final_lb); continue; } int level = current.level; // right node -> Excludes current item // Hence, cp, cw will obtain the value // of that of parent assign(right, upper_bound(current.tv, current.tw, level + 1, arr), lower_bound(current.tv, current.tw, level + 1, arr), level + 1, false, current.tv, current.tw); // Check whether adding the current // item will not exceed the knapsack weight if (current.tw + arr[current.level].weight <= capacity) { // left node -> includes current item // c and lb should be calculated // including the current item. left.ub = upper_bound( current.tv - arr[level].value, current.tw + arr[level].weight, level + 1, arr); left.lb = lower_bound( current.tv - arr[level].value, current.tw + arr[level].weight, level + 1, arr); assign(left, left.ub, left.lb, level + 1, true, current.tv - arr[level].value, current.tw + arr[level].weight); } // If Left node cannot be inserted else { // Stop the left node from // getting added to the // priority queue left.ub = left.lb = 1; } // Update the lower bound min_lb = min(min_lb, left.lb); min_lb = min(min_lb, right.lb); // Exploring nodes whose // upper bound is greater than // min_lb will never give // the optimal result if (min_lb >= left.ub) pq.push(left); if (min_lb >= right.ub) pq.push(right); } cout << \"Items taken into the\" << \" knapsack are : \\n\"; if (final_lb == INT_MAX) final_lb = 0; for (int i = 0; i < size; i++) cout << final_path[i] << \" \"; cout << \"\\n\"; cout << \"Maximum profit is : \" << (-final_lb) << \"\\n\";} // Driver Codeint main(){ size = 4; capacity = 15; vector<Item> arr; arr.push_back({ 2, 10, 0 }); arr.push_back({ 4, 10, 1 }); arr.push_back({ 6, 12, 2 }); arr.push_back({ 9, 18, 3 }); knapsack(arr); return 0;}", "e": 37197, "s": 30459, "text": null }, { "code": "// Java Program to implement// 0/1 knapsack using LC// Branch and Bound import java.util.*;class Item { // Stores the weight // of items float weight; // Stores the values // of items int value; // Stores the index // of items int idx; public Item() {} public Item(int value, float weight, int idx) { this.value = value; this.weight = weight; this.idx = idx; }} class Node { // Upper Bound: Best case // (Fractional Knapsack) float ub; // Lower Bound: Worst case // (0/1) float lb; // Level of the node in // the decision tree int level; // Stores if the current // item is selected or not boolean flag; // Total Value: Stores the // sum of the values of the // items included float tv; // Total Weight: Stores the sum of // the weights of included items float tw; public Node() {} public Node(Node cpy) { this.tv = cpy.tv; this.tw = cpy.tw; this.ub = cpy.ub; this.lb = cpy.lb; this.level = cpy.level; this.flag = cpy.flag; }} // Comparator to sort based on lower boundclass sortByC implements Comparator<Node> { public int compare(Node a, Node b) { boolean temp = a.lb > b.lb; return temp ? 1 : -1; }} class sortByRatio implements Comparator<Item> { public int compare(Item a, Item b) { boolean temp = (float)a.value / a.weight > (float)b.value / b.weight; return temp ? -1 : 1; }} class knapsack { private static int size; private static float capacity; // Function to calculate upper bound // (includes fractional part of the items) static float upperBound(float tv, float tw, int idx, Item arr[]) { float value = tv; float weight = tw; for (int i = idx; i < size; i++) { if (weight + arr[i].weight <= capacity) { weight += arr[i].weight; value -= arr[i].value; } else { value -= (float)(capacity - weight) / arr[i].weight * arr[i].value; break; } } return value; } // Calculate lower bound (doesn't // include fractional part of items) static float lowerBound(float tv, float tw, int idx, Item arr[]) { float value = tv; float weight = tw; for (int i = idx; i < size; i++) { if (weight + arr[i].weight <= capacity) { weight += arr[i].weight; value -= arr[i].value; } else { break; } } return value; } static void assign(Node a, float ub, float lb, int level, boolean flag, float tv, float tw) { a.ub = ub; a.lb = lb; a.level = level; a.flag = flag; a.tv = tv; a.tw = tw; } public static void solve(Item arr[]) { // Sort the items based on the // profit/weight ratio Arrays.sort(arr, new sortByRatio()); Node current, left, right; current = new Node(); left = new Node(); right = new Node(); // min_lb -> Minimum lower bound // of all the nodes explored // final_lb -> Minimum lower bound // of all the paths that reached // the final level float minLB = 0, finalLB = Integer.MAX_VALUE; current.tv = current.tw = current.ub = current.lb = 0; current.level = 0; current.flag = false; // Priority queue to store elements // based on lower bounds PriorityQueue<Node> pq = new PriorityQueue<Node>( new sortByC()); // Insert a dummy node pq.add(current); // curr_path -> Boolean array to store // at every index if the element is // included or not // final_path -> Boolean array to store // the result of selection array when // it reached the last level boolean currPath[] = new boolean[size]; boolean finalPath[] = new boolean[size]; while (!pq.isEmpty()) { current = pq.poll(); if (current.ub > minLB || current.ub >= finalLB) { // if the current node's best case // value is not optimal than minLB, // then there is no reason to // explore that node. Including // finalLB eliminates all those // paths whose best values is equal // to the finalLB continue; } if (current.level != 0) currPath[current.level - 1] = current.flag; if (current.level == size) { if (current.lb < finalLB) { // Reached last level for (int i = 0; i < size; i++) finalPath[arr[i].idx] = currPath[i]; finalLB = current.lb; } continue; } int level = current.level; // right node -> Excludes current item // Hence, cp, cw will obtain the value // of that of parent assign(right, upperBound(current.tv, current.tw, level + 1, arr), lowerBound(current.tv, current.tw, level + 1, arr), level + 1, false, current.tv, current.tw); if (current.tw + arr[current.level].weight <= capacity) { // left node -> includes current item // c and lb should be calculated // including the current item. left.ub = upperBound( current.tv - arr[level].value, current.tw + arr[level].weight, level + 1, arr); left.lb = lowerBound( current.tv - arr[level].value, current.tw + arr[level].weight, level + 1, arr); assign(left, left.ub, left.lb, level + 1, true, current.tv - arr[level].value, current.tw + arr[level].weight); } // If the left node cannot // be inserted else { // Stop the left node from // getting added to the // priority queue left.ub = left.lb = 1; } // Update minLB minLB = Math.min(minLB, left.lb); minLB = Math.min(minLB, right.lb); if (minLB >= left.ub) pq.add(new Node(left)); if (minLB >= right.ub) pq.add(new Node(right)); } System.out.println(\"Items taken\" + \"into the knapsack are\"); for (int i = 0; i < size; i++) { if (finalPath[i]) System.out.print(\"1 \"); else System.out.print(\"0 \"); } System.out.println(\"\\nMaximum profit\" + \" is \" + (-finalLB)); } // Driver code public static void main(String args[]) { size = 4; capacity = 15; Item arr[] = new Item[size]; arr[0] = new Item(10, 2, 0); arr[1] = new Item(10, 4, 1); arr[2] = new Item(12, 6, 2); arr[3] = new Item(18, 9, 3); solve(arr); }}", "e": 45188, "s": 37197, "text": null }, { "code": null, "e": 45257, "s": 45188, "text": "Items taken into the knapsack are : \n1 1 0 1 \nMaximum profit is : 38" }, { "code": null, "e": 45274, "s": 45259, "text": "udaykumar12381" }, { "code": null, "e": 45287, "s": 45274, "text": "singghakshay" }, { "code": null, "e": 45301, "s": 45287, "text": "sumitgumber28" }, { "code": null, "e": 45310, "s": 45301, "text": "knapsack" }, { "code": null, "e": 45325, "s": 45310, "text": "priority-queue" }, { "code": null, "e": 45336, "s": 45325, "text": "Algorithms" }, { "code": null, "e": 45353, "s": 45336, "text": "Branch and Bound" }, { "code": null, "e": 45373, "s": 45353, "text": "Dynamic Programming" }, { "code": null, "e": 45378, "s": 45373, "text": "Heap" }, { "code": null, "e": 45386, "s": 45378, "text": "Sorting" }, { "code": null, "e": 45406, "s": 45386, "text": "Dynamic Programming" }, { "code": null, "e": 45414, "s": 45406, "text": "Sorting" }, { "code": null, "e": 45419, "s": 45414, "text": "Heap" }, { "code": null, "e": 45434, "s": 45419, "text": "priority-queue" }, { "code": null, "e": 45445, "s": 45434, "text": "Algorithms" }, { "code": null, "e": 45543, "s": 45445, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45568, "s": 45543, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 45611, "s": 45568, "text": "SCAN (Elevator) Disk Scheduling Algorithms" }, { "code": null, "e": 45654, "s": 45611, "text": "Program for SSTF disk scheduling algorithm" }, { "code": null, "e": 45700, "s": 45654, "text": "Rail Fence Cipher - Encryption and Decryption" }, { "code": null, "e": 45729, "s": 45700, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 45757, "s": 45729, "text": "Backtracking | Introduction" }, { "code": null, "e": 45797, "s": 45757, "text": "8 puzzle Problem using Branch And Bound" }, { "code": null, "e": 45833, "s": 45797, "text": "0/1 Knapsack using Branch and Bound" }, { "code": null, "e": 45883, "s": 45833, "text": "Traveling Salesman Problem using Branch And Bound" } ]
SQL Interview Questions
Dear readers, these SQL Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of SQL. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer: SQL or Structured Query Language is a language; language that communicates with a relational database thus providing ways of manipulating and creating databases. MySQL and Microsoft’s SQL Server both are relational database management systems that use SQL as their standard relational database language. PL/SQL is a dialect of SQL that adds procedural features of programming languages in SQL. It was developed by Oracle Corporation in the early 90's to enhance the capabilities of SQL. Following are various DDL or Data Definition Language commands in SQL − CREATE − it creates a new table, a view of a table, or other object in database. CREATE − it creates a new table, a view of a table, or other object in database. ALTER − it modifies an existing database object, such as a table. ALTER − it modifies an existing database object, such as a table. DROP − it deletes an entire table, a view of a table or other object in the database. DROP − it deletes an entire table, a view of a table or other object in the database. Following are various DML or Data Manipulation Language commands in SQL − SELECT − it retrieves certain records from one or more tables. SELECT − it retrieves certain records from one or more tables. INSERT − it creates a record. INSERT − it creates a record. UPDATE − it modifies records. UPDATE − it modifies records. DELETE − it deletes records. DELETE − it deletes records. Following are various DCL or Data Control Language commands in SQL − GRANT − it gives a privilege to user. GRANT − it gives a privilege to user. REVOKE − it takes back privileges granted from user. REVOKE − it takes back privileges granted from user. Yes. A column alias could be used in the ORDER BY clause. A NULL value is not same as zero or a blank space. A NULL value is a value which is ‘unavailable, unassigned, unknown or not applicable’. Whereas, zero is a number and blank space is a character. If a column value taking part in an arithmetic expression is NULL, then the result obtained would be NULLM. True. A query result displays all rows including the duplicate rows. To eliminate duplicate rows in the result, the DISTINCT keyword is used in the SELECT clause. The BETWEEN operator displays rows based on a range of values. The IN condition operator checks for values contained in a specific set of values. In such cases, the LIKE condition operator is used to select rows that match a character pattern. This is also called ‘wildcard’ search. The default sorting order is ascending. It can be changed using the DESC keyword, after the column name in the ORDER BY clause. SQL functions have the following uses − Performing calculations on data Performing calculations on data Modifying individual data items Modifying individual data items Manipulating the output Manipulating the output Formatting dates and numbers Formatting dates and numbers Converting data types Converting data types LOWER, UPPER, INITCAP The MOD function returns the remainder in a division operation. The NVL function converts a NULL value to an actual value. The NVL(exp1, exp2) function converts the source expression (or value) exp1 to the target expression (or value) exp2, if exp1 contains NULL. The return value has the same data type as that of exp1. The NVL2(exp1, exp2, exp3) function checks the first expression exp1, if it is not null then, the second expression exp2 is returned. If the first expression exp1 is null, then the third expression exp3 is returned. The NULLIF function compares two expressions. If they are equal, the function returns null. If they are not equal, the first expression is returned. The COALESCE function has the expression COALESCE(exp1, exp2, .... expn) It returns the first non-null expression given in the parameter list. There are two ways to implement conditional processing or IF-THEN-ELSE logic in a SQL statement. Using CASE expression Using CASE expression Using the DECODE function Using the DECODE function The result would be the Cartesian product of two tables with 20 x 10 = 200 rows. The cross join produces the cross product or Cartesian product of two tables. The natural join is based on all the columns having same name and data types in both the tables. Group functions in SQL work on sets of rows and returns one result per group. Examples of group functions are AVG, COUNT, MAX, MIN, STDDEV, SUM, VARIANCE. By default the group functions consider only distinct values in the set. By default, group functions consider all values including the duplicate values. The DISTINCT keyword allows a function consider only non-duplicate values. True. All group functions ignore null values. True. COUNT(*) returns the number of columns in a table. False. COUNT(*) returns the number of rows in a table. SELECT subject_code, count(name) FROM students; It doesn’t have a GROUP BY clause. The subject_code should be in the GROUP BY clause. SELECT subject_code, count(name) FROM students GROUP BY subject_code; SELECT subject_code, AVG (marks) FROM students WHERE AVG(marks) > 75 GROUP BY subject_code; The WHERE clause cannot be used to restrict groups. The HAVING clause should be used. SELECT subject_code, AVG (marks) FROM students HAVING AVG(marks) > 75 GROUP BY subject_code; Group functions cannot be nested. False. Group functions can be nested to a depth of two. A subquery is a SELECT statement embedded in a clause of another SELECT statement. It is used when the inner query, or the subquery returns a value that is used by the outer query. It is very useful in selecting some rows in a table with a condition that depends on some data which is contained in the same table. A single row subquery returns only one row from the outer SELECT statement False. A single row subquery returns only one row from the inner SELECT statement. A multiple row subquery returns more than one row from the inner SELECT statement. True. Multiple column subqueries return more than one column from the inner SELECT statement. True. SELECT student_code, name FROM students WHERE marks = (SELECT MAX(marks) FROM students GROUP BY subject_code); Here a single row operator = is used with a multiple row subquery. IN, ANY, ALL. The DML statements are used to add new rows to a table, update or modify data in existing rows, or remove existing rows from a table. The INSERT INTO statement. While inserting new rows in a table you must list values in the default order of the columns. True. Null values can be inserted into a table by one of the following ways − Implicitly by omitting the column from the column list. Explicitly by specifying the NULL keyword in the VALUES clause. INSERT statement does not allow copying rows from one table to another. False. INSERT statement allows to add rows to a table copying rows from an existing table. The INSERT statement can be used to add rows to a table by copying from another table. In this case, a subquery is used in the place of the VALUES clause. All the rows in the table are modified. Yes. Use of subqueries in UPDATE statements allow you to update rows in a table based on values from another table. The DELETE statement is used to delete a table from the database. False. The DELETE statement is used for removing existing rows from a table. All the rows in the table are deleted. Yes, subqueries can be used to remove rows from a table based on values from another table. Attempting to delete a record with a value attached to an integrity constraint, returns an error. True. You can use a subquery in an INSERT statement. True. The MERGE statement allows conditional update or insertion of data into a database table. It performs an UPDATE if the rows exists, or an INSERT if the row does not exist. A DDL statement or a DCL statement is automatically committed. True. VARCHAR2 represents variable length character data, whereas CHAR represents fixed length character data. A DROP TABLE statement can be rolled back. False. A DROP TABLE statement cannot be rolled back. The ALTER TABLE statement. A view is a logical snapshot based on a table or another view. It is used for − Restricting access to data; Making complex queries simple; Ensuring data independency; Providing different views of same data. A view doesn’t have data of its own. True. Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong. Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-) 42 Lectures 5 hours Anadi Sharma 14 Lectures 2 hours Anadi Sharma 44 Lectures 4.5 hours Anadi Sharma 94 Lectures 7 hours Abhishek And Pukhraj 80 Lectures 6.5 hours Oracle Master Training | 150,000+ Students Worldwide 31 Lectures 6 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2883, "s": 2453, "text": "Dear readers, these SQL Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of SQL. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer:" }, { "code": null, "e": 3187, "s": 2883, "text": "SQL or Structured Query Language is a language; language that communicates with a relational database thus providing ways of manipulating and creating databases. MySQL and Microsoft’s SQL Server both are relational database management systems that use SQL as their standard relational database language." }, { "code": null, "e": 3371, "s": 3187, "text": "PL/SQL is a dialect of SQL that adds procedural features of programming languages in SQL. It was developed by Oracle Corporation in the early 90's to enhance the capabilities of SQL." }, { "code": null, "e": 3443, "s": 3371, "text": "Following are various DDL or Data Definition Language commands in SQL −" }, { "code": null, "e": 3524, "s": 3443, "text": "CREATE − it creates a new table, a view of a table, or other object in database." }, { "code": null, "e": 3605, "s": 3524, "text": "CREATE − it creates a new table, a view of a table, or other object in database." }, { "code": null, "e": 3671, "s": 3605, "text": "ALTER − it modifies an existing database object, such as a table." }, { "code": null, "e": 3737, "s": 3671, "text": "ALTER − it modifies an existing database object, such as a table." }, { "code": null, "e": 3823, "s": 3737, "text": "DROP − it deletes an entire table, a view of a table or other object in the database." }, { "code": null, "e": 3909, "s": 3823, "text": "DROP − it deletes an entire table, a view of a table or other object in the database." }, { "code": null, "e": 3983, "s": 3909, "text": "Following are various DML or Data Manipulation Language commands in SQL −" }, { "code": null, "e": 4046, "s": 3983, "text": "SELECT − it retrieves certain records from one or more tables." }, { "code": null, "e": 4109, "s": 4046, "text": "SELECT − it retrieves certain records from one or more tables." }, { "code": null, "e": 4139, "s": 4109, "text": "INSERT − it creates a record." }, { "code": null, "e": 4169, "s": 4139, "text": "INSERT − it creates a record." }, { "code": null, "e": 4199, "s": 4169, "text": "UPDATE − it modifies records." }, { "code": null, "e": 4229, "s": 4199, "text": "UPDATE − it modifies records." }, { "code": null, "e": 4258, "s": 4229, "text": "DELETE − it deletes records." }, { "code": null, "e": 4287, "s": 4258, "text": "DELETE − it deletes records." }, { "code": null, "e": 4356, "s": 4287, "text": "Following are various DCL or Data Control Language commands in SQL −" }, { "code": null, "e": 4394, "s": 4356, "text": "GRANT − it gives a privilege to user." }, { "code": null, "e": 4432, "s": 4394, "text": "GRANT − it gives a privilege to user." }, { "code": null, "e": 4485, "s": 4432, "text": "REVOKE − it takes back privileges granted from user." }, { "code": null, "e": 4538, "s": 4485, "text": "REVOKE − it takes back privileges granted from user." }, { "code": null, "e": 4596, "s": 4538, "text": "Yes. A column alias could be used in the ORDER BY clause." }, { "code": null, "e": 4792, "s": 4596, "text": "A NULL value is not same as zero or a blank space. A NULL value is a value which is ‘unavailable, unassigned, unknown or not applicable’. Whereas, zero is a number and blank space is a character." }, { "code": null, "e": 4900, "s": 4792, "text": "If a column value taking part in an arithmetic expression is NULL, then the result obtained would be NULLM." }, { "code": null, "e": 4906, "s": 4900, "text": "True." }, { "code": null, "e": 5063, "s": 4906, "text": "A query result displays all rows including the duplicate rows. To eliminate duplicate rows in the result, the DISTINCT keyword is used in the SELECT clause." }, { "code": null, "e": 5209, "s": 5063, "text": "The BETWEEN operator displays rows based on a range of values. The IN condition operator checks for values contained in a specific set of values." }, { "code": null, "e": 5346, "s": 5209, "text": "In such cases, the LIKE condition operator is used to select rows that match a character pattern. This is also called ‘wildcard’ search." }, { "code": null, "e": 5474, "s": 5346, "text": "The default sorting order is ascending. It can be changed using the DESC keyword, after the column name in the ORDER BY clause." }, { "code": null, "e": 5514, "s": 5474, "text": "SQL functions have the following uses −" }, { "code": null, "e": 5546, "s": 5514, "text": "Performing calculations on data" }, { "code": null, "e": 5578, "s": 5546, "text": "Performing calculations on data" }, { "code": null, "e": 5610, "s": 5578, "text": "Modifying individual data items" }, { "code": null, "e": 5642, "s": 5610, "text": "Modifying individual data items" }, { "code": null, "e": 5666, "s": 5642, "text": "Manipulating the output" }, { "code": null, "e": 5690, "s": 5666, "text": "Manipulating the output" }, { "code": null, "e": 5719, "s": 5690, "text": "Formatting dates and numbers" }, { "code": null, "e": 5748, "s": 5719, "text": "Formatting dates and numbers" }, { "code": null, "e": 5770, "s": 5748, "text": "Converting data types" }, { "code": null, "e": 5792, "s": 5770, "text": "Converting data types" }, { "code": null, "e": 5814, "s": 5792, "text": "LOWER, UPPER, INITCAP" }, { "code": null, "e": 5878, "s": 5814, "text": "The MOD function returns the remainder in a division operation." }, { "code": null, "e": 5937, "s": 5878, "text": "The NVL function converts a NULL value to an actual value." }, { "code": null, "e": 6135, "s": 5937, "text": "The NVL(exp1, exp2) function converts the source expression (or value) exp1 to the target expression (or value) exp2, if exp1 contains NULL. The return value has the same data type as that of exp1." }, { "code": null, "e": 6351, "s": 6135, "text": "The NVL2(exp1, exp2, exp3) function checks the first expression exp1, if it is not null then, the second expression exp2 is returned. If the first expression exp1 is null, then the third expression exp3 is returned." }, { "code": null, "e": 6500, "s": 6351, "text": "The NULLIF function compares two expressions. If they are equal, the function returns null. If they are not equal, the first expression is returned." }, { "code": null, "e": 6573, "s": 6500, "text": "The COALESCE function has the expression COALESCE(exp1, exp2, .... expn)" }, { "code": null, "e": 6643, "s": 6573, "text": "It returns the first non-null expression given in the parameter list." }, { "code": null, "e": 6740, "s": 6643, "text": "There are two ways to implement conditional processing or IF-THEN-ELSE logic in a SQL statement." }, { "code": null, "e": 6762, "s": 6740, "text": "Using CASE expression" }, { "code": null, "e": 6784, "s": 6762, "text": "Using CASE expression" }, { "code": null, "e": 6810, "s": 6784, "text": "Using the DECODE function" }, { "code": null, "e": 6836, "s": 6810, "text": "Using the DECODE function" }, { "code": null, "e": 6917, "s": 6836, "text": "The result would be the Cartesian product of two tables with 20 x 10 = 200 rows." }, { "code": null, "e": 7092, "s": 6917, "text": "The cross join produces the cross product or Cartesian product of two tables. The natural join is based on all the columns having same name and data types in both the tables." }, { "code": null, "e": 7247, "s": 7092, "text": "Group functions in SQL work on sets of rows and returns one result per group. Examples of group functions are AVG, COUNT, MAX, MIN, STDDEV, SUM, VARIANCE." }, { "code": null, "e": 7320, "s": 7247, "text": "By default the group functions consider only distinct values in the set." }, { "code": null, "e": 7400, "s": 7320, "text": "By default, group functions consider all values including the duplicate values." }, { "code": null, "e": 7475, "s": 7400, "text": "The DISTINCT keyword allows a function consider only non-duplicate values." }, { "code": null, "e": 7481, "s": 7475, "text": "True." }, { "code": null, "e": 7521, "s": 7481, "text": "All group functions ignore null values." }, { "code": null, "e": 7527, "s": 7521, "text": "True." }, { "code": null, "e": 7578, "s": 7527, "text": "COUNT(*) returns the number of columns in a table." }, { "code": null, "e": 7633, "s": 7578, "text": "False. COUNT(*) returns the number of rows in a table." }, { "code": null, "e": 7683, "s": 7633, "text": "SELECT subject_code, count(name) \nFROM students;" }, { "code": null, "e": 7769, "s": 7683, "text": "It doesn’t have a GROUP BY clause. The subject_code should be in the GROUP BY clause." }, { "code": null, "e": 7848, "s": 7769, "text": " SELECT subject_code, count(name)\n FROM students\n GROUP BY subject_code;" }, { "code": null, "e": 7952, "s": 7848, "text": " SELECT subject_code, AVG (marks)\n FROM students\n WHERE AVG(marks) > 75\n GROUP BY subject_code;" }, { "code": null, "e": 8038, "s": 7952, "text": "The WHERE clause cannot be used to restrict groups. The HAVING clause should be used." }, { "code": null, "e": 8143, "s": 8038, "text": " SELECT subject_code, AVG (marks)\n FROM students\n HAVING AVG(marks) > 75\n GROUP BY subject_code;" }, { "code": null, "e": 8177, "s": 8143, "text": "Group functions cannot be nested." }, { "code": null, "e": 8233, "s": 8177, "text": "False. Group functions can be nested to a depth of two." }, { "code": null, "e": 8547, "s": 8233, "text": "A subquery is a SELECT statement embedded in a clause of another SELECT statement. It is used when the inner query, or the subquery returns a value that is used by the outer query. It is very useful in selecting some rows in a table with a condition that depends on some data which is contained in the same table." }, { "code": null, "e": 8622, "s": 8547, "text": "A single row subquery returns only one row from the outer SELECT statement" }, { "code": null, "e": 8705, "s": 8622, "text": "False. A single row subquery returns only one row from the inner SELECT statement." }, { "code": null, "e": 8788, "s": 8705, "text": "A multiple row subquery returns more than one row from the inner SELECT statement." }, { "code": null, "e": 8794, "s": 8788, "text": "True." }, { "code": null, "e": 8882, "s": 8794, "text": "Multiple column subqueries return more than one column from the inner SELECT statement." }, { "code": null, "e": 8888, "s": 8882, "text": "True." }, { "code": null, "e": 9060, "s": 8888, "text": " SELECT student_code, name\n FROM students\n WHERE marks = \n (SELECT MAX(marks)\n FROM students\n GROUP BY subject_code);" }, { "code": null, "e": 9127, "s": 9060, "text": "Here a single row operator = is used with a multiple row subquery." }, { "code": null, "e": 9141, "s": 9127, "text": "IN, ANY, ALL." }, { "code": null, "e": 9275, "s": 9141, "text": "The DML statements are used to add new rows to a table, update\tor modify data in existing rows, or remove existing rows from a table." }, { "code": null, "e": 9302, "s": 9275, "text": "The INSERT INTO statement." }, { "code": null, "e": 9396, "s": 9302, "text": "While inserting new rows in a table you must list values in the default order of the columns." }, { "code": null, "e": 9402, "s": 9396, "text": "True." }, { "code": null, "e": 9474, "s": 9402, "text": "Null values can be inserted into a table by one of the following ways −" }, { "code": null, "e": 9530, "s": 9474, "text": "Implicitly by omitting the column from the column list." }, { "code": null, "e": 9594, "s": 9530, "text": "Explicitly by specifying the NULL keyword in the VALUES clause." }, { "code": null, "e": 9666, "s": 9594, "text": "INSERT statement does not allow copying rows from one table to another." }, { "code": null, "e": 9757, "s": 9666, "text": "False. INSERT statement allows to add rows to a table copying rows from an existing table." }, { "code": null, "e": 9912, "s": 9757, "text": "The INSERT statement can be used to add rows to a table by copying from another table. In this case, a subquery is used in the place of the VALUES clause." }, { "code": null, "e": 9952, "s": 9912, "text": "All the rows in the table are modified." }, { "code": null, "e": 10068, "s": 9952, "text": "Yes. Use of subqueries in UPDATE statements allow you to update rows in a table based on values from another table." }, { "code": null, "e": 10134, "s": 10068, "text": "The DELETE statement is used to delete a table from the database." }, { "code": null, "e": 10211, "s": 10134, "text": "False. The DELETE statement is used for removing existing rows from a table." }, { "code": null, "e": 10250, "s": 10211, "text": "All the rows in the table are deleted." }, { "code": null, "e": 10342, "s": 10250, "text": "Yes, subqueries can be used to remove rows from a table based on values from another table." }, { "code": null, "e": 10440, "s": 10342, "text": "Attempting to delete a record with a value attached to an integrity constraint, returns an error." }, { "code": null, "e": 10446, "s": 10440, "text": "True." }, { "code": null, "e": 10493, "s": 10446, "text": "You can use a subquery in an INSERT statement." }, { "code": null, "e": 10499, "s": 10493, "text": "True." }, { "code": null, "e": 10671, "s": 10499, "text": "The MERGE statement allows conditional update or insertion of data into a database table. It performs an UPDATE if the rows exists, or an INSERT if the row does not exist." }, { "code": null, "e": 10734, "s": 10671, "text": "A DDL statement or a DCL statement is automatically committed." }, { "code": null, "e": 10740, "s": 10734, "text": "True." }, { "code": null, "e": 10845, "s": 10740, "text": "VARCHAR2 represents variable length character data, whereas CHAR represents fixed length character data." }, { "code": null, "e": 10888, "s": 10845, "text": "A DROP TABLE statement can be rolled back." }, { "code": null, "e": 10941, "s": 10888, "text": "False. A DROP TABLE statement cannot be rolled back." }, { "code": null, "e": 10968, "s": 10941, "text": "The ALTER TABLE statement." }, { "code": null, "e": 11048, "s": 10968, "text": "A view is a logical snapshot based on a table or another view. It is used for −" }, { "code": null, "e": 11076, "s": 11048, "text": "Restricting access to data;" }, { "code": null, "e": 11107, "s": 11076, "text": "Making complex queries simple;" }, { "code": null, "e": 11135, "s": 11107, "text": "Ensuring data independency;" }, { "code": null, "e": 11175, "s": 11135, "text": "Providing different views of same data." }, { "code": null, "e": 11212, "s": 11175, "text": "A view doesn’t have data of its own." }, { "code": null, "e": 11218, "s": 11212, "text": "True." }, { "code": null, "e": 11505, "s": 11218, "text": "Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong." }, { "code": null, "e": 11835, "s": 11505, "text": "Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)" }, { "code": null, "e": 11868, "s": 11835, "text": "\n 42 Lectures \n 5 hours \n" }, { "code": null, "e": 11882, "s": 11868, "text": " Anadi Sharma" }, { "code": null, "e": 11915, "s": 11882, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 11929, "s": 11915, "text": " Anadi Sharma" }, { "code": null, "e": 11964, "s": 11929, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11978, "s": 11964, "text": " Anadi Sharma" }, { "code": null, "e": 12011, "s": 11978, "text": "\n 94 Lectures \n 7 hours \n" }, { "code": null, "e": 12033, "s": 12011, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 12068, "s": 12033, "text": "\n 80 Lectures \n 6.5 hours \n" }, { "code": null, "e": 12122, "s": 12068, "text": " Oracle Master Training | 150,000+ Students Worldwide" }, { "code": null, "e": 12155, "s": 12122, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 12183, "s": 12155, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 12190, "s": 12183, "text": " Print" }, { "code": null, "e": 12201, "s": 12190, "text": " Add Notes" } ]
Biopython - Plotting
This chapter explains about how to plot sequences. Before moving to this topic, let us understand the basics of plotting. Matplotlib is a Python plotting library which produces quality figures in a variety of formats. We can create different types of plots like line chart, histograms, bar chart, pie chart, scatter chart, etc. pyLab is a module that belongs to the matplotlib which combines the numerical module numpy with the graphical plotting module pyplot.Biopython uses pylab module for plotting sequences. To do this, we need to import the below code − import pylab Before importing, we need to install the matplotlib package using pip command with the command given below − pip install matplotlib Create a sample file named plot.fasta in your Biopython directory and add the following changes − >seq0 FQTWEEFSRAAEKLYLADPMKVRVVLKYRHVDGNLCIKVTDDLVCLVYRTDQAQDVKKIEKF >seq1 KYRTWEEFTRAAEKLYQADPMKVRVVLKYRHCDGNLCIKVTDDVVCLLYRTDQAQDVKKIEKFHSQLMRLME >seq2 EEYQTWEEFARAAEKLYLTDPMKVRVVLKYRHCDGNLCMKVTDDAVCLQYKTDQAQDVKKVEKLHGK >seq3 MYQVWEEFSRAVEKLYLTDPMKVRVVLKYRHCDGNLCIKVTDNSVCLQYKTDQAQDV >seq4 EEFSRAVEKLYLTDPMKVRVVLKYRHCDGNLCIKVTDNSVVSYEMRLFGVQKDNFALEHSLL >seq5 SWEEFAKAAEVLYLEDPMKCRMCTKYRHVDHKLVVKLTDNHTVLKYVTDMAQDVKKIEKLTTLLMR >seq6 FTNWEEFAKAAERLHSANPEKCRFVTKYNHTKGELVLKLTDDVVCLQYSTNQLQDVKKLEKLSSTLLRSI >seq7 SWEEFVERSVQLFRGDPNATRYVMKYRHCEGKLVLKVTDDRECLKFKTDQAQDAKKMEKLNNIFF >seq8 SWDEFVDRSVQLFRADPESTRYVMKYRHCDGKLVLKVTDNKECLKFKTDQAQEAKKMEKLNNIFFTLM >seq9 KNWEDFEIAAENMYMANPQNCRYTMKYVHSKGHILLKMSDNVKCVQYRAENMPDLKK >seq10 FDSWDEFVSKSVELFRNHPDTTRYVVKYRHCEGKLVLKVTDNHECLKFKTDQAQDAKKMEK Now, let us create a simple line plot for the above fasta file. Step 1 − Import SeqIO module to read fasta file. >>> from Bio import SeqIO Step 2 − Parse the input file. >>> records = [len(rec) for rec in SeqIO.parse("plot.fasta", "fasta")] >>> len(records) 11 >>> max(records) 72 >>> min(records) 57 Step 3 − Let us import pylab module. >>> import pylab Step 4 − Configure the line chart by assigning x and y axis labels. >>> pylab.xlabel("sequence length") Text(0.5, 0, 'sequence length') >>> pylab.ylabel("count") Text(0, 0.5, 'count') >>> Step 5 − Configure the line chart by setting grid display. >>> pylab.grid() Step 6 − Draw simple line chart by calling plot method and supplying records as input. >>> pylab.plot(records) [<matplotlib.lines.Line2D object at 0x10b6869d 0>] Step 7 − Finally save the chart using the below command. >>> pylab.savefig("lines.png") After executing the above command, you could see the following image saved in your Biopython directory. A histogram is used for continuous data, where the bins represent ranges of data. Drawing histogram is same as line chart except pylab.plot. Instead, call hist method of pylab module with records and some custum value for bins (5). The complete coding is as follows − Step 1 − Import SeqIO module to read fasta file. >>> from Bio import SeqIO Step 2 − Parse the input file. >>> records = [len(rec) for rec in SeqIO.parse("plot.fasta", "fasta")] >>> len(records) 11 >>> max(records) 72 >>> min(records) 57 Step 3 − Let us import pylab module. >>> import pylab Step 4 − Configure the line chart by assigning x and y axis labels. >>> pylab.xlabel("sequence length") Text(0.5, 0, 'sequence length') >>> pylab.ylabel("count") Text(0, 0.5, 'count') >>> Step 5 − Configure the line chart by setting grid display. >>> pylab.grid() Step 6 − Draw simple line chart by calling plot method and supplying records as input. >>> pylab.hist(records,bins=5) (array([2., 3., 1., 3., 2.]), array([57., 60., 63., 66., 69., 72.]), <a list of 5 Patch objects>) >>> Step 7 − Finally save the chart using the below command. >>> pylab.savefig("hist.png") After executing the above command, you could see the following image saved in your Biopython directory. GC percentage is one of the commonly used analytic data to compare different sequences. We can do a simple line chart using GC Percentage of a set of sequences and immediately compare it. Here, we can just change the data from sequence length to GC percentage. The complete coding is given below − Step 1 − Import SeqIO module to read fasta file. >>> from Bio import SeqIO Step 2 − Parse the input file. >>> from Bio.SeqUtils import GC >>> gc = sorted(GC(rec.seq) for rec in SeqIO.parse("plot.fasta", "fasta")) Step 3 − Let us import pylab module. >>> import pylab Step 4 − Configure the line chart by assigning x and y axis labels. >>> pylab.xlabel("Genes") Text(0.5, 0, 'Genes') >>> pylab.ylabel("GC Percentage") Text(0, 0.5, 'GC Percentage') >>> Step 5 − Configure the line chart by setting grid display. >>> pylab.grid() Step 6 − Draw simple line chart by calling plot method and supplying records as input. >>> pylab.plot(gc) [<matplotlib.lines.Line2D object at 0x10b6869d 0>] Step 7 − Finally save the chart using the below command. >>> pylab.savefig("gc.png") After executing the above command, you could see the following image saved in your Biopython directory. Print Add Notes Bookmark this page
[ { "code": null, "e": 2228, "s": 2106, "text": "This chapter explains about how to plot sequences. Before moving to this topic, let us understand the basics of plotting." }, { "code": null, "e": 2434, "s": 2228, "text": "Matplotlib is a Python plotting library which produces quality figures in a variety of formats. We can create different types of plots like line chart, histograms, bar chart, pie chart, scatter chart, etc." }, { "code": null, "e": 2666, "s": 2434, "text": "pyLab is a module that belongs to the matplotlib which combines the numerical module numpy with the graphical plotting module pyplot.Biopython uses pylab module for plotting sequences. To do this, we need to import the below code −" }, { "code": null, "e": 2680, "s": 2666, "text": "import pylab\n" }, { "code": null, "e": 2789, "s": 2680, "text": "Before importing, we need to install the matplotlib package using pip command with the command given below −" }, { "code": null, "e": 2813, "s": 2789, "text": "pip install matplotlib\n" }, { "code": null, "e": 2911, "s": 2813, "text": "Create a sample file named plot.fasta in your Biopython directory and add the following changes −" }, { "code": null, "e": 3705, "s": 2911, "text": ">seq0 FQTWEEFSRAAEKLYLADPMKVRVVLKYRHVDGNLCIKVTDDLVCLVYRTDQAQDVKKIEKF \n>seq1 KYRTWEEFTRAAEKLYQADPMKVRVVLKYRHCDGNLCIKVTDDVVCLLYRTDQAQDVKKIEKFHSQLMRLME \n>seq2 EEYQTWEEFARAAEKLYLTDPMKVRVVLKYRHCDGNLCMKVTDDAVCLQYKTDQAQDVKKVEKLHGK \n>seq3 MYQVWEEFSRAVEKLYLTDPMKVRVVLKYRHCDGNLCIKVTDNSVCLQYKTDQAQDV\n>seq4 EEFSRAVEKLYLTDPMKVRVVLKYRHCDGNLCIKVTDNSVVSYEMRLFGVQKDNFALEHSLL \n>seq5 SWEEFAKAAEVLYLEDPMKCRMCTKYRHVDHKLVVKLTDNHTVLKYVTDMAQDVKKIEKLTTLLMR \n>seq6 FTNWEEFAKAAERLHSANPEKCRFVTKYNHTKGELVLKLTDDVVCLQYSTNQLQDVKKLEKLSSTLLRSI \n>seq7 SWEEFVERSVQLFRGDPNATRYVMKYRHCEGKLVLKVTDDRECLKFKTDQAQDAKKMEKLNNIFF \n>seq8 SWDEFVDRSVQLFRADPESTRYVMKYRHCDGKLVLKVTDNKECLKFKTDQAQEAKKMEKLNNIFFTLM \n>seq9 KNWEDFEIAAENMYMANPQNCRYTMKYVHSKGHILLKMSDNVKCVQYRAENMPDLKK\n>seq10 FDSWDEFVSKSVELFRNHPDTTRYVVKYRHCEGKLVLKVTDNHECLKFKTDQAQDAKKMEK\n" }, { "code": null, "e": 3769, "s": 3705, "text": "Now, let us create a simple line plot for the above fasta file." }, { "code": null, "e": 3818, "s": 3769, "text": "Step 1 − Import SeqIO module to read fasta file." }, { "code": null, "e": 3845, "s": 3818, "text": ">>> from Bio import SeqIO\n" }, { "code": null, "e": 3876, "s": 3845, "text": "Step 2 − Parse the input file." }, { "code": null, "e": 4013, "s": 3876, "text": ">>> records = [len(rec) for rec in SeqIO.parse(\"plot.fasta\", \"fasta\")] \n>>> len(records) \n11 \n>>> max(records) \n72 \n>>> min(records) \n57" }, { "code": null, "e": 4050, "s": 4013, "text": "Step 3 − Let us import pylab module." }, { "code": null, "e": 4068, "s": 4050, "text": ">>> import pylab\n" }, { "code": null, "e": 4136, "s": 4068, "text": "Step 4 − Configure the line chart by assigning x and y axis labels." }, { "code": null, "e": 4261, "s": 4136, "text": ">>> pylab.xlabel(\"sequence length\") \nText(0.5, 0, 'sequence length') \n\n>>> pylab.ylabel(\"count\") \nText(0, 0.5, 'count') \n>>>" }, { "code": null, "e": 4320, "s": 4261, "text": "Step 5 − Configure the line chart by setting grid display." }, { "code": null, "e": 4338, "s": 4320, "text": ">>> pylab.grid()\n" }, { "code": null, "e": 4425, "s": 4338, "text": "Step 6 − Draw simple line chart by calling plot method and supplying records as input." }, { "code": null, "e": 4501, "s": 4425, "text": ">>> pylab.plot(records) \n[<matplotlib.lines.Line2D object at 0x10b6869d 0>]" }, { "code": null, "e": 4558, "s": 4501, "text": "Step 7 − Finally save the chart using the below command." }, { "code": null, "e": 4590, "s": 4558, "text": ">>> pylab.savefig(\"lines.png\")\n" }, { "code": null, "e": 4694, "s": 4590, "text": "After executing the above command, you could see the following image saved in your Biopython directory." }, { "code": null, "e": 4962, "s": 4694, "text": "A histogram is used for continuous data, where the bins represent ranges of data. Drawing histogram is same as line chart except pylab.plot. Instead, call hist method of pylab module with records and some custum value for bins (5). The complete coding is as follows −" }, { "code": null, "e": 5011, "s": 4962, "text": "Step 1 − Import SeqIO module to read fasta file." }, { "code": null, "e": 5038, "s": 5011, "text": ">>> from Bio import SeqIO\n" }, { "code": null, "e": 5069, "s": 5038, "text": "Step 2 − Parse the input file." }, { "code": null, "e": 5206, "s": 5069, "text": ">>> records = [len(rec) for rec in SeqIO.parse(\"plot.fasta\", \"fasta\")] \n>>> len(records) \n11 \n>>> max(records) \n72 \n>>> min(records) \n57" }, { "code": null, "e": 5243, "s": 5206, "text": "Step 3 − Let us import pylab module." }, { "code": null, "e": 5261, "s": 5243, "text": ">>> import pylab\n" }, { "code": null, "e": 5329, "s": 5261, "text": "Step 4 − Configure the line chart by assigning x and y axis labels." }, { "code": null, "e": 5454, "s": 5329, "text": ">>> pylab.xlabel(\"sequence length\") \nText(0.5, 0, 'sequence length') \n\n>>> pylab.ylabel(\"count\") \nText(0, 0.5, 'count') \n>>>" }, { "code": null, "e": 5513, "s": 5454, "text": "Step 5 − Configure the line chart by setting grid display." }, { "code": null, "e": 5531, "s": 5513, "text": ">>> pylab.grid()\n" }, { "code": null, "e": 5618, "s": 5531, "text": "Step 6 − Draw simple line chart by calling plot method and supplying records as input." }, { "code": null, "e": 5754, "s": 5618, "text": ">>> pylab.hist(records,bins=5) \n(array([2., 3., 1., 3., 2.]), array([57., 60., 63., 66., 69., 72.]), <a list \nof 5 Patch objects>) \n>>>" }, { "code": null, "e": 5811, "s": 5754, "text": "Step 7 − Finally save the chart using the below command." }, { "code": null, "e": 5842, "s": 5811, "text": ">>> pylab.savefig(\"hist.png\")\n" }, { "code": null, "e": 5946, "s": 5842, "text": "After executing the above command, you could see the following image saved in your Biopython directory." }, { "code": null, "e": 6244, "s": 5946, "text": "GC percentage is one of the commonly used analytic data to compare different sequences. We can do a simple line chart using GC Percentage of a set of sequences and immediately compare it. Here, we can just change the data from sequence length to GC percentage. The complete coding is given below −" }, { "code": null, "e": 6293, "s": 6244, "text": "Step 1 − Import SeqIO module to read fasta file." }, { "code": null, "e": 6320, "s": 6293, "text": ">>> from Bio import SeqIO\n" }, { "code": null, "e": 6351, "s": 6320, "text": "Step 2 − Parse the input file." }, { "code": null, "e": 6459, "s": 6351, "text": ">>> from Bio.SeqUtils import GC \n>>> gc = sorted(GC(rec.seq) for rec in SeqIO.parse(\"plot.fasta\", \"fasta\"))" }, { "code": null, "e": 6496, "s": 6459, "text": "Step 3 − Let us import pylab module." }, { "code": null, "e": 6514, "s": 6496, "text": ">>> import pylab\n" }, { "code": null, "e": 6582, "s": 6514, "text": "Step 4 − Configure the line chart by assigning x and y axis labels." }, { "code": null, "e": 6703, "s": 6582, "text": ">>> pylab.xlabel(\"Genes\") \nText(0.5, 0, 'Genes') \n\n>>> pylab.ylabel(\"GC Percentage\") \nText(0, 0.5, 'GC Percentage') \n>>>" }, { "code": null, "e": 6762, "s": 6703, "text": "Step 5 − Configure the line chart by setting grid display." }, { "code": null, "e": 6780, "s": 6762, "text": ">>> pylab.grid()\n" }, { "code": null, "e": 6867, "s": 6780, "text": "Step 6 − Draw simple line chart by calling plot method and supplying records as input." }, { "code": null, "e": 6939, "s": 6867, "text": ">>> pylab.plot(gc) \n[<matplotlib.lines.Line2D object at 0x10b6869d 0>]\n" }, { "code": null, "e": 6996, "s": 6939, "text": "Step 7 − Finally save the chart using the below command." }, { "code": null, "e": 7025, "s": 6996, "text": ">>> pylab.savefig(\"gc.png\")\n" }, { "code": null, "e": 7129, "s": 7025, "text": "After executing the above command, you could see the following image saved in your Biopython directory." }, { "code": null, "e": 7136, "s": 7129, "text": " Print" }, { "code": null, "e": 7147, "s": 7136, "text": " Add Notes" } ]
How to Optimize Learning Rate with TensorFlow — It’s Easier Than You Think | by Dario Radečić | Towards Data Science
Tuning neural network models is no joke. There are so many hyperparameters to tune, and tuning all of them at once using a grid search approach could take weeks, even months. Learning rate is a hyperparameter you can tune in a couple of minutes, provided you know how. This article will teach you how. The learning rate controls how much the weights are updated according to the estimated error. Choose too small of a value and your model will train forever and likely get stuck. Opt for a too large learning rate and your model might skip the optimal set of weights during training. You’ll need TensorFlow 2+, Numpy, Pandas, Matplotlib, and Scikit-Learn installed to follow along. Don’t feel like reading? Watch my video instead: You can download the source code on GitHub. I don’t plan to spend much time here. We’ll use the same dataset as in the previous article — the wine quality dataset from Kaggle: You can use the following code to import it to Python and print a random couple of rows: import osimport numpy as npimport pandas as pdimport warningsos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' warnings.filterwarnings('ignore')df = pd.read_csv('data/winequalityN.csv')df.sample(5) We’re ignoring the warnings and changing the default TensorFlow log level just so we don’t get overwhelmed with the output. Here’s how the dataset looks like: The dataset is mostly clean, but isn’t designed for binary classification by default (good/bad wine). Instead, the wines are rated on a scale. We’ll address that now, with a bunch of other things: Delete missing values — There’s only a handful of them so we won’t waste time on imputation. Handle categorical features — The only one is type, indicating whether the wine is white or red. Convert to a binary classification task — We’ll declare any wine with a grade of 6 and above as good, and anything below as bad. Train/test split — A classic 80:20 split. Scale the data — The scale between predictors differs significantly, so we’ll use the StandardScaler to bring the values closer. Here’s the entire data preprocessing code snippet: from sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScaler# Prepare the datadf = df.dropna()df['is_white_wine'] = [ 1 if typ == 'white' else 0 for typ in df['type']]df['is_good_wine'] = [ 1 if quality >= 6 else 0 for quality in df['quality']]df.drop(['type', 'quality'], axis=1, inplace=True)# Train/test splitX = df.drop('is_good_wine', axis=1)y = df['is_good_wine']X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42)# Scalingscaler = StandardScaler()X_train_scaled = scaler.fit_transform(X_train)X_test_scaled = scaler.transform(X_test) And here’s how the first couple of scaled rows look like: Once again, please refer to the previous article if you want more detailed insights into the logic behind data preprocessing. With that out of the way, let’s see how to optimize the learning rate. Optimizing the learning rate is easy once you get the gist of it. The idea is to start small — let’s say with 0.001 and increase the value every epoch. You’ll get terrible accuracy when training the model, but that’s expected. Don’t even mind it, as we’re only interested in how the loss changes as we change the learning rate. Let’s start by importing TensorFlow and setting the seed so you can reproduce the results: import tensorflow as tftf.random.set_seed(42) We’ll train the model for 100 epochs to test 100 different loss/learning rate combinations. Here’s the range for the learning rate values: A learning rate of 0.001 is the default one for, let’s say, Adam optimizer, and 2.15 is definitely too large. Next, let’s define a neural network model architecture, compile the model, and train it. The only new thing here is the LearningRateScheduler. It allows us to enter the above-declared way to change the learning rate as a lambda function. Here’s the entire code: initial_model = tf.keras.Sequential([ tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dense(1, activation='sigmoid')])initial_model.compile( loss=tf.keras.losses.binary_crossentropy, optimizer=tf.keras.optimizers.Adam(), metrics=[ tf.keras.metrics.BinaryAccuracy(name='accuracy') ])initial_history = initial_model.fit( X_train_scaled, y_train, epochs=100, callbacks=[ tf.keras.callbacks.LearningRateScheduler( lambda epoch: 1e-3 * 10 ** (epoch / 30) ) ]) The training will start now and you’ll see a decent accuracy immediately — around 75% — but it will drop after 50-something epochs because the learning rate became too large. After 100 epochs, the initial_model had around 60% accuracy: The initial_history variable now has information on loss, accuracy, and learning rate. Let’s plot all of them: import matplotlib.pyplot as pltfrom matplotlib import rcParamsrcParams['figure.figsize'] = (18, 8)rcParams['axes.spines.top'] = FalsercParams['axes.spines.right'] = False plt.plot( np.arange(1, 101), initial_history.history['loss'], label='Loss', lw=3)plt.plot( np.arange(1, 101), initial_history.history['accuracy'], label='Accuracy', lw=3)plt.plot( np.arange(1, 101), initial_history.history['lr'], label='Learning rate', color='#000', lw=3, linestyle='--')plt.title('Evaluation metrics', size=20)plt.xlabel('Epoch', size=14)plt.legend(); Here’s the chart: The accuracy dipped significantly around epoch 50 and flattened for a while, before starting to dip further. The exact opposite happened to loss, which makes sense. You can now plot the loss against learning rate on a logarithmic scale to eyeball where the minimum loss was achieved: learning_rates = 1e-3 * (10 ** (np.arange(100) / 30))plt.semilogx( learning_rates, initial_history.history['loss'], lw=3, color='#000')plt.title('Learning rate vs. loss', size=20)plt.xlabel('Learning rate', size=14)plt.ylabel('Loss', size=14); Here’s the chart: You’ll generally want to select a learning rate that achieves the lowest loss, provided that the values around it aren’t too volatile. Keep in mind that the X-axis is on a logarithmic scale. The optimal learning rate is around 0.007: So let’s train a model with a supposedly optimal learning rate and see if we can outperform the default one. With a learning rate of 0.007 in mind, let’s write another neural network model. You won’t need the LearningRateScheduler this time: model_optimized = tf.keras.Sequential([ tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dense(1, activation='sigmoid')])model_optimized.compile( loss=tf.keras.losses.binary_crossentropy, optimizer=tf.keras.optimizers.Adam(learning_rate=0.007), metrics=[ tf.keras.metrics.BinaryAccuracy(name='accuracy') ])history_optimized = model_optimized.fit( X_train_scaled, y_train, epochs=100) We got 76% accuracy with the default learning rate in the previous article, so it’ll be interesting to see if learning rate optimization can increase it. The reported accuracy on the train set looks too good to be true, so it’s likely our model is overfitting: It won’t matter too much if we’ve managed to increase the performance on the test set, but you could save yourself some time by training the model for fewer epochs. Here’s how the accuracy vs. loss looks like for the optimized model: plt.plot( np.arange(1, 101), history_optimized.history['loss'], label='Loss', lw=3)plt.plot( np.arange(1, 101), history_optimized.history['accuracy'], label='Accuracy', lw=3)plt.title('Accuracy vs. Loss per epoch', size=20)plt.xlabel('Epoch', size=14)plt.legend() Let’s finally calculate the predictions and evaluate them against the test set. Here’s the code: from sklearn.metrics import confusion_matrixfrom sklearn.metrics import accuracy_scorepredictions = model_optimized.predict(X_test_scaled)prediction_classes = [1 if prob > 0.5 else 0 for prob in np.ravel(predictions)]print(f'Accuracy on the test set: {accuracy_score(y_test, prediction_classes):.2f}')print()print('Confusion matrix:')print(confusion_matrix(y_test, prediction_classes)) And here’s the output: To summarize, optimizing the learning rate alone managed to increase the model accuracy by 3% on the test set. It might not sound huge, but it’s an excellent trade-off for the amount of time it took. Moreover, it’s only the first of many optimizations you can do to a neural network model, and it’s one less hyperparameter you need to worry about. Stay tuned to learn how to optimize a neural network architecture — the post will be up in a couple of days. Thanks for reading! Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you. medium.com Sign up for my newsletter Subscribe on YouTube Connect on LinkedIn
[ { "code": null, "e": 474, "s": 172, "text": "Tuning neural network models is no joke. There are so many hyperparameters to tune, and tuning all of them at once using a grid search approach could take weeks, even months. Learning rate is a hyperparameter you can tune in a couple of minutes, provided you know how. This article will teach you how." }, { "code": null, "e": 756, "s": 474, "text": "The learning rate controls how much the weights are updated according to the estimated error. Choose too small of a value and your model will train forever and likely get stuck. Opt for a too large learning rate and your model might skip the optimal set of weights during training." }, { "code": null, "e": 854, "s": 756, "text": "You’ll need TensorFlow 2+, Numpy, Pandas, Matplotlib, and Scikit-Learn installed to follow along." }, { "code": null, "e": 903, "s": 854, "text": "Don’t feel like reading? Watch my video instead:" }, { "code": null, "e": 947, "s": 903, "text": "You can download the source code on GitHub." }, { "code": null, "e": 1079, "s": 947, "text": "I don’t plan to spend much time here. We’ll use the same dataset as in the previous article — the wine quality dataset from Kaggle:" }, { "code": null, "e": 1168, "s": 1079, "text": "You can use the following code to import it to Python and print a random couple of rows:" }, { "code": null, "e": 1357, "s": 1168, "text": "import osimport numpy as npimport pandas as pdimport warningsos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' warnings.filterwarnings('ignore')df = pd.read_csv('data/winequalityN.csv')df.sample(5)" }, { "code": null, "e": 1481, "s": 1357, "text": "We’re ignoring the warnings and changing the default TensorFlow log level just so we don’t get overwhelmed with the output." }, { "code": null, "e": 1516, "s": 1481, "text": "Here’s how the dataset looks like:" }, { "code": null, "e": 1713, "s": 1516, "text": "The dataset is mostly clean, but isn’t designed for binary classification by default (good/bad wine). Instead, the wines are rated on a scale. We’ll address that now, with a bunch of other things:" }, { "code": null, "e": 1806, "s": 1713, "text": "Delete missing values — There’s only a handful of them so we won’t waste time on imputation." }, { "code": null, "e": 1903, "s": 1806, "text": "Handle categorical features — The only one is type, indicating whether the wine is white or red." }, { "code": null, "e": 2032, "s": 1903, "text": "Convert to a binary classification task — We’ll declare any wine with a grade of 6 and above as good, and anything below as bad." }, { "code": null, "e": 2074, "s": 2032, "text": "Train/test split — A classic 80:20 split." }, { "code": null, "e": 2203, "s": 2074, "text": "Scale the data — The scale between predictors differs significantly, so we’ll use the StandardScaler to bring the values closer." }, { "code": null, "e": 2254, "s": 2203, "text": "Here’s the entire data preprocessing code snippet:" }, { "code": null, "e": 2887, "s": 2254, "text": "from sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScaler# Prepare the datadf = df.dropna()df['is_white_wine'] = [ 1 if typ == 'white' else 0 for typ in df['type']]df['is_good_wine'] = [ 1 if quality >= 6 else 0 for quality in df['quality']]df.drop(['type', 'quality'], axis=1, inplace=True)# Train/test splitX = df.drop('is_good_wine', axis=1)y = df['is_good_wine']X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42)# Scalingscaler = StandardScaler()X_train_scaled = scaler.fit_transform(X_train)X_test_scaled = scaler.transform(X_test)" }, { "code": null, "e": 2945, "s": 2887, "text": "And here’s how the first couple of scaled rows look like:" }, { "code": null, "e": 3071, "s": 2945, "text": "Once again, please refer to the previous article if you want more detailed insights into the logic behind data preprocessing." }, { "code": null, "e": 3142, "s": 3071, "text": "With that out of the way, let’s see how to optimize the learning rate." }, { "code": null, "e": 3470, "s": 3142, "text": "Optimizing the learning rate is easy once you get the gist of it. The idea is to start small — let’s say with 0.001 and increase the value every epoch. You’ll get terrible accuracy when training the model, but that’s expected. Don’t even mind it, as we’re only interested in how the loss changes as we change the learning rate." }, { "code": null, "e": 3561, "s": 3470, "text": "Let’s start by importing TensorFlow and setting the seed so you can reproduce the results:" }, { "code": null, "e": 3607, "s": 3561, "text": "import tensorflow as tftf.random.set_seed(42)" }, { "code": null, "e": 3746, "s": 3607, "text": "We’ll train the model for 100 epochs to test 100 different loss/learning rate combinations. Here’s the range for the learning rate values:" }, { "code": null, "e": 3856, "s": 3746, "text": "A learning rate of 0.001 is the default one for, let’s say, Adam optimizer, and 2.15 is definitely too large." }, { "code": null, "e": 4094, "s": 3856, "text": "Next, let’s define a neural network model architecture, compile the model, and train it. The only new thing here is the LearningRateScheduler. It allows us to enter the above-declared way to change the learning rate as a lambda function." }, { "code": null, "e": 4118, "s": 4094, "text": "Here’s the entire code:" }, { "code": null, "e": 4753, "s": 4118, "text": "initial_model = tf.keras.Sequential([ tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dense(1, activation='sigmoid')])initial_model.compile( loss=tf.keras.losses.binary_crossentropy, optimizer=tf.keras.optimizers.Adam(), metrics=[ tf.keras.metrics.BinaryAccuracy(name='accuracy') ])initial_history = initial_model.fit( X_train_scaled, y_train, epochs=100, callbacks=[ tf.keras.callbacks.LearningRateScheduler( lambda epoch: 1e-3 * 10 ** (epoch / 30) ) ])" }, { "code": null, "e": 4989, "s": 4753, "text": "The training will start now and you’ll see a decent accuracy immediately — around 75% — but it will drop after 50-something epochs because the learning rate became too large. After 100 epochs, the initial_model had around 60% accuracy:" }, { "code": null, "e": 5100, "s": 4989, "text": "The initial_history variable now has information on loss, accuracy, and learning rate. Let’s plot all of them:" }, { "code": null, "e": 5674, "s": 5100, "text": "import matplotlib.pyplot as pltfrom matplotlib import rcParamsrcParams['figure.figsize'] = (18, 8)rcParams['axes.spines.top'] = FalsercParams['axes.spines.right'] = False plt.plot( np.arange(1, 101), initial_history.history['loss'], label='Loss', lw=3)plt.plot( np.arange(1, 101), initial_history.history['accuracy'], label='Accuracy', lw=3)plt.plot( np.arange(1, 101), initial_history.history['lr'], label='Learning rate', color='#000', lw=3, linestyle='--')plt.title('Evaluation metrics', size=20)plt.xlabel('Epoch', size=14)plt.legend();" }, { "code": null, "e": 5692, "s": 5674, "text": "Here’s the chart:" }, { "code": null, "e": 5857, "s": 5692, "text": "The accuracy dipped significantly around epoch 50 and flattened for a while, before starting to dip further. The exact opposite happened to loss, which makes sense." }, { "code": null, "e": 5976, "s": 5857, "text": "You can now plot the loss against learning rate on a logarithmic scale to eyeball where the minimum loss was achieved:" }, { "code": null, "e": 6231, "s": 5976, "text": "learning_rates = 1e-3 * (10 ** (np.arange(100) / 30))plt.semilogx( learning_rates, initial_history.history['loss'], lw=3, color='#000')plt.title('Learning rate vs. loss', size=20)plt.xlabel('Learning rate', size=14)plt.ylabel('Loss', size=14);" }, { "code": null, "e": 6249, "s": 6231, "text": "Here’s the chart:" }, { "code": null, "e": 6483, "s": 6249, "text": "You’ll generally want to select a learning rate that achieves the lowest loss, provided that the values around it aren’t too volatile. Keep in mind that the X-axis is on a logarithmic scale. The optimal learning rate is around 0.007:" }, { "code": null, "e": 6592, "s": 6483, "text": "So let’s train a model with a supposedly optimal learning rate and see if we can outperform the default one." }, { "code": null, "e": 6725, "s": 6592, "text": "With a learning rate of 0.007 in mind, let’s write another neural network model. You won’t need the LearningRateScheduler this time:" }, { "code": null, "e": 7257, "s": 6725, "text": "model_optimized = tf.keras.Sequential([ tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dense(1, activation='sigmoid')])model_optimized.compile( loss=tf.keras.losses.binary_crossentropy, optimizer=tf.keras.optimizers.Adam(learning_rate=0.007), metrics=[ tf.keras.metrics.BinaryAccuracy(name='accuracy') ])history_optimized = model_optimized.fit( X_train_scaled, y_train, epochs=100)" }, { "code": null, "e": 7518, "s": 7257, "text": "We got 76% accuracy with the default learning rate in the previous article, so it’ll be interesting to see if learning rate optimization can increase it. The reported accuracy on the train set looks too good to be true, so it’s likely our model is overfitting:" }, { "code": null, "e": 7683, "s": 7518, "text": "It won’t matter too much if we’ve managed to increase the performance on the test set, but you could save yourself some time by training the model for fewer epochs." }, { "code": null, "e": 7752, "s": 7683, "text": "Here’s how the accuracy vs. loss looks like for the optimized model:" }, { "code": null, "e": 8038, "s": 7752, "text": "plt.plot( np.arange(1, 101), history_optimized.history['loss'], label='Loss', lw=3)plt.plot( np.arange(1, 101), history_optimized.history['accuracy'], label='Accuracy', lw=3)plt.title('Accuracy vs. Loss per epoch', size=20)plt.xlabel('Epoch', size=14)plt.legend()" }, { "code": null, "e": 8135, "s": 8038, "text": "Let’s finally calculate the predictions and evaluate them against the test set. Here’s the code:" }, { "code": null, "e": 8525, "s": 8135, "text": "from sklearn.metrics import confusion_matrixfrom sklearn.metrics import accuracy_scorepredictions = model_optimized.predict(X_test_scaled)prediction_classes = [1 if prob > 0.5 else 0 for prob in np.ravel(predictions)]print(f'Accuracy on the test set: {accuracy_score(y_test, prediction_classes):.2f}')print()print('Confusion matrix:')print(confusion_matrix(y_test, prediction_classes))" }, { "code": null, "e": 8548, "s": 8525, "text": "And here’s the output:" }, { "code": null, "e": 8896, "s": 8548, "text": "To summarize, optimizing the learning rate alone managed to increase the model accuracy by 3% on the test set. It might not sound huge, but it’s an excellent trade-off for the amount of time it took. Moreover, it’s only the first of many optimizations you can do to a neural network model, and it’s one less hyperparameter you need to worry about." }, { "code": null, "e": 9025, "s": 8896, "text": "Stay tuned to learn how to optimize a neural network architecture — the post will be up in a couple of days. Thanks for reading!" }, { "code": null, "e": 9208, "s": 9025, "text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you." }, { "code": null, "e": 9219, "s": 9208, "text": "medium.com" }, { "code": null, "e": 9245, "s": 9219, "text": "Sign up for my newsletter" }, { "code": null, "e": 9266, "s": 9245, "text": "Subscribe on YouTube" } ]
Reshape pandas dataframe in Python | Towards Data Science
There are many different ways to reshape a pandas dataframe from wide to long form. But the melt() method is the most flexible and probably the only one you need to use once you learn it well, just like how you only need to learn one method pivot_table() to reshape from long to wide (see my other post below). towardsdatascience.com This tutorial will walk you through reshaping dataframes using pd.melt() or the melt method associated with pandas dataframes. In other languages like R, melt is also known as gather. Also, R also has a melt function that works in the same way. towardsdatascience.com I highly recommend you try the code in Python while you read this article. Open my DeepNote notebook (you can only run but not edit this notebook) and run the cells while you read this article. Also, you might want to check out the official pandas documentation and my numpy reshape tutorial: towardsdatascience.com It’s easiest to understand what a wide dataframe is or looks like if we look at one and compare it with a long dataframe. And below is the corresponding dataframe (with the same information) but in the long form: Before we begin our pd.melt tutorial, let’s recreate the wide dataframe above in Python with pd.DataFrame. import pandas as pd# create wide dataframedf_wide = pd.DataFrame( {"student": ["Andy", "Bernie", "Cindy", "Deb"], "school": ["Z", "Y", "Z", "Y"], "english": [10, 100, 1000, 10000], # eng grades "math": [20, 200, 2000, 20000], # math grades "physics": [30, 300, 3000, 30000] # physics grades }) We melt the dataframe by specifying the identifier columns via id_vars. The “leftover” non-identifier columns (english, math, physics) will be melted or stacked onto each other into one column. A new indicator column will be created (contains values english, math, physics) and we can rename this new column (cLaSs) via var_name. We can also rename the column in which all the actual grades are contained (gRaDe) via value_name. print(df_wide)> student school english math physics Andy Z 10 20 30 Bernie Y 100 200 300 Cindy Z 1000 2000 3000 Deb Y 10000 20000 30000df_wide.melt(id_vars=["student", "school"], var_name="cLaSs", # rename value_name="gRaDe") # rename> student school cLaSs gRaDe0 Andy Z english 101 Bernie Y english 1002 Cindy Z english 10003 Deb Y english 100004 Andy Z math 205 Bernie Y math 2006 Cindy Z math 20007 Deb Y math 200008 Andy Z physics 309 Bernie Y physics 30010 Cindy Z physics 300011 Deb Y physics 30000 You can use value_vars to specify which columns you want to melt or stack into column (here, we exclude physics column, so value_vars=["english", "math"]). We also drop the school column from id_vars. print(df_wide)> student school english math physics Andy Z 10 20 30 Bernie Y 100 200 300 Cindy Z 1000 2000 3000 Deb Y 10000 20000 30000df_wide.melt(id_vars="student", value_vars=["english", "math"], var_name="cLaSs", # rename value_name="gRaDe") # rename> student cLaSs gRaDe0 Andy english 101 Bernie english 1002 Cindy english 10003 Deb english 100004 Andy math 205 Bernie math 2006 Cindy math 20007 Deb math 2000 Finally, let’s see what happens if we specify only the student column as the identifier column (id_vars="student") but do not specify which columns you want to stack via value_vars. As a result, all non-identifier columns (school, english, math, physics) will be stacked into one column. The resulting long dataframe looks wrong because now the cLaSs and gRaDe columns contain values that shouldn’t be there. The point here is to show you how pd.melt works. print(df_wide)> student school english math physics Andy Z 10 20 30 Bernie Y 100 200 300 Cindy Z 1000 2000 3000 Deb Y 10000 20000 30000df_wide.melt(id_vars="student", var_name="cLaSs", # rename value_name="gRaDe") # rename> student cLaSs gRaDe0 Andy school Z1 Bernie school Y2 Cindy school Z3 Deb school Y4 Andy english 105 Bernie english 1006 Cindy english 10007 Deb english 100008 Andy math 209 Bernie math 20010 Cindy math 200011 Deb math 2000012 Andy physics 3013 Bernie physics 30014 Cindy physics 300015 Deb physics 30000 I hope now you have a better understanding of how pd.meltreshapes dataframes. I look forward to your thoughts and comments. If you find this post useful, follow me and visit my site for more data science tutorials and also my other articles: towardsdatascience.com medium.com towardsdatascience.com medium.com towardsdatascience.com For more posts, subscribe to my mailing list.
[ { "code": null, "e": 483, "s": 172, "text": "There are many different ways to reshape a pandas dataframe from wide to long form. But the melt() method is the most flexible and probably the only one you need to use once you learn it well, just like how you only need to learn one method pivot_table() to reshape from long to wide (see my other post below)." }, { "code": null, "e": 506, "s": 483, "text": "towardsdatascience.com" }, { "code": null, "e": 751, "s": 506, "text": "This tutorial will walk you through reshaping dataframes using pd.melt() or the melt method associated with pandas dataframes. In other languages like R, melt is also known as gather. Also, R also has a melt function that works in the same way." }, { "code": null, "e": 774, "s": 751, "text": "towardsdatascience.com" }, { "code": null, "e": 968, "s": 774, "text": "I highly recommend you try the code in Python while you read this article. Open my DeepNote notebook (you can only run but not edit this notebook) and run the cells while you read this article." }, { "code": null, "e": 1067, "s": 968, "text": "Also, you might want to check out the official pandas documentation and my numpy reshape tutorial:" }, { "code": null, "e": 1090, "s": 1067, "text": "towardsdatascience.com" }, { "code": null, "e": 1212, "s": 1090, "text": "It’s easiest to understand what a wide dataframe is or looks like if we look at one and compare it with a long dataframe." }, { "code": null, "e": 1303, "s": 1212, "text": "And below is the corresponding dataframe (with the same information) but in the long form:" }, { "code": null, "e": 1410, "s": 1303, "text": "Before we begin our pd.melt tutorial, let’s recreate the wide dataframe above in Python with pd.DataFrame." }, { "code": null, "e": 1722, "s": 1410, "text": "import pandas as pd# create wide dataframedf_wide = pd.DataFrame( {\"student\": [\"Andy\", \"Bernie\", \"Cindy\", \"Deb\"], \"school\": [\"Z\", \"Y\", \"Z\", \"Y\"], \"english\": [10, 100, 1000, 10000], # eng grades \"math\": [20, 200, 2000, 20000], # math grades \"physics\": [30, 300, 3000, 30000] # physics grades })" }, { "code": null, "e": 1916, "s": 1722, "text": "We melt the dataframe by specifying the identifier columns via id_vars. The “leftover” non-identifier columns (english, math, physics) will be melted or stacked onto each other into one column." }, { "code": null, "e": 2151, "s": 1916, "text": "A new indicator column will be created (contains values english, math, physics) and we can rename this new column (cLaSs) via var_name. We can also rename the column in which all the actual grades are contained (gRaDe) via value_name." }, { "code": null, "e": 2925, "s": 2151, "text": "print(df_wide)> student school english math physics Andy Z 10 20 30 Bernie Y 100 200 300 Cindy Z 1000 2000 3000 Deb Y 10000 20000 30000df_wide.melt(id_vars=[\"student\", \"school\"], var_name=\"cLaSs\", # rename value_name=\"gRaDe\") # rename> student school cLaSs gRaDe0 Andy Z english 101 Bernie Y english 1002 Cindy Z english 10003 Deb Y english 100004 Andy Z math 205 Bernie Y math 2006 Cindy Z math 20007 Deb Y math 200008 Andy Z physics 309 Bernie Y physics 30010 Cindy Z physics 300011 Deb Y physics 30000" }, { "code": null, "e": 3126, "s": 2925, "text": "You can use value_vars to specify which columns you want to melt or stack into column (here, we exclude physics column, so value_vars=[\"english\", \"math\"]). We also drop the school column from id_vars." }, { "code": null, "e": 3729, "s": 3126, "text": "print(df_wide)> student school english math physics Andy Z 10 20 30 Bernie Y 100 200 300 Cindy Z 1000 2000 3000 Deb Y 10000 20000 30000df_wide.melt(id_vars=\"student\", value_vars=[\"english\", \"math\"], var_name=\"cLaSs\", # rename value_name=\"gRaDe\") # rename> student cLaSs gRaDe0 Andy english 101 Bernie english 1002 Cindy english 10003 Deb english 100004 Andy math 205 Bernie math 2006 Cindy math 20007 Deb math 2000" }, { "code": null, "e": 4017, "s": 3729, "text": "Finally, let’s see what happens if we specify only the student column as the identifier column (id_vars=\"student\") but do not specify which columns you want to stack via value_vars. As a result, all non-identifier columns (school, english, math, physics) will be stacked into one column." }, { "code": null, "e": 4187, "s": 4017, "text": "The resulting long dataframe looks wrong because now the cLaSs and gRaDe columns contain values that shouldn’t be there. The point here is to show you how pd.melt works." }, { "code": null, "e": 4962, "s": 4187, "text": "print(df_wide)> student school english math physics Andy Z 10 20 30 Bernie Y 100 200 300 Cindy Z 1000 2000 3000 Deb Y 10000 20000 30000df_wide.melt(id_vars=\"student\", var_name=\"cLaSs\", # rename value_name=\"gRaDe\") # rename> student cLaSs gRaDe0 Andy school Z1 Bernie school Y2 Cindy school Z3 Deb school Y4 Andy english 105 Bernie english 1006 Cindy english 10007 Deb english 100008 Andy math 209 Bernie math 20010 Cindy math 200011 Deb math 2000012 Andy physics 3013 Bernie physics 30014 Cindy physics 300015 Deb physics 30000" }, { "code": null, "e": 5086, "s": 4962, "text": "I hope now you have a better understanding of how pd.meltreshapes dataframes. I look forward to your thoughts and comments." }, { "code": null, "e": 5204, "s": 5086, "text": "If you find this post useful, follow me and visit my site for more data science tutorials and also my other articles:" }, { "code": null, "e": 5227, "s": 5204, "text": "towardsdatascience.com" }, { "code": null, "e": 5238, "s": 5227, "text": "medium.com" }, { "code": null, "e": 5261, "s": 5238, "text": "towardsdatascience.com" }, { "code": null, "e": 5272, "s": 5261, "text": "medium.com" }, { "code": null, "e": 5295, "s": 5272, "text": "towardsdatascience.com" } ]
Color Spaces in OpenCV | Python - GeeksforGeeks
20 Apr, 2022 Color spaces are a way to represent the color channels present in the image that gives the image that particular hue. There are several different color spaces and each has its own significance. Some of the popular color spaces are RGB (Red, Green, Blue), CMYK (Cyan, Magenta, Yellow, Black), HSV (Hue, Saturation, Value), etc. BGR color space: OpenCV’s default color space is RGB. However, it actually stores color in the BGR format. It is an additive color model where the different intensities of Blue, Green and Red give different shades of color. HSV color space: It stores color information in a cylindrical representation of RGB color points. It attempts to depict the colors as perceived by the human eye. Hue value varies from 0-179, Saturation value varies from 0-255 and Value value varies from 0-255. It is mostly used for color segmentation purpose. CMYK color space: Unlike, RGB it is a subtractive color space. The CMYK model works by partially or entirely masking colors on a lighter, usually white, background. The ink reduces the light that would otherwise be reflected. Such a model is called subtractive because inks “subtract” the colors red, green and blue from white light. White light minus red leaves cyan, white light minus green leaves magenta, and white light minus blue leaves yellow. Visualizing the different color channels of an RGB image. Python3 import cv2 image = cv2.imread('C://Users//Gfg//rgb.png')B, G, R = cv2.split(image)# Corresponding channels are separated cv2.imshow("original", image)cv2.waitKey(0) cv2.imshow("blue", B)cv2.waitKey(0) cv2.imshow("Green", G)cv2.waitKey(0) cv2.imshow("red", R)cv2.waitKey(0) cv2.destroyAllWindows() Output: sweetyty Image-Processing OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26403, "s": 26375, "text": "\n20 Apr, 2022" }, { "code": null, "e": 27778, "s": 26403, "text": "Color spaces are a way to represent the color channels present in the image that gives the image that particular hue. There are several different color spaces and each has its own significance. Some of the popular color spaces are RGB (Red, Green, Blue), CMYK (Cyan, Magenta, Yellow, Black), HSV (Hue, Saturation, Value), etc. BGR color space: OpenCV’s default color space is RGB. However, it actually stores color in the BGR format. It is an additive color model where the different intensities of Blue, Green and Red give different shades of color. HSV color space: It stores color information in a cylindrical representation of RGB color points. It attempts to depict the colors as perceived by the human eye. Hue value varies from 0-179, Saturation value varies from 0-255 and Value value varies from 0-255. It is mostly used for color segmentation purpose. CMYK color space: Unlike, RGB it is a subtractive color space. The CMYK model works by partially or entirely masking colors on a lighter, usually white, background. The ink reduces the light that would otherwise be reflected. Such a model is called subtractive because inks “subtract” the colors red, green and blue from white light. White light minus red leaves cyan, white light minus green leaves magenta, and white light minus blue leaves yellow. Visualizing the different color channels of an RGB image. " }, { "code": null, "e": 27786, "s": 27778, "text": "Python3" }, { "code": "import cv2 image = cv2.imread('C://Users//Gfg//rgb.png')B, G, R = cv2.split(image)# Corresponding channels are separated cv2.imshow(\"original\", image)cv2.waitKey(0) cv2.imshow(\"blue\", B)cv2.waitKey(0) cv2.imshow(\"Green\", G)cv2.waitKey(0) cv2.imshow(\"red\", R)cv2.waitKey(0) cv2.destroyAllWindows()", "e": 28083, "s": 27786, "text": null }, { "code": null, "e": 28092, "s": 28083, "text": "Output: " }, { "code": null, "e": 28101, "s": 28092, "text": "sweetyty" }, { "code": null, "e": 28118, "s": 28101, "text": "Image-Processing" }, { "code": null, "e": 28125, "s": 28118, "text": "OpenCV" }, { "code": null, "e": 28132, "s": 28125, "text": "Python" }, { "code": null, "e": 28230, "s": 28132, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28248, "s": 28230, "text": "Python Dictionary" }, { "code": null, "e": 28283, "s": 28248, "text": "Read a file line by line in Python" }, { "code": null, "e": 28315, "s": 28283, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28337, "s": 28315, "text": "Enumerate() in Python" }, { "code": null, "e": 28379, "s": 28337, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28409, "s": 28379, "text": "Iterate over a list in Python" }, { "code": null, "e": 28435, "s": 28409, "text": "Python String | replace()" }, { "code": null, "e": 28464, "s": 28435, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28508, "s": 28464, "text": "Reading and Writing to text files in Python" } ]
Matplotlib.patches.Circle class in Python - GeeksforGeeks
27 Apr, 2020 Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. The matplotlib.patches.Circle class is used to create a circular patch at a given center xy = (x, y) with a given radius. It uses Bezier splines and is much closer to a scale-free circle. Syntax: class matplotlib.patches.Circle(xy, radius=5, **kwargs) parameters: xy: It is the center of the circle. radius: It sets the radius of the circle to be drawn. Its default value is 5 units and is optional. Below table provides with the optional valid kwargs ; Example 1: import numpy as npfrom matplotlib.patches import Circlefrom matplotlib.collections import PatchCollectionimport matplotlib.pyplot as pltfrom matplotlib import cmfrom matplotlib import animation fig, ax = plt.subplots() patches = []# create circles with random sizes # and locationsN = 12 # number of circlesx = np.random.rand(N)y = np.random.rand(N)radii = 0.1 * np.random.rand(N)for x1, y1, r in zip(x, y, radii): circle = Circle((x1, y1), r) patches.append(circle) # add these circles to a collectionp = PatchCollection(patches, cmap = cm.prism, alpha = 0.4)ax.add_collection(p) def animate(i): # random index to color map colors = 100 * np.random.rand(len(patches)) # set new color colors p.set_array(np.array(colors)) return p, ani = animation.FuncAnimation(fig, animate, frames = 50, interval = 50) plt.show() Output: Example 2: import numpy as npimport matplotlibfrom matplotlib.patches import Circle, Wedge, Polygon, Ellipsefrom matplotlib.collections import PatchCollectionimport matplotlib.pyplot as pltimport matplotlib.patches as matpatches fig, ax = plt.subplots(figsize =(8, 8))patches = [] circle = Circle((2, 2), 2)patches.append(circle) polygon = matpatches.PathPatch(patches[0].get_path())patches.append(polygon) colors = 2 * np.random.rand(len(patches))p = PatchCollection(patches, cmap = matplotlib.cm.jet, alpha = 0.4) p.set_array(np.array(colors))ax.add_collection(p) plt.axis([-10, 10, -10, 10]) plt.show() contain2 = patches[0].get_path().contains_points([[0.5, 0.5], [1.0, 1.0]])contain3 = patches[0].contains_point([0.5, 0.5])contain4 = patches[0].contains_point([1.0, 1.0]) Output: Matplotlib patches-class Python-matplotlib Python Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? Iterate over a list in Python Convert integer to string in Python Convert string to integer in Python Python infinity How to set input type date in dd-mm-yyyy format using HTML ? Matplotlib.pyplot.title() in Python
[ { "code": null, "e": 24798, "s": 24770, "text": "\n27 Apr, 2020" }, { "code": null, "e": 25010, "s": 24798, "text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack." }, { "code": null, "e": 25198, "s": 25010, "text": "The matplotlib.patches.Circle class is used to create a circular patch at a given center xy = (x, y) with a given radius. It uses Bezier splines and is much closer to a scale-free circle." }, { "code": null, "e": 25262, "s": 25198, "text": "Syntax: class matplotlib.patches.Circle(xy, radius=5, **kwargs)" }, { "code": null, "e": 25274, "s": 25262, "text": "parameters:" }, { "code": null, "e": 25310, "s": 25274, "text": "xy: It is the center of the circle." }, { "code": null, "e": 25410, "s": 25310, "text": "radius: It sets the radius of the circle to be drawn. Its default value is 5 units and is optional." }, { "code": null, "e": 25464, "s": 25410, "text": "Below table provides with the optional valid kwargs ;" }, { "code": null, "e": 25475, "s": 25464, "text": "Example 1:" }, { "code": "import numpy as npfrom matplotlib.patches import Circlefrom matplotlib.collections import PatchCollectionimport matplotlib.pyplot as pltfrom matplotlib import cmfrom matplotlib import animation fig, ax = plt.subplots() patches = []# create circles with random sizes # and locationsN = 12 # number of circlesx = np.random.rand(N)y = np.random.rand(N)radii = 0.1 * np.random.rand(N)for x1, y1, r in zip(x, y, radii): circle = Circle((x1, y1), r) patches.append(circle) # add these circles to a collectionp = PatchCollection(patches, cmap = cm.prism, alpha = 0.4)ax.add_collection(p) def animate(i): # random index to color map colors = 100 * np.random.rand(len(patches)) # set new color colors p.set_array(np.array(colors)) return p, ani = animation.FuncAnimation(fig, animate, frames = 50, interval = 50) plt.show()", "e": 26360, "s": 25475, "text": null }, { "code": null, "e": 26368, "s": 26360, "text": "Output:" }, { "code": null, "e": 26379, "s": 26368, "text": "Example 2:" }, { "code": "import numpy as npimport matplotlibfrom matplotlib.patches import Circle, Wedge, Polygon, Ellipsefrom matplotlib.collections import PatchCollectionimport matplotlib.pyplot as pltimport matplotlib.patches as matpatches fig, ax = plt.subplots(figsize =(8, 8))patches = [] circle = Circle((2, 2), 2)patches.append(circle) polygon = matpatches.PathPatch(patches[0].get_path())patches.append(polygon) colors = 2 * np.random.rand(len(patches))p = PatchCollection(patches, cmap = matplotlib.cm.jet, alpha = 0.4) p.set_array(np.array(colors))ax.add_collection(p) plt.axis([-10, 10, -10, 10]) plt.show() contain2 = patches[0].get_path().contains_points([[0.5, 0.5], [1.0, 1.0]])contain3 = patches[0].contains_point([0.5, 0.5])contain4 = patches[0].contains_point([1.0, 1.0])", "e": 27249, "s": 26379, "text": null }, { "code": null, "e": 27257, "s": 27249, "text": "Output:" }, { "code": null, "e": 27282, "s": 27257, "text": "Matplotlib patches-class" }, { "code": null, "e": 27300, "s": 27282, "text": "Python-matplotlib" }, { "code": null, "e": 27307, "s": 27300, "text": "Python" }, { "code": null, "e": 27323, "s": 27307, "text": "Write From Home" }, { "code": null, "e": 27421, "s": 27323, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27430, "s": 27421, "text": "Comments" }, { "code": null, "e": 27443, "s": 27430, "text": "Old Comments" }, { "code": null, "e": 27461, "s": 27443, "text": "Python Dictionary" }, { "code": null, "e": 27483, "s": 27461, "text": "Enumerate() in Python" }, { "code": null, "e": 27518, "s": 27483, "text": "Read a file line by line in Python" }, { "code": null, "e": 27550, "s": 27518, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27580, "s": 27550, "text": "Iterate over a list in Python" }, { "code": null, "e": 27616, "s": 27580, "text": "Convert integer to string in Python" }, { "code": null, "e": 27652, "s": 27616, "text": "Convert string to integer in Python" }, { "code": null, "e": 27668, "s": 27652, "text": "Python infinity" }, { "code": null, "e": 27729, "s": 27668, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Vector of Vectors in C++ STL with Examples
14 Feb, 2020 Prerequisite: Vectors in C++ STL Vectors are known as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector of Vectors is a two-dimensional vector with a variable number of rows where each row is vector. Each index of vector stores a vector which can be traversed and accessed using iterators. It is similar to an Array of Vectors but with dynamic properties. Syntax: vector<vector<data_type>> vec; Example: vector<vector<int>> vec{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9, 4 } }; where vec is the vector of vectors with different number of elements in different rows Insertion in Vector of Vectors Elements can be inserted into a vector using the push_back() function of C++ STL. Below example demonstrates the insertion operation in a vector of vectors. The code creates a 2D vector by using the push_back() function and then displays the matrix. Syntax: vector_name.push_back(value) where value refers to the element to be added in the back of the vector Example 1: v2 = {1, 2, 3} v1.push_back(v2); This function pushes vector v2 into vector of vectors v1. Therefore v1 becomes { {1, 2, 3} }. Example 2: v2 = {4, 5, 6} v1.push_back(v2); This function pushes vector v2 into existing vector of vectors v1 and v1 becomes v1 = { {1, 2, 3}, {4, 5, 6} } Below is the example to demonstrate insertion into a vector of vectors. // C++ program to demonstrate insertion// into a vector of vectors #include <iostream>#include <vector>using namespace std; // Defining the rows and columns of// vector of vectors#define ROW 4#define COL 5 int main(){ // Initializing the vector of vectors vector<vector<int> > vec; // Elements to insert in column int num = 10; // Inserting elements into vector for (int i = 0; i < ROW; i++) { // Vector to store column elements vector<int> v1; for (int j = 0; j < COL; j++) { v1.push_back(num); num += 5; } // Pushing back above 1D vector // to create the 2D vector vec.push_back(v1); } // Displaying the 2D vector for (int i = 0; i < vec.size(); i++) { for (int j = 0; j < vec[i].size(); j++) cout << vec[i][j] << " "; cout << endl; } return 0;} 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 105 Removal or Deletion in a Vector of Vectors Elements can be removed from a vector of vectors using the pop_back() function of C++ STL. Below example demonstrates the removal operation in a vector of vectors. The code removes elements from a 2D vector by using the pop_back() function and then displays the matrix.Syntax: vector_name[row_position].pop_back() Example 1: Let the vector of vectors be vector v = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } } v[2].pop_back() This function removes element 9 from the last row vector. Therefore v becomes { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8 } }. Example 2: v[1].pop_back() This function removes element 6 from the last second row vector. Therefore v becomes { { 1, 2, 3 }, { 4, 5 }, { 7, 8 } }. Below is the example to demonstrate removal from a vector of vectors. // C++ program to demonstrate removal// from a vector of vectors #include <iostream>#include <vector>using namespace std; // Driver Methodint main(){ // Initializing 2D vector "vect" with // sample values vector<vector<int> > vec{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; // Removing elements from the // last row of the vector vec[2].pop_back(); vec[1].pop_back(); // Displaying the 2D vector for (int i = 0; i < 3; i++) { for ( auto it = vec[i].begin(); it != vec[i].end(); it++) cout << *it << " "; cout << endl; } return 0;} 1 2 3 4 5 7 8 Traversal of a Vector of Vectors The vector of vectors can be traversed using the iterators in C++. The following code demonstrates the traversal of a 2D vector. Syntax: for i in [0, n) { for (iterator it = v[i].begin(); it != v[i].end(); it++) { // Operations to be done // For example to print print(*it) } } Below is the example to demonstrate traversal in a vector of vectors. // C++ code to demonstrate traversal// of a 2D vector #include <iostream>#include <vector>using namespace std; // Driver Methodint main(){ // Initializing 2D vector "vect" with // sample values vector<vector<int> > vec{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; // Displaying the 2D vector for (int i = 0; i < 3; i++) { for ( auto it = vec[i].begin(); it != vec[i].end(); it++) cout << *it << " "; cout << endl; } return 0;} 1 2 3 4 5 6 7 8 9 cpp-vector C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ Priority Queue in C++ Standard Template Library (STL) unordered_map in C++ STL Sorting a vector in C++ Substring in C++ C++ Data Types Templates in C++ with Examples Virtual Function in C++ Operator Overloading in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Feb, 2020" }, { "code": null, "e": 85, "s": 52, "text": "Prerequisite: Vectors in C++ STL" }, { "code": null, "e": 274, "s": 85, "text": "Vectors are known as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container." }, { "code": null, "e": 533, "s": 274, "text": "Vector of Vectors is a two-dimensional vector with a variable number of rows where each row is vector. Each index of vector stores a vector which can be traversed and accessed using iterators. It is similar to an Array of Vectors but with dynamic properties." }, { "code": null, "e": 541, "s": 533, "text": "Syntax:" }, { "code": null, "e": 572, "s": 541, "text": "vector<vector<data_type>> vec;" }, { "code": null, "e": 581, "s": 572, "text": "Example:" }, { "code": null, "e": 797, "s": 581, "text": "vector<vector<int>> vec{ { 1, 2, 3 }, \n { 4, 5, 6 }, \n { 7, 8, 9, 4 } }; \nwhere vec is the vector of vectors with different\n number of elements in different rows\n" }, { "code": null, "e": 828, "s": 797, "text": "Insertion in Vector of Vectors" }, { "code": null, "e": 910, "s": 828, "text": "Elements can be inserted into a vector using the push_back() function of C++ STL." }, { "code": null, "e": 1078, "s": 910, "text": "Below example demonstrates the insertion operation in a vector of vectors. The code creates a 2D vector by using the push_back() function and then displays the matrix." }, { "code": null, "e": 1086, "s": 1078, "text": "Syntax:" }, { "code": null, "e": 1195, "s": 1086, "text": "vector_name.push_back(value)\n\nwhere value refers to the element\n to be added in the back of the vector\n" }, { "code": null, "e": 1206, "s": 1195, "text": "Example 1:" }, { "code": null, "e": 1240, "s": 1206, "text": "v2 = {1, 2, 3}\nv1.push_back(v2);\n" }, { "code": null, "e": 1334, "s": 1240, "text": "This function pushes vector v2 into vector of vectors v1. Therefore v1 becomes { {1, 2, 3} }." }, { "code": null, "e": 1345, "s": 1334, "text": "Example 2:" }, { "code": null, "e": 1379, "s": 1345, "text": "v2 = {4, 5, 6}\nv1.push_back(v2);\n" }, { "code": null, "e": 1490, "s": 1379, "text": "This function pushes vector v2 into existing vector of vectors v1 and v1 becomes v1 = { {1, 2, 3}, {4, 5, 6} }" }, { "code": null, "e": 1562, "s": 1490, "text": "Below is the example to demonstrate insertion into a vector of vectors." }, { "code": "// C++ program to demonstrate insertion// into a vector of vectors #include <iostream>#include <vector>using namespace std; // Defining the rows and columns of// vector of vectors#define ROW 4#define COL 5 int main(){ // Initializing the vector of vectors vector<vector<int> > vec; // Elements to insert in column int num = 10; // Inserting elements into vector for (int i = 0; i < ROW; i++) { // Vector to store column elements vector<int> v1; for (int j = 0; j < COL; j++) { v1.push_back(num); num += 5; } // Pushing back above 1D vector // to create the 2D vector vec.push_back(v1); } // Displaying the 2D vector for (int i = 0; i < vec.size(); i++) { for (int j = 0; j < vec[i].size(); j++) cout << vec[i][j] << \" \"; cout << endl; } return 0;}", "e": 2452, "s": 1562, "text": null }, { "code": null, "e": 2518, "s": 2452, "text": "10 15 20 25 30 \n35 40 45 50 55 \n60 65 70 75 80 \n85 90 95 100 105\n" }, { "code": null, "e": 2561, "s": 2518, "text": "Removal or Deletion in a Vector of Vectors" }, { "code": null, "e": 2652, "s": 2561, "text": "Elements can be removed from a vector of vectors using the pop_back() function of C++ STL." }, { "code": null, "e": 2838, "s": 2652, "text": "Below example demonstrates the removal operation in a vector of vectors. The code removes elements from a 2D vector by using the pop_back() function and then displays the matrix.Syntax:" }, { "code": null, "e": 2875, "s": 2838, "text": "vector_name[row_position].pop_back()" }, { "code": null, "e": 2968, "s": 2875, "text": "Example 1: Let the vector of vectors be vector v = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }" }, { "code": null, "e": 2985, "s": 2968, "text": "v[2].pop_back()\n" }, { "code": null, "e": 3103, "s": 2985, "text": "This function removes element 9 from the last row vector. Therefore v becomes { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8 } }." }, { "code": null, "e": 3114, "s": 3103, "text": "Example 2:" }, { "code": null, "e": 3131, "s": 3114, "text": "v[1].pop_back()\n" }, { "code": null, "e": 3253, "s": 3131, "text": "This function removes element 6 from the last second row vector. Therefore v becomes { { 1, 2, 3 }, { 4, 5 }, { 7, 8 } }." }, { "code": null, "e": 3323, "s": 3253, "text": "Below is the example to demonstrate removal from a vector of vectors." }, { "code": "// C++ program to demonstrate removal// from a vector of vectors #include <iostream>#include <vector>using namespace std; // Driver Methodint main(){ // Initializing 2D vector \"vect\" with // sample values vector<vector<int> > vec{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; // Removing elements from the // last row of the vector vec[2].pop_back(); vec[1].pop_back(); // Displaying the 2D vector for (int i = 0; i < 3; i++) { for ( auto it = vec[i].begin(); it != vec[i].end(); it++) cout << *it << \" \"; cout << endl; } return 0;}", "e": 3996, "s": 3323, "text": null }, { "code": null, "e": 4013, "s": 3996, "text": "1 2 3 \n4 5 \n7 8\n" }, { "code": null, "e": 4046, "s": 4013, "text": "Traversal of a Vector of Vectors" }, { "code": null, "e": 4175, "s": 4046, "text": "The vector of vectors can be traversed using the iterators in C++. The following code demonstrates the traversal of a 2D vector." }, { "code": null, "e": 4183, "s": 4175, "text": "Syntax:" }, { "code": null, "e": 4370, "s": 4183, "text": "for i in [0, n)\n{\n for (iterator it = v[i].begin();\n it != v[i].end(); it++) \n {\n // Operations to be done\n // For example to print\n print(*it)\n }\n}\n" }, { "code": null, "e": 4440, "s": 4370, "text": "Below is the example to demonstrate traversal in a vector of vectors." }, { "code": "// C++ code to demonstrate traversal// of a 2D vector #include <iostream>#include <vector>using namespace std; // Driver Methodint main(){ // Initializing 2D vector \"vect\" with // sample values vector<vector<int> > vec{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; // Displaying the 2D vector for (int i = 0; i < 3; i++) { for ( auto it = vec[i].begin(); it != vec[i].end(); it++) cout << *it << \" \"; cout << endl; } return 0;}", "e": 4996, "s": 4440, "text": null }, { "code": null, "e": 5017, "s": 4996, "text": "1 2 3 \n4 5 6 \n7 8 9\n" }, { "code": null, "e": 5028, "s": 5017, "text": "cpp-vector" }, { "code": null, "e": 5032, "s": 5028, "text": "C++" }, { "code": null, "e": 5036, "s": 5032, "text": "CPP" }, { "code": null, "e": 5134, "s": 5036, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5177, "s": 5134, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 5211, "s": 5177, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 5265, "s": 5211, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 5290, "s": 5265, "text": "unordered_map in C++ STL" }, { "code": null, "e": 5314, "s": 5290, "text": "Sorting a vector in C++" }, { "code": null, "e": 5331, "s": 5314, "text": "Substring in C++" }, { "code": null, "e": 5346, "s": 5331, "text": "C++ Data Types" }, { "code": null, "e": 5377, "s": 5346, "text": "Templates in C++ with Examples" }, { "code": null, "e": 5401, "s": 5377, "text": "Virtual Function in C++" } ]
HTML | data value attribute
15 Jul, 2021 The HTML data value attribute is used to Specify the machine-readable translation of the content of the element.Syntax: <data attribute> Contents... </data> Example: html <!DOCTYPE html><html> <head> <title>data tag</title></head> <body> <h1 style="color:green;">GeeksforGeeks</h1> <h2> HTML data value attribute </h2> <p><b><i>GeeksforGeeks Subject List:</i></b></p> <ul> <li> <data value="009"> Data Structure </data> </li> <li> <data value="010"> Algorithm </data> </li> <li> <data value="011"> HTML </data> </li> <li> <data value="019"> Operating System </data> </li> <li> <data value="110"> Computer Network </data> </li> <li> <data value="111"> DBMS </data> </li> </ul></body> </html> Output: Supported Browsers: The browsers supported by data value attribute are listed below: Google Chrome Internet Explorer Firefox Opera arorakashish0911 hritikbhatnagar2182 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Jul, 2021" }, { "code": null, "e": 149, "s": 28, "text": "The HTML data value attribute is used to Specify the machine-readable translation of the content of the element.Syntax: " }, { "code": null, "e": 187, "s": 149, "text": "<data attribute> Contents... </data> " }, { "code": null, "e": 196, "s": 187, "text": "Example:" }, { "code": null, "e": 201, "s": 196, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>data tag</title></head> <body> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h2> HTML data value attribute </h2> <p><b><i>GeeksforGeeks Subject List:</i></b></p> <ul> <li> <data value=\"009\"> Data Structure </data> </li> <li> <data value=\"010\"> Algorithm </data> </li> <li> <data value=\"011\"> HTML </data> </li> <li> <data value=\"019\"> Operating System </data> </li> <li> <data value=\"110\"> Computer Network </data> </li> <li> <data value=\"111\"> DBMS </data> </li> </ul></body> </html>", "e": 1023, "s": 201, "text": null }, { "code": null, "e": 1031, "s": 1023, "text": "Output:" }, { "code": null, "e": 1116, "s": 1031, "text": "Supported Browsers: The browsers supported by data value attribute are listed below:" }, { "code": null, "e": 1130, "s": 1116, "text": "Google Chrome" }, { "code": null, "e": 1148, "s": 1130, "text": "Internet Explorer" }, { "code": null, "e": 1156, "s": 1148, "text": "Firefox" }, { "code": null, "e": 1162, "s": 1156, "text": "Opera" }, { "code": null, "e": 1181, "s": 1164, "text": "arorakashish0911" }, { "code": null, "e": 1201, "s": 1181, "text": "hritikbhatnagar2182" }, { "code": null, "e": 1217, "s": 1201, "text": "HTML-Attributes" }, { "code": null, "e": 1222, "s": 1217, "text": "HTML" }, { "code": null, "e": 1239, "s": 1222, "text": "Web Technologies" }, { "code": null, "e": 1244, "s": 1239, "text": "HTML" } ]
Retrieving File Data From HDFS using Python Snakebite
16 Jun, 2022 Prerequisite: Hadoop Installation, HDFS Python Snakebite is a very popular Python library that we can use to communicate with the HDFS. Using the Python client library provided by the Snakebite package we can easily write Python code that works on HDFS. It uses protobuf messages to communicate directly with the NameNode. The python client library directly works with HDFS without making a system call to hdfs dfs. The Snakebite doesn’t support python3. The hdfs dfs provides multiple commands through which we can perform multiple operations on HDFS. The client library that Snakebite provides will contain various methods that allow us to retrieve data from HDFS. text() method is used to simply read the data from a file available on our HDFS. So let’s perform a quick task to understand how we can retrieve data from a file from HDFS. Task: Retrieving File Data From HDFS. Step 1: Create a text file with the name data.txt and add some data to it. cd Documents/ # Changing directory to Documents(You can choose as per your requirement) touch data.txt # touch command is used to create file in linux environment nano data.txt # nano is a command line text editor for Unix and Linux operating system cat data.txt # to see the content of a file Step 2: Send this data.txt file to Hadoop HDFS with the help of copyFromLocal Command. Syntax: hdfs dfs -copyFromLocal /path 1 /path 2 .... /path n /destination Using the command to sending data.txt to the root directory of HDFS. hdfs dfs -copyFromLocal /home/dikshant/Documents/data.txt / Now, Check whether the file is reached to the root directory of HDFS or not with the help of the below command. hdfs dfs -ls / You can check it manually by visiting http://localhost:50070/ then Utilities -> Browse the file system. Step 3: Now our task is to read the data from data.txt we send to our HDFS. So create a file data_read.py in your local file system and add the below python code to it. Python # importing the libraryfrom snakebite.client import Client # the below line create client connection to the HDFS NameNodeclient = Client('localhost', 9000) # iterate over data.txt file and will show all the content of data.txtfor l in client.text(['/data.txt']): print l Client() method explanation: The Client() method can accept all the below listed arguments: host(string): IP Address of NameNode. port(int): RPC port of Namenode. hadoop_version (int): Hadoop protocol version(by default it is: 9) use_trash (boolean): Use trash when removing the files. effective_use (string): Effective user for the HDFS operations (default user is current user). Step 4: Run the read_data.py file and observe the result. python read_data.py We have successfully fetched the data from data.txt with the help of client library. We can also copy any file from HDFS to our Local file system with the help of Snakebite. To copy a file from HDFS create a file fetch_file.py and copy the below python code to it. copyToLocal() method is used to achieve this. Python from snakebite.client import Clientclient = Client('localhost', 9000)for a in client.copyToLocal(['/data.txt'], '/home/dikshant/Desktop'): print a Now, run this python file you will see the below output. python fetch_file.py We can observe that the file now has been copied to my /home/dikshant/desktop directory. vinayedula Hadoop Python Hadoop Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create Table in Hive? What is Schema On Read and Schema On Write in Hadoop? What is Hadoop Streaming? MapReduce - Understanding With Real-Life Example Apache Hive Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jun, 2022" }, { "code": null, "e": 68, "s": 28, "text": "Prerequisite: Hadoop Installation, HDFS" }, { "code": null, "e": 485, "s": 68, "text": "Python Snakebite is a very popular Python library that we can use to communicate with the HDFS. Using the Python client library provided by the Snakebite package we can easily write Python code that works on HDFS. It uses protobuf messages to communicate directly with the NameNode. The python client library directly works with HDFS without making a system call to hdfs dfs. The Snakebite doesn’t support python3. " }, { "code": null, "e": 871, "s": 485, "text": "The hdfs dfs provides multiple commands through which we can perform multiple operations on HDFS. The client library that Snakebite provides will contain various methods that allow us to retrieve data from HDFS. text() method is used to simply read the data from a file available on our HDFS. So let’s perform a quick task to understand how we can retrieve data from a file from HDFS. " }, { "code": null, "e": 909, "s": 871, "text": "Task: Retrieving File Data From HDFS." }, { "code": null, "e": 984, "s": 909, "text": "Step 1: Create a text file with the name data.txt and add some data to it." }, { "code": null, "e": 1312, "s": 984, "text": "cd Documents/ # Changing directory to Documents(You can choose as per your requirement)\n\ntouch data.txt # touch command is used to create file in linux environment\n\nnano data.txt # nano is a command line text editor for Unix and Linux operating system\n\ncat data.txt # to see the content of a file " }, { "code": null, "e": 1403, "s": 1312, "text": "Step 2: Send this data.txt file to Hadoop HDFS with the help of copyFromLocal Command. " }, { "code": null, "e": 1411, "s": 1403, "text": "Syntax:" }, { "code": null, "e": 1477, "s": 1411, "text": "hdfs dfs -copyFromLocal /path 1 /path 2 .... /path n /destination" }, { "code": null, "e": 1546, "s": 1477, "text": "Using the command to sending data.txt to the root directory of HDFS." }, { "code": null, "e": 1607, "s": 1546, "text": "hdfs dfs -copyFromLocal /home/dikshant/Documents/data.txt / " }, { "code": null, "e": 1719, "s": 1607, "text": "Now, Check whether the file is reached to the root directory of HDFS or not with the help of the below command." }, { "code": null, "e": 1734, "s": 1719, "text": "hdfs dfs -ls /" }, { "code": null, "e": 1838, "s": 1734, "text": "You can check it manually by visiting http://localhost:50070/ then Utilities -> Browse the file system." }, { "code": null, "e": 2009, "s": 1838, "text": "Step 3: Now our task is to read the data from data.txt we send to our HDFS. So create a file data_read.py in your local file system and add the below python code to it. " }, { "code": null, "e": 2016, "s": 2009, "text": "Python" }, { "code": "# importing the libraryfrom snakebite.client import Client # the below line create client connection to the HDFS NameNodeclient = Client('localhost', 9000) # iterate over data.txt file and will show all the content of data.txtfor l in client.text(['/data.txt']): print l", "e": 2294, "s": 2016, "text": null }, { "code": null, "e": 2323, "s": 2294, "text": "Client() method explanation:" }, { "code": null, "e": 2386, "s": 2323, "text": "The Client() method can accept all the below listed arguments:" }, { "code": null, "e": 2424, "s": 2386, "text": "host(string): IP Address of NameNode." }, { "code": null, "e": 2457, "s": 2424, "text": "port(int): RPC port of Namenode." }, { "code": null, "e": 2525, "s": 2457, "text": "hadoop_version (int): Hadoop protocol version(by default it is: 9)" }, { "code": null, "e": 2581, "s": 2525, "text": "use_trash (boolean): Use trash when removing the files." }, { "code": null, "e": 2676, "s": 2581, "text": "effective_use (string): Effective user for the HDFS operations (default user is current user)." }, { "code": null, "e": 2734, "s": 2676, "text": "Step 4: Run the read_data.py file and observe the result." }, { "code": null, "e": 2754, "s": 2734, "text": "python read_data.py" }, { "code": null, "e": 2839, "s": 2754, "text": "We have successfully fetched the data from data.txt with the help of client library." }, { "code": null, "e": 3066, "s": 2839, "text": "We can also copy any file from HDFS to our Local file system with the help of Snakebite. To copy a file from HDFS create a file fetch_file.py and copy the below python code to it. copyToLocal() method is used to achieve this." }, { "code": null, "e": 3073, "s": 3066, "text": "Python" }, { "code": "from snakebite.client import Clientclient = Client('localhost', 9000)for a in client.copyToLocal(['/data.txt'], '/home/dikshant/Desktop'): print a", "e": 3227, "s": 3073, "text": null }, { "code": null, "e": 3284, "s": 3227, "text": "Now, run this python file you will see the below output." }, { "code": null, "e": 3305, "s": 3284, "text": "python fetch_file.py" }, { "code": null, "e": 3394, "s": 3305, "text": "We can observe that the file now has been copied to my /home/dikshant/desktop directory." }, { "code": null, "e": 3405, "s": 3394, "text": "vinayedula" }, { "code": null, "e": 3412, "s": 3405, "text": "Hadoop" }, { "code": null, "e": 3419, "s": 3412, "text": "Python" }, { "code": null, "e": 3426, "s": 3419, "text": "Hadoop" }, { "code": null, "e": 3524, "s": 3426, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3553, "s": 3524, "text": "How to Create Table in Hive?" }, { "code": null, "e": 3607, "s": 3553, "text": "What is Schema On Read and Schema On Write in Hadoop?" }, { "code": null, "e": 3633, "s": 3607, "text": "What is Hadoop Streaming?" }, { "code": null, "e": 3682, "s": 3633, "text": "MapReduce - Understanding With Real-Life Example" }, { "code": null, "e": 3694, "s": 3682, "text": "Apache Hive" }, { "code": null, "e": 3722, "s": 3694, "text": "Read JSON file using Python" }, { "code": null, "e": 3772, "s": 3722, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 3794, "s": 3772, "text": "Python map() function" } ]
HTTP header | X-Forwarded-Host
22 Nov, 2019 The HTTP X-Forwarded-Host header is a request-type header de-facto standard header. This header is used to identify the original request made by the client. Because the hostnames and the ports differ in the reverse proxies that time this header took the leade and identify the original request. This header can also be used for debugging, creating location-based content. So this header kept the privacy of the client. The root version of this header is HTTP Forwarded. Syntax: X-Forwarded-Host: <host> Directives: This header accepts a single directive as mentioned above and described below: <host>: This directive holds the domain name of the forwrded server. Below examples illustrate the HTTP X-Forwarded-Host header:Examples: In this example visited site was forwarded from the mentioned host website.X-Forwarded-Host: www.example-cdn.com X-Forwarded-Host: www.example-cdn.com In this example forwarded host is geeksforgeeks cdn page.X-Forwarded-Host: www.cdn.geeksforgeeks.org X-Forwarded-Host: www.cdn.geeksforgeeks.org To check the X-Forwarded-Host in action go to Inspect Element -> Network check the request header for X-Forwarded-Host like below. Supported Browsers: The browsers are compatible with the HTTP X-Forwarded-Host header is unknown till now. HTTP-headers Picked 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 How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array REST API (Introduction) How to create footer to stay at the bottom of a Web page? Difference Between PUT and PATCH Request How to Open URL in New Tab using JavaScript ? Roadmap to Learn JavaScript For Beginners How to float three div side by side using CSS?
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Nov, 2019" }, { "code": null, "e": 524, "s": 54, "text": "The HTTP X-Forwarded-Host header is a request-type header de-facto standard header. This header is used to identify the original request made by the client. Because the hostnames and the ports differ in the reverse proxies that time this header took the leade and identify the original request. This header can also be used for debugging, creating location-based content. So this header kept the privacy of the client. The root version of this header is HTTP Forwarded." }, { "code": null, "e": 532, "s": 524, "text": "Syntax:" }, { "code": null, "e": 557, "s": 532, "text": "X-Forwarded-Host: <host>" }, { "code": null, "e": 648, "s": 557, "text": "Directives: This header accepts a single directive as mentioned above and described below:" }, { "code": null, "e": 717, "s": 648, "text": "<host>: This directive holds the domain name of the forwrded server." }, { "code": null, "e": 786, "s": 717, "text": "Below examples illustrate the HTTP X-Forwarded-Host header:Examples:" }, { "code": null, "e": 899, "s": 786, "text": "In this example visited site was forwarded from the mentioned host website.X-Forwarded-Host: www.example-cdn.com" }, { "code": null, "e": 937, "s": 899, "text": "X-Forwarded-Host: www.example-cdn.com" }, { "code": null, "e": 1038, "s": 937, "text": "In this example forwarded host is geeksforgeeks cdn page.X-Forwarded-Host: www.cdn.geeksforgeeks.org" }, { "code": null, "e": 1082, "s": 1038, "text": "X-Forwarded-Host: www.cdn.geeksforgeeks.org" }, { "code": null, "e": 1213, "s": 1082, "text": "To check the X-Forwarded-Host in action go to Inspect Element -> Network check the request header for X-Forwarded-Host like below." }, { "code": null, "e": 1320, "s": 1213, "text": "Supported Browsers: The browsers are compatible with the HTTP X-Forwarded-Host header is unknown till now." }, { "code": null, "e": 1333, "s": 1320, "text": "HTTP-headers" }, { "code": null, "e": 1340, "s": 1333, "text": "Picked" }, { "code": null, "e": 1357, "s": 1340, "text": "Web Technologies" }, { "code": null, "e": 1455, "s": 1357, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1516, "s": 1455, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1559, "s": 1516, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 1631, "s": 1559, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 1671, "s": 1631, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1695, "s": 1671, "text": "REST API (Introduction)" }, { "code": null, "e": 1753, "s": 1695, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 1794, "s": 1753, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 1840, "s": 1794, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 1882, "s": 1840, "text": "Roadmap to Learn JavaScript For Beginners" } ]
Operations on Matrices in R
28 Jun, 2022 Matrices in R are a bunch of values, either real or complex numbers, arranged in a group of fixed number of rows and columns. Matrices are used to depict the data in a structured and well-organized format. It is necessary to enclose the elements of a matrix in parentheses or brackets. A matrix with 9 elements is shown below. This Matrix [M] has 3 rows and 3 columns. Each element of matrix [M] can be referred to by its row and column number. For example, a23 = 6 Order of a Matrix : The order of a matrix is defined in terms of its number of rows and columns. Order of a matrix = No. of rows × No. of columns Therefore Matrix [M] is a matrix of order 3 × 3. There are four basic operations i.e. DMAS (Division, Multiplication, Addition, Subtraction) that can be done with matrices. Both the matrices involved in the operation should have the same number of rows and columns. The addition of two same ordered matrices and yields a matrix where every element is the sum of corresponding elements of the input matrices. Python3 # R program to add two matrices # Creating 1st MatrixB = matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3) # Creating 2nd MatrixC = matrix(c(7, 8, 9, 10, 11, 12), nrow = 2, ncol = 3) # Getting number of rows and columnsnum_of_rows = nrow(B)num_of_cols = ncol(B) # Creating matrix to store resultssum = matrix(, nrow = num_of_rows, ncol = num_of_cols) # Printing Original matricesprint(B)print(C) Output: [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 [,1] [,2] [,3] [1,] 7 9 11 [2,] 8 10 12 [,1] [,2] [,3] [1,] 8 12 16 [2,] 10 14 18 In the above code, nrow(B) gives the number of rows in B and ncol(B) gives the number of columns. Here, sum is an empty matrix of the same size as B and C. The elements of sum are the addition of the corresponding elements of B and C through nested for loops. Using ‘+’ operator for matrix addition: Similarly, the following R script uses the in-built operator +: Python3 # R program for matrix addition# using '+' operator # Creating 1st MatrixB = matrix(c(1, 2 + 3i, 5.4, 3, 4, 5), nrow = 2, ncol = 3) # Creating 2nd MatrixC = matrix(c(2, 0i, 0.1, 3, 4, 5), nrow = 2, ncol = 3) # Printing the resultant matrixprint(B + C) Output: [,1] [,2] [,3] [1,] 3+0i 5.5+0i 8+0i [2,] 2+3i 6.0+0i 10+0i R provides the basic inbuilt operator to add the matrices. In the above code, all the elements in the resultant matrix are returned as complex numbers, even if a single element of a matrix is a complex number. Properties of Matrix Addition: Commutative: B + C = C + B Associative: For n number of matrices A + (B + C) = (A + B) + C Order of the matrices involved must be same. The subtraction of two same ordered matrices and yields a matrix where every element is the difference of corresponding elements of the second input matrix from the first. Python3 # R program to add two matrices # Creating 1st MatrixB = matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3) # Creating 2nd MatrixC = matrix(c(7, 8, 9, 10, 11, 12), nrow = 2, ncol = 3) # Getting number of rows and columnsnum_of_rows = nrow(B)num_of_cols = ncol(B) # Creating matrix to store resultsdiff = matrix(, nrow = num_of_rows, ncol = num_of_cols) # Printing Original matricesprint(B)print(C) # Calculating diff of matricesfor(row in 1:num_of_rows){ for(col in 1:num_of_cols) { diff[row, col] <- B[row, col] - C[row, col] }} # Printing resultant matrixprint(diff) Output: [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 [,1] [,2] [,3] [1,] 7 9 11 [2,] 8 10 12 [,1] [,2] [,3] [1,] -6 -6 -6 [2,] -6 -6 -6 Here in the above code, the elements of diff matrix are the subtraction of the corresponding elements of B and C through nested for loops. Using ‘-‘ operator for matrix subtraction: Similarly, the following R script uses the in-built operator ‘-‘: Python3 # R program for matrix addition# using '-' operator # Creating 1st MatrixB = matrix(c(1, 2 + 3i, 5.4, 3, 4, 5), nrow = 2, ncol = 3) # Creating 2nd MatrixC = matrix(c(2, 0i, 0.1, 3, 4, 5), nrow = 2, ncol = 3) # Printing the resultant matrixprint(B - C) Output: [,1] [,2] [,3] [1,] -1+0i 5.3+0i 0+0i [2,] 2+3i 0.0+0i 0+0i Properties of Matrix Subtraction: Non-Commutative: B – C != C – B Non-Associative: For n number of matrices A – (B – C) != (A – B) – C Order of the matrices involved must be same. The multiplication of two same ordered matrices and yields a matrix where every element is the product of corresponding elements of the input matrices. Python3 # R program to multiply two matrices # Creating 1st MatrixB = matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3) # Creating 2nd MatrixC = matrix(c(7, 8, 9, 10, 11, 12), nrow = 2, ncol = 3) # Getting number of rows and columnsnum_of_rows = nrow(B)num_of_cols = ncol(B) # Creating matrix to store resultsprod = matrix(, nrow = num_of_rows, ncol = num_of_cols) # Printing Original matricesprint(B)print(C) # Calculating product of matricesfor(row in 1:num_of_rows){ for(col in 1:num_of_cols) { prod[row, col] <- B[row, col] * C[row, col] }} # Printing resultant matrixprint(prod) Output: [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 [,1] [,2] [,3] [1,] 7 9 11 [2,] 8 10 12 [,1] [,2] [,3] [1,] 7 27 55 [2,] 16 40 72 The elements of sum are the multiplication of the corresponding elements of B and C through nested for loops. Using ‘*’ operator for matrix multiplication: Similarly, the following R script uses the in-built operator *: Python3 # R program for matrix multiplication# using '*' operator # Creating 1st MatrixB = matrix(c(1, 2 + 3i, 5.4), nrow = 1, ncol = 3) # Creating 2nd MatrixC = matrix(c(2, 1i, 0.1), nrow = 1, ncol = 3) # Printing the resultant matrixprint (B * C) Output: [,1] [,2] [,3] [1,] 2+0i -3+2i 0.54+0i Properties of Matrix Multiplication: Commutative: B * C = C * B Associative: For n number of matrices A * (B * C) = (A * B) * C Order of the matrices involved must be same. The division of two same ordered matrices and yields a matrix where every element is the quotient of corresponding elements of the first matrix element divided by the second. Python3 # R program to divide two matrices # Creating 1st MatrixB = matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3) # Creating 2nd MatrixC = matrix(c(7, 8, 9, 10, 11, 12), nrow = 2, ncol = 3) # Getting number of rows and columnsnum_of_rows = nrow(B)num_of_cols = ncol(B) # Creating matrix to store resultsdiv = matrix(, nrow = num_of_rows, ncol = num_of_cols) # Printing Original matricesprint(B)print(C) # Calculating product of matricesfor(row in 1:num_of_rows){ for(col in 1:num_of_cols) { div[row, col] <- B[row, col] / C[row, col] }} # Printing resultant matrixprint(div) Output: [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 [,1] [,2] [,3] [1,] 7 9 11 [2,] 8 10 12 [,1] [,2] [,3] [1,] 0.1428571 0.3333333 0.4545455 [2,] 0.2500000 0.4000000 0.5000000 The elements of div matrix are the division of the corresponding elements of B and C through nested for loops. Using ‘/’ operator for matrix division: Similarly, the following R script uses the in-built operator /: Python3 # R program for matrix division# using '/' operator # Creating 1st MatrixB = matrix(c(4, 6i, -1), nrow = 1, ncol = 3) # Creating 2nd MatrixC = matrix(c(2, 2i, 0), nrow = 1, ncol = 3) # Printing the resultant matrixprint (B / C) Output: [,1] [,2] [,3] [1,] 2+0i 3+0i -Inf+NaNi Properties of Matrix Division: Non-Commutative: B / C != C / B Non-Associative: For n number of matrices A / (B / C) != (A / B) / C Order of the matrices involved must be same. Note: Time Complexity of all the matrix operations = O(r*c) where r*c is the order of the matrix. simmytarika5 Picked R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Loops in R (for, while, repeat) Printing Output of an R Program Group by function in R using Dplyr How to change Row Names of DataFrame in R ? How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column?
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jun, 2022" }, { "code": null, "e": 689, "s": 28, "text": "Matrices in R are a bunch of values, either real or complex numbers, arranged in a group of fixed number of rows and columns. Matrices are used to depict the data in a structured and well-organized format. It is necessary to enclose the elements of a matrix in parentheses or brackets. A matrix with 9 elements is shown below. This Matrix [M] has 3 rows and 3 columns. Each element of matrix [M] can be referred to by its row and column number. For example, a23 = 6 Order of a Matrix : The order of a matrix is defined in terms of its number of rows and columns. Order of a matrix = No. of rows × No. of columns Therefore Matrix [M] is a matrix of order 3 × 3." }, { "code": null, "e": 906, "s": 689, "text": "There are four basic operations i.e. DMAS (Division, Multiplication, Addition, Subtraction) that can be done with matrices. Both the matrices involved in the operation should have the same number of rows and columns." }, { "code": null, "e": 1049, "s": 906, "text": "The addition of two same ordered matrices and yields a matrix where every element is the sum of corresponding elements of the input matrices. " }, { "code": null, "e": 1057, "s": 1049, "text": "Python3" }, { "code": "# R program to add two matrices # Creating 1st MatrixB = matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3) # Creating 2nd MatrixC = matrix(c(7, 8, 9, 10, 11, 12), nrow = 2, ncol = 3) # Getting number of rows and columnsnum_of_rows = nrow(B)num_of_cols = ncol(B) # Creating matrix to store resultssum = matrix(, nrow = num_of_rows, ncol = num_of_cols) # Printing Original matricesprint(B)print(C)", "e": 1451, "s": 1057, "text": null }, { "code": null, "e": 1459, "s": 1451, "text": "Output:" }, { "code": null, "e": 1639, "s": 1459, "text": " [,1] [,2] [,3]\n[1,] 1 3 5\n[2,] 2 4 6\n [,1] [,2] [,3]\n[1,] 7 9 11\n[2,] 8 10 12\n [,1] [,2] [,3]\n[1,] 8 12 16\n[2,] 10 14 18" }, { "code": null, "e": 2004, "s": 1639, "text": "In the above code, nrow(B) gives the number of rows in B and ncol(B) gives the number of columns. Here, sum is an empty matrix of the same size as B and C. The elements of sum are the addition of the corresponding elements of B and C through nested for loops. Using ‘+’ operator for matrix addition: Similarly, the following R script uses the in-built operator +: " }, { "code": null, "e": 2012, "s": 2004, "text": "Python3" }, { "code": "# R program for matrix addition# using '+' operator # Creating 1st MatrixB = matrix(c(1, 2 + 3i, 5.4, 3, 4, 5), nrow = 2, ncol = 3) # Creating 2nd MatrixC = matrix(c(2, 0i, 0.1, 3, 4, 5), nrow = 2, ncol = 3) # Printing the resultant matrixprint(B + C)", "e": 2264, "s": 2012, "text": null }, { "code": null, "e": 2272, "s": 2264, "text": "Output:" }, { "code": null, "e": 2341, "s": 2272, "text": " [,1] [,2] [,3]\n[1,] 3+0i 5.5+0i 8+0i\n[2,] 2+3i 6.0+0i 10+0i" }, { "code": null, "e": 2582, "s": 2341, "text": "R provides the basic inbuilt operator to add the matrices. In the above code, all the elements in the resultant matrix are returned as complex numbers, even if a single element of a matrix is a complex number. Properties of Matrix Addition:" }, { "code": null, "e": 2609, "s": 2582, "text": "Commutative: B + C = C + B" }, { "code": null, "e": 2673, "s": 2609, "text": "Associative: For n number of matrices A + (B + C) = (A + B) + C" }, { "code": null, "e": 2718, "s": 2673, "text": "Order of the matrices involved must be same." }, { "code": null, "e": 2891, "s": 2718, "text": "The subtraction of two same ordered matrices and yields a matrix where every element is the difference of corresponding elements of the second input matrix from the first. " }, { "code": null, "e": 2899, "s": 2891, "text": "Python3" }, { "code": "# R program to add two matrices # Creating 1st MatrixB = matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3) # Creating 2nd MatrixC = matrix(c(7, 8, 9, 10, 11, 12), nrow = 2, ncol = 3) # Getting number of rows and columnsnum_of_rows = nrow(B)num_of_cols = ncol(B) # Creating matrix to store resultsdiff = matrix(, nrow = num_of_rows, ncol = num_of_cols) # Printing Original matricesprint(B)print(C) # Calculating diff of matricesfor(row in 1:num_of_rows){ for(col in 1:num_of_cols) { diff[row, col] <- B[row, col] - C[row, col] }} # Printing resultant matrixprint(diff)", "e": 3481, "s": 2899, "text": null }, { "code": null, "e": 3489, "s": 3481, "text": "Output:" }, { "code": null, "e": 3671, "s": 3489, "text": " [,1] [,2] [,3]\n[1,] 1 3 5\n[2,] 2 4 6\n [,1] [,2] [,3]\n[1,] 7 9 11\n[2,] 8 10 12\n [,1] [,2] [,3]\n[1,] -6 -6 -6\n[2,] -6 -6 -6\n " }, { "code": null, "e": 3920, "s": 3671, "text": "Here in the above code, the elements of diff matrix are the subtraction of the corresponding elements of B and C through nested for loops. Using ‘-‘ operator for matrix subtraction: Similarly, the following R script uses the in-built operator ‘-‘: " }, { "code": null, "e": 3928, "s": 3920, "text": "Python3" }, { "code": "# R program for matrix addition# using '-' operator # Creating 1st MatrixB = matrix(c(1, 2 + 3i, 5.4, 3, 4, 5), nrow = 2, ncol = 3) # Creating 2nd MatrixC = matrix(c(2, 0i, 0.1, 3, 4, 5), nrow = 2, ncol = 3) # Printing the resultant matrixprint(B - C)", "e": 4180, "s": 3928, "text": null }, { "code": null, "e": 4188, "s": 4180, "text": "Output:" }, { "code": null, "e": 4257, "s": 4188, "text": " [,1] [,2] [,3]\n[1,] -1+0i 5.3+0i 0+0i\n[2,] 2+3i 0.0+0i 0+0i" }, { "code": null, "e": 4292, "s": 4257, "text": "Properties of Matrix Subtraction: " }, { "code": null, "e": 4324, "s": 4292, "text": "Non-Commutative: B – C != C – B" }, { "code": null, "e": 4393, "s": 4324, "text": "Non-Associative: For n number of matrices A – (B – C) != (A – B) – C" }, { "code": null, "e": 4438, "s": 4393, "text": "Order of the matrices involved must be same." }, { "code": null, "e": 4591, "s": 4438, "text": "The multiplication of two same ordered matrices and yields a matrix where every element is the product of corresponding elements of the input matrices. " }, { "code": null, "e": 4599, "s": 4591, "text": "Python3" }, { "code": "# R program to multiply two matrices # Creating 1st MatrixB = matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3) # Creating 2nd MatrixC = matrix(c(7, 8, 9, 10, 11, 12), nrow = 2, ncol = 3) # Getting number of rows and columnsnum_of_rows = nrow(B)num_of_cols = ncol(B) # Creating matrix to store resultsprod = matrix(, nrow = num_of_rows, ncol = num_of_cols) # Printing Original matricesprint(B)print(C) # Calculating product of matricesfor(row in 1:num_of_rows){ for(col in 1:num_of_cols) { prod[row, col] <- B[row, col] * C[row, col] }} # Printing resultant matrixprint(prod)", "e": 5189, "s": 4599, "text": null }, { "code": null, "e": 5197, "s": 5189, "text": "Output:" }, { "code": null, "e": 5377, "s": 5197, "text": " [,1] [,2] [,3]\n[1,] 1 3 5\n[2,] 2 4 6\n [,1] [,2] [,3]\n[1,] 7 9 11\n[2,] 8 10 12\n [,1] [,2] [,3]\n[1,] 7 27 55\n[2,] 16 40 72" }, { "code": null, "e": 5598, "s": 5377, "text": "The elements of sum are the multiplication of the corresponding elements of B and C through nested for loops. Using ‘*’ operator for matrix multiplication: Similarly, the following R script uses the in-built operator *: " }, { "code": null, "e": 5606, "s": 5598, "text": "Python3" }, { "code": "# R program for matrix multiplication# using '*' operator # Creating 1st MatrixB = matrix(c(1, 2 + 3i, 5.4), nrow = 1, ncol = 3) # Creating 2nd MatrixC = matrix(c(2, 1i, 0.1), nrow = 1, ncol = 3) # Printing the resultant matrixprint (B * C)", "e": 5847, "s": 5606, "text": null }, { "code": null, "e": 5855, "s": 5847, "text": "Output:" }, { "code": null, "e": 5903, "s": 5855, "text": " [,1] [,2] [,3]\n[1,] 2+0i -3+2i 0.54+0i" }, { "code": null, "e": 5940, "s": 5903, "text": "Properties of Matrix Multiplication:" }, { "code": null, "e": 5967, "s": 5940, "text": "Commutative: B * C = C * B" }, { "code": null, "e": 6031, "s": 5967, "text": "Associative: For n number of matrices A * (B * C) = (A * B) * C" }, { "code": null, "e": 6076, "s": 6031, "text": "Order of the matrices involved must be same." }, { "code": null, "e": 6252, "s": 6076, "text": "The division of two same ordered matrices and yields a matrix where every element is the quotient of corresponding elements of the first matrix element divided by the second. " }, { "code": null, "e": 6260, "s": 6252, "text": "Python3" }, { "code": "# R program to divide two matrices # Creating 1st MatrixB = matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3) # Creating 2nd MatrixC = matrix(c(7, 8, 9, 10, 11, 12), nrow = 2, ncol = 3) # Getting number of rows and columnsnum_of_rows = nrow(B)num_of_cols = ncol(B) # Creating matrix to store resultsdiv = matrix(, nrow = num_of_rows, ncol = num_of_cols) # Printing Original matricesprint(B)print(C) # Calculating product of matricesfor(row in 1:num_of_rows){ for(col in 1:num_of_cols) { div[row, col] <- B[row, col] / C[row, col] }} # Printing resultant matrixprint(div)", "e": 6845, "s": 6260, "text": null }, { "code": null, "e": 6853, "s": 6845, "text": "Output:" }, { "code": null, "e": 7078, "s": 6853, "text": " [,1] [,2] [,3]\n[1,] 1 3 5\n[2,] 2 4 6\n [,1] [,2] [,3]\n[1,] 7 9 11\n[2,] 8 10 12\n [,1] [,2] [,3]\n[1,] 0.1428571 0.3333333 0.4545455\n[2,] 0.2500000 0.4000000 0.5000000" }, { "code": null, "e": 7294, "s": 7078, "text": "The elements of div matrix are the division of the corresponding elements of B and C through nested for loops. Using ‘/’ operator for matrix division: Similarly, the following R script uses the in-built operator /: " }, { "code": null, "e": 7302, "s": 7294, "text": "Python3" }, { "code": "# R program for matrix division# using '/' operator # Creating 1st MatrixB = matrix(c(4, 6i, -1), nrow = 1, ncol = 3) # Creating 2nd MatrixC = matrix(c(2, 2i, 0), nrow = 1, ncol = 3) # Printing the resultant matrixprint (B / C)", "e": 7530, "s": 7302, "text": null }, { "code": null, "e": 7538, "s": 7530, "text": "Output:" }, { "code": null, "e": 7588, "s": 7538, "text": " [,1] [,2] [,3]\n[1,] 2+0i 3+0i -Inf+NaNi" }, { "code": null, "e": 7620, "s": 7588, "text": "Properties of Matrix Division: " }, { "code": null, "e": 7652, "s": 7620, "text": "Non-Commutative: B / C != C / B" }, { "code": null, "e": 7721, "s": 7652, "text": "Non-Associative: For n number of matrices A / (B / C) != (A / B) / C" }, { "code": null, "e": 7766, "s": 7721, "text": "Order of the matrices involved must be same." }, { "code": null, "e": 7864, "s": 7766, "text": "Note: Time Complexity of all the matrix operations = O(r*c) where r*c is the order of the matrix." }, { "code": null, "e": 7877, "s": 7864, "text": "simmytarika5" }, { "code": null, "e": 7884, "s": 7877, "text": "Picked" }, { "code": null, "e": 7895, "s": 7884, "text": "R Language" }, { "code": null, "e": 7993, "s": 7895, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8045, "s": 7993, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 8103, "s": 8045, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 8155, "s": 8103, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 8213, "s": 8155, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 8245, "s": 8213, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 8277, "s": 8245, "text": "Printing Output of an R Program" }, { "code": null, "e": 8312, "s": 8277, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 8356, "s": 8312, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 8394, "s": 8356, "text": "How to Change Axis Scales in R Plots?" } ]
Stern-Brocot Sequence
07 May, 2021 Stern Brocot sequence is similar to Fibonacci sequence but it is different in the way fibonacci sequence is generated . Generation of Stern Brocot sequence : 1. First and second element of the sequence is 1 and 1.2. Consider the second member of the sequence . Then, sum the considered member of the sequence and it’s precedent i.e (1 + 1 = 2) . Now 2 is the next element of our series . Sequence will be [ 1, 1, 2 ]3. After this element, our next element of the sequence will be the considered element of our second step. Now the sequence will be [ 1, 1, 2, 1 ]4. Again we do the step 2, but now the considered element will be 2(3rd element ). So, next number of sequence will be sum of considered number and it’s precedent (2 + 1 = 3). Sequence will be now [ 1, 1, 2, 1, 3 ]5. Like step 3, the next element will be the considered element i.e 2 . Thus sequence will be [ 1, 1, 2, 1, 3, 2 ]6. Hence this process continues, now next considered element will be 1( 4th element ) . Here is the simple program to print Stern Brocot sequence . C++ Java Python3 C# PHP Javascript // CPP program to print Brocot Sequence#include <bits/stdc++.h>using namespace std; void SternSequenceFunc(vector<int>& BrocotSequence, int n){ // loop to create sequence for (int i = 1; BrocotSequence.size() < n; i++) { int considered_element = BrocotSequence[i]; int precedent = BrocotSequence[i - 1]; // adding sum of considered element and it's precedent BrocotSequence.push_back(considered_element + precedent); // adding next considered element BrocotSequence.push_back(considered_element); } // printing sequence.. for (int i = 0; i < 15; ++i) cout << BrocotSequence[i] << " ";} int main(){ int n = 15; vector<int> BrocotSequence; // adding first two element // in the sequence BrocotSequence.push_back(1); BrocotSequence.push_back(1); SternSequenceFunc(BrocotSequence, n); return 0;} // Java program to print// Brocot Sequenceimport java.io.*;import java.util.*; class GFG { static void SternSequenceFunc(Vector<Integer> BrocotSequence, int n){ // loop to create sequence for (int i = 1; BrocotSequence.size() < n; i++) { int considered_element = BrocotSequence.get(i); int precedent = BrocotSequence.get(i-1); // adding sum of considered element and it's precedent BrocotSequence.add(considered_element + precedent); // adding next considered element BrocotSequence.add(considered_element); } // printing sequence.. for (int i = 0; i < 15; ++i) System.out.print(BrocotSequence.get(i) + " ");} // Driver code public static void main (String[] args) { int n = 15; Vector<Integer> BrocotSequence = new Vector<Integer>(); // adding first two element // in the sequence BrocotSequence.add(1); BrocotSequence.add(1); SternSequenceFunc(BrocotSequence, n); }} // This code is contributed by Gitanjali. # Python program to print# Brocot Sequenceimport math def SternSequenceFunc(BrocotSequence, n): # loop to create sequence for i in range(1, n): considered_element = BrocotSequence[i] precedent = BrocotSequence[i-1] # adding sum of considered # element and it's precedent BrocotSequence.append(considered_element + precedent) # adding next considered element BrocotSequence.append(considered_element) # printing sequence.. for i in range(0, 15): print(BrocotSequence[i] , end=" ") # Driver coden = 15BrocotSequence = [] # adding first two element# in the sequenceBrocotSequence.append(1)BrocotSequence.append(1) SternSequenceFunc(BrocotSequence, n) # This code is contributed by Gitanjali. // C# program to print// Brocot Sequenceusing System;using System.Collections.Generic; class GFG{static void SternSequenceFunc(List<int> BrocotSequence, int n){ // loop to create sequence for (int i = 1; BrocotSequence.Count < n; i++) { int considered_element = BrocotSequence[i]; int precedent = BrocotSequence[i - 1]; // adding sum of considered // element and it's precedent BrocotSequence.Add(considered_element + precedent); // adding next // considered element BrocotSequence.Add( considered_element); } // printing sequence.. for (int i = 0; i < 15; ++i) Console.Write( BrocotSequence[i] + " ");}// Driver codestatic void Main (){ int n = 15; List<int> BrocotSequence = new List<int>(); // adding first two element // in the sequence BrocotSequence.Add(1); BrocotSequence.Add(1); SternSequenceFunc(BrocotSequence, n);}} // This code is contributed by// Manish Shaw(manishshaw1) <?php// PHP program to// print Brocot Sequence function SternSequenceFunc(&$BrocotSequence, $n){ // loop to create sequence for ($i = 1; count($BrocotSequence) < $n; $i++) { $considered_element = $BrocotSequence[$i]; $precedent = $BrocotSequence[$i - 1]; // adding sum of considered // element and it's precedent array_push($BrocotSequence, $considered_element + $precedent); // adding next // considered element array_push($BrocotSequence, $considered_element); } // printing sequence.. for ($i = 0; $i < 15; ++$i) echo ($BrocotSequence[$i]." ");} // Driver code$n = 15;$BrocotSequence = array(); // adding first two element// in the sequencearray_push($BrocotSequence, 1);array_push($BrocotSequence, 1); SternSequenceFunc($BrocotSequence, $n); // This code is contributed by// Manish Shaw(manishshaw1)?> <script> // Javascript program to print Brocot Sequence function SternSequenceFunc( BrocotSequence, n){ // loop to create sequence for (var i = 1; BrocotSequence.length < n; i++) { var considered_element = BrocotSequence[i]; var precedent = BrocotSequence[i - 1]; // adding sum of considered element and it's precedent BrocotSequence.push(considered_element + precedent); // adding next considered element BrocotSequence.push(considered_element); } // printing sequence.. for (var i = 0; i < 15; ++i) document.write( BrocotSequence[i] + " ");} var n = 15;var BrocotSequence = []; // adding first two element// in the sequenceBrocotSequence.push(1);BrocotSequence.push(1); SternSequenceFunc(BrocotSequence, n); // This code is contributed by rrrtnx.</script> Output: 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 References : Github manishshaw1 rrrtnx series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Merge two sorted arrays with O(1) extra space Program to print prime numbers from 1 to N. Find next greater number with same set of digits Segment Tree | Set 1 (Sum of given range) Check if a number is Palindrome Count ways to reach the n'th stair Fizz Buzz Implementation Count all possible paths from top left to bottom right of a mXn matrix Product of Array except itself
[ { "code": null, "e": 52, "s": 24, "text": "\n07 May, 2021" }, { "code": null, "e": 211, "s": 52, "text": "Stern Brocot sequence is similar to Fibonacci sequence but it is different in the way fibonacci sequence is generated . Generation of Stern Brocot sequence : " }, { "code": null, "e": 1033, "s": 211, "text": "1. First and second element of the sequence is 1 and 1.2. Consider the second member of the sequence . Then, sum the considered member of the sequence and it’s precedent i.e (1 + 1 = 2) . Now 2 is the next element of our series . Sequence will be [ 1, 1, 2 ]3. After this element, our next element of the sequence will be the considered element of our second step. Now the sequence will be [ 1, 1, 2, 1 ]4. Again we do the step 2, but now the considered element will be 2(3rd element ). So, next number of sequence will be sum of considered number and it’s precedent (2 + 1 = 3). Sequence will be now [ 1, 1, 2, 1, 3 ]5. Like step 3, the next element will be the considered element i.e 2 . Thus sequence will be [ 1, 1, 2, 1, 3, 2 ]6. Hence this process continues, now next considered element will be 1( 4th element ) . " }, { "code": null, "e": 1097, "s": 1035, "text": "Here is the simple program to print Stern Brocot sequence . " }, { "code": null, "e": 1101, "s": 1097, "text": "C++" }, { "code": null, "e": 1106, "s": 1101, "text": "Java" }, { "code": null, "e": 1114, "s": 1106, "text": "Python3" }, { "code": null, "e": 1117, "s": 1114, "text": "C#" }, { "code": null, "e": 1121, "s": 1117, "text": "PHP" }, { "code": null, "e": 1132, "s": 1121, "text": "Javascript" }, { "code": "// CPP program to print Brocot Sequence#include <bits/stdc++.h>using namespace std; void SternSequenceFunc(vector<int>& BrocotSequence, int n){ // loop to create sequence for (int i = 1; BrocotSequence.size() < n; i++) { int considered_element = BrocotSequence[i]; int precedent = BrocotSequence[i - 1]; // adding sum of considered element and it's precedent BrocotSequence.push_back(considered_element + precedent); // adding next considered element BrocotSequence.push_back(considered_element); } // printing sequence.. for (int i = 0; i < 15; ++i) cout << BrocotSequence[i] << \" \";} int main(){ int n = 15; vector<int> BrocotSequence; // adding first two element // in the sequence BrocotSequence.push_back(1); BrocotSequence.push_back(1); SternSequenceFunc(BrocotSequence, n); return 0;}", "e": 2037, "s": 1132, "text": null }, { "code": "// Java program to print// Brocot Sequenceimport java.io.*;import java.util.*; class GFG { static void SternSequenceFunc(Vector<Integer> BrocotSequence, int n){ // loop to create sequence for (int i = 1; BrocotSequence.size() < n; i++) { int considered_element = BrocotSequence.get(i); int precedent = BrocotSequence.get(i-1); // adding sum of considered element and it's precedent BrocotSequence.add(considered_element + precedent); // adding next considered element BrocotSequence.add(considered_element); } // printing sequence.. for (int i = 0; i < 15; ++i) System.out.print(BrocotSequence.get(i) + \" \");} // Driver code public static void main (String[] args) { int n = 15; Vector<Integer> BrocotSequence = new Vector<Integer>(); // adding first two element // in the sequence BrocotSequence.add(1); BrocotSequence.add(1); SternSequenceFunc(BrocotSequence, n); }} // This code is contributed by Gitanjali.", "e": 3148, "s": 2037, "text": null }, { "code": "# Python program to print# Brocot Sequenceimport math def SternSequenceFunc(BrocotSequence, n): # loop to create sequence for i in range(1, n): considered_element = BrocotSequence[i] precedent = BrocotSequence[i-1] # adding sum of considered # element and it's precedent BrocotSequence.append(considered_element + precedent) # adding next considered element BrocotSequence.append(considered_element) # printing sequence.. for i in range(0, 15): print(BrocotSequence[i] , end=\" \") # Driver coden = 15BrocotSequence = [] # adding first two element# in the sequenceBrocotSequence.append(1)BrocotSequence.append(1) SternSequenceFunc(BrocotSequence, n) # This code is contributed by Gitanjali.", "e": 3949, "s": 3148, "text": null }, { "code": "// C# program to print// Brocot Sequenceusing System;using System.Collections.Generic; class GFG{static void SternSequenceFunc(List<int> BrocotSequence, int n){ // loop to create sequence for (int i = 1; BrocotSequence.Count < n; i++) { int considered_element = BrocotSequence[i]; int precedent = BrocotSequence[i - 1]; // adding sum of considered // element and it's precedent BrocotSequence.Add(considered_element + precedent); // adding next // considered element BrocotSequence.Add( considered_element); } // printing sequence.. for (int i = 0; i < 15; ++i) Console.Write( BrocotSequence[i] + \" \");}// Driver codestatic void Main (){ int n = 15; List<int> BrocotSequence = new List<int>(); // adding first two element // in the sequence BrocotSequence.Add(1); BrocotSequence.Add(1); SternSequenceFunc(BrocotSequence, n);}} // This code is contributed by// Manish Shaw(manishshaw1)", "e": 5121, "s": 3949, "text": null }, { "code": "<?php// PHP program to// print Brocot Sequence function SternSequenceFunc(&$BrocotSequence, $n){ // loop to create sequence for ($i = 1; count($BrocotSequence) < $n; $i++) { $considered_element = $BrocotSequence[$i]; $precedent = $BrocotSequence[$i - 1]; // adding sum of considered // element and it's precedent array_push($BrocotSequence, $considered_element + $precedent); // adding next // considered element array_push($BrocotSequence, $considered_element); } // printing sequence.. for ($i = 0; $i < 15; ++$i) echo ($BrocotSequence[$i].\" \");} // Driver code$n = 15;$BrocotSequence = array(); // adding first two element// in the sequencearray_push($BrocotSequence, 1);array_push($BrocotSequence, 1); SternSequenceFunc($BrocotSequence, $n); // This code is contributed by// Manish Shaw(manishshaw1)?>", "e": 6112, "s": 5121, "text": null }, { "code": "<script> // Javascript program to print Brocot Sequence function SternSequenceFunc( BrocotSequence, n){ // loop to create sequence for (var i = 1; BrocotSequence.length < n; i++) { var considered_element = BrocotSequence[i]; var precedent = BrocotSequence[i - 1]; // adding sum of considered element and it's precedent BrocotSequence.push(considered_element + precedent); // adding next considered element BrocotSequence.push(considered_element); } // printing sequence.. for (var i = 0; i < 15; ++i) document.write( BrocotSequence[i] + \" \");} var n = 15;var BrocotSequence = []; // adding first two element// in the sequenceBrocotSequence.push(1);BrocotSequence.push(1); SternSequenceFunc(BrocotSequence, n); // This code is contributed by rrrtnx.</script>", "e": 6948, "s": 6112, "text": null }, { "code": null, "e": 6958, "s": 6948, "text": "Output: " }, { "code": null, "e": 6988, "s": 6958, "text": "1 1 2 1 3 2 3 1 4 3 5 2 5 3 4" }, { "code": null, "e": 7009, "s": 6988, "text": "References : Github " }, { "code": null, "e": 7021, "s": 7009, "text": "manishshaw1" }, { "code": null, "e": 7028, "s": 7021, "text": "rrrtnx" }, { "code": null, "e": 7035, "s": 7028, "text": "series" }, { "code": null, "e": 7048, "s": 7035, "text": "Mathematical" }, { "code": null, "e": 7061, "s": 7048, "text": "Mathematical" }, { "code": null, "e": 7068, "s": 7061, "text": "series" }, { "code": null, "e": 7166, "s": 7068, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7198, "s": 7166, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 7244, "s": 7198, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 7288, "s": 7244, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 7337, "s": 7288, "text": "Find next greater number with same set of digits" }, { "code": null, "e": 7379, "s": 7337, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 7411, "s": 7379, "text": "Check if a number is Palindrome" }, { "code": null, "e": 7446, "s": 7411, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 7471, "s": 7446, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 7542, "s": 7471, "text": "Count all possible paths from top left to bottom right of a mXn matrix" } ]
PostgreSQL – WHERE clause
28 Aug, 2020 The PostgreSQL WHERE clause is used to filter results returned by the SELECT statement. Syntax: SELECT select_list FROM table_name WHERE condition; Let’s analyze the above syntax: The WHERE clause appears right after the FROM clause of the SELECT statement The condition evaluates to true, false, or unknown. It can either be a Boolean expression or a combination of Boolean expressions where AND and OR operators are used. The WHERE clause can also be used with the UPDATE and DELETE statement to specify rows to be updated or deleted. Below table provides us with the list of comparison operators valid in PostgreSQL: For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link.Now, let’s look into some examples. Example 1:Using WHERE clause with the equal (=) operator. Here we will be using the equal operator in the “customer” table of our sample database. SELECT last_name, first_name FROM customer WHERE first_name = 'Kelly'; Output: Example 2:Using the WHERE clause with the AND operator. Here we will be using the AND operator in the “customer” table of our sample database. SELECT last_name, first_name FROM customer WHERE first_name = 'Kelly' AND last_name = 'Knott'; Output: Example 3:Using the WHERE clause with the OR operator. Here we will be using the OR operator in the “customer” table of our sample database. SELECT first_name, last_name FROM customer WHERE last_name = 'Cooper' OR first_name = 'Jo'; Output: Example 4:Using the WHERE clause with the IN operator. The IN operator is used for string matching. Here we will be using the IN operator in the “customer” table of our sample database. SELECT first_name, last_name FROM customer WHERE first_name IN ('Kelly', 'Jo', ' Alexander'); Output: Example 5:Using the WHERE clause with the LIKE operator. The LIKE operator is used to find string matching a particular pattern. Here we will be using the LIKE operator in the “customer” table of our sample database. SELECT first_name, last_name FROM customer WHERE first_name LIKE 'Kath%'; Output: Example 6:Using the WHERE clause with the BETWEEN operator. The BETWEEN operator return if a value is in the mentioned range. Here we will be using the BETWEEN operator in the “customer” table of our sample database. SELECT first_name, LENGTH(first_name) name_length FROM customer WHERE first_name LIKE 'K%' AND LENGTH(first_name) BETWEEN 3 AND 7 ORDER BY name_length; Output: Example 7:Using the WHERE clause with the not equal operator (<>). Here we will be using the <> operator in the “customer” table of our sample database. SELECT first_name, last_name FROM customer WHERE first_name LIKE 'Bra%' AND last_name <> 'Motley'; Output: postgreSQL-clauses PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Aug, 2020" }, { "code": null, "e": 116, "s": 28, "text": "The PostgreSQL WHERE clause is used to filter results returned by the SELECT statement." }, { "code": null, "e": 176, "s": 116, "text": "Syntax: SELECT select_list FROM table_name WHERE condition;" }, { "code": null, "e": 208, "s": 176, "text": "Let’s analyze the above syntax:" }, { "code": null, "e": 285, "s": 208, "text": "The WHERE clause appears right after the FROM clause of the SELECT statement" }, { "code": null, "e": 452, "s": 285, "text": "The condition evaluates to true, false, or unknown. It can either be a Boolean expression or a combination of Boolean expressions where AND and OR operators are used." }, { "code": null, "e": 565, "s": 452, "text": "The WHERE clause can also be used with the UPDATE and DELETE statement to specify rows to be updated or deleted." }, { "code": null, "e": 648, "s": 565, "text": "Below table provides us with the list of comparison operators valid in PostgreSQL:" }, { "code": null, "e": 833, "s": 648, "text": "For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link.Now, let’s look into some examples." }, { "code": null, "e": 980, "s": 833, "text": "Example 1:Using WHERE clause with the equal (=) operator. Here we will be using the equal operator in the “customer” table of our sample database." }, { "code": null, "e": 1067, "s": 980, "text": "SELECT\n last_name,\n first_name\nFROM\n customer\nWHERE\n first_name = 'Kelly';" }, { "code": null, "e": 1075, "s": 1067, "text": "Output:" }, { "code": null, "e": 1218, "s": 1075, "text": "Example 2:Using the WHERE clause with the AND operator. Here we will be using the AND operator in the “customer” table of our sample database." }, { "code": null, "e": 1329, "s": 1218, "text": "SELECT\n last_name,\n first_name\nFROM\n customer\nWHERE\n first_name = 'Kelly'\nAND last_name = 'Knott';" }, { "code": null, "e": 1337, "s": 1329, "text": "Output:" }, { "code": null, "e": 1478, "s": 1337, "text": "Example 3:Using the WHERE clause with the OR operator. Here we will be using the OR operator in the “customer” table of our sample database." }, { "code": null, "e": 1591, "s": 1478, "text": "SELECT\n first_name,\n last_name\nFROM\n customer\nWHERE\n last_name = 'Cooper' OR \n first_name = 'Jo';" }, { "code": null, "e": 1599, "s": 1591, "text": "Output:" }, { "code": null, "e": 1785, "s": 1599, "text": "Example 4:Using the WHERE clause with the IN operator. The IN operator is used for string matching. Here we will be using the IN operator in the “customer” table of our sample database." }, { "code": null, "e": 1896, "s": 1785, "text": "SELECT\n first_name,\n last_name\nFROM\n customer\nWHERE \n first_name IN ('Kelly', 'Jo', ' Alexander');" }, { "code": null, "e": 1904, "s": 1896, "text": "Output:" }, { "code": null, "e": 2121, "s": 1904, "text": "Example 5:Using the WHERE clause with the LIKE operator. The LIKE operator is used to find string matching a particular pattern. Here we will be using the LIKE operator in the “customer” table of our sample database." }, { "code": null, "e": 2212, "s": 2121, "text": "SELECT\n first_name,\n last_name\nFROM\n customer\nWHERE \n first_name LIKE 'Kath%';" }, { "code": null, "e": 2220, "s": 2212, "text": "Output:" }, { "code": null, "e": 2437, "s": 2220, "text": "Example 6:Using the WHERE clause with the BETWEEN operator. The BETWEEN operator return if a value is in the mentioned range. Here we will be using the BETWEEN operator in the “customer” table of our sample database." }, { "code": null, "e": 2614, "s": 2437, "text": "SELECT\n first_name,\n LENGTH(first_name) name_length\nFROM\n customer\nWHERE \n first_name LIKE 'K%' AND\n LENGTH(first_name) BETWEEN 3 AND 7\nORDER BY\n name_length;" }, { "code": null, "e": 2622, "s": 2614, "text": "Output:" }, { "code": null, "e": 2775, "s": 2622, "text": "Example 7:Using the WHERE clause with the not equal operator (<>). Here we will be using the <> operator in the “customer” table of our sample database." }, { "code": null, "e": 2900, "s": 2775, "text": "SELECT \n first_name, \n last_name\nFROM \n customer \nWHERE \n first_name LIKE 'Bra%' AND \n last_name <> 'Motley';" }, { "code": null, "e": 2908, "s": 2900, "text": "Output:" }, { "code": null, "e": 2927, "s": 2908, "text": "postgreSQL-clauses" }, { "code": null, "e": 2938, "s": 2927, "text": "PostgreSQL" } ]
Python | sympy.evalf() method
18 Jun, 2019 With the help of sympy.evalf() method, we are able to evaluate the mathematical expressions. Syntax : sympy.evalf()Return : Return the evaluated mathematical expression. Example #1 :In this example we can see that by using sympy.evalf() method, we are able to evaluate the mathematical expressions. # Import sympyfrom sympy import * # Use sympy.evalf() methodexpn = sqrt(9)gfg = expn.evalf() print(gfg) Output : 3.00000000000000 Example #2 : # Import sympyfrom sympy import * # Use sympy.evalf() methodexpn = sqrt(9)*cos(45)gfg = expn.evalf() print(gfg) Output : 1.57596596645319 SymPy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jun, 2019" }, { "code": null, "e": 121, "s": 28, "text": "With the help of sympy.evalf() method, we are able to evaluate the mathematical expressions." }, { "code": null, "e": 198, "s": 121, "text": "Syntax : sympy.evalf()Return : Return the evaluated mathematical expression." }, { "code": null, "e": 327, "s": 198, "text": "Example #1 :In this example we can see that by using sympy.evalf() method, we are able to evaluate the mathematical expressions." }, { "code": "# Import sympyfrom sympy import * # Use sympy.evalf() methodexpn = sqrt(9)gfg = expn.evalf() print(gfg)", "e": 433, "s": 327, "text": null }, { "code": null, "e": 442, "s": 433, "text": "Output :" }, { "code": null, "e": 459, "s": 442, "text": "3.00000000000000" }, { "code": null, "e": 472, "s": 459, "text": "Example #2 :" }, { "code": "# Import sympyfrom sympy import * # Use sympy.evalf() methodexpn = sqrt(9)*cos(45)gfg = expn.evalf() print(gfg)", "e": 586, "s": 472, "text": null }, { "code": null, "e": 595, "s": 586, "text": "Output :" }, { "code": null, "e": 612, "s": 595, "text": "1.57596596645319" }, { "code": null, "e": 618, "s": 612, "text": "SymPy" }, { "code": null, "e": 625, "s": 618, "text": "Python" } ]
GUI Billing System and Menu Card Using Python
25 May, 2022 So imagine that we’re starting a new restaurant or being appointed as one of the employees in a restaurant company, and we find out that there’s no fast method of doing the billing of customers, and it usually takes times for us to calculate the amount that a customer has to pay. This can be really annoying and time taking thing for us as well as for customers. So now what to do? Here’s when python comes to the rescue and since we know it, it will be just a few seconds of work. So, in this article, we’re going to build a GUI billing system and a menu card with the help of python’s module Tkinter. Step 1: Importing the tkinter package from tkinter import * Step 2: Downloading the required files Here’s only one file we have to install in this project which will work as the background image of our GUI Billing System or we can choose any other image. After downloading make sure that the python program which we are creating and these assets are in the same folder. Image Used: Step 3: Making tkinter window and setting the background Now we make the tkinter window and set the background for the GUI Python3 # import tkinter modulefrom tkinter import * # make a windowwindow = Tk() # specify it's sizewindow.geometry("700x600") # take a image for backgroundbg = PhotoImage(file='bg.png') # label it in the backgroundlabel17 = Label(window, image=bg) # position the image as welllabel17.place(x=0, y=0) # closing the main loopwindow.mainloop() Output: Step 4: Adding the title and menu card Now we will add the title and menu card for the GUI billing system with help of “Label()” function. Tkinter Label is a widget that is used to implement display boxes where we can place text or images. The text displayed by this widget can be changed by the developer at any time you want. It is also used to perform tasks such as underlining the part of the text and span the text across multiple lines. It is important to note that a label can use only one font at a time to display text. To use a label, we just have to specify what to display in it (this can be text, a bitmap, or an image). Syntax: w = Label ( master, option, ... ) Parameters: master: This represents the parent window options: These options can be used as key-value pairs separated by commas Python3 # main titlelabel8 = Label(window, text="Saransh Restaurant", font="times 28 bold")label8.place(x=350, y=20, anchor="center") # Menu Cardlabel1 = Label(window, text="Menu", font="times 28 bold")label1.place(x=520, y=70) label2 = Label(window, text="Aloo Paratha Rs 30", font="times 18")label2.place(x=450, y=120) label3 = Label(window, text="Samosa Rs 5", font="times 18")label3.place(x=450, y=150) label4 = Label(window, text="Pizza Rs 150", font="times 18")label4.place(x=450, y=180) label5 = Label(window, text="Chilli Potato Rs 50", font="times 18")label5.place(x=450, y=210) label6 = Label(window, text="Chowmein Rs 70", font="times 18")label6.place(x=450, y=240) label7 = Label(window, text="Gulab Jamun Rs 35", font="times 18")label7.place(x=450, y=270) # closing the main loopwindow.mainloop() Output: Step 5: Adding the billing section Now we will add the billing section by using the same label widget and the entry widget. The Entry Widget is a Tkinter Widget used to Enter or display a single line of text. Also, Label.place(x,y) indicates the position of the label in the tkinter window. Syntax: entry = tk.Entry(parent, options) Parameters: parent: This represents the parent window options: These options can be used as key-value pairs separated by commas Python3 #------billing section---------label9=Label(window,text="Select the items", font="times 18")label9.place(x=115,y=70) label10=Label(window,text="Aloo Paratha", font="times 18")label10.place(x=20,y=120) e1=Entry(window)e1.place(x=20,y=150) label11=Label(window,text="Samosa", font="times 18")label11.place(x=20,y=200) e2=Entry(window)e2.place(x=20,y=230) label12=Label(window,text="Pizza", font="times 18")label12.place(x=20,y=280) e3=Entry(window)e3.place(x=20,y=310) label13=Label(window,text="Chilli Potato", font="times 18")label13.place(x=20,y=360) e4=Entry(window)e4.place(x=20,y=390) label14=Label(window,text="Chowmein", font="times 18")label14.place(x=250,y=120) e5=Entry(window)e5.place(x=250,y=150) label15=Label(window,text="Gulab Jamun", font="times 18")label15.place(x=250,y=200) e6=Entry(window)e6.place(x=250,y=230) # closing the main loopwindow.mainloop() Output: Step 6: Calculating the bill and refreshing the window After that, we have to add the calculate function which will get executed every second. In the calculate function we have to do simple math where if e.get() returns an empty string then it means that there’s no quantity selected for that particular food, else if there’s any value present in the e.get() then since it is of string type we convert it to int type and multiply this quantity of food with the price of that food. The food variable along with its quantity and price is kept in a dictionary. We look for every key in the dictionary and accordingly increment our ‘total’ variable. After that, we make another label where we use the total variable’s value to display the total amount of foods ordered. Then we made a command that after every 1000 milliseconds we refresh the window to again calculate the total amount of foods ordered which will update our GUI. Also, the total amount label gets updated by destroying the previous one and updating it with a new one every second. Python3 # function to calculate the# price of all the orders def calculate(): # dic for storing the food quantity and price dic = {'aloo_partha': [e1, 30], 'samosa': [e2, 5], 'pizza': [e3, 150], 'chilli_potato': [e4, 50], 'chowmein': [e5, 70], 'gulab_jamun': [e6, 35]} total = 0 for key, val in dic.items(): if val[0].get() != "": total += int(val[0].get())*val[1] label16 = Label(window, text="Your Total Bill is - "+str(total), font="times 18") # position label16.place(x=20, y=490) # it will update the label with a new one label16.after(1000, label16.destroy) # refreshing the window window.after(1000, calculate) # execute calculate function after 1 secondwindow.after(1000, calculate)window.mainloop() Output: Below is the full implementation: Python3 # import tkinter modulefrom tkinter import * # make a windowwindow = Tk() # specify it's sizewindow.geometry("700x600") # take a image for backgroundbg = PhotoImage(file='bg.png') # label it in the backgroundlabel17 = Label(window, image=bg) # position the image as welllabel17.place(x=0, y=0) # function to calculate the# price of all the ordersdef calculate(): # dic for storing the # food quantity and price dic = {'aloo_partha': [e1, 30], 'samosa': [e2, 5], 'pizza': [e3, 150], 'chilli_potato': [e4, 50], 'chowmein': [e5, 70], 'gulab_jamun': [e6, 35]} total = 0 for key, val in dic.items(): if val[0].get() != "": total += int(val[0].get())*val[1] label16 = Label(window, text="Your Total Bill is - "+str(total), font="times 18") # position it label16.place(x=20, y=490) label16.after(1000, label16.destroy) window.after(1000, calculate) label8 = Label(window, text="Saransh Restaurant", font="times 28 bold")label8.place(x=350, y=20, anchor="center") label1 = Label(window, text="Menu", font="times 28 bold") label1.place(x=520, y=70) label2 = Label(window, text="Aloo Paratha \Rs 30", font="times 18") label2.place(x=450, y=120) label3 = Label(window, text="Samosa \Rs 5", font="times 18") label3.place(x=450, y=150) label4 = Label(window, text="Pizza \Rs 150", font="times 18")label4.place(x=450, y=180) label5 = Label(window, text="Chilli Potato \Rs 50", font="times 18") label5.place(x=450, y=210) label6 = Label(window, text="Chowmein \Rs 70", font="times 18") label6.place(x=450, y=240) label7 = Label(window, text="Gulab Jamun \Rs 35", font="times 18") label7.place(x=450, y=270) # billing sectionlabel9 = Label(window, text="Select the items", font="times 18")label9.place(x=115, y=70) label10 = Label(window, text="Aloo Paratha", font="times 18")label10.place(x=20, y=120) e1 = Entry(window)e1.place(x=20, y=150) label11 = Label(window, text="Samosa", font="times 18")label11.place(x=20, y=200) e2 = Entry(window)e2.place(x=20, y=230) label12 = Label(window, text="Pizza", font="times 18")label12.place(x=20, y=280) e3 = Entry(window)e3.place(x=20, y=310) label13 = Label(window, text="Chilli Potato", font="times 18")label13.place(x=20, y=360) e4 = Entry(window)e4.place(x=20, y=390) label14 = Label(window, text="Chowmein", font="times 18")label14.place(x=250, y=120) e5 = Entry(window)e5.place(x=250, y=150) label15 = Label(window, text="Gulab Jamun", font="times 18") label15.place(x=250, y=200) e6 = Entry(window)e6.place(x=250, y=230) # execute calculate function after 1 secondwindow.after(1000, calculate) # closing the main loopwindow.mainloop() Output: akshaysingh98088 Python Tkinter-projects Python-projects Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 52, "s": 24, "text": "\n25 May, 2022" }, { "code": null, "e": 535, "s": 52, "text": "So imagine that we’re starting a new restaurant or being appointed as one of the employees in a restaurant company, and we find out that there’s no fast method of doing the billing of customers, and it usually takes times for us to calculate the amount that a customer has to pay. This can be really annoying and time taking thing for us as well as for customers. So now what to do? Here’s when python comes to the rescue and since we know it, it will be just a few seconds of work." }, { "code": null, "e": 656, "s": 535, "text": "So, in this article, we’re going to build a GUI billing system and a menu card with the help of python’s module Tkinter." }, { "code": null, "e": 694, "s": 656, "text": "Step 1: Importing the tkinter package" }, { "code": null, "e": 716, "s": 694, "text": "from tkinter import *" }, { "code": null, "e": 755, "s": 716, "text": "Step 2: Downloading the required files" }, { "code": null, "e": 1026, "s": 755, "text": "Here’s only one file we have to install in this project which will work as the background image of our GUI Billing System or we can choose any other image. After downloading make sure that the python program which we are creating and these assets are in the same folder." }, { "code": null, "e": 1038, "s": 1026, "text": "Image Used:" }, { "code": null, "e": 1095, "s": 1038, "text": "Step 3: Making tkinter window and setting the background" }, { "code": null, "e": 1162, "s": 1095, "text": "Now we make the tkinter window and set the background for the GUI " }, { "code": null, "e": 1170, "s": 1162, "text": "Python3" }, { "code": "# import tkinter modulefrom tkinter import * # make a windowwindow = Tk() # specify it's sizewindow.geometry(\"700x600\") # take a image for backgroundbg = PhotoImage(file='bg.png') # label it in the backgroundlabel17 = Label(window, image=bg) # position the image as welllabel17.place(x=0, y=0) # closing the main loopwindow.mainloop()", "e": 1511, "s": 1170, "text": null }, { "code": null, "e": 1520, "s": 1511, "text": "Output: " }, { "code": null, "e": 1559, "s": 1520, "text": "Step 4: Adding the title and menu card" }, { "code": null, "e": 2154, "s": 1559, "text": "Now we will add the title and menu card for the GUI billing system with help of “Label()” function. Tkinter Label is a widget that is used to implement display boxes where we can place text or images. The text displayed by this widget can be changed by the developer at any time you want. It is also used to perform tasks such as underlining the part of the text and span the text across multiple lines. It is important to note that a label can use only one font at a time to display text. To use a label, we just have to specify what to display in it (this can be text, a bitmap, or an image)." }, { "code": null, "e": 2196, "s": 2154, "text": "Syntax: w = Label ( master, option, ... )" }, { "code": null, "e": 2210, "s": 2196, "text": "Parameters: " }, { "code": null, "e": 2252, "s": 2210, "text": "master: This represents the parent window" }, { "code": null, "e": 2326, "s": 2252, "text": "options: These options can be used as key-value pairs separated by commas" }, { "code": null, "e": 2334, "s": 2326, "text": "Python3" }, { "code": "# main titlelabel8 = Label(window, text=\"Saransh Restaurant\", font=\"times 28 bold\")label8.place(x=350, y=20, anchor=\"center\") # Menu Cardlabel1 = Label(window, text=\"Menu\", font=\"times 28 bold\")label1.place(x=520, y=70) label2 = Label(window, text=\"Aloo Paratha Rs 30\", font=\"times 18\")label2.place(x=450, y=120) label3 = Label(window, text=\"Samosa Rs 5\", font=\"times 18\")label3.place(x=450, y=150) label4 = Label(window, text=\"Pizza Rs 150\", font=\"times 18\")label4.place(x=450, y=180) label5 = Label(window, text=\"Chilli Potato Rs 50\", font=\"times 18\")label5.place(x=450, y=210) label6 = Label(window, text=\"Chowmein Rs 70\", font=\"times 18\")label6.place(x=450, y=240) label7 = Label(window, text=\"Gulab Jamun Rs 35\", font=\"times 18\")label7.place(x=450, y=270) # closing the main loopwindow.mainloop()", "e": 3263, "s": 2334, "text": null }, { "code": null, "e": 3273, "s": 3263, "text": "Output: " }, { "code": null, "e": 3308, "s": 3273, "text": "Step 5: Adding the billing section" }, { "code": null, "e": 3564, "s": 3308, "text": "Now we will add the billing section by using the same label widget and the entry widget. The Entry Widget is a Tkinter Widget used to Enter or display a single line of text. Also, Label.place(x,y) indicates the position of the label in the tkinter window." }, { "code": null, "e": 3606, "s": 3564, "text": "Syntax: entry = tk.Entry(parent, options)" }, { "code": null, "e": 3620, "s": 3606, "text": "Parameters: " }, { "code": null, "e": 3662, "s": 3620, "text": "parent: This represents the parent window" }, { "code": null, "e": 3736, "s": 3662, "text": "options: These options can be used as key-value pairs separated by commas" }, { "code": null, "e": 3744, "s": 3736, "text": "Python3" }, { "code": "#------billing section---------label9=Label(window,text=\"Select the items\", font=\"times 18\")label9.place(x=115,y=70) label10=Label(window,text=\"Aloo Paratha\", font=\"times 18\")label10.place(x=20,y=120) e1=Entry(window)e1.place(x=20,y=150) label11=Label(window,text=\"Samosa\", font=\"times 18\")label11.place(x=20,y=200) e2=Entry(window)e2.place(x=20,y=230) label12=Label(window,text=\"Pizza\", font=\"times 18\")label12.place(x=20,y=280) e3=Entry(window)e3.place(x=20,y=310) label13=Label(window,text=\"Chilli Potato\", font=\"times 18\")label13.place(x=20,y=360) e4=Entry(window)e4.place(x=20,y=390) label14=Label(window,text=\"Chowmein\", font=\"times 18\")label14.place(x=250,y=120) e5=Entry(window)e5.place(x=250,y=150) label15=Label(window,text=\"Gulab Jamun\", font=\"times 18\")label15.place(x=250,y=200) e6=Entry(window)e6.place(x=250,y=230) # closing the main loopwindow.mainloop() ", "e": 4719, "s": 3744, "text": null }, { "code": null, "e": 4728, "s": 4719, "text": "Output: " }, { "code": null, "e": 4783, "s": 4728, "text": "Step 6: Calculating the bill and refreshing the window" }, { "code": null, "e": 5774, "s": 4783, "text": "After that, we have to add the calculate function which will get executed every second. In the calculate function we have to do simple math where if e.get() returns an empty string then it means that there’s no quantity selected for that particular food, else if there’s any value present in the e.get() then since it is of string type we convert it to int type and multiply this quantity of food with the price of that food. The food variable along with its quantity and price is kept in a dictionary. We look for every key in the dictionary and accordingly increment our ‘total’ variable. After that, we make another label where we use the total variable’s value to display the total amount of foods ordered. Then we made a command that after every 1000 milliseconds we refresh the window to again calculate the total amount of foods ordered which will update our GUI. Also, the total amount label gets updated by destroying the previous one and updating it with a new one every second. " }, { "code": null, "e": 5782, "s": 5774, "text": "Python3" }, { "code": "# function to calculate the# price of all the orders def calculate(): # dic for storing the food quantity and price dic = {'aloo_partha': [e1, 30], 'samosa': [e2, 5], 'pizza': [e3, 150], 'chilli_potato': [e4, 50], 'chowmein': [e5, 70], 'gulab_jamun': [e6, 35]} total = 0 for key, val in dic.items(): if val[0].get() != \"\": total += int(val[0].get())*val[1] label16 = Label(window, text=\"Your Total Bill is - \"+str(total), font=\"times 18\") # position label16.place(x=20, y=490) # it will update the label with a new one label16.after(1000, label16.destroy) # refreshing the window window.after(1000, calculate) # execute calculate function after 1 secondwindow.after(1000, calculate)window.mainloop()", "e": 6642, "s": 5782, "text": null }, { "code": null, "e": 6651, "s": 6642, "text": "Output: " }, { "code": null, "e": 6685, "s": 6651, "text": "Below is the full implementation:" }, { "code": null, "e": 6693, "s": 6685, "text": "Python3" }, { "code": "# import tkinter modulefrom tkinter import * # make a windowwindow = Tk() # specify it's sizewindow.geometry(\"700x600\") # take a image for backgroundbg = PhotoImage(file='bg.png') # label it in the backgroundlabel17 = Label(window, image=bg) # position the image as welllabel17.place(x=0, y=0) # function to calculate the# price of all the ordersdef calculate(): # dic for storing the # food quantity and price dic = {'aloo_partha': [e1, 30], 'samosa': [e2, 5], 'pizza': [e3, 150], 'chilli_potato': [e4, 50], 'chowmein': [e5, 70], 'gulab_jamun': [e6, 35]} total = 0 for key, val in dic.items(): if val[0].get() != \"\": total += int(val[0].get())*val[1] label16 = Label(window, text=\"Your Total Bill is - \"+str(total), font=\"times 18\") # position it label16.place(x=20, y=490) label16.after(1000, label16.destroy) window.after(1000, calculate) label8 = Label(window, text=\"Saransh Restaurant\", font=\"times 28 bold\")label8.place(x=350, y=20, anchor=\"center\") label1 = Label(window, text=\"Menu\", font=\"times 28 bold\") label1.place(x=520, y=70) label2 = Label(window, text=\"Aloo Paratha \\Rs 30\", font=\"times 18\") label2.place(x=450, y=120) label3 = Label(window, text=\"Samosa \\Rs 5\", font=\"times 18\") label3.place(x=450, y=150) label4 = Label(window, text=\"Pizza \\Rs 150\", font=\"times 18\")label4.place(x=450, y=180) label5 = Label(window, text=\"Chilli Potato \\Rs 50\", font=\"times 18\") label5.place(x=450, y=210) label6 = Label(window, text=\"Chowmein \\Rs 70\", font=\"times 18\") label6.place(x=450, y=240) label7 = Label(window, text=\"Gulab Jamun \\Rs 35\", font=\"times 18\") label7.place(x=450, y=270) # billing sectionlabel9 = Label(window, text=\"Select the items\", font=\"times 18\")label9.place(x=115, y=70) label10 = Label(window, text=\"Aloo Paratha\", font=\"times 18\")label10.place(x=20, y=120) e1 = Entry(window)e1.place(x=20, y=150) label11 = Label(window, text=\"Samosa\", font=\"times 18\")label11.place(x=20, y=200) e2 = Entry(window)e2.place(x=20, y=230) label12 = Label(window, text=\"Pizza\", font=\"times 18\")label12.place(x=20, y=280) e3 = Entry(window)e3.place(x=20, y=310) label13 = Label(window, text=\"Chilli Potato\", font=\"times 18\")label13.place(x=20, y=360) e4 = Entry(window)e4.place(x=20, y=390) label14 = Label(window, text=\"Chowmein\", font=\"times 18\")label14.place(x=250, y=120) e5 = Entry(window)e5.place(x=250, y=150) label15 = Label(window, text=\"Gulab Jamun\", font=\"times 18\") label15.place(x=250, y=200) e6 = Entry(window)e6.place(x=250, y=230) # execute calculate function after 1 secondwindow.after(1000, calculate) # closing the main loopwindow.mainloop()", "e": 9685, "s": 6693, "text": null }, { "code": null, "e": 9693, "s": 9685, "text": "Output:" }, { "code": null, "e": 9710, "s": 9693, "text": "akshaysingh98088" }, { "code": null, "e": 9734, "s": 9710, "text": "Python Tkinter-projects" }, { "code": null, "e": 9750, "s": 9734, "text": "Python-projects" }, { "code": null, "e": 9765, "s": 9750, "text": "Python-tkinter" }, { "code": null, "e": 9772, "s": 9765, "text": "Python" }, { "code": null, "e": 9870, "s": 9772, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9902, "s": 9870, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 9929, "s": 9902, "text": "Python Classes and Objects" }, { "code": null, "e": 9950, "s": 9929, "text": "Python OOPs Concepts" }, { "code": null, "e": 9973, "s": 9950, "text": "Introduction To PYTHON" }, { "code": null, "e": 10029, "s": 9973, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 10060, "s": 10029, "text": "Python | os.path.join() method" }, { "code": null, "e": 10102, "s": 10060, "text": "Check if element exists in list in Python" }, { "code": null, "e": 10144, "s": 10102, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 10183, "s": 10144, "text": "Python | Get unique values from a list" } ]
Neural Network: How Many Layers and Neurons Are Necessary | by Angela Shi | Towards Data Science
When creating Neural Networks, one has to ask: how many hidden layers, and how many neurons in each layer are necessary? When it comes to complex real data, Andrew Ng suggests in his course on Coursera: Improving Deep Neural Networks, that it is a highly iterative process, and so we have to run many tests to find the optimal hyperparameters. But, what is the intuition behind how the hidden layers and neurons impact the final model? Let’s create a dataset using make_circles. from sklearn import datasetsX,y=datasets.make_circles(n_samples=200,shuffle=True, noise=0.1,random_state=None, factor=0.1) And you can visualize the dataset: import matplotlib.pyplot as pltplt.scatter(X[:, 0], X[:, 1], c=y,s=20)plt.axis(‘equal’) Each neuron creates a linear decision boundary. By looking at the dataset, the intuition is to create one layer of 3 neurons. And we should be able to create a perfect classifier. Now, what about only 2 neurons? It seems not enough, and what if we try to add more layers? With these questions, let’s try to do some tests. If we use 3 neurons with the following code: from sklearn.neural_network import MLPClassifierclf =MLPClassifier(solver=’lbfgs’,hidden_layer_sizes(3,),activation=”tanh”,max_iter=1000)clf.fit(X, y)clf.score(X,y) Then we are able to create 3 decision boundaries within the hidden layer. And we can notice that there are an infinite number of possibilities to create these 3 lines (so there are an infinite number of global minimum in the cost function of this neural network). To create the visualization of the decision boundaries of the hidden layer, we can use the coefficients and intercepts of the hidden layer. n_neurons=3xdecseq=np.repeat(np.linspace(-1,1,100),n_neurons).reshape(-1,n_neurons)ydecseq=-(xdecseq*clf.coefs_[0][0]+clf.intercepts_[0])/clf.coefs_[0][1] Then we can plot these three lines with the original dataset: fig, ax = plt.subplots(figsize=(8,8))ax.scatter(X[:, 0], X[:, 1], c=y,s=20)ax.plot(xdecseq[:, 0], ydecseq[:, 0])ax.plot(xdecseq[:, 1], ydecseq[:, 1])ax.plot(xdecseq[:, 2], ydecseq[:, 2])ax.set_xlim(-1.5, 1.5)ax.set_ylim(-1.5, 1.5) If we use only 2 neurons, it is quite easy to see that we will not be able to perfectly classify all observations. Using similar codes, we can plot the following graph with 2 decision boundaries from the hidden layer. What if we create 2 neurons in many hidden layers? To better understand what happened in the first hidden layer with 2 neurons, I created this visualization. Now it is quite clearly that no matter how many layers you add, you will never to able to classify the data in the red circle below. You can test yourself: you can add more layers in the argument hidden_layer_sizes. For example (2,3,2) means 3 hidden layers with 2, 3, and 2 neurons for each. from sklearn.neural_network import MLPClassifierclf = MLPClassifier(solver=’lbfgs’,hidden_layer_sizes=(2,3,2),activation=”tanh”,max_iter=1000)clf.fit(X, y)clf.score(X,y) From this simple example, we can end with this intuition: The number of neurons in the first hidden layer creates as many linear decision boundaries to classify the original data. It is not helpful (in theory) to create a deeper neural network if the first layer doesn’t contain the necessary number of neurons. If you want to see other animations to understand how neural networks work, you can also read this article.
[ { "code": null, "e": 293, "s": 172, "text": "When creating Neural Networks, one has to ask: how many hidden layers, and how many neurons in each layer are necessary?" }, { "code": null, "e": 516, "s": 293, "text": "When it comes to complex real data, Andrew Ng suggests in his course on Coursera: Improving Deep Neural Networks, that it is a highly iterative process, and so we have to run many tests to find the optimal hyperparameters." }, { "code": null, "e": 608, "s": 516, "text": "But, what is the intuition behind how the hidden layers and neurons impact the final model?" }, { "code": null, "e": 651, "s": 608, "text": "Let’s create a dataset using make_circles." }, { "code": null, "e": 774, "s": 651, "text": "from sklearn import datasetsX,y=datasets.make_circles(n_samples=200,shuffle=True, noise=0.1,random_state=None, factor=0.1)" }, { "code": null, "e": 809, "s": 774, "text": "And you can visualize the dataset:" }, { "code": null, "e": 897, "s": 809, "text": "import matplotlib.pyplot as pltplt.scatter(X[:, 0], X[:, 1], c=y,s=20)plt.axis(‘equal’)" }, { "code": null, "e": 1169, "s": 897, "text": "Each neuron creates a linear decision boundary. By looking at the dataset, the intuition is to create one layer of 3 neurons. And we should be able to create a perfect classifier. Now, what about only 2 neurons? It seems not enough, and what if we try to add more layers?" }, { "code": null, "e": 1219, "s": 1169, "text": "With these questions, let’s try to do some tests." }, { "code": null, "e": 1264, "s": 1219, "text": "If we use 3 neurons with the following code:" }, { "code": null, "e": 1429, "s": 1264, "text": "from sklearn.neural_network import MLPClassifierclf =MLPClassifier(solver=’lbfgs’,hidden_layer_sizes(3,),activation=”tanh”,max_iter=1000)clf.fit(X, y)clf.score(X,y)" }, { "code": null, "e": 1693, "s": 1429, "text": "Then we are able to create 3 decision boundaries within the hidden layer. And we can notice that there are an infinite number of possibilities to create these 3 lines (so there are an infinite number of global minimum in the cost function of this neural network)." }, { "code": null, "e": 1833, "s": 1693, "text": "To create the visualization of the decision boundaries of the hidden layer, we can use the coefficients and intercepts of the hidden layer." }, { "code": null, "e": 1988, "s": 1833, "text": "n_neurons=3xdecseq=np.repeat(np.linspace(-1,1,100),n_neurons).reshape(-1,n_neurons)ydecseq=-(xdecseq*clf.coefs_[0][0]+clf.intercepts_[0])/clf.coefs_[0][1]" }, { "code": null, "e": 2050, "s": 1988, "text": "Then we can plot these three lines with the original dataset:" }, { "code": null, "e": 2281, "s": 2050, "text": "fig, ax = plt.subplots(figsize=(8,8))ax.scatter(X[:, 0], X[:, 1], c=y,s=20)ax.plot(xdecseq[:, 0], ydecseq[:, 0])ax.plot(xdecseq[:, 1], ydecseq[:, 1])ax.plot(xdecseq[:, 2], ydecseq[:, 2])ax.set_xlim(-1.5, 1.5)ax.set_ylim(-1.5, 1.5)" }, { "code": null, "e": 2396, "s": 2281, "text": "If we use only 2 neurons, it is quite easy to see that we will not be able to perfectly classify all observations." }, { "code": null, "e": 2499, "s": 2396, "text": "Using similar codes, we can plot the following graph with 2 decision boundaries from the hidden layer." }, { "code": null, "e": 2657, "s": 2499, "text": "What if we create 2 neurons in many hidden layers? To better understand what happened in the first hidden layer with 2 neurons, I created this visualization." }, { "code": null, "e": 2790, "s": 2657, "text": "Now it is quite clearly that no matter how many layers you add, you will never to able to classify the data in the red circle below." }, { "code": null, "e": 2950, "s": 2790, "text": "You can test yourself: you can add more layers in the argument hidden_layer_sizes. For example (2,3,2) means 3 hidden layers with 2, 3, and 2 neurons for each." }, { "code": null, "e": 3120, "s": 2950, "text": "from sklearn.neural_network import MLPClassifierclf = MLPClassifier(solver=’lbfgs’,hidden_layer_sizes=(2,3,2),activation=”tanh”,max_iter=1000)clf.fit(X, y)clf.score(X,y)" }, { "code": null, "e": 3178, "s": 3120, "text": "From this simple example, we can end with this intuition:" }, { "code": null, "e": 3300, "s": 3178, "text": "The number of neurons in the first hidden layer creates as many linear decision boundaries to classify the original data." }, { "code": null, "e": 3432, "s": 3300, "text": "It is not helpful (in theory) to create a deeper neural network if the first layer doesn’t contain the necessary number of neurons." } ]
How to join two Arrays using STL in C++? - GeeksforGeeks
19 Mar, 2019 Given two arrays, join these two arrays using STL in C++. Example: Input:arr1[] = {1, 45, 54, 71, 76, 12},arr2[] = {1, 7, 5, 4, 6, 12}Output: {1, 4, 5, 6, 7, 12, 45, 54, 71, 76} Input:arr1[] = {1, 7, 5, 4, 6, 12},arr2[] = {10, 12, 11}Output: {1, 4, 5, 6, 7, 10, 11, 12} Approach: Joining can be done with the help of set_union() function provided in STL. Syntax: set_union (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result); Below is the implementation of the above approach: // C++ program to join two Arrays// using set_union() in STL #include <bits/stdc++.h>using namespace std; int main(){ // Get the array int arr1[] = { 1, 45, 54, 71, 76, 12 }; int arr2[] = { 1, 7, 5, 4, 6, 12 }; // Compute the sizes int n1 = sizeof(arr1) / sizeof(arr1[0]); int n2 = sizeof(arr2) / sizeof(arr2[0]); // Sort the arrays sort(arr1, arr1 + n1); sort(arr2, arr2 + n2); // Print the array cout << "First Array: "; for (int i = 0; i < n1; i++) cout << arr1[i] << " "; cout << endl; cout << "Second Array: "; for (int i = 0; i < n2; i++) cout << arr2[i] << " "; cout << endl; // Initialise a vector // to store the merged values // and an iterator // to traverse this vector vector<int> v(n1 + n2); vector<int>::iterator it, st; it = set_union(arr1, arr1 + n1, arr2, arr2 + n2, v.begin()); // Print the merged array cout << "\nAfter joining:\n"; for (st = v.begin(); st != it; ++st) cout << *st << ", "; cout << '\n'; return 0;} First Array: 1 12 45 54 71 76 Second Array: 1 4 5 6 7 12 After joining: 1, 4, 5, 6, 7, 12, 45, 54, 71, 76, cpp-array STL C++ C++ Programs STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Iterators in C++ STL Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Inline Functions in C++ Header files in C/C++ and its uses How to return multiple values from a function in C or C++? C++ Program for QuickSort C++ program for hashing with chaining delete keyword in C++
[ { "code": null, "e": 23732, "s": 23704, "text": "\n19 Mar, 2019" }, { "code": null, "e": 23790, "s": 23732, "text": "Given two arrays, join these two arrays using STL in C++." }, { "code": null, "e": 23799, "s": 23790, "text": "Example:" }, { "code": null, "e": 23910, "s": 23799, "text": "Input:arr1[] = {1, 45, 54, 71, 76, 12},arr2[] = {1, 7, 5, 4, 6, 12}Output: {1, 4, 5, 6, 7, 12, 45, 54, 71, 76}" }, { "code": null, "e": 24002, "s": 23910, "text": "Input:arr1[] = {1, 7, 5, 4, 6, 12},arr2[] = {10, 12, 11}Output: {1, 4, 5, 6, 7, 10, 11, 12}" }, { "code": null, "e": 24087, "s": 24002, "text": "Approach: Joining can be done with the help of set_union() function provided in STL." }, { "code": null, "e": 24095, "s": 24087, "text": "Syntax:" }, { "code": null, "e": 24243, "s": 24095, "text": "set_union (InputIterator1 first1, InputIterator1 last1,\n InputIterator2 first2, InputIterator2 last2,\n OutputIterator result);\n" }, { "code": null, "e": 24294, "s": 24243, "text": "Below is the implementation of the above approach:" }, { "code": "// C++ program to join two Arrays// using set_union() in STL #include <bits/stdc++.h>using namespace std; int main(){ // Get the array int arr1[] = { 1, 45, 54, 71, 76, 12 }; int arr2[] = { 1, 7, 5, 4, 6, 12 }; // Compute the sizes int n1 = sizeof(arr1) / sizeof(arr1[0]); int n2 = sizeof(arr2) / sizeof(arr2[0]); // Sort the arrays sort(arr1, arr1 + n1); sort(arr2, arr2 + n2); // Print the array cout << \"First Array: \"; for (int i = 0; i < n1; i++) cout << arr1[i] << \" \"; cout << endl; cout << \"Second Array: \"; for (int i = 0; i < n2; i++) cout << arr2[i] << \" \"; cout << endl; // Initialise a vector // to store the merged values // and an iterator // to traverse this vector vector<int> v(n1 + n2); vector<int>::iterator it, st; it = set_union(arr1, arr1 + n1, arr2, arr2 + n2, v.begin()); // Print the merged array cout << \"\\nAfter joining:\\n\"; for (st = v.begin(); st != it; ++st) cout << *st << \", \"; cout << '\\n'; return 0;}", "e": 25391, "s": 24294, "text": null }, { "code": null, "e": 25502, "s": 25391, "text": "First Array: 1 12 45 54 71 76 \nSecond Array: 1 4 5 6 7 12 \n\nAfter joining:\n1, 4, 5, 6, 7, 12, 45, 54, 71, 76,\n" }, { "code": null, "e": 25512, "s": 25502, "text": "cpp-array" }, { "code": null, "e": 25516, "s": 25512, "text": "STL" }, { "code": null, "e": 25520, "s": 25516, "text": "C++" }, { "code": null, "e": 25533, "s": 25520, "text": "C++ Programs" }, { "code": null, "e": 25537, "s": 25533, "text": "STL" }, { "code": null, "e": 25541, "s": 25537, "text": "CPP" }, { "code": null, "e": 25639, "s": 25541, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25648, "s": 25639, "text": "Comments" }, { "code": null, "e": 25661, "s": 25648, "text": "Old Comments" }, { "code": null, "e": 25682, "s": 25661, "text": "Iterators in C++ STL" }, { "code": null, "e": 25710, "s": 25682, "text": "Operator Overloading in C++" }, { "code": null, "e": 25730, "s": 25710, "text": "Polymorphism in C++" }, { "code": null, "e": 25763, "s": 25730, "text": "Friend class and function in C++" }, { "code": null, "e": 25787, "s": 25763, "text": "Inline Functions in C++" }, { "code": null, "e": 25822, "s": 25787, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 25881, "s": 25822, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 25907, "s": 25881, "text": "C++ Program for QuickSort" }, { "code": null, "e": 25945, "s": 25907, "text": "C++ program for hashing with chaining" } ]
How to use subSet() method of Java NavigableSet Class
Use the subset() method to get elements from a limit. At first, create NavigableSet and add elements − NavigableSet<Integer> set = new TreeSet<>(); set.add(10); set.add(25); set.add(40); set.add(55); set.add(70); set.add(85); Now, use the subset() method − set.subSet(40, 85) The following is an example to implement subset() method of Java NaviagbleSet class − Live Demo import java.util.NavigableSet; import java.util.TreeSet; public class Demo { public static void main(String[] args) { NavigableSet<Integer> set = new TreeSet<>(); set.add(10); set.add(25); set.add(40); set.add(55); set.add(70); set.add(85); set.add(100); System.out.println("Returned Value = " + set.subSet(40, 85)); } } Returned Value = [40, 55, 70]
[ { "code": null, "e": 1165, "s": 1062, "text": "Use the subset() method to get elements from a limit. At first, create NavigableSet and add elements −" }, { "code": null, "e": 1288, "s": 1165, "text": "NavigableSet<Integer> set = new TreeSet<>();\nset.add(10);\nset.add(25);\nset.add(40);\nset.add(55);\nset.add(70);\nset.add(85);" }, { "code": null, "e": 1319, "s": 1288, "text": "Now, use the subset() method −" }, { "code": null, "e": 1338, "s": 1319, "text": "set.subSet(40, 85)" }, { "code": null, "e": 1424, "s": 1338, "text": "The following is an example to implement subset() method of Java NaviagbleSet class −" }, { "code": null, "e": 1435, "s": 1424, "text": " Live Demo" }, { "code": null, "e": 1816, "s": 1435, "text": "import java.util.NavigableSet;\nimport java.util.TreeSet;\npublic class Demo {\n public static void main(String[] args) {\n NavigableSet<Integer> set = new TreeSet<>();\n set.add(10);\n set.add(25);\n set.add(40);\n set.add(55);\n set.add(70);\n set.add(85);\n set.add(100);\n System.out.println(\"Returned Value = \" + set.subSet(40, 85));\n }\n}" }, { "code": null, "e": 1846, "s": 1816, "text": "Returned Value = [40, 55, 70]" } ]
Spring Boot Hazelcast Cache Example OnlineTutorialsPoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws Hazelcast is an in-memory distributed caching mechanism. In this tutorial, I am going to show you how to enable the Spring Boot Hazelcast cache. Hazelcast is an in-memory caching mechanism provided by the spring boot. Spring boot auto-configures the Hazelcast instance if the hazelcast is available in our application’s classpath and the required configuration is available. Here I am going to create a simple spring boot rest service to read Items from the database using the hazelcast cache. Spring Boot 2.0.5 RELEASE Hazelcast Spring Boot JDBC MySQL Java 8 Add the below hazelcast dependencies in pom.xml <dependency> <groupId>com.hazelcast</groupId> <artifactId>hazelcast</artifactId> </dependency> <dependency> <groupId>com.hazelcast</groupId> <artifactId>hazelcast-spring</artifactId> </dependency> Complete pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.onlinetutorialspoint</groupId> <artifactId>SpringBoot_Hazelcast_Cache_Example</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>SpringBoot_Hazelcast_Cache_Example</name> <description>Spring Boot Hazelcast Cache Example</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.5.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.hazelcast</groupId> <artifactId>hazelcast</artifactId> </dependency> <dependency> <groupId>com.hazelcast</groupId> <artifactId>hazelcast-spring</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Database configuration details. server.port=8080 spring.datasource.driver-class-name: com.mysql.jdbc.Driver spring.datasource.url: jdbc:mysql://localhost:3306/otp spring.datasource.username: root spring.datasource.password: Chandu@123 Hazelcast configuration. Creating a Hazelcast Config bean with the required configuration. package com.onlinetutorialspoint.config; import com.hazelcast.config.Config; import com.hazelcast.config.EvictionPolicy; import com.hazelcast.config.MapConfig; import com.hazelcast.config.MaxSizeConfig; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class HazelcastCacheConfig { @Bean public Config hazelcastConfig(){ return new Config().setInstanceName("hazelcast-instance") .addMapConfig(new MapConfig().setName("itemCache") .setMaxSizeConfig(new MaxSizeConfig(300,MaxSizeConfig.MaxSizePolicy.FREE_HEAP_SIZE)) .setEvictionPolicy(EvictionPolicy.LRU) .setTimeToLiveSeconds(2000)); } } Mapping the itemCache to hazelCache config and giving eviction policy as LRU (Last Recently Used). Preparing ItemCache component. package com.onlinetutorialspoint.cache; import com.onlinetutorialspoint.model.Item; import com.onlinetutorialspoint.repo.ItemRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Component; @Component public class ItemCache { @Autowired ItemRepository itemRepo; @Cacheable(value="itemCache", key="#id") public Item getItem(int id){ System.out.println("In ItemCache Component.."); Item item = null; try{ item = itemRepo.getItem(id); Thread.sleep(2000); }catch(Exception e){ e.printStackTrace(); } return item; } @CacheEvict(value="itemCache",key = "#id") public int deleteItem(int id){ System.out.println("In ItemCache Component.."); return itemRepo.deleteItem(id); } @CachePut(value="itemCache") public void updateItem(Item item){ System.out.println("In ItemCache Component.."); itemRepo.updateItem(item); } } @Cachable: Is used to adding the cache behavior to a method. We can also give the name to it, where the cache results would be saved. @CacheEvict: Is used to remove the one or more cached values. allEntries=true parameter allows us to remove all entries from the cache. @CachePut: Is used to update the cached value. Creating an Item model package com.onlinetutorialspoint.model; import java.io.Serializable; public class Item implements Serializable { private int id; private String name; private String category; public Item() { } public Item(int id, String name, String category) { this.id = id; this.name = name; this.category = category; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } } Creating Item Repository responsible to read items from MySQL database using JdbcTemplate. package com.onlinetutorialspoint.repo; import com.onlinetutorialspoint.model.Item; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; @Repository public class ItemRepository { @Autowired JdbcTemplate template; /*Getting a specific item by item id from table*/ public Item getItem(int itemId){ System.out.println("Reading Item From Repository.."); String query = "SELECT * FROM ITEM WHERE ID=?"; return template.queryForObject(query,new Object[]{itemId},new BeanPropertyRowMapper<>(Item.class)); } /*delete an item from database*/ public int deleteItem(int id){ String query = "DELETE FROM ITEM WHERE ID =?"; int size = template.update(query,id); return size; } /*update an item from database*/ public void updateItem(Item item){ String query = "UPDATE ITEM SET name=?, category=? WHERE id =?"; template.update(query, new Object[] { item.getName(),item.getCategory(), Integer.valueOf(item.getId()) }); } } Creating rest endpoints to access item data package com.onlinetutorialspoint.controller; import com.onlinetutorialspoint.cache.ItemCache; import com.onlinetutorialspoint.model.Item; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController public class ItemController { @Autowired ItemCache itemCache; @GetMapping("/item/{itemId}") @ResponseBody public ResponseEntity<Item> getItem(@PathVariable int itemId){ System.out.println("RestController.."); long start = System.currentTimeMillis(); Item item = itemCache.getItem(itemId); long end = System.currentTimeMillis(); System.out.println("Took : " + ((end - start) / 1000+" sec.")); return new ResponseEntity<Item>(item, HttpStatus.OK); } @PutMapping("/updateItem") @ResponseBody public ResponseEntity<Item> updateItem(@RequestBody Item item){ if(item != null){ itemCache.updateItem(item); } return new ResponseEntity<Item>(item, HttpStatus.OK); } @DeleteMapping("/delete/{id}") @ResponseBody public ResponseEntity<Void> deleteItem(@PathVariable int id){ itemCache.deleteItem(id); return new ResponseEntity<Void>(HttpStatus.ACCEPTED); } } Main class with the @EnablingCache annotation to enable the cache. package com.onlinetutorialspoint; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; @SpringBootApplication @EnableCaching public class SpringBootHazelcastCacheExampleApplication { public static void main(String[] args) { SpringApplication.run(SpringBootHazelcastCacheExampleApplication.class, args); } } mvn spring-boot:run . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.0.5.RELEASE) 2018-10-14 17:43:02.414 INFO 5196 --- [ main] ringBootHazelcastCacheExampleApplication : Starting SpringBootHazelcastCacheExampleApplication on DESKTOP-RN4SMHT with PID 5196 (E:\work\SpringBoot_Hazelcast_Cache_Example\target\classes started by Lenovo in E:\work\SpringBoot_Hazelcast_Cache_Example) 2018-10-14 17:43:02.414 INFO 5196 --- [ main] ringBootHazelcastCacheExampleApplication : No active profile set, falling back to default profiles: default ..... ..... Console logs: RestController.. In ItemCache Component.. Reading Item From Repository.. Took : 3 sec. For the first time when we access the item 1, it took 3 Sec to get the data from the database. Accessing the same item again and observe the log statements. RestController.. Took : 0 sec. For the second time, it took zero seconds to get the same data because for this time the data came from the hazelCast cache. Happy Learning 🙂 SpringBoot_Hazelcast_Cache_Example File size: 85 KB Downloads: 794 Spring Boot MockMvc JUnit Test Example Spring Boot In Memory Basic Authentication Security Spring Boot Actuator Database Health Check Sending Spring Boot Kafka JSON Message to Kafka Topic Spring Boot Kafka Consume JSON Messages Example Spring Boot Lazy Loading Beans Example Spring Boot H2 Database + JDBC Template Example Spring Boot Redis Data Example CRUD Operations Spring Boot RabbitMQ Consumer Messages Example Spring Boot Redis Cache Example – Redis Server Spring Boot MongoDB + Spring Data Example Simple Spring Boot Example How To Change Spring Boot Context Path Spring Boot How to change the Tomcat to Jetty Server Spring Boot Validation Login Form Example Spring Boot MockMvc JUnit Test Example Spring Boot In Memory Basic Authentication Security Spring Boot Actuator Database Health Check Sending Spring Boot Kafka JSON Message to Kafka Topic Spring Boot Kafka Consume JSON Messages Example Spring Boot Lazy Loading Beans Example Spring Boot H2 Database + JDBC Template Example Spring Boot Redis Data Example CRUD Operations Spring Boot RabbitMQ Consumer Messages Example Spring Boot Redis Cache Example – Redis Server Spring Boot MongoDB + Spring Data Example Simple Spring Boot Example How To Change Spring Boot Context Path Spring Boot How to change the Tomcat to Jetty Server Spring Boot Validation Login Form Example Δ Spring Boot – Hello World Spring Boot – MVC Example Spring Boot- Change Context Path Spring Boot – Change Tomcat Port Number Spring Boot – Change Tomcat to Jetty Server Spring Boot – Tomcat session timeout Spring Boot – Enable Random Port Spring Boot – Properties File Spring Boot – Beans Lazy Loading Spring Boot – Set Favicon image Spring Boot – Set Custom Banner Spring Boot – Set Application TimeZone Spring Boot – Send Mail Spring Boot – FileUpload Ajax Spring Boot – Actuator Spring Boot – Actuator Database Health Check Spring Boot – Swagger Spring Boot – Enable CORS Spring Boot – External Apache ActiveMQ Setup Spring Boot – Inmemory Apache ActiveMq Spring Boot – Scheduler Job Spring Boot – Exception Handling Spring Boot – Hibernate CRUD Spring Boot – JPA Integration CRUD Spring Boot – JPA DataRest CRUD Spring Boot – JdbcTemplate CRUD Spring Boot – Multiple Data Sources Config Spring Boot – JNDI Configuration Spring Boot – H2 Database CRUD Spring Boot – MongoDB CRUD Spring Boot – Redis Data CRUD Spring Boot – MVC Login Form Validation Spring Boot – Custom Error Pages Spring Boot – iText PDF Spring Boot – Enable SSL (HTTPs) Spring Boot – Basic Authentication Spring Boot – In Memory Basic Authentication Spring Boot – Security MySQL Database Integration Spring Boot – Redis Cache – Redis Server Spring Boot – Hazelcast Cache Spring Boot – EhCache Spring Boot – Kafka Producer Spring Boot – Kafka Consumer Spring Boot – Kafka JSON Message to Kafka Topic Spring Boot – RabbitMQ Publisher Spring Boot – RabbitMQ Consumer Spring Boot – SOAP Consumer Spring Boot – Soap WebServices Spring Boot – Batch Csv to Database Spring Boot – Eureka Server Spring Boot – MockMvc JUnit Spring Boot – Docker Deployment
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 543, "s": 398, "text": "Hazelcast is an in-memory distributed caching mechanism. In this tutorial, I am going to show you how to enable the Spring Boot Hazelcast cache." }, { "code": null, "e": 773, "s": 543, "text": "Hazelcast is an in-memory caching mechanism provided by the spring boot. Spring boot auto-configures the Hazelcast instance if the hazelcast is available in our application’s classpath and the required configuration is available." }, { "code": null, "e": 892, "s": 773, "text": "Here I am going to create a simple spring boot rest service to read Items from the database using the hazelcast cache." }, { "code": null, "e": 918, "s": 892, "text": "Spring Boot 2.0.5 RELEASE" }, { "code": null, "e": 928, "s": 918, "text": "Hazelcast" }, { "code": null, "e": 945, "s": 928, "text": "Spring Boot JDBC" }, { "code": null, "e": 951, "s": 945, "text": "MySQL" }, { "code": null, "e": 958, "s": 951, "text": "Java 8" }, { "code": null, "e": 1006, "s": 958, "text": "Add the below hazelcast dependencies in pom.xml" }, { "code": null, "e": 1211, "s": 1006, "text": "<dependency>\n <groupId>com.hazelcast</groupId>\n <artifactId>hazelcast</artifactId>\n</dependency>\n<dependency>\n <groupId>com.hazelcast</groupId>\n <artifactId>hazelcast-spring</artifactId>\n</dependency>" }, { "code": null, "e": 1228, "s": 1211, "text": "Complete pom.xml" }, { "code": null, "e": 3146, "s": 1228, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n\n <groupId>com.onlinetutorialspoint</groupId>\n <artifactId>SpringBoot_Hazelcast_Cache_Example</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>jar</packaging>\n <name>SpringBoot_Hazelcast_Cache_Example</name>\n <description>Spring Boot Hazelcast Cache Example</description>\n\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>2.0.5.RELEASE</version>\n <relativePath/> <!-- lookup parent from repository -->\n </parent>\n\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n <java.version>1.8</java.version>\n </properties>\n <dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n </dependency>\n <dependency>\n <groupId>com.hazelcast</groupId>\n <artifactId>hazelcast</artifactId>\n </dependency>\n <dependency>\n <groupId>com.hazelcast</groupId>\n <artifactId>hazelcast-spring</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-jdbc</artifactId>\n </dependency>\n <dependency>\n <groupId>mysql</groupId>\n <artifactId>mysql-connector-java</artifactId>\n <scope>runtime</scope>\n </dependency>\n </dependencies>\n <build>\n <plugins>\n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n </plugin>\n </plugins>\n </build>\n</project>\n" }, { "code": null, "e": 3178, "s": 3146, "text": "Database configuration details." }, { "code": null, "e": 3381, "s": 3178, "text": "server.port=8080\nspring.datasource.driver-class-name: com.mysql.jdbc.Driver\nspring.datasource.url: jdbc:mysql://localhost:3306/otp\nspring.datasource.username: root\nspring.datasource.password: Chandu@123" }, { "code": null, "e": 3406, "s": 3381, "text": "Hazelcast configuration." }, { "code": null, "e": 3472, "s": 3406, "text": "Creating a Hazelcast Config bean with the required configuration." }, { "code": null, "e": 4233, "s": 3472, "text": "package com.onlinetutorialspoint.config;\n\nimport com.hazelcast.config.Config;\nimport com.hazelcast.config.EvictionPolicy;\nimport com.hazelcast.config.MapConfig;\nimport com.hazelcast.config.MaxSizeConfig;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\n\n@Configuration\npublic class HazelcastCacheConfig {\n\n @Bean\n public Config hazelcastConfig(){\n return new Config().setInstanceName(\"hazelcast-instance\")\n .addMapConfig(new MapConfig().setName(\"itemCache\")\n .setMaxSizeConfig(new MaxSizeConfig(300,MaxSizeConfig.MaxSizePolicy.FREE_HEAP_SIZE))\n .setEvictionPolicy(EvictionPolicy.LRU)\n .setTimeToLiveSeconds(2000));\n }\n\n}\n" }, { "code": null, "e": 4332, "s": 4233, "text": "Mapping the itemCache to hazelCache config and giving eviction policy as LRU (Last Recently Used)." }, { "code": null, "e": 4363, "s": 4332, "text": "Preparing ItemCache component." }, { "code": null, "e": 5564, "s": 4363, "text": "package com.onlinetutorialspoint.cache;\n\nimport com.onlinetutorialspoint.model.Item;\nimport com.onlinetutorialspoint.repo.ItemRepository;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.cache.annotation.CacheEvict;\nimport org.springframework.cache.annotation.CachePut;\nimport org.springframework.cache.annotation.Cacheable;\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class ItemCache {\n\n @Autowired\n ItemRepository itemRepo;\n\n @Cacheable(value=\"itemCache\", key=\"#id\")\n public Item getItem(int id){\n System.out.println(\"In ItemCache Component..\");\n Item item = null;\n try{\n item = itemRepo.getItem(id);\n Thread.sleep(2000);\n }catch(Exception e){\n e.printStackTrace();\n }\n return item;\n }\n\n @CacheEvict(value=\"itemCache\",key = \"#id\")\n public int deleteItem(int id){\n System.out.println(\"In ItemCache Component..\");\n return itemRepo.deleteItem(id);\n }\n\n @CachePut(value=\"itemCache\")\n public void updateItem(Item item){\n System.out.println(\"In ItemCache Component..\");\n itemRepo.updateItem(item);\n }\n}\n" }, { "code": null, "e": 5881, "s": 5564, "text": "@Cachable: Is used to adding the cache behavior to a method. We can also give the name to it, where the cache results would be saved.\n@CacheEvict: Is used to remove the one or more cached values. allEntries=true parameter allows us to remove all entries from the cache.\n@CachePut: Is used to update the cached value." }, { "code": null, "e": 5904, "s": 5881, "text": "Creating an Item model" }, { "code": null, "e": 6664, "s": 5904, "text": "package com.onlinetutorialspoint.model;\n\nimport java.io.Serializable;\n\npublic class Item implements Serializable {\n private int id;\n private String name;\n private String category;\n\n public Item() {\n }\n\n public Item(int id, String name, String category) {\n this.id = id;\n this.name = name;\n this.category = category;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getCategory() {\n return category;\n }\n\n public void setCategory(String category) {\n this.category = category;\n }\n}\n" }, { "code": null, "e": 6755, "s": 6664, "text": "Creating Item Repository responsible to read items from MySQL database using JdbcTemplate." }, { "code": null, "e": 8005, "s": 6755, "text": "package com.onlinetutorialspoint.repo;\n\nimport com.onlinetutorialspoint.model.Item;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.jdbc.core.BeanPropertyRowMapper;\nimport org.springframework.jdbc.core.JdbcTemplate;\nimport org.springframework.stereotype.Repository;\n\n@Repository\npublic class ItemRepository {\n\n @Autowired\n JdbcTemplate template;\n\n /*Getting a specific item by item id from table*/\n public Item getItem(int itemId){\n System.out.println(\"Reading Item From Repository..\");\n String query = \"SELECT * FROM ITEM WHERE ID=?\";\n return template.queryForObject(query,new Object[]{itemId},new BeanPropertyRowMapper<>(Item.class));\n }\n\n /*delete an item from database*/\n public int deleteItem(int id){\n String query = \"DELETE FROM ITEM WHERE ID =?\";\n int size = template.update(query,id);\n return size;\n }\n\n /*update an item from database*/\n public void updateItem(Item item){\n String query = \"UPDATE ITEM SET name=?, category=? WHERE id =?\";\n template.update(query,\n new Object[] {\n item.getName(),item.getCategory(), Integer.valueOf(item.getId())\n });\n }\n\n}\n" }, { "code": null, "e": 8049, "s": 8005, "text": "Creating rest endpoints to access item data" }, { "code": null, "e": 9419, "s": 8049, "text": "package com.onlinetutorialspoint.controller;\n\nimport com.onlinetutorialspoint.cache.ItemCache;\nimport com.onlinetutorialspoint.model.Item;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.*;\n\n@RestController\npublic class ItemController {\n\n @Autowired\n ItemCache itemCache;\n @GetMapping(\"/item/{itemId}\")\n @ResponseBody\n public ResponseEntity<Item> getItem(@PathVariable int itemId){\n System.out.println(\"RestController..\");\n long start = System.currentTimeMillis();\n Item item = itemCache.getItem(itemId);\n long end = System.currentTimeMillis();\n System.out.println(\"Took : \" + ((end - start) / 1000+\" sec.\"));\n return new ResponseEntity<Item>(item, HttpStatus.OK);\n }\n\n @PutMapping(\"/updateItem\")\n @ResponseBody\n public ResponseEntity<Item> updateItem(@RequestBody Item item){\n if(item != null){\n itemCache.updateItem(item);\n }\n return new ResponseEntity<Item>(item, HttpStatus.OK);\n }\n\n @DeleteMapping(\"/delete/{id}\")\n @ResponseBody\n public ResponseEntity<Void> deleteItem(@PathVariable int id){\n itemCache.deleteItem(id);\n return new ResponseEntity<Void>(HttpStatus.ACCEPTED);\n }\n\n}\n" }, { "code": null, "e": 9486, "s": 9419, "text": "Main class with the @EnablingCache annotation to enable the cache." }, { "code": null, "e": 9931, "s": 9486, "text": "package com.onlinetutorialspoint;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.cache.annotation.EnableCaching;\n\n@SpringBootApplication\n@EnableCaching\npublic class SpringBootHazelcastCacheExampleApplication {\n\n public static void main(String[] args) {\n SpringApplication.run(SpringBootHazelcastCacheExampleApplication.class, args);\n }\n}\n" }, { "code": null, "e": 10733, "s": 9931, "text": "mvn spring-boot:run\n\n . ____ _ __ _ _\n /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\\n( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\\n \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )\n ' |____| .__|_| |_|_| |_\\__, | / / / /\n =========|_|==============|___/=/_/_/_/\n :: Spring Boot :: (v2.0.5.RELEASE)\n\n2018-10-14 17:43:02.414 INFO 5196 --- [ main] ringBootHazelcastCacheExampleApplication : Starting SpringBootHazelcastCacheExampleApplication on DESKTOP-RN4SMHT with PID 5196 (E:\\work\\SpringBoot_Hazelcast_Cache_Example\\target\\classes started by Lenovo in E:\\work\\SpringBoot_Hazelcast_Cache_Example)\n2018-10-14 17:43:02.414 INFO 5196 --- [ main] ringBootHazelcastCacheExampleApplication : No active profile set, falling back to default profiles: default\n.....\n.....\n\n" }, { "code": null, "e": 10747, "s": 10733, "text": "Console logs:" }, { "code": null, "e": 10835, "s": 10747, "text": "RestController..\nIn ItemCache Component..\nReading Item From Repository..\nTook : 3 sec.\n" }, { "code": null, "e": 10930, "s": 10835, "text": "For the first time when we access the item 1, it took 3 Sec to get the data from the database." }, { "code": null, "e": 10992, "s": 10930, "text": "Accessing the same item again and observe the log statements." }, { "code": null, "e": 11023, "s": 10992, "text": "RestController..\nTook : 0 sec." }, { "code": null, "e": 11148, "s": 11023, "text": "For the second time, it took zero seconds to get the same data because for this time the data came from the hazelCast cache." }, { "code": null, "e": 11165, "s": 11148, "text": "Happy Learning 🙂" }, { "code": null, "e": 11236, "s": 11165, "text": "\n\nSpringBoot_Hazelcast_Cache_Example\n\nFile size: 85 KB\nDownloads: 794\n" }, { "code": null, "e": 11905, "s": 11236, "text": "\nSpring Boot MockMvc JUnit Test Example\nSpring Boot In Memory Basic Authentication Security\nSpring Boot Actuator Database Health Check\nSending Spring Boot Kafka JSON Message to Kafka Topic\nSpring Boot Kafka Consume JSON Messages Example\nSpring Boot Lazy Loading Beans Example\nSpring Boot H2 Database + JDBC Template Example\nSpring Boot Redis Data Example CRUD Operations\nSpring Boot RabbitMQ Consumer Messages Example\nSpring Boot Redis Cache Example – Redis Server\nSpring Boot MongoDB + Spring Data Example\nSimple Spring Boot Example\nHow To Change Spring Boot Context Path\nSpring Boot How to change the Tomcat to Jetty Server\nSpring Boot Validation Login Form Example\n" }, { "code": null, "e": 11944, "s": 11905, "text": "Spring Boot MockMvc JUnit Test Example" }, { "code": null, "e": 11996, "s": 11944, "text": "Spring Boot In Memory Basic Authentication Security" }, { "code": null, "e": 12039, "s": 11996, "text": "Spring Boot Actuator Database Health Check" }, { "code": null, "e": 12093, "s": 12039, "text": "Sending Spring Boot Kafka JSON Message to Kafka Topic" }, { "code": null, "e": 12141, "s": 12093, "text": "Spring Boot Kafka Consume JSON Messages Example" }, { "code": null, "e": 12180, "s": 12141, "text": "Spring Boot Lazy Loading Beans Example" }, { "code": null, "e": 12228, "s": 12180, "text": "Spring Boot H2 Database + JDBC Template Example" }, { "code": null, "e": 12275, "s": 12228, "text": "Spring Boot Redis Data Example CRUD Operations" }, { "code": null, "e": 12322, "s": 12275, "text": "Spring Boot RabbitMQ Consumer Messages Example" }, { "code": null, "e": 12369, "s": 12322, "text": "Spring Boot Redis Cache Example – Redis Server" }, { "code": null, "e": 12411, "s": 12369, "text": "Spring Boot MongoDB + Spring Data Example" }, { "code": null, "e": 12438, "s": 12411, "text": "Simple Spring Boot Example" }, { "code": null, "e": 12477, "s": 12438, "text": "How To Change Spring Boot Context Path" }, { "code": null, "e": 12530, "s": 12477, "text": "Spring Boot How to change the Tomcat to Jetty Server" }, { "code": null, "e": 12572, "s": 12530, "text": "Spring Boot Validation Login Form Example" }, { "code": null, "e": 12578, "s": 12576, "text": "Δ" }, { "code": null, "e": 12605, "s": 12578, "text": " Spring Boot – Hello World" }, { "code": null, "e": 12632, "s": 12605, "text": " Spring Boot – MVC Example" }, { "code": null, "e": 12666, "s": 12632, "text": " Spring Boot- Change Context Path" }, { "code": null, "e": 12707, "s": 12666, "text": " Spring Boot – Change Tomcat Port Number" }, { "code": null, "e": 12752, "s": 12707, "text": " Spring Boot – Change Tomcat to Jetty Server" }, { "code": null, "e": 12790, "s": 12752, "text": " Spring Boot – Tomcat session timeout" }, { "code": null, "e": 12824, "s": 12790, "text": " Spring Boot – Enable Random Port" }, { "code": null, "e": 12855, "s": 12824, "text": " Spring Boot – Properties File" }, { "code": null, "e": 12889, "s": 12855, "text": " Spring Boot – Beans Lazy Loading" }, { "code": null, "e": 12922, "s": 12889, "text": " Spring Boot – Set Favicon image" }, { "code": null, "e": 12955, "s": 12922, "text": " Spring Boot – Set Custom Banner" }, { "code": null, "e": 12995, "s": 12955, "text": " Spring Boot – Set Application TimeZone" }, { "code": null, "e": 13020, "s": 12995, "text": " Spring Boot – Send Mail" }, { "code": null, "e": 13051, "s": 13020, "text": " Spring Boot – FileUpload Ajax" }, { "code": null, "e": 13075, "s": 13051, "text": " Spring Boot – Actuator" }, { "code": null, "e": 13121, "s": 13075, "text": " Spring Boot – Actuator Database Health Check" }, { "code": null, "e": 13144, "s": 13121, "text": " Spring Boot – Swagger" }, { "code": null, "e": 13171, "s": 13144, "text": " Spring Boot – Enable CORS" }, { "code": null, "e": 13217, "s": 13171, "text": " Spring Boot – External Apache ActiveMQ Setup" }, { "code": null, "e": 13257, "s": 13217, "text": " Spring Boot – Inmemory Apache ActiveMq" }, { "code": null, "e": 13286, "s": 13257, "text": " Spring Boot – Scheduler Job" }, { "code": null, "e": 13320, "s": 13286, "text": " Spring Boot – Exception Handling" }, { "code": null, "e": 13350, "s": 13320, "text": " Spring Boot – Hibernate CRUD" }, { "code": null, "e": 13386, "s": 13350, "text": " Spring Boot – JPA Integration CRUD" }, { "code": null, "e": 13419, "s": 13386, "text": " Spring Boot – JPA DataRest CRUD" }, { "code": null, "e": 13452, "s": 13419, "text": " Spring Boot – JdbcTemplate CRUD" }, { "code": null, "e": 13496, "s": 13452, "text": " Spring Boot – Multiple Data Sources Config" }, { "code": null, "e": 13530, "s": 13496, "text": " Spring Boot – JNDI Configuration" }, { "code": null, "e": 13562, "s": 13530, "text": " Spring Boot – H2 Database CRUD" }, { "code": null, "e": 13590, "s": 13562, "text": " Spring Boot – MongoDB CRUD" }, { "code": null, "e": 13621, "s": 13590, "text": " Spring Boot – Redis Data CRUD" }, { "code": null, "e": 13662, "s": 13621, "text": " Spring Boot – MVC Login Form Validation" }, { "code": null, "e": 13696, "s": 13662, "text": " Spring Boot – Custom Error Pages" }, { "code": null, "e": 13721, "s": 13696, "text": " Spring Boot – iText PDF" }, { "code": null, "e": 13755, "s": 13721, "text": " Spring Boot – Enable SSL (HTTPs)" }, { "code": null, "e": 13791, "s": 13755, "text": " Spring Boot – Basic Authentication" }, { "code": null, "e": 13837, "s": 13791, "text": " Spring Boot – In Memory Basic Authentication" }, { "code": null, "e": 13888, "s": 13837, "text": " Spring Boot – Security MySQL Database Integration" }, { "code": null, "e": 13930, "s": 13888, "text": " Spring Boot – Redis Cache – Redis Server" }, { "code": null, "e": 13961, "s": 13930, "text": " Spring Boot – Hazelcast Cache" }, { "code": null, "e": 13984, "s": 13961, "text": " Spring Boot – EhCache" }, { "code": null, "e": 14014, "s": 13984, "text": " Spring Boot – Kafka Producer" }, { "code": null, "e": 14044, "s": 14014, "text": " Spring Boot – Kafka Consumer" }, { "code": null, "e": 14093, "s": 14044, "text": " Spring Boot – Kafka JSON Message to Kafka Topic" }, { "code": null, "e": 14127, "s": 14093, "text": " Spring Boot – RabbitMQ Publisher" }, { "code": null, "e": 14160, "s": 14127, "text": " Spring Boot – RabbitMQ Consumer" }, { "code": null, "e": 14189, "s": 14160, "text": " Spring Boot – SOAP Consumer" }, { "code": null, "e": 14221, "s": 14189, "text": " Spring Boot – Soap WebServices" }, { "code": null, "e": 14258, "s": 14221, "text": " Spring Boot – Batch Csv to Database" }, { "code": null, "e": 14287, "s": 14258, "text": " Spring Boot – Eureka Server" }, { "code": null, "e": 14316, "s": 14287, "text": " Spring Boot – MockMvc JUnit" } ]
Calculate Inverse cosine of a value in R Programming - acos() Function - GeeksforGeeks
01 Jun, 2020 acos() function in R Language is used to calculate the inverse cosine value of the numeric value passed to it as argument. Syntax: acos(x) Parameter:x: Numeric value Example 1: # R code to calculate inverse cosine of a value # Assigning values to variables x1 <- -1x2 <- 0.5 # Using acos() Functionacos(x1)acos(x2) Output: [1] 3.141593 [1] 1.047198 Example 2: # R code to calculate inverse cosine of a value # Assigning values to variablesx1 <- 0.224587x2 <- 0.456732 # Using acos() Functionacos(x1)acos(x2) Output: [1] 1.344277 [1] 1.096478 R Math-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) How to change Row Names of DataFrame in R ? Group by function in R using Dplyr Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? How to Change Axis Scales in R Plots? Printing Output of an R Program K-Means Clustering in R Programming
[ { "code": null, "e": 24900, "s": 24872, "text": "\n01 Jun, 2020" }, { "code": null, "e": 25023, "s": 24900, "text": "acos() function in R Language is used to calculate the inverse cosine value of the numeric value passed to it as argument." }, { "code": null, "e": 25039, "s": 25023, "text": "Syntax: acos(x)" }, { "code": null, "e": 25066, "s": 25039, "text": "Parameter:x: Numeric value" }, { "code": null, "e": 25077, "s": 25066, "text": "Example 1:" }, { "code": "# R code to calculate inverse cosine of a value # Assigning values to variables x1 <- -1x2 <- 0.5 # Using acos() Functionacos(x1)acos(x2)", "e": 25217, "s": 25077, "text": null }, { "code": null, "e": 25225, "s": 25217, "text": "Output:" }, { "code": null, "e": 25251, "s": 25225, "text": "[1] 3.141593\n[1] 1.047198" }, { "code": null, "e": 25262, "s": 25251, "text": "Example 2:" }, { "code": "# R code to calculate inverse cosine of a value # Assigning values to variablesx1 <- 0.224587x2 <- 0.456732 # Using acos() Functionacos(x1)acos(x2)", "e": 25412, "s": 25262, "text": null }, { "code": null, "e": 25420, "s": 25412, "text": "Output:" }, { "code": null, "e": 25446, "s": 25420, "text": "[1] 1.344277\n[1] 1.096478" }, { "code": null, "e": 25462, "s": 25446, "text": "R Math-Function" }, { "code": null, "e": 25473, "s": 25462, "text": "R Language" }, { "code": null, "e": 25571, "s": 25473, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25629, "s": 25571, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 25681, "s": 25629, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 25713, "s": 25681, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 25757, "s": 25713, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 25792, "s": 25757, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 25844, "s": 25792, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 25902, "s": 25844, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 25940, "s": 25902, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 25972, "s": 25940, "text": "Printing Output of an R Program" } ]
Scala Set toArray() method with example - GeeksforGeeks
18 Oct, 2019 The toArray() is utilized to return an array consisting of all the elements of the set. Method Definition: def toArray: Array[A] Return Type: It returns an array consisting of all the elements of the set. Example #1: // Scala program of toArray() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(1, 2, 3, 4, 7) // Applying toArray method val result = s1.toArray // Display output for (elem <- result) println(elem) } } 1 2 7 3 4 Example #2: // Scala program of toArray() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(41, 12, 23, 43, 1, 72) // Applying toArray method val result = s1.toArray // Display output for (elem <- result) println(elem) } } 1 41 12 72 43 23 Scala scala-collection Scala-Method Scala-Set Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Scala ListBuffer Inheritance in Scala Scala | Case Class and Case Object Hello World in Scala Scala | Traits Scala | Try-Catch Exceptions Scala List map() method with example How to install Scala on Windows? Comments In Scala Scala | Option
[ { "code": null, "e": 25411, "s": 25383, "text": "\n18 Oct, 2019" }, { "code": null, "e": 25499, "s": 25411, "text": "The toArray() is utilized to return an array consisting of all the elements of the set." }, { "code": null, "e": 25540, "s": 25499, "text": "Method Definition: def toArray: Array[A]" }, { "code": null, "e": 25616, "s": 25540, "text": "Return Type: It returns an array consisting of all the elements of the set." }, { "code": null, "e": 25628, "s": 25616, "text": "Example #1:" }, { "code": "// Scala program of toArray() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(1, 2, 3, 4, 7) // Applying toArray method val result = s1.toArray // Display output for (elem <- result) println(elem) } } ", "e": 26011, "s": 25628, "text": null }, { "code": null, "e": 26022, "s": 26011, "text": "1\n2\n7\n3\n4\n" }, { "code": null, "e": 26034, "s": 26022, "text": "Example #2:" }, { "code": "// Scala program of toArray() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(41, 12, 23, 43, 1, 72) // Applying toArray method val result = s1.toArray // Display output for (elem <- result) println(elem) } } ", "e": 26425, "s": 26034, "text": null }, { "code": null, "e": 26443, "s": 26425, "text": "1\n41\n12\n72\n43\n23\n" }, { "code": null, "e": 26449, "s": 26443, "text": "Scala" }, { "code": null, "e": 26466, "s": 26449, "text": "scala-collection" }, { "code": null, "e": 26479, "s": 26466, "text": "Scala-Method" }, { "code": null, "e": 26489, "s": 26479, "text": "Scala-Set" }, { "code": null, "e": 26495, "s": 26489, "text": "Scala" }, { "code": null, "e": 26593, "s": 26495, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26610, "s": 26593, "text": "Scala ListBuffer" }, { "code": null, "e": 26631, "s": 26610, "text": "Inheritance in Scala" }, { "code": null, "e": 26666, "s": 26631, "text": "Scala | Case Class and Case Object" }, { "code": null, "e": 26687, "s": 26666, "text": "Hello World in Scala" }, { "code": null, "e": 26702, "s": 26687, "text": "Scala | Traits" }, { "code": null, "e": 26731, "s": 26702, "text": "Scala | Try-Catch Exceptions" }, { "code": null, "e": 26768, "s": 26731, "text": "Scala List map() method with example" }, { "code": null, "e": 26801, "s": 26768, "text": "How to install Scala on Windows?" }, { "code": null, "e": 26819, "s": 26801, "text": "Comments In Scala" } ]
Program to calculate volume of Ellipsoid - GeeksforGeeks
17 Mar, 2021 Ellipsoid, closed surface of which all plane cross sections are either ellipses or circles. An ellipsoid is symmetrical about three mutually perpendicular axes that intersect at the center. It is a three-dimensional, closed geometric shape, all planar sections of which are ellipses or circles. An ellipsoid has three independent axes, and is usually specified by the lengths a, b, c of the three semi-axes. If an ellipsoid is made by rotating an ellipse about one of its axes, then two axes of the ellipsoid are the same, and it is called an ellipsoid of revolution, or spheroid. If the lengths of all three of its axes are the same, it is a sphere. Standard equation of Ellipsoid : x2 / a2 + y2 / b2 + z2 / c2 = 1 where a, b, c are positive real numbers. Volume of Ellipsoid : (4/3) * pi * r1 * r2 * r3 Below is code for calculating volume of ellipsoid : C++ Java Python C# PHP Javascript // CPP program to find the// volume of Ellipsoid.#include <bits/stdc++.h>using namespace std; // Function to find the volumefloat volumeOfEllipsoid(float r1, float r2, float r3){ float pi = 3.14; return 1.33 * pi * r1 * r2 * r3;} // Driver Codeint main(){ float r1 = 2.3, r2 = 3.4, r3 = 5.7; cout << "volume of ellipsoid is : " << volumeOfEllipsoid(r1, r2, r3); return 0;} // Java program to find the// volume of Ellipsoid.import java.util.*;import java.lang.*; class GfG{ // Function to find the volume public static float volumeOfEllipsoid(float r1, float r2, float r3) { float pi = (float)3.14; return (float) 1.33 * pi * r1 * r2 * r3; } // Driver Code public static void main(String args[]) { float r1 = (float) 2.3, r2 = (float) 3.4, r3 = (float) 5.7; System.out.println("volume of ellipsoid is : " + volumeOfEllipsoid(r1, r2, r3)); }} // This code is contributed by Sagar Shukla ''' Python3 program to Volume of ellipsoid'''import math # Function To calculate Volumedef volumeOfEllipsoid(r1, r2, r3): return 1.33 * math.pi * r1 * r2 * r3 # Driver Coder1 = float(2.3)r2 = float(3.4)r3 = float(5.7)print( "Volume of ellipsoid is : ", volumeOfEllipsoid(r1, r2, r3) ) // C# program to find the// volume of Ellipsoid.using System; class GfG{ // Function to find the volume public static float volumeOfEllipsoid(float r1, float r2, float r3) { float pi = (float)3.14; return (float) 1.33 * pi * r1 * r2 * r3; } // Driver Code public static void Main() { float r1 = (float)2.3, r2 =(float) 3.4, r3 = (float)5.7; Console.WriteLine("volume of ellipsoid is : " + volumeOfEllipsoid(r1, r2, r3)); }} // This code is contributed by vt_m <?php// PHP program to find the// volume of Ellipsoid. // Function to find the volumefunction volumeOfEllipsoid( $r1, $r2, $r3){ $pi = 3.14; return 1.33 * $pi * $r1 * $r2 * $r3;} // Driver Code $r1 = 2.3; $r2 = 3.4; $r3 = 5.7; echo ( "volume of ellipsoid is : "); echo( volumeOfEllipsoid($r1, $r2, $r3)); // This code is contributed by vt_m .?> <script>// javascript program to find the// volume of Ellipsoid. // Function to find the volumefunction volumeOfEllipsoid( r1, r2, r3){ let pi = 3.14; return 1.33 * pi * r1 * r2 * r3;} // Driver Code let r1 = 2.3, r2 = 3.4, r3 = 5.7; document.write( "volume of ellipsoid is : " + volumeOfEllipsoid(r1, r2, r3).toFixed(2)); // This code contributed by Rajput-Ji </script> Output : Volume of ellipsoid is : 186.15 vt_m Rajput-Ji area-volume-programs Geometric School Programming Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convex Hull | Set 2 (Graham Scan) Check whether a given point lies inside a triangle or not Convex Hull using Divide and Conquer Algorithm Optimum location of point to minimize total distance Given n line segments, find if any two segments intersect Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26277, "s": 26249, "text": "\n17 Mar, 2021" }, { "code": null, "e": 26930, "s": 26277, "text": "Ellipsoid, closed surface of which all plane cross sections are either ellipses or circles. An ellipsoid is symmetrical about three mutually perpendicular axes that intersect at the center. It is a three-dimensional, closed geometric shape, all planar sections of which are ellipses or circles. An ellipsoid has three independent axes, and is usually specified by the lengths a, b, c of the three semi-axes. If an ellipsoid is made by rotating an ellipse about one of its axes, then two axes of the ellipsoid are the same, and it is called an ellipsoid of revolution, or spheroid. If the lengths of all three of its axes are the same, it is a sphere. " }, { "code": null, "e": 27090, "s": 26930, "text": "Standard equation of Ellipsoid :\nx2 / a2 + y2 / b2 + z2 / c2 = 1\n \nwhere a, b, c are positive real numbers.\nVolume of Ellipsoid : (4/3) * pi * r1 * r2 * r3 " }, { "code": null, "e": 27145, "s": 27092, "text": "Below is code for calculating volume of ellipsoid : " }, { "code": null, "e": 27149, "s": 27145, "text": "C++" }, { "code": null, "e": 27154, "s": 27149, "text": "Java" }, { "code": null, "e": 27161, "s": 27154, "text": "Python" }, { "code": null, "e": 27164, "s": 27161, "text": "C#" }, { "code": null, "e": 27168, "s": 27164, "text": "PHP" }, { "code": null, "e": 27179, "s": 27168, "text": "Javascript" }, { "code": "// CPP program to find the// volume of Ellipsoid.#include <bits/stdc++.h>using namespace std; // Function to find the volumefloat volumeOfEllipsoid(float r1, float r2, float r3){ float pi = 3.14; return 1.33 * pi * r1 * r2 * r3;} // Driver Codeint main(){ float r1 = 2.3, r2 = 3.4, r3 = 5.7; cout << \"volume of ellipsoid is : \" << volumeOfEllipsoid(r1, r2, r3); return 0;}", "e": 27638, "s": 27179, "text": null }, { "code": "// Java program to find the// volume of Ellipsoid.import java.util.*;import java.lang.*; class GfG{ // Function to find the volume public static float volumeOfEllipsoid(float r1, float r2, float r3) { float pi = (float)3.14; return (float) 1.33 * pi * r1 * r2 * r3; } // Driver Code public static void main(String args[]) { float r1 = (float) 2.3, r2 = (float) 3.4, r3 = (float) 5.7; System.out.println(\"volume of ellipsoid is : \" + volumeOfEllipsoid(r1, r2, r3)); }} // This code is contributed by Sagar Shukla", "e": 28335, "s": 27638, "text": null }, { "code": "''' Python3 program to Volume of ellipsoid'''import math # Function To calculate Volumedef volumeOfEllipsoid(r1, r2, r3): return 1.33 * math.pi * r1 * r2 * r3 # Driver Coder1 = float(2.3)r2 = float(3.4)r3 = float(5.7)print( \"Volume of ellipsoid is : \", volumeOfEllipsoid(r1, r2, r3) )", "e": 28631, "s": 28335, "text": null }, { "code": "// C# program to find the// volume of Ellipsoid.using System; class GfG{ // Function to find the volume public static float volumeOfEllipsoid(float r1, float r2, float r3) { float pi = (float)3.14; return (float) 1.33 * pi * r1 * r2 * r3; } // Driver Code public static void Main() { float r1 = (float)2.3, r2 =(float) 3.4, r3 = (float)5.7; Console.WriteLine(\"volume of ellipsoid is : \" + volumeOfEllipsoid(r1, r2, r3)); }} // This code is contributed by vt_m", "e": 29280, "s": 28631, "text": null }, { "code": "<?php// PHP program to find the// volume of Ellipsoid. // Function to find the volumefunction volumeOfEllipsoid( $r1, $r2, $r3){ $pi = 3.14; return 1.33 * $pi * $r1 * $r2 * $r3;} // Driver Code $r1 = 2.3; $r2 = 3.4; $r3 = 5.7; echo ( \"volume of ellipsoid is : \"); echo( volumeOfEllipsoid($r1, $r2, $r3)); // This code is contributed by vt_m .?>", "e": 29721, "s": 29280, "text": null }, { "code": "<script>// javascript program to find the// volume of Ellipsoid. // Function to find the volumefunction volumeOfEllipsoid( r1, r2, r3){ let pi = 3.14; return 1.33 * pi * r1 * r2 * r3;} // Driver Code let r1 = 2.3, r2 = 3.4, r3 = 5.7; document.write( \"volume of ellipsoid is : \" + volumeOfEllipsoid(r1, r2, r3).toFixed(2)); // This code contributed by Rajput-Ji </script>", "e": 30128, "s": 29721, "text": null }, { "code": null, "e": 30139, "s": 30128, "text": "Output : " }, { "code": null, "e": 30171, "s": 30139, "text": "Volume of ellipsoid is : 186.15" }, { "code": null, "e": 30178, "s": 30173, "text": "vt_m" }, { "code": null, "e": 30188, "s": 30178, "text": "Rajput-Ji" }, { "code": null, "e": 30209, "s": 30188, "text": "area-volume-programs" }, { "code": null, "e": 30219, "s": 30209, "text": "Geometric" }, { "code": null, "e": 30238, "s": 30219, "text": "School Programming" }, { "code": null, "e": 30248, "s": 30238, "text": "Geometric" }, { "code": null, "e": 30346, "s": 30248, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30380, "s": 30346, "text": "Convex Hull | Set 2 (Graham Scan)" }, { "code": null, "e": 30438, "s": 30380, "text": "Check whether a given point lies inside a triangle or not" }, { "code": null, "e": 30485, "s": 30438, "text": "Convex Hull using Divide and Conquer Algorithm" }, { "code": null, "e": 30538, "s": 30485, "text": "Optimum location of point to minimize total distance" }, { "code": null, "e": 30596, "s": 30538, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 30614, "s": 30596, "text": "Python Dictionary" }, { "code": null, "e": 30630, "s": 30614, "text": "Arrays in C/C++" }, { "code": null, "e": 30649, "s": 30630, "text": "Inheritance in C++" }, { "code": null, "e": 30674, "s": 30649, "text": "Reverse a string in Java" } ]
BinarySearch() method in C#
BinarySearch() works on a sorted list whether its numeric, alphanumeric or strings. It finds you the index of an element. Let’s say the following is our list. List<int> list = new List<int>(); list.Add(70); list.Add(150); list.Add(220); list.Add(250); list.Add(300); Now to check the index where 250 is placed, use BinarySearch() method. list.BinarySearch(250); Live Demo using System; using System.Collections.Generic; class Demo { static void Main() { List<int> list = new List<int>(); list.Add(70); list.Add(150); list.Add(220); list.Add(250); list.Add(300); int value = list.BinarySearch(250); Console.WriteLine("Element 250 at Index: "+value); } } Element 250 at Index: 3
[ { "code": null, "e": 1184, "s": 1062, "text": "BinarySearch() works on a sorted list whether its numeric, alphanumeric or strings. It finds you the index of an element." }, { "code": null, "e": 1221, "s": 1184, "text": "Let’s say the following is our list." }, { "code": null, "e": 1329, "s": 1221, "text": "List<int> list = new List<int>();\nlist.Add(70);\nlist.Add(150);\nlist.Add(220);\nlist.Add(250);\nlist.Add(300);" }, { "code": null, "e": 1400, "s": 1329, "text": "Now to check the index where 250 is placed, use BinarySearch() method." }, { "code": null, "e": 1424, "s": 1400, "text": "list.BinarySearch(250);" }, { "code": null, "e": 1435, "s": 1424, "text": " Live Demo" }, { "code": null, "e": 1770, "s": 1435, "text": "using System;\nusing System.Collections.Generic;\nclass Demo {\n static void Main() {\n List<int> list = new List<int>();\n list.Add(70);\n list.Add(150);\n list.Add(220);\n list.Add(250);\n list.Add(300);\n int value = list.BinarySearch(250);\n Console.WriteLine(\"Element 250 at Index: \"+value);\n }\n}" }, { "code": null, "e": 1794, "s": 1770, "text": "Element 250 at Index: 3" } ]
Option Greeks in Python. JAX for automatic... | by Roman Paolucci | Towards Data Science
Option greeks are essential to every options trader. But, what are the greeks precisely? The greeks are the partial-derivatives of the Black-Scholes equation with respect to each variable... The Greeks Delta — Δ — first partial-derivative with respect to the underlying asset Gamma — γ — 2nd partial-derivative with respect to the underlying asset Vega — v — partial-derivative with respect to volatility Theta — θ — partial-derivative with respect to time until expiration Rho — ρ — partial derivative with respect to the given interest rate In plain English, the greeks tell us how an option’s price changes when only that parameter is varied (all others are held constant). Trading platforms often compute the greeks automatically for each contract. However, when streaming market data to Python, or with your own pricing models, you will need to compute these values on your own. Though there are closed-form solutions for Black-Scholes greeks (which dramatically speed up their computation). Nevertheless, I thought it would be a cool introduction to the Python library JAX which can be used to automatically compute the gradient for any function. The beauty of JAX derived greeks is that it can be used for any pricing model, not just the Black-Scholes model making hedging exotics a little less painful. The gradient vector, or simply the gradient, is the collection of partial-derivatives for any given multivariable function. Given the following function f... The gradient — ∇ — is the following... This notion follows for all functions regardless of dimensionality... For more information regarding the gradient check out The Gradient Vector. You’ll notice the intersection of these two concepts lies in the partial-differentiation. The greeks (except gamma) are the first partial-derivatives of the Black-Scholes equation with respect to each variable. If we can derive the gradient from the Black-Scholes equation we will have a function yielding the 4 of the 5 greeks! JAX is a library developed and maintained by Google, primarily used for machine learning, offering a simple way to automatically compute the gradient function. Unfortunately as of the writing of this article, JAX is only supported on IOS. Before we get started, it’s important to note that in order to use JAX we are going to need to reference any linear algebra (numpy) or statistical distributions (scipy) through JAX itself... I have already built classes for European calls and puts in Python correctly structured for use with JAX... Often JAX will return errors if the types of the variables are not floats as there are a variety of approximation techniques used to solve for the derivatives. You’ll see throughout the classes above there are references to .astype(‘float’) for this very reason. Let’s implement JAX’s grad function to automatically compute the greeks... In the code above after computing each option price I add a field with a call to JAX’s grad function. The grad function takes both a function and a tuple regarding which parameters to include in the gradient. After computing the gradient_func, I use it to assign the values of delta, vega, theta, and rho respectively. You will also notice that we need to make some adjustments as vega and rho are expressed as percents and theta is annualized. Now let’s use this class to compute the greeks for an example option... To implement these classes we create a JAX — numpy array of our option’s parameters in the following order... Asset price Volatility Strike price Time to expiration (annualized) Risk-free rate (or interest rate) Then we create an instance of the European option class and feed the JAX — numpy array using .astype(‘float’) to avoid errors computing the gradient. Lastly, we print the values of our greeks derived using the gradient function... 0.6300359 3.1931925 -1.3295598 1.3750976[Finished in 1.253s]
[ { "code": null, "e": 238, "s": 47, "text": "Option greeks are essential to every options trader. But, what are the greeks precisely? The greeks are the partial-derivatives of the Black-Scholes equation with respect to each variable..." }, { "code": null, "e": 249, "s": 238, "text": "The Greeks" }, { "code": null, "e": 323, "s": 249, "text": "Delta — Δ — first partial-derivative with respect to the underlying asset" }, { "code": null, "e": 395, "s": 323, "text": "Gamma — γ — 2nd partial-derivative with respect to the underlying asset" }, { "code": null, "e": 452, "s": 395, "text": "Vega — v — partial-derivative with respect to volatility" }, { "code": null, "e": 521, "s": 452, "text": "Theta — θ — partial-derivative with respect to time until expiration" }, { "code": null, "e": 590, "s": 521, "text": "Rho — ρ — partial derivative with respect to the given interest rate" }, { "code": null, "e": 1200, "s": 590, "text": "In plain English, the greeks tell us how an option’s price changes when only that parameter is varied (all others are held constant). Trading platforms often compute the greeks automatically for each contract. However, when streaming market data to Python, or with your own pricing models, you will need to compute these values on your own. Though there are closed-form solutions for Black-Scholes greeks (which dramatically speed up their computation). Nevertheless, I thought it would be a cool introduction to the Python library JAX which can be used to automatically compute the gradient for any function." }, { "code": null, "e": 1358, "s": 1200, "text": "The beauty of JAX derived greeks is that it can be used for any pricing model, not just the Black-Scholes model making hedging exotics a little less painful." }, { "code": null, "e": 1482, "s": 1358, "text": "The gradient vector, or simply the gradient, is the collection of partial-derivatives for any given multivariable function." }, { "code": null, "e": 1516, "s": 1482, "text": "Given the following function f..." }, { "code": null, "e": 1555, "s": 1516, "text": "The gradient — ∇ — is the following..." }, { "code": null, "e": 1625, "s": 1555, "text": "This notion follows for all functions regardless of dimensionality..." }, { "code": null, "e": 1700, "s": 1625, "text": "For more information regarding the gradient check out The Gradient Vector." }, { "code": null, "e": 2029, "s": 1700, "text": "You’ll notice the intersection of these two concepts lies in the partial-differentiation. The greeks (except gamma) are the first partial-derivatives of the Black-Scholes equation with respect to each variable. If we can derive the gradient from the Black-Scholes equation we will have a function yielding the 4 of the 5 greeks!" }, { "code": null, "e": 2189, "s": 2029, "text": "JAX is a library developed and maintained by Google, primarily used for machine learning, offering a simple way to automatically compute the gradient function." }, { "code": null, "e": 2268, "s": 2189, "text": "Unfortunately as of the writing of this article, JAX is only supported on IOS." }, { "code": null, "e": 2459, "s": 2268, "text": "Before we get started, it’s important to note that in order to use JAX we are going to need to reference any linear algebra (numpy) or statistical distributions (scipy) through JAX itself..." }, { "code": null, "e": 2567, "s": 2459, "text": "I have already built classes for European calls and puts in Python correctly structured for use with JAX..." }, { "code": null, "e": 2830, "s": 2567, "text": "Often JAX will return errors if the types of the variables are not floats as there are a variety of approximation techniques used to solve for the derivatives. You’ll see throughout the classes above there are references to .astype(‘float’) for this very reason." }, { "code": null, "e": 2905, "s": 2830, "text": "Let’s implement JAX’s grad function to automatically compute the greeks..." }, { "code": null, "e": 3350, "s": 2905, "text": "In the code above after computing each option price I add a field with a call to JAX’s grad function. The grad function takes both a function and a tuple regarding which parameters to include in the gradient. After computing the gradient_func, I use it to assign the values of delta, vega, theta, and rho respectively. You will also notice that we need to make some adjustments as vega and rho are expressed as percents and theta is annualized." }, { "code": null, "e": 3422, "s": 3350, "text": "Now let’s use this class to compute the greeks for an example option..." }, { "code": null, "e": 3532, "s": 3422, "text": "To implement these classes we create a JAX — numpy array of our option’s parameters in the following order..." }, { "code": null, "e": 3544, "s": 3532, "text": "Asset price" }, { "code": null, "e": 3555, "s": 3544, "text": "Volatility" }, { "code": null, "e": 3568, "s": 3555, "text": "Strike price" }, { "code": null, "e": 3600, "s": 3568, "text": "Time to expiration (annualized)" }, { "code": null, "e": 3634, "s": 3600, "text": "Risk-free rate (or interest rate)" }, { "code": null, "e": 3865, "s": 3634, "text": "Then we create an instance of the European option class and feed the JAX — numpy array using .astype(‘float’) to avoid errors computing the gradient. Lastly, we print the values of our greeks derived using the gradient function..." } ]
MySQL - Insert current date/time?
To insert only date value, use curdate() in MySQL. With that, if you want to get the entire datetime, then you can use now() method. Let us first create a table − mysql> create table CurDateDemo -> ( -> ArrivalDate datetime -> ); Query OK, 0 rows affected (0.74 sec) Now you can insert only date with the help of curdate() method − mysql> insert into CurDateDemo values(curdate()); Query OK, 1 row affected (0.15 sec) Display the inserted date with the help of select statement. The query is as follows − mysql> select *from CurDateDemo; Here is the output − +---------------------+ | ArrivalDate | +---------------------+ | 2018-11-23 00:00:00 | +---------------------+ 1 row in set (0.00 sec) Let us now create a table and display the current datetime − mysql> create table NowDemo -> ( -> ArrivalDate datetime -> ); Query OK, 0 rows affected (0.47 sec) Insert both date and time with the help of now(). The query to insert record is as follows − mysql> insert into NowDemo values(now()); Query OK, 1 row affected (0.16 sec) Let us now check whether the date and time is inserted or not. The query to display records is as follows − mysql> select *from NowDemo; The following is the output − +---------------------+ | ArrivalDate | +---------------------+ | 2018-11-23 17:31:26 | +---------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1195, "s": 1062, "text": "To insert only date value, use curdate() in MySQL. With that, if you want to get the entire datetime, then you can use now() method." }, { "code": null, "e": 1225, "s": 1195, "text": "Let us first create a table −" }, { "code": null, "e": 1338, "s": 1225, "text": "mysql> create table CurDateDemo\n -> (\n -> ArrivalDate datetime\n -> );\nQuery OK, 0 rows affected (0.74 sec)" }, { "code": null, "e": 1403, "s": 1338, "text": "Now you can insert only date with the help of curdate() method −" }, { "code": null, "e": 1489, "s": 1403, "text": "mysql> insert into CurDateDemo values(curdate());\nQuery OK, 1 row affected (0.15 sec)" }, { "code": null, "e": 1576, "s": 1489, "text": "Display the inserted date with the help of select statement. The query is as follows −" }, { "code": null, "e": 1609, "s": 1576, "text": "mysql> select *from CurDateDemo;" }, { "code": null, "e": 1630, "s": 1609, "text": "Here is the output −" }, { "code": null, "e": 1774, "s": 1630, "text": "+---------------------+\n| ArrivalDate |\n+---------------------+\n| 2018-11-23 00:00:00 |\n+---------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 1835, "s": 1774, "text": "Let us now create a table and display the current datetime −" }, { "code": null, "e": 1944, "s": 1835, "text": "mysql> create table NowDemo\n -> (\n -> ArrivalDate datetime\n -> );\nQuery OK, 0 rows affected (0.47 sec)" }, { "code": null, "e": 1994, "s": 1944, "text": "Insert both date and time with the help of now()." }, { "code": null, "e": 2037, "s": 1994, "text": "The query to insert record is as follows −" }, { "code": null, "e": 2115, "s": 2037, "text": "mysql> insert into NowDemo values(now());\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 2223, "s": 2115, "text": "Let us now check whether the date and time is inserted or not. The query to display records is as follows −" }, { "code": null, "e": 2252, "s": 2223, "text": "mysql> select *from NowDemo;" }, { "code": null, "e": 2282, "s": 2252, "text": "The following is the output −" }, { "code": null, "e": 2426, "s": 2282, "text": "+---------------------+\n| ArrivalDate |\n+---------------------+\n| 2018-11-23 17:31:26 |\n+---------------------+\n1 row in set (0.00 sec)" } ]
Java Virtual Machine - The JIT Compiler
In this chapter, we shall learn about JIT compiler, and the difference between compiled and interpreted languages. Languages such as C, C++ and FORTRAN are compiled languages. Their code is delivered as binary code targeted at the underlying machine. This means that the high-level code is compiled into binary code at once by a static compiler written specifically for the underlying architecture. The binary that is produced will not run on any other architecture. On the other hand, interpreted languages like Python and Perl can run on any machine, as long as they have a valid interpreter. It goes over line-by-line over the high-level code, converting that into binary code. Interpreted code is typically slower than compiled code. For example, consider a loop. An interpreted will convert the corresponding code for each iteration of the loop. On the other hand, a compiled code will make the translation only one. Further, since interpreters see only one line at a time, they are unable to perform any significant code such as, changing the order of execution of statements like compilers. We shall look into an example of such optimization below − Adding two numbers stored in memory. Since accessing memory can consume multiple CPU cycles, a good compiler will issue instructions to fetch the data from memory and execute the addition only when the data is available. It will not wait and in the meantime, execute other instructions. On the other hand, no such optimization would be possible during interpretation since the interpreter is not aware of the entire code at any given time. But then, interpreted languages can run on any machine that has a valid interpreter of that language. Java tried to find a middle ground. Since the JVM sits in between the javac compiler and the underlying hardware, the javac (or any other compiler) compiler compiles Java code in the Bytecode, which is understood by a platform specific JVM. The JVM then compiles the Bytecode in binary using JIT (Just-in-time) compilation, as the code executes. In a typical program, there’s only a small section of code that is executed frequently, and often, it is this code that affects the performance of the whole application significantly. Such sections of code are called HotSpots. If some section of code is executed only once, then compiling it would be a waste of effort, and it would be faster to interpret the Bytecode instead. But if the section is a hot section and is executed multiple times, the JVM would compile it instead. For example, if a method is called multiple times, the extra cycles that it would take to compile the code would be offset by the faster binary that is generated. Further, the more the JVM runs a particular method or a loop, the more information it gathers to make sundry optimizations so that a faster binary is generated. Let us consider the following code − for(int i = 0 ; I <= 100; i++) { System.out.println(obj1.equals(obj2)); //two objects } If this code is interpreted, the interpreter would deduce for each iteration that classes of obj1. This is because each class in Java has an .equals() method, that is extended from the Object class and can be overridden. So even if obj1 is a string for each iteration, the deduction will still be done. On the other hand, what would actually happen is that the JVM would notice that for each iteration, obj1 is of class String and hence, it would generate code corresponding to the .equals() method of the String class directly. Thus, no lookups will be required, and the compiled code would execute faster. This kind of behavior is only possible when the JVM knows how the code behaves. Thus, it waits before compiling certain sections of the code. Below is another example − int sum = 7; for(int i = 0 ; i <= 100; i++) { sum += i; } An interpreter, for each loop, fetches the value of ‘sum’ from the memory, adds ‘I’ to it, and stores it back into memory. Memory access is an expensive operation and typically takes multiple CPU cycles. Since this code runs multiple times, it is a HotSpot. The JIT will compile this code and make the following optimization. A local copy of ‘sum’ would be stored in a register, specific to a particular thread. All the operations would be done to the value in the register and when the loop completes, the value would be written back to the memory. What if other threads are accessing the variable as well? Since updates are being done to a local copy of the variable by some other thread, they would see a stale value. Thread synchronization is needed in such cases. A very basic sync primitive would be to declare ‘sum’ as volatile. Now, before accessing a variable, a thread would flush its local registers and fetch the value from the memory. After accessing it, the value is immediately written to the memory. Below are some general optimizations that are done by the JIT compilers − Method inlining Dead code elimination Heuristics for optimizing call sites Constant folding 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 1965, "s": 1850, "text": "In this chapter, we shall learn about JIT compiler, and the difference between compiled and interpreted languages." }, { "code": null, "e": 2317, "s": 1965, "text": "Languages such as C, C++ and FORTRAN are compiled languages. Their code is delivered as binary code targeted at the underlying machine. This means that the high-level code is compiled into binary code at once by a static compiler written specifically for the underlying architecture. The binary that is produced will not run on any other architecture." }, { "code": null, "e": 2531, "s": 2317, "text": "On the other hand, interpreted languages like Python and Perl can run on any machine, as long as they have a valid interpreter. It goes over line-by-line over the high-level code, converting that into binary code." }, { "code": null, "e": 2948, "s": 2531, "text": "Interpreted code is typically slower than compiled code. For example, consider a loop. An interpreted will convert the corresponding code for each iteration of the loop. On the other hand, a compiled code will make the translation only one. Further, since interpreters see only one line at a time, they are unable to perform any significant code such as, changing the order of execution of statements like compilers." }, { "code": null, "e": 3007, "s": 2948, "text": "We shall look into an example of such optimization below −" }, { "code": null, "e": 3447, "s": 3007, "text": "Adding two numbers stored in memory. Since accessing memory can consume multiple CPU cycles, a good compiler will issue instructions to fetch the data from memory and execute the addition only when the data is available. It will not wait and in the meantime, execute other instructions. On the other hand, no such optimization would be possible during interpretation since the interpreter is not aware of the entire code at any given time." }, { "code": null, "e": 3549, "s": 3447, "text": "But then, interpreted languages can run on any machine that has a valid interpreter of that language." }, { "code": null, "e": 3895, "s": 3549, "text": "Java tried to find a middle ground. Since the JVM sits in between the javac compiler and the underlying hardware, the javac (or any other compiler) compiler compiles Java code in the Bytecode, which is understood by a platform specific JVM. The JVM then compiles the Bytecode in binary using JIT (Just-in-time) compilation, as the code executes." }, { "code": null, "e": 4122, "s": 3895, "text": "In a typical program, there’s only a small section of code that is executed frequently, and often, it is this code that affects the performance of the whole application significantly. Such sections of code are called HotSpots." }, { "code": null, "e": 4538, "s": 4122, "text": "If some section of code is executed only once, then compiling it would be a waste of effort, and it would be faster to interpret the Bytecode instead. But if the section is a hot section and is executed multiple times, the JVM would compile it instead. For example, if a method is called multiple times, the extra cycles that it would take to compile the code would be offset by the faster binary that is generated." }, { "code": null, "e": 4699, "s": 4538, "text": "Further, the more the JVM runs a particular method or a loop, the more information it gathers to make sundry optimizations so that a faster binary is generated." }, { "code": null, "e": 4736, "s": 4699, "text": "Let us consider the following code −" }, { "code": null, "e": 4827, "s": 4736, "text": "for(int i = 0 ; I <= 100; i++) {\n System.out.println(obj1.equals(obj2)); //two objects\n}" }, { "code": null, "e": 5130, "s": 4827, "text": "If this code is interpreted, the interpreter would deduce for each iteration that classes of obj1. This is because each class in Java has an .equals() method, that is extended from the Object class and can be overridden. So even if obj1 is a string for each iteration, the deduction will still be done." }, { "code": null, "e": 5435, "s": 5130, "text": "On the other hand, what would actually happen is that the JVM would notice that for each iteration, obj1 is of class String and hence, it would generate code corresponding to the .equals() method of the String class directly. Thus, no lookups will be required, and the compiled code would execute faster." }, { "code": null, "e": 5577, "s": 5435, "text": "This kind of behavior is only possible when the JVM knows how the code behaves. Thus, it waits before compiling certain sections of the code." }, { "code": null, "e": 5604, "s": 5577, "text": "Below is another example −" }, { "code": null, "e": 5665, "s": 5604, "text": "int sum = 7;\nfor(int i = 0 ; i <= 100; i++) {\n sum += i;\n}" }, { "code": null, "e": 5991, "s": 5665, "text": "An interpreter, for each loop, fetches the value of ‘sum’ from the memory, adds ‘I’ to it, and stores it back into memory. Memory access is an expensive operation and typically takes multiple CPU cycles. Since this code runs multiple times, it is a HotSpot. The JIT will compile this code and make the following optimization." }, { "code": null, "e": 6215, "s": 5991, "text": "A local copy of ‘sum’ would be stored in a register, specific to a particular thread. All the operations would be done to the value in the register and when the loop completes, the value would be written back to the memory." }, { "code": null, "e": 6681, "s": 6215, "text": "What if other threads are accessing the variable as well? Since updates are being done to a local copy of the variable by some other thread, they would see a stale value. Thread synchronization is needed in such cases. A very basic sync primitive would be to declare ‘sum’ as volatile. Now, before accessing a variable, a thread would flush its local registers and fetch the value from the memory. After accessing it, the value is immediately written to the memory." }, { "code": null, "e": 6755, "s": 6681, "text": "Below are some general optimizations that are done by the JIT compilers −" }, { "code": null, "e": 6771, "s": 6755, "text": "Method inlining" }, { "code": null, "e": 6793, "s": 6771, "text": "Dead code elimination" }, { "code": null, "e": 6830, "s": 6793, "text": "Heuristics for optimizing call sites" }, { "code": null, "e": 6847, "s": 6830, "text": "Constant folding" }, { "code": null, "e": 6880, "s": 6847, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 6896, "s": 6880, "text": " Malhar Lathkar" }, { "code": null, "e": 6929, "s": 6896, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 6945, "s": 6929, "text": " Malhar Lathkar" }, { "code": null, "e": 6980, "s": 6945, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6994, "s": 6980, "text": " Anadi Sharma" }, { "code": null, "e": 7028, "s": 6994, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 7042, "s": 7028, "text": " Tushar Kale" }, { "code": null, "e": 7079, "s": 7042, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 7094, "s": 7079, "text": " Monica Mittal" }, { "code": null, "e": 7127, "s": 7094, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 7146, "s": 7127, "text": " Arnab Chakraborty" }, { "code": null, "e": 7153, "s": 7146, "text": " Print" }, { "code": null, "e": 7164, "s": 7153, "text": " Add Notes" } ]
Bootstrap 4 .justify-content-*-start class
Use the justify-content-start class in Bootstrap to justify content in the beginning. The justify-content-*-start class is used in Bootstrap to justify content in the beginning on different screen sizes like the following on small, medium, and large screen sizes − You can try to run the following code to implement the justify-content-*-start class − Live Demo <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> </head> <body> <div class="container mt-3"> <h3>Entertainment</h3> <div class="d-flex justify-content-sm-start bg-info mb-5"> <div class="p-2 bg-danger">Bollywood</div> <div class="p-2 bg-secondary">Tollywood</div> <div class="p-2 bg-warning">Hollywood</div> </div> <div class="d-flex justify-content-md-start bg-info mb-5"> <div class="p-2 bg-secondary">Bollywood</div> <div class="p-2 bg-warning">Tollywood</div> <div class="p-2 bg-primary">Hollywood</div> </div> <div class="d-flex justify-content-lg-start bg-info mb-5"> <div class="p-2 bg-secondary">Bollywood</div> <div class="p-2 bg-warning">Tollywood</div> <div class="p-2 bg-primary">Hollywood</div> </div> </div> </body> </html>
[ { "code": null, "e": 1148, "s": 1062, "text": "Use the justify-content-start class in Bootstrap to justify content in the beginning." }, { "code": null, "e": 1327, "s": 1148, "text": "The justify-content-*-start class is used in Bootstrap to justify content in the beginning on different screen sizes like the following on small, medium, and large screen sizes −" }, { "code": null, "e": 1414, "s": 1327, "text": "You can try to run the following code to implement the justify-content-*-start class −" }, { "code": null, "e": 1424, "s": 1414, "text": "Live Demo" }, { "code": null, "e": 2684, "s": 1424, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title> \n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n\n<body>\n\n <div class=\"container mt-3\">\n <h3>Entertainment</h3>\n <div class=\"d-flex justify-content-sm-start bg-info mb-5\">\n <div class=\"p-2 bg-danger\">Bollywood</div>\n <div class=\"p-2 bg-secondary\">Tollywood</div>\n <div class=\"p-2 bg-warning\">Hollywood</div>\n </div>\n <div class=\"d-flex justify-content-md-start bg-info mb-5\">\n <div class=\"p-2 bg-secondary\">Bollywood</div>\n <div class=\"p-2 bg-warning\">Tollywood</div>\n <div class=\"p-2 bg-primary\">Hollywood</div>\n </div>\n <div class=\"d-flex justify-content-lg-start bg-info mb-5\">\n <div class=\"p-2 bg-secondary\">Bollywood</div>\n <div class=\"p-2 bg-warning\">Tollywood</div>\n <div class=\"p-2 bg-primary\">Hollywood</div>\n </div>\n </div>\n\n</body>\n</html>" } ]
javac - Unix, Linux Command
There are two ways to pass source code file names to javac: Inner class definitions produce additional class files. These class files have names combining the inner and outer class names, such as MyClass$MyInnerClass.class. You should arrange source files in a directory tree that reflects their package tree. For example, if you keep all your source files in /workspace, the source code for com.mysoft.mypack.MyClass should be in /workspace/com/mysoft/mypack/MyClass.java. By default, the compiler puts each class file in the same directory as its source file. You can specify a separate destination directory with -d (see OPTIONS, below). For example, when you subclass java.applet.Applet, you are also using Applet’s ancestor classes: java.awt.Panel, java.awt.Container, java.awt.Component, and java.awt.Object. When the compiler needs type information, it looks for a source file or class file which defines the type. The compiler searches first in the bootstrap and extension classes, then in the user class path (which by default is the current directory). The user class path is defined by setting the CLASSPATH environment variable or by using the -classpath command line option. (For details, see Setting the Class Path.) If you use the -sourcepath option, the compiler searches the indicated path for source files; otherwise the compiler searches the user class path both for class files and source files. You can specify different bootstrap or extension classes with the -bootclasspath and -extdirs options; see Cross-Compilation Options below. A successful type search may produce a class file, a source file, or both. Here is how javac handles each situation: By default, javac considers a class file out of date only if it is older than the source file. If the -sourcepath option is not specified, the user class path is searched for both source files and class files. If -d is not specified, javac puts the class file in the same directory as the source file. Note: The directory specified by -d is not automatically added to your user class path. Note: Classes found through the classpath are subject to automatic recompilation if their sources are found. switch (x) { case 1: System.out.println("1"); // No break; statement here. case 2: System.out.println("2"); } An argument file can include javac options and source filenames in any combination. The arguments within a file can be space-separated or newline-separated. Filenames within an argument file are relative to the current directory, not the location of the argument file. Wildcards (*) are not allowed in these lists (such as for specifying *.java). Use of the @ character to recursively interpret files is not supported. When executing javac, pass in the path and name of each argument file with the @ leading character. When javac encounters an argument beginning with the character @, it expands the contents of that file into the argument list. C:> javac @argfile This argument file could contain the contents of both files shown in the next example. Create a file named options containing: -d classes -g -sourcepath \java\pubs\ws\1.3\src\share\classes MyClass1.java MyClass2.java MyClass3.java % javac @options @classes % javac @path1/options @path2/classes % ls greetings/ % ls greetings Hello.java % cat greetings/Hello.java package greetings; public class Hello { public static void main(String[] args) { for (int i=0; i < args.length; i++) { System.out.println("Hello " + args[i]); } } } % javac greetings/Hello.java % ls greetings Hello.class Hello.java % java greetings.Hello World Universe Everyone Hello World Hello Universe Hello Everyone % ls greetings/ % ls greetings Aloha.java GutenTag.java Hello.java Hi.java % javac greetings/*.java % ls greetings Aloha.class GutenTag.class Hello.class Hi.class Aloha.java GutenTag.java Hello.java Hi.java % pwd /examples % javac greetings/Hi.java Since greetings.Hi refers to other classes in the greetings package, the compiler needs to find these other classes. The example above works, because our default user class path happens to be the directory containing the package directory. But suppose we want to recompile this file and not worry about which directory we’re in? Then we need to add /examples to the user class path. We can do this by setting CLASSPATH, but here we’ll use the -classpath option. % javac -classpath \examples /examples/greetings/Hi.java If we change greetings.Hi again, to use a banner utility, that utility also needs to be accessible through the user class path. % javac -classpath /examples:/lib/Banners.jar \ /examples/greetings/Hi.java To execute a class in greetings, we need access both to greetings and to the classes it uses. % java -classpath /examples:/lib/Banners.jar greetings.Hi % ls classes/ lib/ src/ % ls src farewells/ % ls src/farewells Base.java GoodBye.java % ls lib Banners.jar % ls classes % javac -sourcepath src -classpath classes:lib/Banners.jar \ src/farewells/GoodBye.java -d classes % ls classes farewells/ % ls classes/farewells Base.class GoodBye.class Note: The compiler compiled src/farewells/Base.java, even though we didn’t specify it on the command line. To trace automatic compiles, use the -verbose option. % javac -target 1.4 -bootclasspath jdk1.4.2/lib/classes.zip \ -extdirs "" OldCode.java The -target 1.4 option ensures that the generated class files will be compatible with 1.4 VMs. BY default, javac compiles for 1.5. The Java 2 SDk’s javac would also by default compile against its own bootstrap classes, so we need to tell javac to compile against JDK 1.4 bootstrap classes instead. We do this with -bootclasspath and -extdirs. Failing to do this might allow compilation against a Java 2 Platform API that would not be present on a 1.4 VM and would fail at runtime. jar (1) jar (1) java (1) java (1) javadoc (1) javadoc (1) javah (1) javah (1) javap (1) javap (1) jdb (1) jdb (1) Advertisements 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": 10639, "s": 10577, "text": "\nThere are two ways to pass source code file names to\njavac: " }, { "code": null, "e": 10805, "s": 10639, "text": "\nInner class definitions produce additional class files.\nThese class files have names combining the inner and outer class names,\nsuch as\nMyClass$MyInnerClass.class. " }, { "code": null, "e": 11057, "s": 10805, "text": "\nYou should arrange source files in a directory tree that reflects\ntheir package tree.\nFor example, if you keep all your source files in\n/workspace, the source code for\ncom.mysoft.mypack.MyClass should be in\n/workspace/com/mysoft/mypack/MyClass.java. " }, { "code": null, "e": 11226, "s": 11057, "text": "\nBy default, the compiler puts each class file in the same\ndirectory as its source file.\nYou can specify a separate\ndestination directory with\n-d (see\nOPTIONS, below).\n" }, { "code": null, "e": 11402, "s": 11226, "text": "\nFor example, when you subclass\njava.applet.Applet, you are also\nusing Applet’s ancestor classes:\njava.awt.Panel, java.awt.Container, java.awt.Component, and\njava.awt.Object. " }, { "code": null, "e": 11820, "s": 11402, "text": "\nWhen the compiler needs type information, it looks for a source\nfile or class file which defines the type.\nThe compiler searches\nfirst in the bootstrap and extension classes, then in the user\nclass path (which by default is the current directory).\nThe user class path is defined by setting the\nCLASSPATH environment variable or by using the\n-classpath command line option.\n(For details, see\nSetting the Class Path.) " }, { "code": null, "e": 12147, "s": 11820, "text": "\nIf you use the\n-sourcepath option, the compiler\nsearches the indicated path for source files; otherwise the\ncompiler searches the user class path both for class files and\nsource files.\nYou can specify different bootstrap or extension\nclasses with the\n-bootclasspath and\n-extdirs options; see\nCross-Compilation Options below.\n" }, { "code": null, "e": 12266, "s": 12147, "text": "\nA successful type search may produce a class file, a source file,\nor both.\nHere is how\njavac handles each situation:\n" }, { "code": null, "e": 12363, "s": 12266, "text": "\nBy default,\njavac considers a class file out of date only if\nit is older than the source file.\n" }, { "code": null, "e": 12480, "s": 12363, "text": "\nIf the\n-sourcepath option is not specified, the user class\npath is searched for both source files and class files.\n" }, { "code": null, "e": 12574, "s": 12480, "text": "\nIf\n-d is not specified,\njavac puts the class file in the same\ndirectory as the source file.\n" }, { "code": null, "e": 12664, "s": 12574, "text": "\nNote: The directory specified by\n-d is not automatically\nadded to your user class path.\n" }, { "code": null, "e": 12775, "s": 12664, "text": "\nNote: Classes found through the classpath are subject to\nautomatic recompilation if their sources are found.\n" }, { "code": null, "e": 12929, "s": 12777, "text": "switch (x) {\ncase 1:\n System.out.println(\"1\");\n // No break; statement here.\ncase 2:\n System.out.println(\"2\");\n}\n" }, { "code": null, "e": 13353, "s": 12929, "text": "\nAn argument file can include javac options and source filenames in any\ncombination. The arguments within a file can be space-separated or\nnewline-separated. Filenames within an argument file are relative to\nthe current directory, not the location of the argument file.\nWildcards (*) are not allowed in these lists (such as for specifying\n*.java). Use of the\n@ character to recursively\ninterpret files is not supported. \n" }, { "code": null, "e": 13582, "s": 13353, "text": "\nWhen executing javac, pass in the path and name of each argument\nfile with the\n@ leading character.\nWhen javac encounters an argument beginning with\nthe character\n@, it expands the contents of\nthat file into the argument list.\n" }, { "code": null, "e": 13606, "s": 13584, "text": " C:> javac @argfile\n" }, { "code": null, "e": 13695, "s": 13606, "text": "\nThis argument file could contain the contents of both files shown\nin the next example.\n" }, { "code": null, "e": 13737, "s": 13695, "text": "\nCreate a file named\noptions containing:\n" }, { "code": null, "e": 13802, "s": 13739, "text": "-d classes\n-g\n-sourcepath \\java\\pubs\\ws\\1.3\\src\\share\\classes\n" }, { "code": null, "e": 13847, "s": 13804, "text": "MyClass1.java\nMyClass2.java\nMyClass3.java\n" }, { "code": null, "e": 13876, "s": 13849, "text": "% javac @options @classes\n" }, { "code": null, "e": 13917, "s": 13878, "text": "% javac @path1/options @path2/classes\n" }, { "code": null, "e": 14455, "s": 13919, "text": " % ls\n greetings/\n % ls greetings\n Hello.java\n % cat greetings/Hello.java\n package greetings;\n \n public class Hello {\n public static void main(String[] args) {\n for (int i=0; i < args.length; i++) {\n System.out.println(\"Hello \" + args[i]);\n }\n }\n }\n % javac greetings/Hello.java\n % ls greetings\n Hello.class Hello.java\n % java greetings.Hello World Universe Everyone\n Hello World\n Hello Universe\n Hello Everyone\n" }, { "code": null, "e": 14737, "s": 14457, "text": " % ls\n greetings/\n % ls greetings\n Aloha.java GutenTag.java Hello.java Hi.java\n % javac greetings/*.java\n % ls greetings\n Aloha.class GutenTag.class Hello.class Hi.class\n Aloha.java GutenTag.java Hello.java Hi.java\n" }, { "code": null, "e": 14794, "s": 14739, "text": " % pwd\n /examples\n % javac greetings/Hi.java\n" }, { "code": null, "e": 15258, "s": 14794, "text": "\nSince\ngreetings.Hi refers to other classes in the greetings\npackage, the compiler needs to find these other classes.\nThe example above works, because our default user class path happens\nto be the directory containing the package directory.\nBut suppose\nwe want to recompile this file and not worry about which directory\nwe’re in?\nThen we need to add\n/examples to the user class path.\nWe can do this by setting CLASSPATH, but here we’ll use the\n-classpath option.\n" }, { "code": null, "e": 15321, "s": 15260, "text": " % javac -classpath \\examples /examples/greetings/Hi.java\n" }, { "code": null, "e": 15451, "s": 15321, "text": "\nIf we change\ngreetings.Hi again, to use a banner utility, that\nutility also needs to be accessible through the user class path.\n" }, { "code": null, "e": 15554, "s": 15453, "text": " % javac -classpath /examples:/lib/Banners.jar \\\n /examples/greetings/Hi.java\n" }, { "code": null, "e": 15650, "s": 15554, "text": "\nTo execute a class in greetings, we need access both to greetings\nand to the classes it uses.\n" }, { "code": null, "e": 15714, "s": 15652, "text": " % java -classpath /examples:/lib/Banners.jar greetings.Hi\n" }, { "code": null, "e": 16090, "s": 15716, "text": " % ls\n classes/ lib/ src/\n % ls src\n farewells/\n % ls src/farewells\n Base.java GoodBye.java\n % ls lib\n Banners.jar\n % ls classes\n % javac -sourcepath src -classpath classes:lib/Banners.jar \\\n src/farewells/GoodBye.java -d classes\n % ls classes\n farewells/\n % ls classes/farewells\n Base.class GoodBye.class\n" }, { "code": null, "e": 16253, "s": 16090, "text": "\nNote: The compiler compiled src/farewells/Base.java, even\nthough we didn’t specify it on the command line.\nTo trace automatic compiles, use the\n-verbose option.\n" }, { "code": null, "e": 16354, "s": 16255, "text": " % javac -target 1.4 -bootclasspath jdk1.4.2/lib/classes.zip \\\n -extdirs \"\" OldCode.java\n" }, { "code": null, "e": 16487, "s": 16354, "text": "\nThe\n-target 1.4 option ensures that the generated class files will\nbe compatible with 1.4\nVMs. BY default,\njavac compiles for 1.5.\n" }, { "code": null, "e": 16840, "s": 16487, "text": "\nThe Java 2 SDk’s\njavac would also by default compile against its own\nbootstrap classes, so we need to tell\njavac to compile against\nJDK 1.4 bootstrap classes instead.\nWe do this with\n-bootclasspath and\n-extdirs. Failing to do this might allow compilation against a\nJava 2 Platform\nAPI that would not be present on a 1.4\nVM and would fail at runtime.\n\n" }, { "code": null, "e": 16848, "s": 16840, "text": "jar (1)" }, { "code": null, "e": 16856, "s": 16848, "text": "jar (1)" }, { "code": null, "e": 16865, "s": 16856, "text": "java (1)" }, { "code": null, "e": 16874, "s": 16865, "text": "java (1)" }, { "code": null, "e": 16886, "s": 16874, "text": "javadoc (1)" }, { "code": null, "e": 16898, "s": 16886, "text": "javadoc (1)" }, { "code": null, "e": 16908, "s": 16898, "text": "javah (1)" }, { "code": null, "e": 16918, "s": 16908, "text": "javah (1)" }, { "code": null, "e": 16928, "s": 16918, "text": "javap (1)" }, { "code": null, "e": 16938, "s": 16928, "text": "javap (1)" }, { "code": null, "e": 16946, "s": 16938, "text": "jdb (1)" }, { "code": null, "e": 16954, "s": 16946, "text": "jdb (1)" }, { "code": null, "e": 16973, "s": 16956, "text": "\nAdvertisements\n" }, { "code": null, "e": 17008, "s": 16973, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 17036, "s": 17008, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 17070, "s": 17036, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 17087, "s": 17070, "text": " Frahaan Hussain" }, { "code": null, "e": 17120, "s": 17087, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 17131, "s": 17120, "text": " Pradeep D" }, { "code": null, "e": 17166, "s": 17131, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 17182, "s": 17166, "text": " Musab Zayadneh" }, { "code": null, "e": 17215, "s": 17182, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 17227, "s": 17215, "text": " GUHARAJANM" }, { "code": null, "e": 17259, "s": 17227, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 17267, "s": 17259, "text": " Uplatz" }, { "code": null, "e": 17274, "s": 17267, "text": " Print" }, { "code": null, "e": 17285, "s": 17274, "text": " Add Notes" } ]
Support Vector Machine (SVM) for Anomaly Detection | by Mahbubul Alam | Towards Data Science
An expert or a novice in machine learning, you probably have heard about Support Vector Machine (SVM) — a supervised machine learning algorithm frequently cited and used in classification problems. SVMs use hyperplanes in multi-dimensional space to separate one class of observations from another. Naturally, SVM is used in solving multi-class classification problems. However, SVM is also increasingly being used in one class problem, where all data belong to a single class. In this case, the algorithm is trained to learn what is “normal”, so that when a new data is shown the algorithm can identify whether it should belong to the group or not. If not, the new data is labeled as out of ordinary or anomaly. To learn more about one-class SVM check out this lengthy article by Roemer Vlasveld. One last thing to mention, if you are familiar with sklearn library you will notice that there’s an algorithm specifically designed for what is known as “novelty detection”. It works in a similar fashion as the one I just described in anomaly detection using one-class SVM. In my mind, it’s just the context that determines whether to call it novelty detection or outlier detection or anything like that. Today’s article is a continuation of my series on anomaly, outlier and fraud detection algorithms with hands-on example codes. My previous 7articles touched on different tools and techniques available in the field of anomaly detection, if you are interested to learn about them the following are the links: DBSCAN, an unsupervised algorithm Elliptic Envelope Local Outlier Factor (LOF) Z-score Boxplot Statistical techniques Time series anomaly detection Below is a simple demonstration of One-Class SVM in Python programming language. Note that I am using outlier and anomaly interchangeably. For this demo we need three core libraries — for data wrangling python and numpy, for model building sklearn and for visualization matlotlib. # import librariesimport pandas as pdfrom sklearn.svm import OneClassSVMimport matplotlib.pyplot as pltfrom numpy import where I am using the famous Iris dataset from an online source, so you can practice along without worrying about where to get the data from how to clean that up. # import datadata = pd.read_csv("https://raw.githubusercontent.com/uiuc-cse/data-fa14/gh-pages/data/iris.csv")# input datadf = data[["sepal_length", "sepal_width"]] Instead of hyperparameter tuning as in other classification algorithms, one-class SVM uses nu as a hyperparameter which is used to define what portion of data should be classified as outliers. nu = 0.03 means that the algorithm will designate 3% data as outliers. # model specificationmodel = OneClassSVM(kernel = 'rbf', gamma = 0.001, nu = 0.03).fit(df) The predicted dataset will have either 1 or -1 values, where -1 values are outliers detected by the algorithm. # predictiony_pred = model.predict(df)y_pred # filter outlier indexoutlier_index = where(y_pred == -1) # filter outlier valuesoutlier_values = df.iloc[outlier_index]outlier_values # visualize outputsplt.scatter(data["sepal_length"], df["sepal_width"])plt.scatter(outlier_values["sepal_length"], outlier_values["sepal_width"], c = "r") In this article, I wanted to give a gentle introduction to One-Class SVM — a machine learning algorithm used for fraud/outlier/anomaly detection. I showed some simple steps to build the intuition, but of course, a real-world implementation would require much more experimentation to find out what works and what doesn’t for a particular context and industry. Thanks for following along, to learn more about my work you can follow me on Twitter or LinkedIn
[ { "code": null, "e": 541, "s": 172, "text": "An expert or a novice in machine learning, you probably have heard about Support Vector Machine (SVM) — a supervised machine learning algorithm frequently cited and used in classification problems. SVMs use hyperplanes in multi-dimensional space to separate one class of observations from another. Naturally, SVM is used in solving multi-class classification problems." }, { "code": null, "e": 969, "s": 541, "text": "However, SVM is also increasingly being used in one class problem, where all data belong to a single class. In this case, the algorithm is trained to learn what is “normal”, so that when a new data is shown the algorithm can identify whether it should belong to the group or not. If not, the new data is labeled as out of ordinary or anomaly. To learn more about one-class SVM check out this lengthy article by Roemer Vlasveld." }, { "code": null, "e": 1374, "s": 969, "text": "One last thing to mention, if you are familiar with sklearn library you will notice that there’s an algorithm specifically designed for what is known as “novelty detection”. It works in a similar fashion as the one I just described in anomaly detection using one-class SVM. In my mind, it’s just the context that determines whether to call it novelty detection or outlier detection or anything like that." }, { "code": null, "e": 1681, "s": 1374, "text": "Today’s article is a continuation of my series on anomaly, outlier and fraud detection algorithms with hands-on example codes. My previous 7articles touched on different tools and techniques available in the field of anomaly detection, if you are interested to learn about them the following are the links:" }, { "code": null, "e": 1715, "s": 1681, "text": "DBSCAN, an unsupervised algorithm" }, { "code": null, "e": 1733, "s": 1715, "text": "Elliptic Envelope" }, { "code": null, "e": 1760, "s": 1733, "text": "Local Outlier Factor (LOF)" }, { "code": null, "e": 1768, "s": 1760, "text": "Z-score" }, { "code": null, "e": 1776, "s": 1768, "text": "Boxplot" }, { "code": null, "e": 1799, "s": 1776, "text": "Statistical techniques" }, { "code": null, "e": 1829, "s": 1799, "text": "Time series anomaly detection" }, { "code": null, "e": 1968, "s": 1829, "text": "Below is a simple demonstration of One-Class SVM in Python programming language. Note that I am using outlier and anomaly interchangeably." }, { "code": null, "e": 2110, "s": 1968, "text": "For this demo we need three core libraries — for data wrangling python and numpy, for model building sklearn and for visualization matlotlib." }, { "code": null, "e": 2237, "s": 2110, "text": "# import librariesimport pandas as pdfrom sklearn.svm import OneClassSVMimport matplotlib.pyplot as pltfrom numpy import where" }, { "code": null, "e": 2393, "s": 2237, "text": "I am using the famous Iris dataset from an online source, so you can practice along without worrying about where to get the data from how to clean that up." }, { "code": null, "e": 2558, "s": 2393, "text": "# import datadata = pd.read_csv(\"https://raw.githubusercontent.com/uiuc-cse/data-fa14/gh-pages/data/iris.csv\")# input datadf = data[[\"sepal_length\", \"sepal_width\"]]" }, { "code": null, "e": 2822, "s": 2558, "text": "Instead of hyperparameter tuning as in other classification algorithms, one-class SVM uses nu as a hyperparameter which is used to define what portion of data should be classified as outliers. nu = 0.03 means that the algorithm will designate 3% data as outliers." }, { "code": null, "e": 2913, "s": 2822, "text": "# model specificationmodel = OneClassSVM(kernel = 'rbf', gamma = 0.001, nu = 0.03).fit(df)" }, { "code": null, "e": 3024, "s": 2913, "text": "The predicted dataset will have either 1 or -1 values, where -1 values are outliers detected by the algorithm." }, { "code": null, "e": 3069, "s": 3024, "text": "# predictiony_pred = model.predict(df)y_pred" }, { "code": null, "e": 3204, "s": 3069, "text": "# filter outlier indexoutlier_index = where(y_pred == -1) # filter outlier valuesoutlier_values = df.iloc[outlier_index]outlier_values" }, { "code": null, "e": 3359, "s": 3204, "text": "# visualize outputsplt.scatter(data[\"sepal_length\"], df[\"sepal_width\"])plt.scatter(outlier_values[\"sepal_length\"], outlier_values[\"sepal_width\"], c = \"r\")" }, { "code": null, "e": 3718, "s": 3359, "text": "In this article, I wanted to give a gentle introduction to One-Class SVM — a machine learning algorithm used for fraud/outlier/anomaly detection. I showed some simple steps to build the intuition, but of course, a real-world implementation would require much more experimentation to find out what works and what doesn’t for a particular context and industry." } ]
Deploying a basic Streamlit app. This article demonstrates the... | by KSV Muralidhar | Towards Data Science
Streamlit is an app framework to deploy machine learning apps built using Python. It is an open-source framework which is similar to the Shiny package in R. This article assumes the reader to have basic working knowledge of Conda environment, Git and machine learning with Python. We’ll fit a Logistic Regression model to the Iris dataset from the Scikit-Learn package. The code below splits the dataset into train and test sets, to evaluate the model after deployment on the test set. We’ll use the mutual information metric for feature selection using ‘SelectKBest’ method. Hyperparameter tuning of ‘SelectKBest’ and the regularization parameter of Logistic Regression is done using GridSearchCV with 3 folds. From the above ‘GridSearchCV’ result, only 3 input features were found to be important. We’ve refit the pipeline to the data using the best hyperparameters found from ‘GridSearchCV’ and found that ‘sepal width (cm)’ wasn’t important. We’ll build another model by eliminating the ‘feature_selection’ step from the pipeline. Also, the ‘sepal width (cm)’ column is removed from the training data. The above ‘GridSearchCV’ result returned the same cross-validation score for model 1 & 2. However, we’ll deploy ‘model 1' to keep things simple . The ‘model 1’ is saved using ‘joblib’ to a file named ‘iris_model.pkl’. Once the model is developed, evaluated and saved, we need to import the ‘streamlit’ package to develop our app. Using the (above) code we used for model development will not work. We need to create a new Python script (not a Jupyter notebook) for model deployment. We’ll create a deployment/project folder having The deployment Python script named ‘iris_streamlit_demo.py’ (by convention, the name of the file should be ‘streamlit_app.py’, but it is not compulsory).The saved model (‘iris_model.pkl’).‘requirements.txt’ file which specifies the packages to be installed. The versions of the packages must be specified to avoid the ‘it works on my machine’ problem. The version of the packages must match with the ones in our Conda environment. The ‘requirements.txt’ file and the deployment/project folder structure we’ll be using are shown below. The deployment Python script named ‘iris_streamlit_demo.py’ (by convention, the name of the file should be ‘streamlit_app.py’, but it is not compulsory). The saved model (‘iris_model.pkl’). ‘requirements.txt’ file which specifies the packages to be installed. The versions of the packages must be specified to avoid the ‘it works on my machine’ problem. The version of the packages must match with the ones in our Conda environment. The ‘requirements.txt’ file and the deployment/project folder structure we’ll be using are shown below. streamlit==0.79.0numpy==1.19.2joblib==0.17.0scikit-learn==0.23.2 ‘iris_streamlit_demo.py’ is shown below. We’ve added 4 numeric input text boxes using ‘numeric_input’ method of Streamlit. We’ve added a ‘Predict’ button which returns an error ‘Inputs must be greater than 0’ when any of the input is lesser than or equal to 0. If all the inputs are greater than 0, then the result would be a prediction. We’ll test the app by running it from the terminal using the below command. The screenshot of the app running on the local machine is shown below. To deploy the app to Streamlit Sharing, we need to create an account with Streamlit. Once the account is created, we need to push the deployment folder (local repo) to ‘Github’ (remote repo) and Streamlit takes care of the rest. Below is the screenshot of the deployment page on streamlit.io. Below is the screenshot of the deployed app to Streamlit Sharing. The test set used to evaluate the deployed model is shown below. The score on unseen data is found to be 1 (by chance). This is a demonstration of deploying a basic app to Streamlit Sharing. An important point to note is that the apps deployed to Streamlit Sharing are not private. Streamlit has become an alternative to Flask for deploying machine learning apps. Apps built using Streamlit can also be deployed on popular cloud platforms (not only Streamlit Sharing).
[ { "code": null, "e": 452, "s": 171, "text": "Streamlit is an app framework to deploy machine learning apps built using Python. It is an open-source framework which is similar to the Shiny package in R. This article assumes the reader to have basic working knowledge of Conda environment, Git and machine learning with Python." }, { "code": null, "e": 883, "s": 452, "text": "We’ll fit a Logistic Regression model to the Iris dataset from the Scikit-Learn package. The code below splits the dataset into train and test sets, to evaluate the model after deployment on the test set. We’ll use the mutual information metric for feature selection using ‘SelectKBest’ method. Hyperparameter tuning of ‘SelectKBest’ and the regularization parameter of Logistic Regression is done using GridSearchCV with 3 folds." }, { "code": null, "e": 1117, "s": 883, "text": "From the above ‘GridSearchCV’ result, only 3 input features were found to be important. We’ve refit the pipeline to the data using the best hyperparameters found from ‘GridSearchCV’ and found that ‘sepal width (cm)’ wasn’t important." }, { "code": null, "e": 1277, "s": 1117, "text": "We’ll build another model by eliminating the ‘feature_selection’ step from the pipeline. Also, the ‘sepal width (cm)’ column is removed from the training data." }, { "code": null, "e": 1495, "s": 1277, "text": "The above ‘GridSearchCV’ result returned the same cross-validation score for model 1 & 2. However, we’ll deploy ‘model 1' to keep things simple . The ‘model 1’ is saved using ‘joblib’ to a file named ‘iris_model.pkl’." }, { "code": null, "e": 1808, "s": 1495, "text": "Once the model is developed, evaluated and saved, we need to import the ‘streamlit’ package to develop our app. Using the (above) code we used for model development will not work. We need to create a new Python script (not a Jupyter notebook) for model deployment. We’ll create a deployment/project folder having" }, { "code": null, "e": 2343, "s": 1808, "text": "The deployment Python script named ‘iris_streamlit_demo.py’ (by convention, the name of the file should be ‘streamlit_app.py’, but it is not compulsory).The saved model (‘iris_model.pkl’).‘requirements.txt’ file which specifies the packages to be installed. The versions of the packages must be specified to avoid the ‘it works on my machine’ problem. The version of the packages must match with the ones in our Conda environment. The ‘requirements.txt’ file and the deployment/project folder structure we’ll be using are shown below." }, { "code": null, "e": 2497, "s": 2343, "text": "The deployment Python script named ‘iris_streamlit_demo.py’ (by convention, the name of the file should be ‘streamlit_app.py’, but it is not compulsory)." }, { "code": null, "e": 2533, "s": 2497, "text": "The saved model (‘iris_model.pkl’)." }, { "code": null, "e": 2880, "s": 2533, "text": "‘requirements.txt’ file which specifies the packages to be installed. The versions of the packages must be specified to avoid the ‘it works on my machine’ problem. The version of the packages must match with the ones in our Conda environment. The ‘requirements.txt’ file and the deployment/project folder structure we’ll be using are shown below." }, { "code": null, "e": 2945, "s": 2880, "text": "streamlit==0.79.0numpy==1.19.2joblib==0.17.0scikit-learn==0.23.2" }, { "code": null, "e": 3283, "s": 2945, "text": "‘iris_streamlit_demo.py’ is shown below. We’ve added 4 numeric input text boxes using ‘numeric_input’ method of Streamlit. We’ve added a ‘Predict’ button which returns an error ‘Inputs must be greater than 0’ when any of the input is lesser than or equal to 0. If all the inputs are greater than 0, then the result would be a prediction." }, { "code": null, "e": 3430, "s": 3283, "text": "We’ll test the app by running it from the terminal using the below command. The screenshot of the app running on the local machine is shown below." }, { "code": null, "e": 3723, "s": 3430, "text": "To deploy the app to Streamlit Sharing, we need to create an account with Streamlit. Once the account is created, we need to push the deployment folder (local repo) to ‘Github’ (remote repo) and Streamlit takes care of the rest. Below is the screenshot of the deployment page on streamlit.io." }, { "code": null, "e": 3789, "s": 3723, "text": "Below is the screenshot of the deployed app to Streamlit Sharing." }, { "code": null, "e": 3909, "s": 3789, "text": "The test set used to evaluate the deployed model is shown below. The score on unseen data is found to be 1 (by chance)." } ]
Finding first non-repeating character JavaScript
We have an array of Numbers/String literals where most of the entries are repeated. Our job is to write a function that takes in this array and returns the index of first such element which does not make consecutive appearances. If there are no such elements in the array, our function should return -1. So now, let's write the code for this function. We will use a simple loop to iterate over the array and return where we find non-repeating characters, if we find no such characters, we return -1 − const arr = ['d', 'd', 'e', 'e', 'e', 'k', 'j', 'j', 'h']; const firstNonRepeating = arr => { let count = 0; for(let ind = 0; ind < arr.length-1; ind++){ if(arr[ind] !== arr[ind+1]){ if(!count){ return ind; }; count = 0; } else { count++; } }; return -1; }; console.log(firstNonRepeating(arr)); The output in the console will be − 5
[ { "code": null, "e": 1291, "s": 1062, "text": "We have an array of Numbers/String literals where most of the entries are repeated. Our job is\nto write a function that takes in this array and returns the index of first such element which does\nnot make consecutive appearances." }, { "code": null, "e": 1563, "s": 1291, "text": "If there are no such elements in the array, our function should return -1. So now, let's write the\ncode for this function. We will use a simple loop to iterate over the array and return where we\nfind non-repeating characters, if we find no such characters, we return -1 −" }, { "code": null, "e": 1936, "s": 1563, "text": "const arr = ['d', 'd', 'e', 'e', 'e', 'k', 'j', 'j', 'h'];\nconst firstNonRepeating = arr => {\n let count = 0;\n for(let ind = 0; ind < arr.length-1; ind++){\n if(arr[ind] !== arr[ind+1]){\n if(!count){\n return ind;\n };\n count = 0;\n } else {\n count++;\n }\n };\n return -1;\n};\nconsole.log(firstNonRepeating(arr));" }, { "code": null, "e": 1972, "s": 1936, "text": "The output in the console will be −" }, { "code": null, "e": 1974, "s": 1972, "text": "5" } ]
Segment-Tree Module in Python - GeeksforGeeks
21 Aug, 2021 Prerequisite: Segment Tree Implementation A Segment Tree is a data structure that allows programmers to solve range queries over the given array effectively and to modifying the array values. Basically, Segment Tree is a very flexible and efficient data structure and a large number of problems can be solved with the help of segment trees. Python Segment tree Module is also used to solve range query problems. It performs various operations in given range like sum , max , min, and update value in a range. This modules helps to avoid the implementation of segmentation tree as we can directly use segment tree function for performing all operations. It generally reduces the stress of implementing the Segment tree . Installing Library: pip install segment-tree Query: It is the major function of segment tree which perform operations like finding maximum number in a range, finding minimum number in a range, and finding the sum of given range. It takes 3 arguments as input which are start_index(i.e. from where the range will start), End_index(i.e. upto which index range end) and operation to be performed.Syntax: obj.query(Start_index, End_index, operation_name) Update: The second major function of segment tree is update which will update the value of a particular index within the range.It will replace the existing value present at that index with the new value.Syntax: obj.update(index, value) Example 1: Python3 from segment_tree import SegmentTree # an array with some elementsarr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] # here we are fitting our array# into segment tree where t is# taken as object of segment tree# t will be used for performing# operations on that segmentTree t = SegmentTree(arr) # here we are finding value# of maximum number in a rangea = t.query(2, 9, "max")print("The maximum value of this range is : ", a) # here we are finding the value# of minimum number in a rangea = t.query(2, 9, "min")print("The minimum value of this range is : ", a) # here we are finding the value# of sum of a rangea = t.query(2, 7, "sum")print("The sum of this range is : ", a) # here we are updating the value# of a particular indext.update(2, 25) # it will replace the value of# index '2' with 25print("The updated array is : ", arr) Output: The maximum value of this range is : 10 The minimum value of this range is : 3 The sum of this range is : 33 The updated array is : [1, 2, 25, 4, 5, 6, 7, 8, 9, 10, 11] Example 2: Python3 from segment_tree import SegmentTree # an array with some elementsarr = [14, 28, 55, 105, 78, 4, 24, 99, 48, 200] # here we are fitting our array# into segment tree where t is# taken as object of segment tree# t will be used for performing# operations on that segmentTree t = SegmentTree(arr) # here we are finding value of# maximum number in a rangea = t.query(0, 9, "max")print("The maximum value of this range is : ", a) # here we are finding value of# minimum number in a rangea = t.query(0, 9, "min")print("The minimum value of this range is : ", a) # here we are finding value# of sum of a rangea = t.query(0, 9, "sum")print("The sum of this range is : ", a) # here we are updating the value# of a particular indext.update(5, 0)print("The updated array is : ", arr) # here we are finding value of# sum of a rangea = t.query(1, 5, "sum")print("The sum of this range is : ", a) # here we are updating the value# of a particular indext.update(4, 10)print("The updated array is : ", arr) Output: The maximum value of this range is : 200 The minimum value of this range is : 4 The sum of this range is : 655 The updated array is : [14, 28, 55, 105, 78, 0, 24, 99, 48, 200] The sum of this range is : 266 The updated array is : [14, 28, 55, 105, 10, 0, 24, 99, 48, 200] surindertarika1234 simmytarika5 python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Selecting rows in pandas DataFrame based on conditions Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Split string into list of characters
[ { "code": null, "e": 24292, "s": 24264, "text": "\n21 Aug, 2021" }, { "code": null, "e": 24633, "s": 24292, "text": "Prerequisite: Segment Tree Implementation A Segment Tree is a data structure that allows programmers to solve range queries over the given array effectively and to modifying the array values. Basically, Segment Tree is a very flexible and efficient data structure and a large number of problems can be solved with the help of segment trees." }, { "code": null, "e": 25012, "s": 24633, "text": "Python Segment tree Module is also used to solve range query problems. It performs various operations in given range like sum , max , min, and update value in a range. This modules helps to avoid the implementation of segmentation tree as we can directly use segment tree function for performing all operations. It generally reduces the stress of implementing the Segment tree ." }, { "code": null, "e": 25032, "s": 25012, "text": "Installing Library:" }, { "code": null, "e": 25057, "s": 25032, "text": "pip install segment-tree" }, { "code": null, "e": 25414, "s": 25057, "text": "Query: It is the major function of segment tree which perform operations like finding maximum number in a range, finding minimum number in a range, and finding the sum of given range. It takes 3 arguments as input which are start_index(i.e. from where the range will start), End_index(i.e. upto which index range end) and operation to be performed.Syntax: " }, { "code": null, "e": 25464, "s": 25414, "text": "obj.query(Start_index, End_index, operation_name)" }, { "code": null, "e": 25675, "s": 25464, "text": "Update: The second major function of segment tree is update which will update the value of a particular index within the range.It will replace the existing value present at that index with the new value.Syntax:" }, { "code": null, "e": 25700, "s": 25675, "text": "obj.update(index, value)" }, { "code": null, "e": 25711, "s": 25700, "text": "Example 1:" }, { "code": null, "e": 25719, "s": 25711, "text": "Python3" }, { "code": "from segment_tree import SegmentTree # an array with some elementsarr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] # here we are fitting our array# into segment tree where t is# taken as object of segment tree# t will be used for performing# operations on that segmentTree t = SegmentTree(arr) # here we are finding value# of maximum number in a rangea = t.query(2, 9, \"max\")print(\"The maximum value of this range is : \", a) # here we are finding the value# of minimum number in a rangea = t.query(2, 9, \"min\")print(\"The minimum value of this range is : \", a) # here we are finding the value# of sum of a rangea = t.query(2, 7, \"sum\")print(\"The sum of this range is : \", a) # here we are updating the value# of a particular indext.update(2, 25) # it will replace the value of# index '2' with 25print(\"The updated array is : \", arr)", "e": 26547, "s": 25719, "text": null }, { "code": null, "e": 26556, "s": 26547, "text": "Output: " }, { "code": null, "e": 26729, "s": 26556, "text": "The maximum value of this range is : 10\nThe minimum value of this range is : 3\nThe sum of this range is : 33\nThe updated array is : [1, 2, 25, 4, 5, 6, 7, 8, 9, 10, 11]" }, { "code": null, "e": 26740, "s": 26729, "text": "Example 2:" }, { "code": null, "e": 26748, "s": 26740, "text": "Python3" }, { "code": "from segment_tree import SegmentTree # an array with some elementsarr = [14, 28, 55, 105, 78, 4, 24, 99, 48, 200] # here we are fitting our array# into segment tree where t is# taken as object of segment tree# t will be used for performing# operations on that segmentTree t = SegmentTree(arr) # here we are finding value of# maximum number in a rangea = t.query(0, 9, \"max\")print(\"The maximum value of this range is : \", a) # here we are finding value of# minimum number in a rangea = t.query(0, 9, \"min\")print(\"The minimum value of this range is : \", a) # here we are finding value# of sum of a rangea = t.query(0, 9, \"sum\")print(\"The sum of this range is : \", a) # here we are updating the value# of a particular indext.update(5, 0)print(\"The updated array is : \", arr) # here we are finding value of# sum of a rangea = t.query(1, 5, \"sum\")print(\"The sum of this range is : \", a) # here we are updating the value# of a particular indext.update(4, 10)print(\"The updated array is : \", arr)", "e": 27740, "s": 26748, "text": null }, { "code": null, "e": 27748, "s": 27740, "text": "Output:" }, { "code": null, "e": 28026, "s": 27748, "text": "The maximum value of this range is : 200\nThe minimum value of this range is : 4\nThe sum of this range is : 655\nThe updated array is : [14, 28, 55, 105, 78, 0, 24, 99, 48, 200]\nThe sum of this range is : 266\nThe updated array is : [14, 28, 55, 105, 10, 0, 24, 99, 48, 200]" }, { "code": null, "e": 28045, "s": 28026, "text": "surindertarika1234" }, { "code": null, "e": 28058, "s": 28045, "text": "simmytarika5" }, { "code": null, "e": 28073, "s": 28058, "text": "python-modules" }, { "code": null, "e": 28080, "s": 28073, "text": "Python" }, { "code": null, "e": 28178, "s": 28080, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28210, "s": 28178, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28266, "s": 28210, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28308, "s": 28266, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28350, "s": 28308, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28405, "s": 28350, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 28427, "s": 28405, "text": "Defaultdict in Python" }, { "code": null, "e": 28466, "s": 28427, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28497, "s": 28466, "text": "Python | os.path.join() method" }, { "code": null, "e": 28526, "s": 28497, "text": "Create a directory in Python" } ]
Generate pseudo-random numbers in Python
Many computer applications need random number to be generated. However, none of them generate a truly random number. Python, like any other programming technique, uses a pseudo-random generator. Python’s random generation is based upon Mersenne Twister algorithm that produces 53-bit precision floats. The technique is fast and thread-safe but not suitable from cryptographic purpose. Python’s standard library contains random module which defines various functions for handling randomization. random.seed() − This function initializes the random number generator. When random module is imported, the generator is initialized with the help of system time. To reseed the generator, use any int, str, byte or bytearray object. random.getstate() − This function along with setstate() function helps in reproducing same random data again and again. The getstate() function returns internal state of random number generator. random.setstate() − This function reinstates the internal state of generator. Following functions handle random integer number generation − random.randrange() − This function generates a random integer between given range. It can take three parameters. random.randrange(start, stop, step) The start and step parameters are optional. Their default values are 0 and 1 respectively. Step determines interval between successive numbers. >>> random.randrange(10) 5 >>> random.randrange(10, 20) 17 >>> random.randrange(100, 200, 2) 188 (Note: Remember that output of above statements, and also rest of the statements in this article may not be same as they are randomly generated) random.randint() − This function generates a random integer between two parameters. It is similar to randrange() function without step parameter. Start parameter is mandatory. >>> random.randint(1,10) 6 >>> random.randint(100, 200) 134 Following functions deal with floating point random numbers. random.random() − This function randomly generates a floating point number between 0.0 and 1.0 >>> random.random() 0.668544544081956 random.uniform() − This function returns a floating point random number between two parameters. >>> random.uniform(0.5,1.5) 1.2760281470664903 >>> random.uniform(1,10) 7.336985794193224 >>> random.uniform(10,5) 7.817794757786727 Following functions act upon sequence objects viz. string, list or tuple. random.choice() − This function picks a random element from the sequence. If the sequence is empty, IndexError is thrown. >>> random.choice("Tutorialspoint") 'o' >>> random.choice(range(10)) 2 >>> random.choice([15,31,6,29,55, 5]) 55 >>> random.choice((15,31,6,29,25, 55)) 15 random.choices() − This function chooses multiple elements from a list in random manner. First parameter to this function is the sequence and second parameter is the number of choices to be made. >>> name = "TutorialsPoint" >>> random.choices(name, k = 2) ['T', 'o'] random.shuffle() − This function reorders elements in a mutable sequence and places them randomly. >>> num = [10,20,30,40,50] >>> random.shuffle(num) >>> num [50, 20, 40, 30, 10] random.sample() − This function works with immutable sequence. It returns a list of randomly selected items from the sequence leaving it intact. >>> name = "TutorialsPoint" >>> nm = random.sample(name, k = 2) >>> name, nm ('TutorialsPoint', ['i', 'a'])
[ { "code": null, "e": 1447, "s": 1062, "text": "Many computer applications need random number to be generated. However, none of them generate a truly random number. Python, like any other programming technique, uses a pseudo-random generator. Python’s random generation is based upon Mersenne Twister algorithm that produces 53-bit precision floats. The technique is fast and thread-safe but not suitable from cryptographic purpose." }, { "code": null, "e": 1556, "s": 1447, "text": "Python’s standard library contains random module which defines various functions for handling randomization." }, { "code": null, "e": 1787, "s": 1556, "text": "random.seed() − This function initializes the random number generator. When random module is imported, the generator is initialized with the help of system time. To reseed the generator, use any int, str, byte or bytearray object." }, { "code": null, "e": 1982, "s": 1787, "text": "random.getstate() − This function along with setstate() function helps in reproducing same random data again and again. The getstate() function returns internal state of random number generator." }, { "code": null, "e": 2060, "s": 1982, "text": "random.setstate() − This function reinstates the internal state of generator." }, { "code": null, "e": 2122, "s": 2060, "text": "Following functions handle random integer number generation −" }, { "code": null, "e": 2235, "s": 2122, "text": "random.randrange() − This function generates a random integer between given range. It can take three parameters." }, { "code": null, "e": 2271, "s": 2235, "text": "random.randrange(start, stop, step)" }, { "code": null, "e": 2415, "s": 2271, "text": "The start and step parameters are optional. Their default values are 0 and 1 respectively. Step determines interval between successive numbers." }, { "code": null, "e": 2512, "s": 2415, "text": ">>> random.randrange(10)\n5\n>>> random.randrange(10, 20)\n17\n>>> random.randrange(100, 200, 2)\n188" }, { "code": null, "e": 2657, "s": 2512, "text": "(Note: Remember that output of above statements, and also rest of the statements in this article may not be same as they are randomly generated)" }, { "code": null, "e": 2833, "s": 2657, "text": "random.randint() − This function generates a random integer between two parameters. It is similar to randrange() function without step parameter. Start parameter is mandatory." }, { "code": null, "e": 2893, "s": 2833, "text": ">>> random.randint(1,10)\n6\n>>> random.randint(100, 200)\n134" }, { "code": null, "e": 2954, "s": 2893, "text": "Following functions deal with floating point random numbers." }, { "code": null, "e": 3049, "s": 2954, "text": "random.random() − This function randomly generates a floating point number between 0.0 and 1.0" }, { "code": null, "e": 3087, "s": 3049, "text": ">>> random.random()\n0.668544544081956" }, { "code": null, "e": 3183, "s": 3087, "text": "random.uniform() − This function returns a floating point random number between two parameters." }, { "code": null, "e": 3316, "s": 3183, "text": ">>> random.uniform(0.5,1.5)\n1.2760281470664903\n>>> random.uniform(1,10)\n7.336985794193224\n>>> random.uniform(10,5)\n7.817794757786727" }, { "code": null, "e": 3390, "s": 3316, "text": "Following functions act upon sequence objects viz. string, list or tuple." }, { "code": null, "e": 3512, "s": 3390, "text": "random.choice() − This function picks a random element from the sequence. If the sequence is empty, IndexError is thrown." }, { "code": null, "e": 3666, "s": 3512, "text": ">>> random.choice(\"Tutorialspoint\")\n'o'\n>>> random.choice(range(10))\n2\n>>> random.choice([15,31,6,29,55, 5])\n55\n>>> random.choice((15,31,6,29,25, 55))\n15" }, { "code": null, "e": 3862, "s": 3666, "text": "random.choices() − This function chooses multiple elements from a list in random manner. First parameter to this function is the sequence and second parameter is the number of choices to be made." }, { "code": null, "e": 3933, "s": 3862, "text": ">>> name = \"TutorialsPoint\"\n>>> random.choices(name, k = 2)\n['T', 'o']" }, { "code": null, "e": 4032, "s": 3933, "text": "random.shuffle() − This function reorders elements in a mutable sequence and places them randomly." }, { "code": null, "e": 4112, "s": 4032, "text": ">>> num = [10,20,30,40,50]\n>>> random.shuffle(num)\n>>> num\n[50, 20, 40, 30, 10]" }, { "code": null, "e": 4257, "s": 4112, "text": "random.sample() − This function works with immutable sequence. It returns a list of randomly selected items from the sequence leaving it intact." }, { "code": null, "e": 4365, "s": 4257, "text": ">>> name = \"TutorialsPoint\"\n>>> nm = random.sample(name, k = 2)\n>>> name, nm\n('TutorialsPoint', ['i', 'a'])" } ]
PyTorch for Deep Learning: A Quick Guide for Starters | by Javaid Nabi | Towards Data Science
In 2019, the war for ML frameworks has two main contenders: PyTorch and TensorFlow. There is a growing adoption of PyTorch by researchers and students due to ease of use, while in industry, Tensorflow is currently still the platform of choice. Some of the key advantages of PyTorch are: Simplicity: It is very pythonic and integrates easily with the rest of the Python ecosystem. It is easy to learn, use, extend, and debug. Great API: PyTorch shines in term of usability due to better designed Object Oriented classes which encapsulate all of the important data choices along with the choice of model architecture. The documentation of PyTorch is also very brilliant and helpful for beginners. Dynamic Graphs: PyTorch implements dynamic computational graphs. Which means that the network can change behavior as it is being run, with little or no overhead. This is extremely helpful for debugging and also for constructing sophisticated models with minimal effort. allowing PyTorch expressions to be automatically differentiated. There is a growing popularity of PyTorch in research. Below plot showing monthly number of mentions of the word “PyTorch” as a percentage of all mentions among other deep learning frameworks. We can see there is an steep upward trend of PyTorch in arXiv in 2019 reaching almost 50%. Dynamic graph generation, tight Python language integration, and a relatively simple API makes PyTorch an excellent platform for research and experimentation. PyTorch provides a very clean interface to get the right combination of tools to be installed. Below a snapshot to choose and the corresponding command. Stable represents the most currently tested and supported version of PyTorch. This should be suitable for many users. Preview is available if you want the latest version, not fully tested and supported. You can choose from Anaconda (recommended) and Pip installation packages and supporting various CUDA versions as well. Now we will discuss key PyTorch Library modules like Tensors, Autograd, Optimizers and Neural Networks (NN ) which are essential to create and train neural networks. Tensors are the workhorse of PyTorch. We can think of tensors as multi-dimensional arrays. PyTorch has an extensive library of operations on them provided by the torch module. PyTorch Tensors are very close to the very popular NumPy arrays . In fact, PyTorch features seamless interoperability with NumPy. Compared with NumPy arrays, PyTorch tensors have added advantage that both tensors and related operations can run on the CPU or GPU. The second important thing that PyTorch provides allows tensors to keep track of the operations performed on them that helps to compute gradients or derivatives of an output with respect to any of its inputs. Tensor refers to the generalization of vectors and matrices to an arbitrary number of dimensions. The dimensionality of a tensor coincides with the number of indexes used to refer to scalar values within the tensor. A tensor of order zero (0D tensor) is just a number or a scalar. A tensor of order one (1D tensor) is an array of numbers or a vector. Similarly a 2nd-order tensor (2D)is an array of vectors or a matrix. Now let us create a tensor in PyTorch. After importing the torch module, we called a function torch.ones that creates a (2D) tensor of size 9 filled with the values 1.0. Other ways include using torch.zeros; zero filled tensor, torch.randn; from random uniform distribution. Each tensor has an associated type and size. The default tensor type when you use the torch.Tensor constructor is torch.FloatTensor. However, you can convert a tensor to a different type (float, long, double, etc.) by specifying it at initialization or later using one of the typecasting methods. There are two ways to specify the initialization type: either by directly calling the constructor of a specific tensor type, such as FloatTensor or LongTensor, or using a special method, torch.tensor(), and providing the dtype. To find the maximum item in a tensor as well as the index that contains the maximum value. These can be done with the max() and argmax() functions. We can also use item() to extract a standard Python value from a 1D tensor. Most functions that operate on a tensor and return a tensor create a new tensor to store the result. If you need an in-place function look for a function with an appended underscore (_) e.g torch.transpose_ will do in-place transpose of a tensor. Converting between tensors and Numpy is very simple using torch.from_numpy & torch.numpy(). Another common operation is reshaping a tensor. This is one of the frequently used operations and very useful too. We can do this with either view() or reshape(): Tensor.reshape() and Tensor.view() though are not the same. Tensor.view() works only on contiguous tensors and will never copy memory. It will raise an error on a non-contiguous tensor. But you can make the tensor contiguous by calling contiguous() and then you can call view(). Tensor.reshape() will work on any tensor and can make a clone if it is needed. PyTorch supports broadcasting similar to NumPy. Broadcasting allows you to perform operations between two tensors. Refer here for the broadcasting semantics. Three attributes which uniquely define a tensor are: dtype: What is actually stored in each element of the tensor? This could be floats or integers etc. PyTorch has nine different data types. layout: How we logically interpret this physical memory. The most common layout is a strided tensor. Strides are a list of integers: the k-th stride represents the jump in the memory necessary to go from one element to the next one in the k-th dimension of the Tensor. device: Where the tensor’s physical memory is actually stored, e.g., on a CPU, or a GPU. The torch.device contains a device type ('cpu' or 'cuda') and optional device ordinal for the device type. Autograd is automatic differentiation system. What does automatic differentiation do? Given a network, it calculates the gradients automatically. When computing the forwards pass, autograd simultaneously performs the requested computations and builds up a graph representing the function that computes the gradient. PyTorch tensors can remember where they come from in terms of the operations and parent tensors that originated them, and they can provide the chain of derivatives of such operations with respect to their inputs automatically. This is achieved through requires_grad, if set to True. t= torch.tensor([1.0, 0.0], requires_grad=True) After calculating the gradient, the value of the derivative is automatically populated as a grad attribute of the tensor. For any composition of functions with any number of tensors with requires_grad= True; PyTorch would compute derivatives throughout the chain of functions and accumulate their values in the grad attribute of those tensors. Optimizers are used to update weights and biases i.e. the internal parameters of a model to reduce the error. Please refer to my another article for more details. PyTorch has an torch.optim package with various optimization algorithms like SGD (Stochastic Gradient Descent), Adam, RMSprop etc . Let us see how we can create one of the provided optimizers SGD or Adam. import torch.optim as optimparams = torch.tensor([1.0, 0.0], requires_grad=True)learning_rate = 1e-3## SGDoptimizer = optim.SGD([params], lr=learning_rate)## Adamoptimizer = optim.Adam([params], lr=learning_rate) Without using optimizers, we would need to manually update the model parameters by something like: for params in model.parameters(): params -= params.grad * learning_rate We can use the step() method from our optimizer to take a forward step, instead of manually updating each parameter. optimizer.step() The value of params is updated when step is called. The optimizer looks into params.grad and updates params by subtracting learning_rate times grad from it, exactly as we did in without using optimizer. torch.optim module helps us to abstract away the specific optimization scheme with just passing a list of params. Since there are multiple optimization schemes to choose from, we just need to choose one for our problem and rest the underlying PyTorch library does the magic for us. In PyTorch the torch.nn package defines a set of modules which are similar to the layers of a neural network. A module receives input tensors and computes output tensors. The torch.nn package also defines a set of useful loss functions that are commonly used when training neural networks. Steps of building a neural network are: Neural Network Construction: Create the neural network layers. setting up parameters (weights, biases) Forward Propagation: Calculate the predicted output. Measure error. Back-propagation: After finding the error, we backward propagate our error gradient to update our weight parameters. We do this by taking the derivative of the error function with respect to the parameters of our NN. Iterative Optimization: We want to minimize error as much as possible. We keep updating the parameters iteratively by gradient descent. Let us follow the above steps and create a simple neural network in PyTorch. We call our NNNet here. We’re inheriting from nn.Module. Combined with super().__init__() this creates a class that tracks the architecture and provides a lot of useful methods and attributes. Our neural network Net has one hidden layer self.hl and one output layer self.ol. self.hl = nn.Linear(1, 10) This line creates a module for a linear transformation with 1 inputs and 10 outputs. It also automatically creates the weight and bias tensors. You can access the weight and bias tensors once the network net is created with net.hl.weight and net.hl.bias. We have defined activation using self.relu = nn.ReLU() . PyTorch networks created with nn.Module must have a forward() method defined. It takes in a tensor x and passes it through the operations you defined in the __init__ method. def forward(self, x): hidden = self.hl(x) activation = self.relu(hidden) output = self.ol(activation) We can see that the input tensor goes through the hidden layer, then activation function (relu), then the output layer. Here we have to calculate error or loss and backward propagate our error gradient to update our weight parameters. A loss function takes the (output, target) and computes a value that estimates how far away the output is from the target.There are several different loss functions under the torch.nn package . A simple loss is nn.MSELoss which computes the mean-squared error between the input and the target. output = net(input)loss_fn = nn.MSELoss()loss = loss_fn(output, target) A simple function callloss.backward() propagates the error. Don’t forget to clear the existing gradients though else gradients will be accumulated to existing gradients. After callingloss.backward() have a look at hidden layer bias gradients before and after the backward call. So after calling the backward(), we see the gradients are calculated for the hidden layer. We have already seen how optimizer helps us to update the parameters of the model. # create your optimizeroptimizer = optim.Adam(net.parameters(), lr=1e-2)optimizer.zero_grad() # zero the gradient buffersoutput = net(input) # calculate outputloss = loss_fn(output, target) #calculate lossloss.backward() # calculate gradientoptimizer.step() # update parameters Please be careful not to miss the zero_grad() call. If you miss calling it, gradients would get accumulated at every call to backward, and your gradient descent will not converge. Below a recent tweet from Andrej shows the frustration and the time it can take to fix such bugs. Now with our basic steps (1,2,3) complete, we just need to iteratively train our neural network to find the minimum loss. So we run the training_loop for many epochs until we minimize the loss. Let us run our neural network to train for input x_t and targety_t. We call training_loop for 1500 epochs an pass all other arguments like optimizer, model, loss_fn inputs, and target. After every 300 epochs we print the loss and we can see the loss decreasing after every iteration. Looks like our very basic neural network is learning. We plot the model output (black crosses) and target data (red circles), the model seems to learn quickly. So far we discussed the basic or essential elements of PyTorch to get you started. We can see how modular the code we build with each component providing the basic blocks which can be further extended to create a machine learning solution as per our requirements. Creating machine learning based solutions for real problems involves significant effort into data preparation. However, PyTorch library provides many tools to make data loading easy and more readable like torchvision, torchtext and torchaudio to work with image, text and audio data respectively. Training machine learning models is often very hard. A tool that can help in visualizing our model and understanding the training progress is always needed, when we encounter some problems. TensorBoard is one such tool that helps to log events from our model training, including various scalars (e.g. accuracy, loss), images, histograms etc. Since release of PyTorch 1.2.0, TensorBoard is now a PyTorch built-in feature. Please follow this and this tutorials for installation and use of TensorBoard in Pytorch. Thanks for the read. See you soon with another post :)
[ { "code": null, "e": 290, "s": 46, "text": "In 2019, the war for ML frameworks has two main contenders: PyTorch and TensorFlow. There is a growing adoption of PyTorch by researchers and students due to ease of use, while in industry, Tensorflow is currently still the platform of choice." }, { "code": null, "e": 333, "s": 290, "text": "Some of the key advantages of PyTorch are:" }, { "code": null, "e": 471, "s": 333, "text": "Simplicity: It is very pythonic and integrates easily with the rest of the Python ecosystem. It is easy to learn, use, extend, and debug." }, { "code": null, "e": 741, "s": 471, "text": "Great API: PyTorch shines in term of usability due to better designed Object Oriented classes which encapsulate all of the important data choices along with the choice of model architecture. The documentation of PyTorch is also very brilliant and helpful for beginners." }, { "code": null, "e": 1076, "s": 741, "text": "Dynamic Graphs: PyTorch implements dynamic computational graphs. Which means that the network can change behavior as it is being run, with little or no overhead. This is extremely helpful for debugging and also for constructing sophisticated models with minimal effort. allowing PyTorch expressions to be automatically differentiated." }, { "code": null, "e": 1359, "s": 1076, "text": "There is a growing popularity of PyTorch in research. Below plot showing monthly number of mentions of the word “PyTorch” as a percentage of all mentions among other deep learning frameworks. We can see there is an steep upward trend of PyTorch in arXiv in 2019 reaching almost 50%." }, { "code": null, "e": 1518, "s": 1359, "text": "Dynamic graph generation, tight Python language integration, and a relatively simple API makes PyTorch an excellent platform for research and experimentation." }, { "code": null, "e": 1993, "s": 1518, "text": "PyTorch provides a very clean interface to get the right combination of tools to be installed. Below a snapshot to choose and the corresponding command. Stable represents the most currently tested and supported version of PyTorch. This should be suitable for many users. Preview is available if you want the latest version, not fully tested and supported. You can choose from Anaconda (recommended) and Pip installation packages and supporting various CUDA versions as well." }, { "code": null, "e": 2159, "s": 1993, "text": "Now we will discuss key PyTorch Library modules like Tensors, Autograd, Optimizers and Neural Networks (NN ) which are essential to create and train neural networks." }, { "code": null, "e": 2807, "s": 2159, "text": "Tensors are the workhorse of PyTorch. We can think of tensors as multi-dimensional arrays. PyTorch has an extensive library of operations on them provided by the torch module. PyTorch Tensors are very close to the very popular NumPy arrays . In fact, PyTorch features seamless interoperability with NumPy. Compared with NumPy arrays, PyTorch tensors have added advantage that both tensors and related operations can run on the CPU or GPU. The second important thing that PyTorch provides allows tensors to keep track of the operations performed on them that helps to compute gradients or derivatives of an output with respect to any of its inputs." }, { "code": null, "e": 3227, "s": 2807, "text": "Tensor refers to the generalization of vectors and matrices to an arbitrary number of dimensions. The dimensionality of a tensor coincides with the number of indexes used to refer to scalar values within the tensor. A tensor of order zero (0D tensor) is just a number or a scalar. A tensor of order one (1D tensor) is an array of numbers or a vector. Similarly a 2nd-order tensor (2D)is an array of vectors or a matrix." }, { "code": null, "e": 3266, "s": 3227, "text": "Now let us create a tensor in PyTorch." }, { "code": null, "e": 3397, "s": 3266, "text": "After importing the torch module, we called a function torch.ones that creates a (2D) tensor of size 9 filled with the values 1.0." }, { "code": null, "e": 3502, "s": 3397, "text": "Other ways include using torch.zeros; zero filled tensor, torch.randn; from random uniform distribution." }, { "code": null, "e": 4027, "s": 3502, "text": "Each tensor has an associated type and size. The default tensor type when you use the torch.Tensor constructor is torch.FloatTensor. However, you can convert a tensor to a different type (float, long, double, etc.) by specifying it at initialization or later using one of the typecasting methods. There are two ways to specify the initialization type: either by directly calling the constructor of a specific tensor type, such as FloatTensor or LongTensor, or using a special method, torch.tensor(), and providing the dtype." }, { "code": null, "e": 4251, "s": 4027, "text": "To find the maximum item in a tensor as well as the index that contains the maximum value. These can be done with the max() and argmax() functions. We can also use item() to extract a standard Python value from a 1D tensor." }, { "code": null, "e": 4498, "s": 4251, "text": "Most functions that operate on a tensor and return a tensor create a new tensor to store the result. If you need an in-place function look for a function with an appended underscore (_) e.g torch.transpose_ will do in-place transpose of a tensor." }, { "code": null, "e": 4590, "s": 4498, "text": "Converting between tensors and Numpy is very simple using torch.from_numpy & torch.numpy()." }, { "code": null, "e": 4753, "s": 4590, "text": "Another common operation is reshaping a tensor. This is one of the frequently used operations and very useful too. We can do this with either view() or reshape():" }, { "code": null, "e": 4813, "s": 4753, "text": "Tensor.reshape() and Tensor.view() though are not the same." }, { "code": null, "e": 5032, "s": 4813, "text": "Tensor.view() works only on contiguous tensors and will never copy memory. It will raise an error on a non-contiguous tensor. But you can make the tensor contiguous by calling contiguous() and then you can call view()." }, { "code": null, "e": 5111, "s": 5032, "text": "Tensor.reshape() will work on any tensor and can make a clone if it is needed." }, { "code": null, "e": 5269, "s": 5111, "text": "PyTorch supports broadcasting similar to NumPy. Broadcasting allows you to perform operations between two tensors. Refer here for the broadcasting semantics." }, { "code": null, "e": 5322, "s": 5269, "text": "Three attributes which uniquely define a tensor are:" }, { "code": null, "e": 5461, "s": 5322, "text": "dtype: What is actually stored in each element of the tensor? This could be floats or integers etc. PyTorch has nine different data types." }, { "code": null, "e": 5730, "s": 5461, "text": "layout: How we logically interpret this physical memory. The most common layout is a strided tensor. Strides are a list of integers: the k-th stride represents the jump in the memory necessary to go from one element to the next one in the k-th dimension of the Tensor." }, { "code": null, "e": 5926, "s": 5730, "text": "device: Where the tensor’s physical memory is actually stored, e.g., on a CPU, or a GPU. The torch.device contains a device type ('cpu' or 'cuda') and optional device ordinal for the device type." }, { "code": null, "e": 6242, "s": 5926, "text": "Autograd is automatic differentiation system. What does automatic differentiation do? Given a network, it calculates the gradients automatically. When computing the forwards pass, autograd simultaneously performs the requested computations and builds up a graph representing the function that computes the gradient." }, { "code": null, "e": 6525, "s": 6242, "text": "PyTorch tensors can remember where they come from in terms of the operations and parent tensors that originated them, and they can provide the chain of derivatives of such operations with respect to their inputs automatically. This is achieved through requires_grad, if set to True." }, { "code": null, "e": 6573, "s": 6525, "text": "t= torch.tensor([1.0, 0.0], requires_grad=True)" }, { "code": null, "e": 6917, "s": 6573, "text": "After calculating the gradient, the value of the derivative is automatically populated as a grad attribute of the tensor. For any composition of functions with any number of tensors with requires_grad= True; PyTorch would compute derivatives throughout the chain of functions and accumulate their values in the grad attribute of those tensors." }, { "code": null, "e": 7080, "s": 6917, "text": "Optimizers are used to update weights and biases i.e. the internal parameters of a model to reduce the error. Please refer to my another article for more details." }, { "code": null, "e": 7212, "s": 7080, "text": "PyTorch has an torch.optim package with various optimization algorithms like SGD (Stochastic Gradient Descent), Adam, RMSprop etc ." }, { "code": null, "e": 7285, "s": 7212, "text": "Let us see how we can create one of the provided optimizers SGD or Adam." }, { "code": null, "e": 7498, "s": 7285, "text": "import torch.optim as optimparams = torch.tensor([1.0, 0.0], requires_grad=True)learning_rate = 1e-3## SGDoptimizer = optim.SGD([params], lr=learning_rate)## Adamoptimizer = optim.Adam([params], lr=learning_rate)" }, { "code": null, "e": 7597, "s": 7498, "text": "Without using optimizers, we would need to manually update the model parameters by something like:" }, { "code": null, "e": 7680, "s": 7597, "text": " for params in model.parameters(): params -= params.grad * learning_rate" }, { "code": null, "e": 7797, "s": 7680, "text": "We can use the step() method from our optimizer to take a forward step, instead of manually updating each parameter." }, { "code": null, "e": 7814, "s": 7797, "text": "optimizer.step()" }, { "code": null, "e": 8017, "s": 7814, "text": "The value of params is updated when step is called. The optimizer looks into params.grad and updates params by subtracting learning_rate times grad from it, exactly as we did in without using optimizer." }, { "code": null, "e": 8299, "s": 8017, "text": "torch.optim module helps us to abstract away the specific optimization scheme with just passing a list of params. Since there are multiple optimization schemes to choose from, we just need to choose one for our problem and rest the underlying PyTorch library does the magic for us." }, { "code": null, "e": 8589, "s": 8299, "text": "In PyTorch the torch.nn package defines a set of modules which are similar to the layers of a neural network. A module receives input tensors and computes output tensors. The torch.nn package also defines a set of useful loss functions that are commonly used when training neural networks." }, { "code": null, "e": 8629, "s": 8589, "text": "Steps of building a neural network are:" }, { "code": null, "e": 8732, "s": 8629, "text": "Neural Network Construction: Create the neural network layers. setting up parameters (weights, biases)" }, { "code": null, "e": 8800, "s": 8732, "text": "Forward Propagation: Calculate the predicted output. Measure error." }, { "code": null, "e": 9017, "s": 8800, "text": "Back-propagation: After finding the error, we backward propagate our error gradient to update our weight parameters. We do this by taking the derivative of the error function with respect to the parameters of our NN." }, { "code": null, "e": 9153, "s": 9017, "text": "Iterative Optimization: We want to minimize error as much as possible. We keep updating the parameters iteratively by gradient descent." }, { "code": null, "e": 9230, "s": 9153, "text": "Let us follow the above steps and create a simple neural network in PyTorch." }, { "code": null, "e": 9423, "s": 9230, "text": "We call our NNNet here. We’re inheriting from nn.Module. Combined with super().__init__() this creates a class that tracks the architecture and provides a lot of useful methods and attributes." }, { "code": null, "e": 9505, "s": 9423, "text": "Our neural network Net has one hidden layer self.hl and one output layer self.ol." }, { "code": null, "e": 9532, "s": 9505, "text": "self.hl = nn.Linear(1, 10)" }, { "code": null, "e": 9787, "s": 9532, "text": "This line creates a module for a linear transformation with 1 inputs and 10 outputs. It also automatically creates the weight and bias tensors. You can access the weight and bias tensors once the network net is created with net.hl.weight and net.hl.bias." }, { "code": null, "e": 9844, "s": 9787, "text": "We have defined activation using self.relu = nn.ReLU() ." }, { "code": null, "e": 10018, "s": 9844, "text": "PyTorch networks created with nn.Module must have a forward() method defined. It takes in a tensor x and passes it through the operations you defined in the __init__ method." }, { "code": null, "e": 10126, "s": 10018, "text": "def forward(self, x): hidden = self.hl(x) activation = self.relu(hidden) output = self.ol(activation)" }, { "code": null, "e": 10246, "s": 10126, "text": "We can see that the input tensor goes through the hidden layer, then activation function (relu), then the output layer." }, { "code": null, "e": 10361, "s": 10246, "text": "Here we have to calculate error or loss and backward propagate our error gradient to update our weight parameters." }, { "code": null, "e": 10655, "s": 10361, "text": "A loss function takes the (output, target) and computes a value that estimates how far away the output is from the target.There are several different loss functions under the torch.nn package . A simple loss is nn.MSELoss which computes the mean-squared error between the input and the target." }, { "code": null, "e": 10727, "s": 10655, "text": "output = net(input)loss_fn = nn.MSELoss()loss = loss_fn(output, target)" }, { "code": null, "e": 11005, "s": 10727, "text": "A simple function callloss.backward() propagates the error. Don’t forget to clear the existing gradients though else gradients will be accumulated to existing gradients. After callingloss.backward() have a look at hidden layer bias gradients before and after the backward call." }, { "code": null, "e": 11096, "s": 11005, "text": "So after calling the backward(), we see the gradients are calculated for the hidden layer." }, { "code": null, "e": 11179, "s": 11096, "text": "We have already seen how optimizer helps us to update the parameters of the model." }, { "code": null, "e": 11472, "s": 11179, "text": "# create your optimizeroptimizer = optim.Adam(net.parameters(), lr=1e-2)optimizer.zero_grad() # zero the gradient buffersoutput = net(input) # calculate outputloss = loss_fn(output, target) #calculate lossloss.backward() # calculate gradientoptimizer.step() # update parameters" }, { "code": null, "e": 11750, "s": 11472, "text": "Please be careful not to miss the zero_grad() call. If you miss calling it, gradients would get accumulated at every call to backward, and your gradient descent will not converge. Below a recent tweet from Andrej shows the frustration and the time it can take to fix such bugs." }, { "code": null, "e": 11944, "s": 11750, "text": "Now with our basic steps (1,2,3) complete, we just need to iteratively train our neural network to find the minimum loss. So we run the training_loop for many epochs until we minimize the loss." }, { "code": null, "e": 12012, "s": 11944, "text": "Let us run our neural network to train for input x_t and targety_t." }, { "code": null, "e": 12282, "s": 12012, "text": "We call training_loop for 1500 epochs an pass all other arguments like optimizer, model, loss_fn inputs, and target. After every 300 epochs we print the loss and we can see the loss decreasing after every iteration. Looks like our very basic neural network is learning." }, { "code": null, "e": 12388, "s": 12282, "text": "We plot the model output (black crosses) and target data (red circles), the model seems to learn quickly." }, { "code": null, "e": 12652, "s": 12388, "text": "So far we discussed the basic or essential elements of PyTorch to get you started. We can see how modular the code we build with each component providing the basic blocks which can be further extended to create a machine learning solution as per our requirements." }, { "code": null, "e": 12949, "s": 12652, "text": "Creating machine learning based solutions for real problems involves significant effort into data preparation. However, PyTorch library provides many tools to make data loading easy and more readable like torchvision, torchtext and torchaudio to work with image, text and audio data respectively." }, { "code": null, "e": 13460, "s": 12949, "text": "Training machine learning models is often very hard. A tool that can help in visualizing our model and understanding the training progress is always needed, when we encounter some problems. TensorBoard is one such tool that helps to log events from our model training, including various scalars (e.g. accuracy, loss), images, histograms etc. Since release of PyTorch 1.2.0, TensorBoard is now a PyTorch built-in feature. Please follow this and this tutorials for installation and use of TensorBoard in Pytorch." } ]
Createview - Class Based Views Django - GeeksforGeeks
16 Jan, 2020 Create View refers to a view (logic) to create an instance of a table in the database. We have already discussed basics of Create View in Create View – Function based Views Django. Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based views: Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed by separate methods instead of conditional branching. Object oriented techniques such as mixins (multiple inheritance) can be used to factor code into reusable components. Class based views are simpler and efficient to manage than function-based views. A function based view with tons of lines of code can be converted into a class based views with few lines only. This is where Object Oriented Programming comes into impact. Illustration of How to create and use create view using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? After you have a project and an app, let’s create a model of which we will be creating instances through our view. In geeks/models.py, # import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name "GeeksModel"class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() # renames the instances of the model # with their title name def __str__(self): return self.title After creating this model, we need to run two commands in order to create Database for the same. Python manage.py makemigrations Python manage.py migrate Class Based Views automatically setup everything from A to Z. One just needs to specify which model to create Create View for and the fields. Then Class based CreateView will automatically try to find a template in app_name/modelname_form.html. In our case it is geeks/templates/geeks/geeksmodel_form.html. Let’s create our class based view. In geeks/views.py, from django.views.generic.edit import CreateViewfrom .models import GeeksModel class GeeksCreate(CreateView): # specify the model for create view model = GeeksModel # specify the fields to be displayed fields = ['title', 'description'] Now create a url path to map the view. In geeks/urls.py, from django.urls import path # importing views from views..pyfrom .views import GeeksCreateurlpatterns = [ path('', GeeksCreate.as_view() ),] Create a template in templates/geeks/geeksmodel_form.html, <form method="POST" enctype="multipart/form-data"> <!-- Security token --> {% csrf_token %} <!-- Using the formset --> {{ form.as_p }} <input type="submit" value="Submit"></form> Let’s check what is there on http://localhost:8000/ Now let’s try to enter data in this form, Bingo.! Create view is working and we can verify it using the instance created through the admin panel.This way one can create create view for a model in Django. Django-views Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() sum() function in Python Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe *args and **kwargs in Python Graph Plotting in Python | Set 1 Print lists in Python (4 Different Ways)
[ { "code": null, "e": 23937, "s": 23909, "text": "\n16 Jan, 2020" }, { "code": null, "e": 24347, "s": 23937, "text": "Create View refers to a view (logic) to create an instance of a table in the database. We have already discussed basics of Create View in Create View – Function based Views Django. Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based views:" }, { "code": null, "e": 24490, "s": 24347, "text": "Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed by separate methods instead of conditional branching." }, { "code": null, "e": 24608, "s": 24490, "text": "Object oriented techniques such as mixins (multiple inheritance) can be used to factor code into reusable components." }, { "code": null, "e": 24862, "s": 24608, "text": "Class based views are simpler and efficient to manage than function-based views. A function based view with tons of lines of code can be converted into a class based views with few lines only. This is where Object Oriented Programming comes into impact." }, { "code": null, "e": 24996, "s": 24862, "text": "Illustration of How to create and use create view using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 25083, "s": 24996, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 25134, "s": 25083, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 25167, "s": 25134, "text": "How to Create an App in Django ?" }, { "code": null, "e": 25302, "s": 25167, "text": "After you have a project and an app, let’s create a model of which we will be creating instances through our view. In geeks/models.py," }, { "code": "# import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name \"GeeksModel\"class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() # renames the instances of the model # with their title name def __str__(self): return self.title", "e": 25693, "s": 25302, "text": null }, { "code": null, "e": 25790, "s": 25693, "text": "After creating this model, we need to run two commands in order to create Database for the same." }, { "code": null, "e": 25848, "s": 25790, "text": "Python manage.py makemigrations\nPython manage.py migrate\n" }, { "code": null, "e": 26209, "s": 25848, "text": "Class Based Views automatically setup everything from A to Z. One just needs to specify which model to create Create View for and the fields. Then Class based CreateView will automatically try to find a template in app_name/modelname_form.html. In our case it is geeks/templates/geeks/geeksmodel_form.html. Let’s create our class based view. In geeks/views.py," }, { "code": "from django.views.generic.edit import CreateViewfrom .models import GeeksModel class GeeksCreate(CreateView): # specify the model for create view model = GeeksModel # specify the fields to be displayed fields = ['title', 'description']", "e": 26464, "s": 26209, "text": null }, { "code": null, "e": 26521, "s": 26464, "text": "Now create a url path to map the view. In geeks/urls.py," }, { "code": "from django.urls import path # importing views from views..pyfrom .views import GeeksCreateurlpatterns = [ path('', GeeksCreate.as_view() ),]", "e": 26667, "s": 26521, "text": null }, { "code": null, "e": 26726, "s": 26667, "text": "Create a template in templates/geeks/geeksmodel_form.html," }, { "code": "<form method=\"POST\" enctype=\"multipart/form-data\"> <!-- Security token --> {% csrf_token %} <!-- Using the formset --> {{ form.as_p }} <input type=\"submit\" value=\"Submit\"></form>", "e": 26930, "s": 26726, "text": null }, { "code": null, "e": 26982, "s": 26930, "text": "Let’s check what is there on http://localhost:8000/" }, { "code": null, "e": 27024, "s": 26982, "text": "Now let’s try to enter data in this form," }, { "code": null, "e": 27186, "s": 27024, "text": "Bingo.! Create view is working and we can verify it using the instance created through the admin panel.This way one can create create view for a model in Django." }, { "code": null, "e": 27199, "s": 27186, "text": "Django-views" }, { "code": null, "e": 27213, "s": 27199, "text": "Python Django" }, { "code": null, "e": 27220, "s": 27213, "text": "Python" }, { "code": null, "e": 27318, "s": 27220, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27327, "s": 27318, "text": "Comments" }, { "code": null, "e": 27340, "s": 27327, "text": "Old Comments" }, { "code": null, "e": 27362, "s": 27340, "text": "Enumerate() in Python" }, { "code": null, "e": 27394, "s": 27362, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27436, "s": 27394, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27462, "s": 27436, "text": "Python String | replace()" }, { "code": null, "e": 27487, "s": 27462, "text": "sum() function in Python" }, { "code": null, "e": 27524, "s": 27487, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27580, "s": 27524, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27609, "s": 27580, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27642, "s": 27609, "text": "Graph Plotting in Python | Set 1" } ]
How to check Internet connection availability on Android?
This example demonstrates how do I check internet connection availability 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"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Connection Status: " android:textSize="20sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout> Step 3 − Add the following code to src/MainActivity.java import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (haveNetwork()){ Toast.makeText(MainActivity.this, "Network connection is available", Toast.LENGTH_SHORT).show(); } else if (!haveNetwork()) { Toast.makeText(MainActivity.this, "Network connection is not available", Toast.LENGTH_SHORT).show(); } } private boolean haveNetwork(){ boolean have_WIFI= false; boolean have_MobileData = false; ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE); NetworkInfo[] networkInfos = connectivityManager.getAllNetworkInfo(); for(NetworkInfo info:networkInfos){ if (info.getTypeName().equalsIgnoreCase("WIFI"))if (info.isConnected())have_WIFI=true; if (info.getTypeName().equalsIgnoreCase("MOBILE DATA"))if (info.isConnected())have_MobileData=true; } return have_WIFI||have_MobileData; } } 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"> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/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 − Click here to download the project code.
[ { "code": null, "e": 1148, "s": 1062, "text": "This example demonstrates how do I check internet connection availability in android." }, { "code": null, "e": 1276, "s": 1148, "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": 1341, "s": 1276, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2159, "s": 1341, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<android.support.constraint.ConstraintLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Connection Status: \"\n android:textSize=\"20sp\"\n android:textStyle=\"bold\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintLeft_toLeftOf=\"parent\"\n app:layout_constraintRight_toRightOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\" />\n</android.support.constraint.ConstraintLayout>" }, { "code": null, "e": 2216, "s": 2159, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3486, "s": 2216, "text": "import android.net.ConnectivityManager;\nimport android.net.NetworkInfo;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n if (haveNetwork()){\n Toast.makeText(MainActivity.this, \"Network connection is available\", Toast.LENGTH_SHORT).show();\n } else if (!haveNetwork()) {\n Toast.makeText(MainActivity.this, \"Network connection is not available\", Toast.LENGTH_SHORT).show();\n }\n }\n private boolean haveNetwork(){\n boolean have_WIFI= false;\n boolean have_MobileData = false;\n ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);\n NetworkInfo[] networkInfos = connectivityManager.getAllNetworkInfo();\n for(NetworkInfo info:networkInfos){\n if (info.getTypeName().equalsIgnoreCase(\"WIFI\"))if (info.isConnected())have_WIFI=true;\n if (info.getTypeName().equalsIgnoreCase(\"MOBILE DATA\"))if (info.isConnected())have_MobileData=true;\n }\n return have_WIFI||have_MobileData;\n }\n}" }, { "code": null, "e": 3541, "s": 3486, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4288, "s": 3541, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/>\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": 4635, "s": 4288, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 4676, "s": 4635, "text": "Click here to download the project code." } ]
Find the largest number that can be formed with the given digits - GeeksforGeeks
19 Apr, 2022 Given an array of integers arr[] representing digits of a number. The task is to write a program to generate the largest number possible using these digits.Note: The digits in the array are in between 0 and 9. That is, 0<arr[i]<9.Examples: Input : arr[] = {4, 7, 9, 2, 3} Output : Largest number: 97432 Input : arr[] = {8, 6, 0, 4, 6, 4, 2, 7} Output : Largest number: 87664420 Naive Approach: The naive approach is to sort the given array of digits in descending order and then form the number using the digits in array keeping the order of digits in the number same as that of the sorted array.Time Complexity: O(N logN), where N is the number of digits.Below is the implementation of above idea: C++ Java Python3 C# PHP Javascript // C++ program to generate largest possible// number with given digits#include <bits/stdc++.h> using namespace std; // Function to generate largest possible// number with given digitsint findMaxNum(int arr[], int n){ // sort the given array in // descending order sort(arr, arr+n, greater<int>()); int num = arr[0]; // generate the number for(int i=1; i<n; i++) { num = num*10 + arr[i]; } return num;} // Driver codeint main(){ int arr[] = {1, 2, 3, 4, 5, 0}; int n = sizeof(arr)/sizeof(arr[0]); cout<<findMaxNum(arr,n); return 0;} // Java program to generate largest// possible number with given digitsimport java.*;import java.util.Arrays; class GFG{// Function to generate largest// possible number with given digitsstatic int findMaxNum(int arr[], int n){ // sort the given array in // ascending order and then // traverse into descending Arrays.sort(arr); int num = arr[0]; // generate the number for(int i = n - 1; i >= 0; i--) { num = num * 10 + arr[i]; } return num;} // Driver codepublic static void main(String[] args){ int arr[] = {1, 2, 3, 4, 5, 0}; int n = arr.length; System.out.println(findMaxNum(arr, n));}} // This code is contributed by mits # Python3 program to generate largest possible# number with given digits # Function to generate largest possible# number with given digitsdef findMaxNum(arr,n) : # sort the given array in # descending order arr.sort(reverse = True) # initialize num with starting # element of an arr num = arr[0] # generate the number for i in range(1,n) : num = num * 10 + arr[i] return num # Driver codeif __name__ == "__main__" : arr = [1,2,3,4,5,0] n = len(arr) print(findMaxNum(arr,n)) // C# program to generate largest// possible number with given digitsusing System; public class GFG{ // Function to generate largest// possible number with given digitsstatic int findMaxNum(int []arr, int n){ // sort the given array in // ascending order and then // traverse into descending Array.Sort(arr); int num = arr[0]; // generate the number for(int i = n - 1; i >= 0; i--) { num = num * 10 + arr[i]; } return num;} // Driver code static public void Main (){ int []arr = {1, 2, 3, 4, 5, 0}; int n = arr.Length; Console.WriteLine(findMaxNum(arr, n));}} // This code is contributed by Sachin.. <?php// PHP program to generate// largest possible number// with given digits // Function to generate// largest possible number// with given digitsfunction findMaxNum(&$arr, $n){ // sort the given array // in descending order rsort($arr); $num = $arr[0]; // generate the number for($i = 1; $i < $n; $i++) { $num = $num * 10 + $arr[$i]; } return $num;} // Driver code$arr = array(1, 2, 3, 4, 5, 0);$n = sizeof($arr);echo findMaxNum($arr,$n); // This code is contributed// by ChitraNayal?> <script> // Javascript program to generate largest possible// number with given digits // Function to generate largest possible// number with given digitsfunction findMaxNum(arr, n){ // sort the given array in // descending order arr.sort(function(a,b){return b-a;}); var num = arr[0]; // generate the number for(var i=1; i<n; i++) { num = num*10 + arr[i]; } return num;} // Driver codevar arr = [1, 2, 3, 4, 5, 0]; var n = arr.length; document.write(findMaxNum(arr,n)); </script> 543210 Efficient Approach: An efficient approach is to observe that we have to form the number using only digits from 0-9. Hence we can create a hash of size 10 to store the number of occurrences of the digits in the given array into the hash table. Where the key in the hash table will be digits from 0 to 9 and their values will be the count of their occurrences in the array.Finally, print the digits the number of times they occur in descending order starting from the digit 9.Below is the implementation of above approach: C++ C Java Python 3 C# PHP Javascript // C++ program to generate largest possible number with// given digits#include <bits/stdc++.h>using namespace std; // Function to generate largest possible number with given// digitsvoid findMaxNum(int arr[], int n){ // Declare a hash array of size 10 and initialize all // the elements to zero int hash[10] = { 0 }; // store the number of occurrences of the digits in the // given array into the hash table for (int i = 0; i < n; i++) hash[arr[i]]++; // Traverse the hash in descending order to print the // required number for (int i = 9; i >= 0; i--) // Print the number of times a digits occurs for (int j = 0; j < hash[i]; j++) cout << i;} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 0 }; int n = sizeof(arr) / sizeof(arr[0]); findMaxNum(arr, n); return 0;} // This code is contributed by Sania Kumari Gupta // C program to generate largest possible number with// given digits#include <stdio.h> // Function to generate largest possible number with given// digitsvoid findMaxNum(int arr[], int n){ // Declare a hash array of size 10 and initialize all // the elements to zero int hash[10] = { 0 }; // store the number of occurrences of the digits in the // given array into the hash table for (int i = 0; i < n; i++) hash[arr[i]]++; // Traverse the hash in descending order to print the // required number for (int i = 9; i >= 0; i--) // Print the number of times a digits occurs for (int j = 0; j < hash[i]; j++) printf("%d", i);} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 0 }; int n = sizeof(arr) / sizeof(arr[0]); findMaxNum(arr, n); return 0;} // This code is contributed by Sania Kumari Gupta // Java program to generate largest possible number with// given digitsclass GFG { // Function to generate largest possible number with // given digits static void findMaxNum(int arr[], int n) { // Declare a hash array of size 10 and initialize // all the elements to zero int[] hash = new int[10]; // store the number of occurrences of the digits in // the given array into the hash table for (int i = 0; i < n; i++) hash[arr[i]]++; // Traverse the hash in descending order to print // the required number for (int i = 9; i >= 0; i--) // Print the number of times a digits occurs for (int j = 0; j < hash[i]; j++) System.out.print(i); } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5, 0 }; int n = arr.length; findMaxNum(arr, n); }} // This code is contributed by Sania Kumari Gupta # Python 3 program to generate# largest possible number# with given digits # Function to generate# largest possible number# with given digitsdef findMaxNum(arr, n): # Declare a hash array of # size 10 and initialize # all the elements to zero hash = [0] * 10 # store the number of occurrences # of the digits in the given array # into the hash table for i in range(n): hash[arr[i]] += 1 # Traverse the hash in # descending order to # print the required number for i in range(9, -1, -1): # Print the number of # times a digits occurs for j in range(hash[i]): print(i, end = "") # Driver codeif __name__ == "__main__": arr = [1, 2, 3, 4, 5, 0] n =len(arr) findMaxNum(arr,n) # This code is contributed# by ChitraNayal // C# program to generate// largest possible number// with given digitsusing System; class GFG{ // Function to generate// largest possible number// with given digitsstatic void findMaxNum(int[] arr, int n){// Declare a hash array of// size 10 and initialize// all the elements to zeroint[] hash = new int[10]; // store the number of// occurrences of the// digits in the given// array into the hash tablefor(int i = 0; i < n; i++){ hash[arr[i]]++;} // Traverse the hash in// descending order to// print the required numberfor(int i = 9; i >= 0; i--){ // Print the number of // times a digits occurs for(int j = 0; j < hash[i]; j++) Console.Write(i);}} // Driver codepublic static void Main(){ int[] arr = {1, 2, 3, 4, 5, 0}; int n = arr.Length; findMaxNum(arr,n);}} // This code is contributed// by ChitraNayal <?php// PHP program to generate// largest possible number// with given digits // Function to generate// largest possible number// with given digitsfunction findMaxNum($arr, $n){ // Declare a hash array of // size 10 and initialize // all the elements to zero $hash = array_fill(0, 10, 0); // store the number of occurrences // of the digits in the given array // into the hash table for($i = 0; $i < $n; $i++) $hash[$arr[$i]] += 1; // Traverse the hash in // descending order to // print the required number for($i = 9; $i >= 0; $i--) // Print the number of // times a digits occurs for($j = 0; $j < $hash[$i]; $j++) echo $i;} // Driver code$arr = array(1, 2, 3, 4, 5, 0);$n = sizeof($arr);findMaxNum($arr,$n); // This code is contributed// by mits?> <script> // Javascript program to generate largest possible// number with given digits // Function to generate largest possible// number with given digitsfunction findMaxNum( arr, n){ // Declare a hash array of size 10 // and initialize all the elements to zero var hash = Array(10).fill(0); // store the number of occurrences of the digits // in the given array into the hash table for(var i=0; i<n; i++) { hash[arr[i]]++; } // Traverse the hash in descending order // to print the required number for(var i=9; i>=0; i--) { // Print the number of times a digits occurs for(var j=0; j<hash[i]; j++) document.write(i); }} // Driver codevar arr = [1, 2, 3, 4, 5, 0]; var n = arr.length; findMaxNum(arr,n); </script> 543210 Time Complexity: O(N), where N is the number of digits. Auxiliary Space: O(1), size of hash is only 10 which is a constant. ankthon ukasp Mithun Kumar Sach_Code rrrtnx krisania804 Arrays C-String-Question Hash Sorting Quiz Arrays Sorting Arrays Hash Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Arrays Python | Using 2D arrays/lists the right way Linked List vs Array Queue | Set 1 (Introduction and Array Implementation) Find the Missing Number
[ { "code": null, "e": 25517, "s": 25489, "text": "\n19 Apr, 2022" }, { "code": null, "e": 25759, "s": 25517, "text": "Given an array of integers arr[] representing digits of a number. The task is to write a program to generate the largest number possible using these digits.Note: The digits in the array are in between 0 and 9. That is, 0<arr[i]<9.Examples: " }, { "code": null, "e": 25900, "s": 25759, "text": "Input : arr[] = {4, 7, 9, 2, 3}\nOutput : Largest number: 97432 \n\nInput : arr[] = {8, 6, 0, 4, 6, 4, 2, 7}\nOutput : Largest number: 87664420 " }, { "code": null, "e": 26225, "s": 25902, "text": "Naive Approach: The naive approach is to sort the given array of digits in descending order and then form the number using the digits in array keeping the order of digits in the number same as that of the sorted array.Time Complexity: O(N logN), where N is the number of digits.Below is the implementation of above idea: " }, { "code": null, "e": 26229, "s": 26225, "text": "C++" }, { "code": null, "e": 26234, "s": 26229, "text": "Java" }, { "code": null, "e": 26242, "s": 26234, "text": "Python3" }, { "code": null, "e": 26245, "s": 26242, "text": "C#" }, { "code": null, "e": 26249, "s": 26245, "text": "PHP" }, { "code": null, "e": 26260, "s": 26249, "text": "Javascript" }, { "code": "// C++ program to generate largest possible// number with given digits#include <bits/stdc++.h> using namespace std; // Function to generate largest possible// number with given digitsint findMaxNum(int arr[], int n){ // sort the given array in // descending order sort(arr, arr+n, greater<int>()); int num = arr[0]; // generate the number for(int i=1; i<n; i++) { num = num*10 + arr[i]; } return num;} // Driver codeint main(){ int arr[] = {1, 2, 3, 4, 5, 0}; int n = sizeof(arr)/sizeof(arr[0]); cout<<findMaxNum(arr,n); return 0;}", "e": 26870, "s": 26260, "text": null }, { "code": "// Java program to generate largest// possible number with given digitsimport java.*;import java.util.Arrays; class GFG{// Function to generate largest// possible number with given digitsstatic int findMaxNum(int arr[], int n){ // sort the given array in // ascending order and then // traverse into descending Arrays.sort(arr); int num = arr[0]; // generate the number for(int i = n - 1; i >= 0; i--) { num = num * 10 + arr[i]; } return num;} // Driver codepublic static void main(String[] args){ int arr[] = {1, 2, 3, 4, 5, 0}; int n = arr.length; System.out.println(findMaxNum(arr, n));}} // This code is contributed by mits", "e": 27569, "s": 26870, "text": null }, { "code": "# Python3 program to generate largest possible# number with given digits # Function to generate largest possible# number with given digitsdef findMaxNum(arr,n) : # sort the given array in # descending order arr.sort(reverse = True) # initialize num with starting # element of an arr num = arr[0] # generate the number for i in range(1,n) : num = num * 10 + arr[i] return num # Driver codeif __name__ == \"__main__\" : arr = [1,2,3,4,5,0] n = len(arr) print(findMaxNum(arr,n)) ", "e": 28101, "s": 27569, "text": null }, { "code": "// C# program to generate largest// possible number with given digitsusing System; public class GFG{ // Function to generate largest// possible number with given digitsstatic int findMaxNum(int []arr, int n){ // sort the given array in // ascending order and then // traverse into descending Array.Sort(arr); int num = arr[0]; // generate the number for(int i = n - 1; i >= 0; i--) { num = num * 10 + arr[i]; } return num;} // Driver code static public void Main (){ int []arr = {1, 2, 3, 4, 5, 0}; int n = arr.Length; Console.WriteLine(findMaxNum(arr, n));}} // This code is contributed by Sachin..", "e": 28769, "s": 28101, "text": null }, { "code": "<?php// PHP program to generate// largest possible number// with given digits // Function to generate// largest possible number// with given digitsfunction findMaxNum(&$arr, $n){ // sort the given array // in descending order rsort($arr); $num = $arr[0]; // generate the number for($i = 1; $i < $n; $i++) { $num = $num * 10 + $arr[$i]; } return $num;} // Driver code$arr = array(1, 2, 3, 4, 5, 0);$n = sizeof($arr);echo findMaxNum($arr,$n); // This code is contributed// by ChitraNayal?>", "e": 29306, "s": 28769, "text": null }, { "code": "<script> // Javascript program to generate largest possible// number with given digits // Function to generate largest possible// number with given digitsfunction findMaxNum(arr, n){ // sort the given array in // descending order arr.sort(function(a,b){return b-a;}); var num = arr[0]; // generate the number for(var i=1; i<n; i++) { num = num*10 + arr[i]; } return num;} // Driver codevar arr = [1, 2, 3, 4, 5, 0]; var n = arr.length; document.write(findMaxNum(arr,n)); </script>", "e": 29836, "s": 29306, "text": null }, { "code": null, "e": 29843, "s": 29836, "text": "543210" }, { "code": null, "e": 30368, "s": 29845, "text": "Efficient Approach: An efficient approach is to observe that we have to form the number using only digits from 0-9. Hence we can create a hash of size 10 to store the number of occurrences of the digits in the given array into the hash table. Where the key in the hash table will be digits from 0 to 9 and their values will be the count of their occurrences in the array.Finally, print the digits the number of times they occur in descending order starting from the digit 9.Below is the implementation of above approach: " }, { "code": null, "e": 30372, "s": 30368, "text": "C++" }, { "code": null, "e": 30374, "s": 30372, "text": "C" }, { "code": null, "e": 30379, "s": 30374, "text": "Java" }, { "code": null, "e": 30388, "s": 30379, "text": "Python 3" }, { "code": null, "e": 30391, "s": 30388, "text": "C#" }, { "code": null, "e": 30395, "s": 30391, "text": "PHP" }, { "code": null, "e": 30406, "s": 30395, "text": "Javascript" }, { "code": "// C++ program to generate largest possible number with// given digits#include <bits/stdc++.h>using namespace std; // Function to generate largest possible number with given// digitsvoid findMaxNum(int arr[], int n){ // Declare a hash array of size 10 and initialize all // the elements to zero int hash[10] = { 0 }; // store the number of occurrences of the digits in the // given array into the hash table for (int i = 0; i < n; i++) hash[arr[i]]++; // Traverse the hash in descending order to print the // required number for (int i = 9; i >= 0; i--) // Print the number of times a digits occurs for (int j = 0; j < hash[i]; j++) cout << i;} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 0 }; int n = sizeof(arr) / sizeof(arr[0]); findMaxNum(arr, n); return 0;} // This code is contributed by Sania Kumari Gupta", "e": 31303, "s": 30406, "text": null }, { "code": "// C program to generate largest possible number with// given digits#include <stdio.h> // Function to generate largest possible number with given// digitsvoid findMaxNum(int arr[], int n){ // Declare a hash array of size 10 and initialize all // the elements to zero int hash[10] = { 0 }; // store the number of occurrences of the digits in the // given array into the hash table for (int i = 0; i < n; i++) hash[arr[i]]++; // Traverse the hash in descending order to print the // required number for (int i = 9; i >= 0; i--) // Print the number of times a digits occurs for (int j = 0; j < hash[i]; j++) printf(\"%d\", i);} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 0 }; int n = sizeof(arr) / sizeof(arr[0]); findMaxNum(arr, n); return 0;} // This code is contributed by Sania Kumari Gupta", "e": 32178, "s": 31303, "text": null }, { "code": "// Java program to generate largest possible number with// given digitsclass GFG { // Function to generate largest possible number with // given digits static void findMaxNum(int arr[], int n) { // Declare a hash array of size 10 and initialize // all the elements to zero int[] hash = new int[10]; // store the number of occurrences of the digits in // the given array into the hash table for (int i = 0; i < n; i++) hash[arr[i]]++; // Traverse the hash in descending order to print // the required number for (int i = 9; i >= 0; i--) // Print the number of times a digits occurs for (int j = 0; j < hash[i]; j++) System.out.print(i); } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5, 0 }; int n = arr.length; findMaxNum(arr, n); }} // This code is contributed by Sania Kumari Gupta", "e": 33165, "s": 32178, "text": null }, { "code": "# Python 3 program to generate# largest possible number# with given digits # Function to generate# largest possible number# with given digitsdef findMaxNum(arr, n): # Declare a hash array of # size 10 and initialize # all the elements to zero hash = [0] * 10 # store the number of occurrences # of the digits in the given array # into the hash table for i in range(n): hash[arr[i]] += 1 # Traverse the hash in # descending order to # print the required number for i in range(9, -1, -1): # Print the number of # times a digits occurs for j in range(hash[i]): print(i, end = \"\") # Driver codeif __name__ == \"__main__\": arr = [1, 2, 3, 4, 5, 0] n =len(arr) findMaxNum(arr,n) # This code is contributed# by ChitraNayal", "e": 33996, "s": 33165, "text": null }, { "code": "// C# program to generate// largest possible number// with given digitsusing System; class GFG{ // Function to generate// largest possible number// with given digitsstatic void findMaxNum(int[] arr, int n){// Declare a hash array of// size 10 and initialize// all the elements to zeroint[] hash = new int[10]; // store the number of// occurrences of the// digits in the given// array into the hash tablefor(int i = 0; i < n; i++){ hash[arr[i]]++;} // Traverse the hash in// descending order to// print the required numberfor(int i = 9; i >= 0; i--){ // Print the number of // times a digits occurs for(int j = 0; j < hash[i]; j++) Console.Write(i);}} // Driver codepublic static void Main(){ int[] arr = {1, 2, 3, 4, 5, 0}; int n = arr.Length; findMaxNum(arr,n);}} // This code is contributed// by ChitraNayal", "e": 34866, "s": 33996, "text": null }, { "code": "<?php// PHP program to generate// largest possible number// with given digits // Function to generate// largest possible number// with given digitsfunction findMaxNum($arr, $n){ // Declare a hash array of // size 10 and initialize // all the elements to zero $hash = array_fill(0, 10, 0); // store the number of occurrences // of the digits in the given array // into the hash table for($i = 0; $i < $n; $i++) $hash[$arr[$i]] += 1; // Traverse the hash in // descending order to // print the required number for($i = 9; $i >= 0; $i--) // Print the number of // times a digits occurs for($j = 0; $j < $hash[$i]; $j++) echo $i;} // Driver code$arr = array(1, 2, 3, 4, 5, 0);$n = sizeof($arr);findMaxNum($arr,$n); // This code is contributed// by mits?>", "e": 35707, "s": 34866, "text": null }, { "code": "<script> // Javascript program to generate largest possible// number with given digits // Function to generate largest possible// number with given digitsfunction findMaxNum( arr, n){ // Declare a hash array of size 10 // and initialize all the elements to zero var hash = Array(10).fill(0); // store the number of occurrences of the digits // in the given array into the hash table for(var i=0; i<n; i++) { hash[arr[i]]++; } // Traverse the hash in descending order // to print the required number for(var i=9; i>=0; i--) { // Print the number of times a digits occurs for(var j=0; j<hash[i]; j++) document.write(i); }} // Driver codevar arr = [1, 2, 3, 4, 5, 0]; var n = arr.length; findMaxNum(arr,n); </script>", "e": 36502, "s": 35707, "text": null }, { "code": null, "e": 36509, "s": 36502, "text": "543210" }, { "code": null, "e": 36636, "s": 36511, "text": "Time Complexity: O(N), where N is the number of digits. Auxiliary Space: O(1), size of hash is only 10 which is a constant. " }, { "code": null, "e": 36644, "s": 36636, "text": "ankthon" }, { "code": null, "e": 36650, "s": 36644, "text": "ukasp" }, { "code": null, "e": 36663, "s": 36650, "text": "Mithun Kumar" }, { "code": null, "e": 36673, "s": 36663, "text": "Sach_Code" }, { "code": null, "e": 36680, "s": 36673, "text": "rrrtnx" }, { "code": null, "e": 36692, "s": 36680, "text": "krisania804" }, { "code": null, "e": 36699, "s": 36692, "text": "Arrays" }, { "code": null, "e": 36717, "s": 36699, "text": "C-String-Question" }, { "code": null, "e": 36722, "s": 36717, "text": "Hash" }, { "code": null, "e": 36735, "s": 36722, "text": "Sorting Quiz" }, { "code": null, "e": 36742, "s": 36735, "text": "Arrays" }, { "code": null, "e": 36750, "s": 36742, "text": "Sorting" }, { "code": null, "e": 36757, "s": 36750, "text": "Arrays" }, { "code": null, "e": 36762, "s": 36757, "text": "Hash" }, { "code": null, "e": 36770, "s": 36762, "text": "Sorting" }, { "code": null, "e": 36868, "s": 36770, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36891, "s": 36868, "text": "Introduction to Arrays" }, { "code": null, "e": 36936, "s": 36891, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 36957, "s": 36936, "text": "Linked List vs Array" }, { "code": null, "e": 37011, "s": 36957, "text": "Queue | Set 1 (Introduction and Array Implementation)" } ]
An Easy Way to Draw Spider Charts on Tableau — Part I | by Brant W | Towards Data Science
A spider chart is also called radar chart, it can be used to describe data with 3 or more dimensions with quantitative measures. Basically, whenever you want to analyze data using a pie chart, you can consider if you want to try a more advanced radar chart. Tableau is one of the most popular data visualization tools now, but it doesn’t have a built-in spider chart to work with. I read many articles written about how to build a radar chart on Tableau and I worked out this very easy and simple method after trying many other complicated methods. In this article, I will use the data set of Canada University Ranking 2015 posted on Kaggle as an example trying to compare universities in Canada by 6 dimensions: employment, faculty, publication, influence, broad and patents. Let’s have a look at the radar chart I created on Tableau firstly. You can also find the radar chart I created on Tableau from here.👈 >>> Step 1: Pivot Data Holding [Ctrl] select all the 6 qualities > right-click > click [Pivot] Make sure dimension [Quality] names in a column and value [Score] of dimensions in another column. >>> Step 2: Create Calculated Fields No1. [Path] [Path] field tells Tableau the sequencing by which the ‘web’ should walk. CASE [Quality]WHEN 'employment' THEN 1WHEN 'broad' THEN 2WHEN 'influence' THEN 3WHEN 'patents' THEN 4WHEN 'publications' THEN 5WHEN 'faculty' THEN 6END No2. [X-axis] We’ll use Trigonometry to indicate the direction of each corner of our “spider web”, X-axis is cos value of an angel and Y-axis is sin value of the coordinating angel. For example, we want ‘employment’ to sit at 30° direction, then X-axis of ‘employment’ is [Score]*cos 30° = [Score]*(SQRT(3)/2) and Y-axis will be [Score]*sin 30° = [Score]*(1/2) Because we have 6 dimensions dividing 360°, so each dimension will sit at 30°, 90°, 150°, 210°, 270° and 330°. CASE [Quality]WHEN 'employment' THEN [Score]*(SQRT(3)/2)WHEN 'broad' THEN 0WHEN 'influence' THEN [Score]*(-SQRT(3)/2)WHEN 'patents' THEN [Score]*(-SQRT(3)/2)WHEN 'publications' THEN 0WHEN 'faculty' THEN [Score]*(SQRT(3)/2)END No3. [Y-axis] CASE [Quality]WHEN 'employment' THEN [Score]*(1/2)WHEN 'broad' THEN [Score]*1WHEN 'influence' THEN [Score]*(1/2)WHEN 'patents' THEN [Score]*(-1/2)WHEN 'publications' THEN [Score]*(-1)WHEN 'faculty' THEN [Score]*(-1/2)END >>> Step 3: Filter a University Drag [University] filed into ‘Filters’ box and I selected ‘Queen’s University’ for example. >>> Step 4: Build a Polygon Drag [X-axis] into ‘Columns’Drag [Y-axis] into ‘Rows’ Drag [X-axis] into ‘Columns’ Drag [Y-axis] into ‘Rows’ 3. Drag [Quality] into ‘Details’ 4. Drag [Path] into ‘Path’ Then we got this graph, hummmm... 😒looks like “stupid”? Don’t worry! We’ll format it at the end. >>> Step 5: Draw Points & Labels Duplicate an Y-axisChange one of the two charts to ‘Shape’Drag [Quality] into ‘Label’Drag [Quality] into ‘Shape’ Duplicate an Y-axis Change one of the two charts to ‘Shape’ Drag [Quality] into ‘Label’ Drag [Quality] into ‘Shape’ 5. Right-click the [Y-axis] of ‘Shape’ chart > click ‘Dual Axis’ > select ‘Synchronize Axis’ Then we will get this chart. >>> Step 6: Formatting There are a bunch of formatting we need to do: change axes to fixed same length and width. (here, X: -300, +300, Y: -300, +300)choose a color you like for the Polygon, make it transparent and maybe add a border for it.change font of labels.remove all the borders and all the lines.add [University], [Quality] and [Score] into ‘Tooltip’ change axes to fixed same length and width. (here, X: -300, +300, Y: -300, +300) choose a color you like for the Polygon, make it transparent and maybe add a border for it. change font of labels. remove all the borders and all the lines. add [University], [Quality] and [Score] into ‘Tooltip’ Finally, we got the radar chart. Yay!!!!🥳 But wait... it seems a little bit different from a normal radar chart? — we didn’t provide a “web” for it! Don’t worry! I will show how to manually draw a background “web” for our “spiders” in next article An Easy Way to Draw A Spider Chart on Tableau — Part II.👈 Different from other articles showing how to draw it using Tableau coding, I will use a little bit of “trick” there to make the process easier and simpler. Please feel free to contact me if you have any questions about this article! I look forward to talking about data science and data visualizations with you! 🙋‍♂️
[ { "code": null, "e": 430, "s": 172, "text": "A spider chart is also called radar chart, it can be used to describe data with 3 or more dimensions with quantitative measures. Basically, whenever you want to analyze data using a pie chart, you can consider if you want to try a more advanced radar chart." }, { "code": null, "e": 721, "s": 430, "text": "Tableau is one of the most popular data visualization tools now, but it doesn’t have a built-in spider chart to work with. I read many articles written about how to build a radar chart on Tableau and I worked out this very easy and simple method after trying many other complicated methods." }, { "code": null, "e": 949, "s": 721, "text": "In this article, I will use the data set of Canada University Ranking 2015 posted on Kaggle as an example trying to compare universities in Canada by 6 dimensions: employment, faculty, publication, influence, broad and patents." }, { "code": null, "e": 1083, "s": 949, "text": "Let’s have a look at the radar chart I created on Tableau firstly. You can also find the radar chart I created on Tableau from here.👈" }, { "code": null, "e": 1106, "s": 1083, "text": ">>> Step 1: Pivot Data" }, { "code": null, "e": 1178, "s": 1106, "text": "Holding [Ctrl] select all the 6 qualities > right-click > click [Pivot]" }, { "code": null, "e": 1277, "s": 1178, "text": "Make sure dimension [Quality] names in a column and value [Score] of dimensions in another column." }, { "code": null, "e": 1314, "s": 1277, "text": ">>> Step 2: Create Calculated Fields" }, { "code": null, "e": 1326, "s": 1314, "text": "No1. [Path]" }, { "code": null, "e": 1400, "s": 1326, "text": "[Path] field tells Tableau the sequencing by which the ‘web’ should walk." }, { "code": null, "e": 1552, "s": 1400, "text": "CASE [Quality]WHEN 'employment' THEN 1WHEN 'broad' THEN 2WHEN 'influence' THEN 3WHEN 'patents' THEN 4WHEN 'publications' THEN 5WHEN 'faculty' THEN 6END" }, { "code": null, "e": 1566, "s": 1552, "text": "No2. [X-axis]" }, { "code": null, "e": 1734, "s": 1566, "text": "We’ll use Trigonometry to indicate the direction of each corner of our “spider web”, X-axis is cos value of an angel and Y-axis is sin value of the coordinating angel." }, { "code": null, "e": 1913, "s": 1734, "text": "For example, we want ‘employment’ to sit at 30° direction, then X-axis of ‘employment’ is [Score]*cos 30° = [Score]*(SQRT(3)/2) and Y-axis will be [Score]*sin 30° = [Score]*(1/2)" }, { "code": null, "e": 2024, "s": 1913, "text": "Because we have 6 dimensions dividing 360°, so each dimension will sit at 30°, 90°, 150°, 210°, 270° and 330°." }, { "code": null, "e": 2250, "s": 2024, "text": "CASE [Quality]WHEN 'employment' THEN [Score]*(SQRT(3)/2)WHEN 'broad' THEN 0WHEN 'influence' THEN [Score]*(-SQRT(3)/2)WHEN 'patents' THEN [Score]*(-SQRT(3)/2)WHEN 'publications' THEN 0WHEN 'faculty' THEN [Score]*(SQRT(3)/2)END" }, { "code": null, "e": 2264, "s": 2250, "text": "No3. [Y-axis]" }, { "code": null, "e": 2485, "s": 2264, "text": "CASE [Quality]WHEN 'employment' THEN [Score]*(1/2)WHEN 'broad' THEN [Score]*1WHEN 'influence' THEN [Score]*(1/2)WHEN 'patents' THEN [Score]*(-1/2)WHEN 'publications' THEN [Score]*(-1)WHEN 'faculty' THEN [Score]*(-1/2)END" }, { "code": null, "e": 2517, "s": 2485, "text": ">>> Step 3: Filter a University" }, { "code": null, "e": 2609, "s": 2517, "text": "Drag [University] filed into ‘Filters’ box and I selected ‘Queen’s University’ for example." }, { "code": null, "e": 2637, "s": 2609, "text": ">>> Step 4: Build a Polygon" }, { "code": null, "e": 2691, "s": 2637, "text": "Drag [X-axis] into ‘Columns’Drag [Y-axis] into ‘Rows’" }, { "code": null, "e": 2720, "s": 2691, "text": "Drag [X-axis] into ‘Columns’" }, { "code": null, "e": 2746, "s": 2720, "text": "Drag [Y-axis] into ‘Rows’" }, { "code": null, "e": 2779, "s": 2746, "text": "3. Drag [Quality] into ‘Details’" }, { "code": null, "e": 2806, "s": 2779, "text": "4. Drag [Path] into ‘Path’" }, { "code": null, "e": 2903, "s": 2806, "text": "Then we got this graph, hummmm... 😒looks like “stupid”? Don’t worry! We’ll format it at the end." }, { "code": null, "e": 2936, "s": 2903, "text": ">>> Step 5: Draw Points & Labels" }, { "code": null, "e": 3049, "s": 2936, "text": "Duplicate an Y-axisChange one of the two charts to ‘Shape’Drag [Quality] into ‘Label’Drag [Quality] into ‘Shape’" }, { "code": null, "e": 3069, "s": 3049, "text": "Duplicate an Y-axis" }, { "code": null, "e": 3109, "s": 3069, "text": "Change one of the two charts to ‘Shape’" }, { "code": null, "e": 3137, "s": 3109, "text": "Drag [Quality] into ‘Label’" }, { "code": null, "e": 3165, "s": 3137, "text": "Drag [Quality] into ‘Shape’" }, { "code": null, "e": 3258, "s": 3165, "text": "5. Right-click the [Y-axis] of ‘Shape’ chart > click ‘Dual Axis’ > select ‘Synchronize Axis’" }, { "code": null, "e": 3287, "s": 3258, "text": "Then we will get this chart." }, { "code": null, "e": 3310, "s": 3287, "text": ">>> Step 6: Formatting" }, { "code": null, "e": 3357, "s": 3310, "text": "There are a bunch of formatting we need to do:" }, { "code": null, "e": 3646, "s": 3357, "text": "change axes to fixed same length and width. (here, X: -300, +300, Y: -300, +300)choose a color you like for the Polygon, make it transparent and maybe add a border for it.change font of labels.remove all the borders and all the lines.add [University], [Quality] and [Score] into ‘Tooltip’" }, { "code": null, "e": 3727, "s": 3646, "text": "change axes to fixed same length and width. (here, X: -300, +300, Y: -300, +300)" }, { "code": null, "e": 3819, "s": 3727, "text": "choose a color you like for the Polygon, make it transparent and maybe add a border for it." }, { "code": null, "e": 3842, "s": 3819, "text": "change font of labels." }, { "code": null, "e": 3884, "s": 3842, "text": "remove all the borders and all the lines." }, { "code": null, "e": 3939, "s": 3884, "text": "add [University], [Quality] and [Score] into ‘Tooltip’" }, { "code": null, "e": 4088, "s": 3939, "text": "Finally, we got the radar chart. Yay!!!!🥳 But wait... it seems a little bit different from a normal radar chart? — we didn’t provide a “web” for it!" }, { "code": null, "e": 4401, "s": 4088, "text": "Don’t worry! I will show how to manually draw a background “web” for our “spiders” in next article An Easy Way to Draw A Spider Chart on Tableau — Part II.👈 Different from other articles showing how to draw it using Tableau coding, I will use a little bit of “trick” there to make the process easier and simpler." } ]
Python Design Patterns - Gist
Python is an open source scripting language, which is high-level, interpreted, interactive and object-oriented. It is designed to be highly readable. The syntax of Python language is easy to understand and uses English keywords frequently. In this section, we will learn about the different features of Python language. Python is processed at runtime using the interpreter. There is no need to compile program before execution. It is similar to PERL and PHP. Python follows object-oriented style and design patterns. It includes class definition with various features like encapsulation, polymorphism and many more. Python code written in Windows operating system and can be used in Mac operating system. The code can be reused and portable as per the requirements. Python syntax is easy to understand and code. Any developer can understand the syntax of Python within few hours. Python can be described as “programmer-friendly” If needed, a user can write some of Python code in C language as well. It is also possible to put python code in source code in different languages like C++. This makes Python an extensible language. Consider the following important points related to Python programming language − It includes functional and structured programming methods as well as object-oriented programming methods. It includes functional and structured programming methods as well as object-oriented programming methods. It can be used as scripting language or as a programming language. It can be used as scripting language or as a programming language. It includes automatic garbage collection. It includes automatic garbage collection. It includes high-level dynamic data types and supports various dynamic type checking. It includes high-level dynamic data types and supports various dynamic type checking. Python includes a feature of integration with C, C++ and languages like Java. Python includes a feature of integration with C, C++ and languages like Java. To download Python language in your system, follow this link − It includes packages for various operating systems like Windows, MacOS and Linux distributions. In this section, we will learn in brief about a few important tools in Python. The basic declaration of strings is as follows − str = 'Hello World!' The lists of python can be declared as compound data types separated by commas and enclosed within square brackets ([]). list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] A tuple is dynamic data type of Python, which consists of number of values separated by commas. Tuples are enclosed with parentheses. tinytuple = (123, 'john') Python dictionary is a type of hash table. A dictionary key can be almost any data type of Python. The data types are usually numbers or strings. tinydict = {'name': 'omkar','code':6734, 'dept': 'sales'} Python helps in constituting a design pattern using the following parameters − Pattern Name Intent Aliases Motivation Problem Solution Structure Participants Constraints Sample Code 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2719, "s": 2479, "text": "Python is an open source scripting language, which is high-level, interpreted, interactive and object-oriented. It is designed to be highly readable. The syntax of Python language is easy to understand and uses English keywords frequently." }, { "code": null, "e": 2799, "s": 2719, "text": "In this section, we will learn about the different features of Python language." }, { "code": null, "e": 2938, "s": 2799, "text": "Python is processed at runtime using the interpreter. There is no need to compile program before execution. It is similar to PERL and PHP." }, { "code": null, "e": 3095, "s": 2938, "text": "Python follows object-oriented style and design patterns. It includes class definition with various features like encapsulation, polymorphism and many more." }, { "code": null, "e": 3245, "s": 3095, "text": "Python code written in Windows operating system and can be used in Mac operating system. The code can be reused and portable as per the requirements." }, { "code": null, "e": 3408, "s": 3245, "text": "Python syntax is easy to understand and code. Any developer can understand the syntax of Python within few hours. Python can be described as “programmer-friendly”" }, { "code": null, "e": 3608, "s": 3408, "text": "If needed, a user can write some of Python code in C language as well. It is also possible to put python code in source code in different languages like C++. This makes Python an extensible language." }, { "code": null, "e": 3689, "s": 3608, "text": "Consider the following important points related to Python programming language −" }, { "code": null, "e": 3795, "s": 3689, "text": "It includes functional and structured programming methods as well as object-oriented programming methods." }, { "code": null, "e": 3901, "s": 3795, "text": "It includes functional and structured programming methods as well as object-oriented programming methods." }, { "code": null, "e": 3968, "s": 3901, "text": "It can be used as scripting language or as a programming language." }, { "code": null, "e": 4035, "s": 3968, "text": "It can be used as scripting language or as a programming language." }, { "code": null, "e": 4077, "s": 4035, "text": "It includes automatic garbage collection." }, { "code": null, "e": 4119, "s": 4077, "text": "It includes automatic garbage collection." }, { "code": null, "e": 4205, "s": 4119, "text": "It includes high-level dynamic data types and supports various dynamic type checking." }, { "code": null, "e": 4291, "s": 4205, "text": "It includes high-level dynamic data types and supports various dynamic type checking." }, { "code": null, "e": 4369, "s": 4291, "text": "Python includes a feature of integration with C, C++ and languages like Java." }, { "code": null, "e": 4447, "s": 4369, "text": "Python includes a feature of integration with C, C++ and languages like Java." }, { "code": null, "e": 4510, "s": 4447, "text": "To download Python language in your system, follow this link −" }, { "code": null, "e": 4606, "s": 4510, "text": "It includes packages for various operating systems like Windows, MacOS and Linux distributions." }, { "code": null, "e": 4685, "s": 4606, "text": "In this section, we will learn in brief about a few important tools in Python." }, { "code": null, "e": 4734, "s": 4685, "text": "The basic declaration of strings is as follows −" }, { "code": null, "e": 4756, "s": 4734, "text": "str = 'Hello World!'\n" }, { "code": null, "e": 4877, "s": 4756, "text": "The lists of python can be declared as compound data types separated by commas and enclosed within square brackets ([])." }, { "code": null, "e": 4947, "s": 4877, "text": "list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]\ntinylist = [123, 'john']\n" }, { "code": null, "e": 5081, "s": 4947, "text": "A tuple is dynamic data type of Python, which consists of number of values separated by commas. Tuples are enclosed with parentheses." }, { "code": null, "e": 5108, "s": 5081, "text": "tinytuple = (123, 'john')\n" }, { "code": null, "e": 5254, "s": 5108, "text": "Python dictionary is a type of hash table. A dictionary key can be almost any data type of Python. The data types are usually numbers or strings." }, { "code": null, "e": 5313, "s": 5254, "text": "tinydict = {'name': 'omkar','code':6734, 'dept': 'sales'}\n" }, { "code": null, "e": 5392, "s": 5313, "text": "Python helps in constituting a design pattern using the following parameters −" }, { "code": null, "e": 5405, "s": 5392, "text": "Pattern Name" }, { "code": null, "e": 5412, "s": 5405, "text": "Intent" }, { "code": null, "e": 5420, "s": 5412, "text": "Aliases" }, { "code": null, "e": 5431, "s": 5420, "text": "Motivation" }, { "code": null, "e": 5439, "s": 5431, "text": "Problem" }, { "code": null, "e": 5448, "s": 5439, "text": "Solution" }, { "code": null, "e": 5458, "s": 5448, "text": "Structure" }, { "code": null, "e": 5471, "s": 5458, "text": "Participants" }, { "code": null, "e": 5483, "s": 5471, "text": "Constraints" }, { "code": null, "e": 5495, "s": 5483, "text": "Sample Code" }, { "code": null, "e": 5532, "s": 5495, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 5548, "s": 5532, "text": " Malhar Lathkar" }, { "code": null, "e": 5581, "s": 5548, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 5600, "s": 5581, "text": " Arnab Chakraborty" }, { "code": null, "e": 5635, "s": 5600, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 5657, "s": 5635, "text": " In28Minutes Official" }, { "code": null, "e": 5691, "s": 5657, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 5719, "s": 5691, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5754, "s": 5719, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 5768, "s": 5754, "text": " Lets Kode It" }, { "code": null, "e": 5801, "s": 5768, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 5818, "s": 5801, "text": " Abhilash Nelson" }, { "code": null, "e": 5825, "s": 5818, "text": " Print" }, { "code": null, "e": 5836, "s": 5825, "text": " Add Notes" } ]
Difference between @Inject and @Autowired
@Inject and @Autowired both annotations are used for autowiring in your application. @Inject annotation is part of Java CDI which was introduced in Java 6, whereas @Autowire annotation is part of spring framework. Both annotations fulfill same purpose therefore, anything of these we can use in our application. public class InjectionExample { @Inject private CarBean carbean; } public class AutowiredExample { @Autowired private CarBean carbean; }
[ { "code": null, "e": 1147, "s": 1062, "text": "@Inject and @Autowired both annotations are used for autowiring in your application." }, { "code": null, "e": 1374, "s": 1147, "text": "@Inject annotation is part of Java CDI which was introduced in Java 6, whereas @Autowire annotation is part of spring framework. Both annotations fulfill same purpose therefore, anything of these we can use in our application." }, { "code": null, "e": 1447, "s": 1374, "text": "public class InjectionExample {\n @Inject\n private CarBean carbean;\n}" }, { "code": null, "e": 1523, "s": 1447, "text": "public class AutowiredExample {\n @Autowired\n private CarBean carbean;\n}" } ]
Program to find total unique duration from a list of intervals in Python
Suppose we have a list of intervals where each list represents an interval [start, end] (inclusive). We have to find the total unique duration it covers. So, if the input is like intervals = [[2, 11],[13, 31],[41, 61]], then the output will be 50, as the total unique covered distance is (11 - 2 + 1) = 10 then (31 - 13 + 1) = 19 and (61 - 41 + 1) = 21, so total is 50. To solve this, we will follow these steps − if intervals list is empty, thenreturn 0 return 0 sort the list intervals [start, end] := intervals[0] ans := 0 for each start and end (s, e) in intervals, doif s > end, thenans := ans + end - start + 1start := s, end := eotherwise,end := maximum of end, e if s > end, thenans := ans + end - start + 1start := s, end := e ans := ans + end - start + 1 start := s, end := e otherwise,end := maximum of end, e end := maximum of end, e ans := ans + end - start + 1 return ans Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, intervals): if not intervals: return 0 intervals.sort() start, end = intervals[0] ans = 0 for s, e in intervals: if s > end: ans += end - start + 1 start = s end = e else: end = max(end, e) ans += end - start + 1 return ans ob = Solution() intervals = [[2, 11],[13, 31],[41, 61]] print(ob.solve(intervals)) [[2, 11],[13, 31],[41, 61]] 50
[ { "code": null, "e": 1216, "s": 1062, "text": "Suppose we have a list of intervals where each list represents an interval [start, end] (inclusive). We have to find the total unique duration it covers." }, { "code": null, "e": 1432, "s": 1216, "text": "So, if the input is like intervals = [[2, 11],[13, 31],[41, 61]], then the output will be 50, as the total unique covered distance is (11 - 2 + 1) = 10 then (31 - 13 + 1) = 19 and (61 - 41 + 1) = 21, so total is 50." }, { "code": null, "e": 1476, "s": 1432, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1517, "s": 1476, "text": "if intervals list is empty, thenreturn 0" }, { "code": null, "e": 1526, "s": 1517, "text": "return 0" }, { "code": null, "e": 1550, "s": 1526, "text": "sort the list intervals" }, { "code": null, "e": 1579, "s": 1550, "text": "[start, end] := intervals[0]" }, { "code": null, "e": 1588, "s": 1579, "text": "ans := 0" }, { "code": null, "e": 1733, "s": 1588, "text": "for each start and end (s, e) in intervals, doif s > end, thenans := ans + end - start + 1start := s, end := eotherwise,end := maximum of end, e" }, { "code": null, "e": 1798, "s": 1733, "text": "if s > end, thenans := ans + end - start + 1start := s, end := e" }, { "code": null, "e": 1827, "s": 1798, "text": "ans := ans + end - start + 1" }, { "code": null, "e": 1848, "s": 1827, "text": "start := s, end := e" }, { "code": null, "e": 1883, "s": 1848, "text": "otherwise,end := maximum of end, e" }, { "code": null, "e": 1908, "s": 1883, "text": "end := maximum of end, e" }, { "code": null, "e": 1937, "s": 1908, "text": "ans := ans + end - start + 1" }, { "code": null, "e": 1948, "s": 1937, "text": "return ans" }, { "code": null, "e": 2018, "s": 1948, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2029, "s": 2018, "text": " Live Demo" }, { "code": null, "e": 2527, "s": 2029, "text": "class Solution:\n def solve(self, intervals):\n if not intervals:\n return 0\n intervals.sort()\n start, end = intervals[0]\n ans = 0\n for s, e in intervals:\n if s > end:\n ans += end - start + 1\n start = s\n end = e\n else:\n end = max(end, e)\n ans += end - start + 1\n return ans\nob = Solution()\nintervals = [[2, 11],[13, 31],[41, 61]]\nprint(ob.solve(intervals))" }, { "code": null, "e": 2555, "s": 2527, "text": "[[2, 11],[13, 31],[41, 61]]" }, { "code": null, "e": 2558, "s": 2555, "text": "50" } ]
How to make a phone call using intent in Android using Kotlin?
This example demonstrates how to make a phone call using intent in Android using Kotlin Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="8dp" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="70dp" android:background="#008080" android:padding="5dp" android:text="TutorialsPoint" android:textColor="#fff" android:textSize="24sp" android:textStyle="bold" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:onClick="call" android:text="Call" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.kt import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" } fun call(view: View) { val dialIntent = Intent(Intent.ACTION_DIAL) dialIntent.data = Uri.parse("tel:" + "8344814819") startActivity(dialIntent) } } 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="com.example.q11"> <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 the 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": 1150, "s": 1062, "text": "This example demonstrates how to make a phone call using intent in Android using Kotlin" }, { "code": null, "e": 1279, "s": 1150, "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": 1344, "s": 1279, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2269, "s": 1344, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"8dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"70dp\"\n android:background=\"#008080\"\n android:padding=\"5dp\"\n android:text=\"TutorialsPoint\"\n android:textColor=\"#fff\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <Button\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:onClick=\"call\"\n android:text=\"Call\" />\n</RelativeLayout>" }, { "code": null, "e": 2324, "s": 2269, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 2863, "s": 2324, "text": "import android.content.Intent\nimport android.net.Uri\nimport android.os.Bundle\nimport android.view.View\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n }\n fun call(view: View) {\n val dialIntent = Intent(Intent.ACTION_DIAL)\n dialIntent.data = Uri.parse(\"tel:\" + \"8344814819\")\n startActivity(dialIntent)\n }\n}" }, { "code": null, "e": 2918, "s": 2863, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3592, "s": 2918, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q11\">\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": 3941, "s": 3592, "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 the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen." } ]
Check if two strings can be made equal by reversing a substring of one of the strings - GeeksforGeeks
16 Jun, 2021 Given two strings X and Y of length N, the task is to check if both the strings can be made equal by reversing any substring of X exactly once. If it is possible, then print “Yes”. Otherwise, print “No”. Examples: Input: X = “adcbef”, Y = “abcdef”Output: YesExplanation: Strings can be made equal by reversing the substring “dcb” of string X. Input: X = “126543”, Y = “123456”Output: YesExplanation: Strings can be made equal by reversing the substring “6543” of string X. Naive Approach: The simplest approach to solve the problem is to reversing every possible substring of the string X and for each reversal, check if both the strings are equal. If found to be true after any reversal, then print “Yes”. Otherwise, print “No”. Time Complexity: O(N2)Auxiliary Space: O(1) Efficient Approach: To optimize the above approach, follow the steps below to solve the problem: Initialize a variable, say L as -1, to store the first index from the left having unequal characters in the two strings. Traverse the string X over the range [0, N – 1] using a variable i and if for any index, if the characters in the two strings are found to be unequal, set L = i and break out of the loop. Initialize a variable, say R as -1, to store the first index from the right having unequal characters in the two strings. Traverse the string X over the range [N – 1, 0] using the variable i and if for any index, if the characters in the two strings are found to be unequal, set R = i and break out of the loop. Reverse the characters of the string X over the indices [L, R]. After completing the above steps, check if both the strings are equal or not. If found to be equal, then print “Yes”. Otherwise, print “No”. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if the strings// can be made equal or not by// reversing a substring of Xbool checkString(string X, string Y){ // Store the first index from // the left which contains unequal // characters in both the strings int L = -1; // Store the first element from // the right which contains unequal // characters in both the strings int R = -1; // Checks for the first index from // left in which characters in both // the strings are unequal for (int i = 0; i < X.length(); ++i) { if (X[i] != Y[i]) { // Store the current index L = i; // Break out of the loop break; } } // Checks for the first index from // right in which characters in both // the strings are unequal for (int i = X.length() - 1; i > 0; --i) { if (X[i] != Y[i]) { // Store the current index R = i; // Break out of the loop break; } } // Reverse the substring X[L, R] reverse(X.begin() + L, X.begin() + R + 1); // If X and Y are equal if (X == Y) { cout << "Yes"; } // Otherwise else { cout << "No"; }} // Driver Codeint main(){ string X = "adcbef", Y = "abcdef"; // Function Call checkString(X, Y); return 0;} // Java program for the above approachimport java.util.*; class GFG{ // Function to check if the Strings// can be made equal or not by// reversing a subString of Xstatic void checkString(String X, String Y){ // Store the first index from // the left which contains unequal // characters in both the Strings int L = -1; // Store the first element from // the right which contains unequal // characters in both the Strings int R = -1; // Checks for the first index from // left in which characters in both // the Strings are unequal for (int i = 0; i < X.length(); ++i) { if (X.charAt(i) != Y.charAt(i)) { // Store the current index L = i; // Break out of the loop break; } } // Checks for the first index from // right in which characters in both // the Strings are unequal for (int i = X.length() - 1; i > 0; --i) { if (X.charAt(i) != Y.charAt(i)) { // Store the current index R = i; // Break out of the loop break; } } // Reverse the subString X[L, R] X = X.substring(0, L) + reverse(X.substring(L, R + 1)) + X.substring(R + 1); // If X and Y are equal if (X.equals(Y)) { System.out.print("Yes"); } // Otherwise else { System.out.print("No"); }}static String reverse(String input) { char[] a = input.toCharArray(); int l, r = a.length - 1; for (l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.valueOf(a);} // Driver Codepublic static void main(String[] args){ String X = "adcbef", Y = "abcdef"; // Function Call checkString(X, Y);}} // This code is contributed by 29AjayKumar # Python3 program for the above approach # Function to check if the strings# can be made equal or not by# reversing a substring of Xdef checkString(X, Y): # Store the first index from # the left which contains unequal # characters in both the strings L = -1 # Store the first element from # the right which contains unequal # characters in both the strings R = -1 # Checks for the first index from # left in which characters in both # the strings are unequal for i in range(len(X)): if (X[i] != Y[i]): # Store the current index L = i # Break out of the loop break # Checks for the first index from # right in which characters in both # the strings are unequal for i in range(len(X) - 1, 0, -1): if (X[i] != Y[i]): # Store the current index R = i # Break out of the loop break X = list(X) X = X[:L] + X[R : L - 1 : -1 ] + X[R + 1:] # If X and Y are equal if (X == list(Y)): print("Yes") # Otherwise else: print("No") # Driver Codeif __name__ == "__main__" : X = "adcbef" Y = "abcdef" # Function Call checkString(X, Y) # This code is contributed by AnkThon // C# program for the above approachusing System; class GFG{ // Function to check if the Strings// can be made equal or not by// reversing a subString of Xstatic void checkString(String X, String Y){ // Store the first index from // the left which contains unequal // characters in both the Strings int L = -1; // Store the first element from // the right which contains unequal // characters in both the Strings int R = -1; // Checks for the first index from // left in which characters in both // the Strings are unequal for(int i = 0; i < X.Length; ++i) { if (X[i] != Y[i]) { // Store the current index L = i; // Break out of the loop break; } } // Checks for the first index from // right in which characters in both // the Strings are unequal for(int i = X.Length - 1; i > 0; --i) { if (X[i] != Y[i]) { // Store the current index R = i; // Break out of the loop break; } } // Reverse the subString X[L, R] X = X.Substring(0, L) + reverse(X.Substring(L, R + 1 - L)) + X.Substring(R + 1); // If X and Y are equal if (X.Equals(Y)) { Console.Write("Yes"); } // Otherwise else { Console.Write("No"); }} static String reverse(String input){ char[] a = input.ToCharArray(); int l, r = a.Length - 1; for(l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.Join("",a);} // Driver Codepublic static void Main(String[] args){ String X = "adcbef", Y = "abcdef"; // Function Call checkString(X, Y);}} // This code is contributed by Amit Katiyar <script> // JavaScript program for the above approach // Function to check if the Strings // can be made equal or not by // reversing a subString of X function checkString(X, Y) { // Store the first index from // the left which contains unequal // characters in both the Strings var L = -1; // Store the first element from // the right which contains unequal // characters in both the Strings var R = -1; // Checks for the first index from // left in which characters in both // the Strings are unequal for (var i = 0; i < X.length; ++i) { if (X[i] !== Y[i]) { // Store the current index L = i; // Break out of the loop break; } } // Checks for the first index from // right in which characters in both // the Strings are unequal for (var i = X.length - 1; i > 0; --i) { if (X[i] !== Y[i]) { // Store the current index R = i; // Break out of the loop break; } } // Reverse the subString X[L, R] X = X.substring(0, L) + reverse(X.substring(L, R + 1)) + X.substring(R + 1); // If X and Y are equal if (X === Y) { document.write("Yes"); } // Otherwise else { document.write("No"); } } function reverse(input) { var a = input.split(""); var l, r = a.length - 1; for (l = 0; l < r; l++, r--) { var temp = a[l]; a[l] = a[r]; a[r] = temp; } return a.join(""); } // Driver Code var X = "adcbef", Y = "abcdef"; // Function Call checkString(X, Y); </script> Yes Time Complexity: O(N)Auxiliary Space: O(1) 29AjayKumar amit143katiyar ankthon khushboogoyal499 rdtank Reverse substring two-pointer-algorithm Searching Strings two-pointer-algorithm Searching Strings Reverse Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Best First Search (Informed Search) Program to remove vowels from a String Find whether an array is subset of another array | Added Method 5 Find common elements in three sorted arrays 3 Different ways to print Fibonacci series in Java Write a program to reverse an array or string Reverse a string in Java Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types
[ { "code": null, "e": 24944, "s": 24916, "text": "\n16 Jun, 2021" }, { "code": null, "e": 25148, "s": 24944, "text": "Given two strings X and Y of length N, the task is to check if both the strings can be made equal by reversing any substring of X exactly once. If it is possible, then print “Yes”. Otherwise, print “No”." }, { "code": null, "e": 25158, "s": 25148, "text": "Examples:" }, { "code": null, "e": 25287, "s": 25158, "text": "Input: X = “adcbef”, Y = “abcdef”Output: YesExplanation: Strings can be made equal by reversing the substring “dcb” of string X." }, { "code": null, "e": 25417, "s": 25287, "text": "Input: X = “126543”, Y = “123456”Output: YesExplanation: Strings can be made equal by reversing the substring “6543” of string X." }, { "code": null, "e": 25674, "s": 25417, "text": "Naive Approach: The simplest approach to solve the problem is to reversing every possible substring of the string X and for each reversal, check if both the strings are equal. If found to be true after any reversal, then print “Yes”. Otherwise, print “No”." }, { "code": null, "e": 25718, "s": 25674, "text": "Time Complexity: O(N2)Auxiliary Space: O(1)" }, { "code": null, "e": 25815, "s": 25718, "text": "Efficient Approach: To optimize the above approach, follow the steps below to solve the problem:" }, { "code": null, "e": 25936, "s": 25815, "text": "Initialize a variable, say L as -1, to store the first index from the left having unequal characters in the two strings." }, { "code": null, "e": 26124, "s": 25936, "text": "Traverse the string X over the range [0, N – 1] using a variable i and if for any index, if the characters in the two strings are found to be unequal, set L = i and break out of the loop." }, { "code": null, "e": 26246, "s": 26124, "text": "Initialize a variable, say R as -1, to store the first index from the right having unequal characters in the two strings." }, { "code": null, "e": 26436, "s": 26246, "text": "Traverse the string X over the range [N – 1, 0] using the variable i and if for any index, if the characters in the two strings are found to be unequal, set R = i and break out of the loop." }, { "code": null, "e": 26500, "s": 26436, "text": "Reverse the characters of the string X over the indices [L, R]." }, { "code": null, "e": 26641, "s": 26500, "text": "After completing the above steps, check if both the strings are equal or not. If found to be equal, then print “Yes”. Otherwise, print “No”." }, { "code": null, "e": 26692, "s": 26641, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26696, "s": 26692, "text": "C++" }, { "code": null, "e": 26701, "s": 26696, "text": "Java" }, { "code": null, "e": 26709, "s": 26701, "text": "Python3" }, { "code": null, "e": 26712, "s": 26709, "text": "C#" }, { "code": null, "e": 26723, "s": 26712, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if the strings// can be made equal or not by// reversing a substring of Xbool checkString(string X, string Y){ // Store the first index from // the left which contains unequal // characters in both the strings int L = -1; // Store the first element from // the right which contains unequal // characters in both the strings int R = -1; // Checks for the first index from // left in which characters in both // the strings are unequal for (int i = 0; i < X.length(); ++i) { if (X[i] != Y[i]) { // Store the current index L = i; // Break out of the loop break; } } // Checks for the first index from // right in which characters in both // the strings are unequal for (int i = X.length() - 1; i > 0; --i) { if (X[i] != Y[i]) { // Store the current index R = i; // Break out of the loop break; } } // Reverse the substring X[L, R] reverse(X.begin() + L, X.begin() + R + 1); // If X and Y are equal if (X == Y) { cout << \"Yes\"; } // Otherwise else { cout << \"No\"; }} // Driver Codeint main(){ string X = \"adcbef\", Y = \"abcdef\"; // Function Call checkString(X, Y); return 0;}", "e": 28141, "s": 26723, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to check if the Strings// can be made equal or not by// reversing a subString of Xstatic void checkString(String X, String Y){ // Store the first index from // the left which contains unequal // characters in both the Strings int L = -1; // Store the first element from // the right which contains unequal // characters in both the Strings int R = -1; // Checks for the first index from // left in which characters in both // the Strings are unequal for (int i = 0; i < X.length(); ++i) { if (X.charAt(i) != Y.charAt(i)) { // Store the current index L = i; // Break out of the loop break; } } // Checks for the first index from // right in which characters in both // the Strings are unequal for (int i = X.length() - 1; i > 0; --i) { if (X.charAt(i) != Y.charAt(i)) { // Store the current index R = i; // Break out of the loop break; } } // Reverse the subString X[L, R] X = X.substring(0, L) + reverse(X.substring(L, R + 1)) + X.substring(R + 1); // If X and Y are equal if (X.equals(Y)) { System.out.print(\"Yes\"); } // Otherwise else { System.out.print(\"No\"); }}static String reverse(String input) { char[] a = input.toCharArray(); int l, r = a.length - 1; for (l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.valueOf(a);} // Driver Codepublic static void main(String[] args){ String X = \"adcbef\", Y = \"abcdef\"; // Function Call checkString(X, Y);}} // This code is contributed by 29AjayKumar", "e": 29933, "s": 28141, "text": null }, { "code": "# Python3 program for the above approach # Function to check if the strings# can be made equal or not by# reversing a substring of Xdef checkString(X, Y): # Store the first index from # the left which contains unequal # characters in both the strings L = -1 # Store the first element from # the right which contains unequal # characters in both the strings R = -1 # Checks for the first index from # left in which characters in both # the strings are unequal for i in range(len(X)): if (X[i] != Y[i]): # Store the current index L = i # Break out of the loop break # Checks for the first index from # right in which characters in both # the strings are unequal for i in range(len(X) - 1, 0, -1): if (X[i] != Y[i]): # Store the current index R = i # Break out of the loop break X = list(X) X = X[:L] + X[R : L - 1 : -1 ] + X[R + 1:] # If X and Y are equal if (X == list(Y)): print(\"Yes\") # Otherwise else: print(\"No\") # Driver Codeif __name__ == \"__main__\" : X = \"adcbef\" Y = \"abcdef\" # Function Call checkString(X, Y) # This code is contributed by AnkThon", "e": 31221, "s": 29933, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to check if the Strings// can be made equal or not by// reversing a subString of Xstatic void checkString(String X, String Y){ // Store the first index from // the left which contains unequal // characters in both the Strings int L = -1; // Store the first element from // the right which contains unequal // characters in both the Strings int R = -1; // Checks for the first index from // left in which characters in both // the Strings are unequal for(int i = 0; i < X.Length; ++i) { if (X[i] != Y[i]) { // Store the current index L = i; // Break out of the loop break; } } // Checks for the first index from // right in which characters in both // the Strings are unequal for(int i = X.Length - 1; i > 0; --i) { if (X[i] != Y[i]) { // Store the current index R = i; // Break out of the loop break; } } // Reverse the subString X[L, R] X = X.Substring(0, L) + reverse(X.Substring(L, R + 1 - L)) + X.Substring(R + 1); // If X and Y are equal if (X.Equals(Y)) { Console.Write(\"Yes\"); } // Otherwise else { Console.Write(\"No\"); }} static String reverse(String input){ char[] a = input.ToCharArray(); int l, r = a.Length - 1; for(l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.Join(\"\",a);} // Driver Codepublic static void Main(String[] args){ String X = \"adcbef\", Y = \"abcdef\"; // Function Call checkString(X, Y);}} // This code is contributed by Amit Katiyar", "e": 33035, "s": 31221, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to check if the Strings // can be made equal or not by // reversing a subString of X function checkString(X, Y) { // Store the first index from // the left which contains unequal // characters in both the Strings var L = -1; // Store the first element from // the right which contains unequal // characters in both the Strings var R = -1; // Checks for the first index from // left in which characters in both // the Strings are unequal for (var i = 0; i < X.length; ++i) { if (X[i] !== Y[i]) { // Store the current index L = i; // Break out of the loop break; } } // Checks for the first index from // right in which characters in both // the Strings are unequal for (var i = X.length - 1; i > 0; --i) { if (X[i] !== Y[i]) { // Store the current index R = i; // Break out of the loop break; } } // Reverse the subString X[L, R] X = X.substring(0, L) + reverse(X.substring(L, R + 1)) + X.substring(R + 1); // If X and Y are equal if (X === Y) { document.write(\"Yes\"); } // Otherwise else { document.write(\"No\"); } } function reverse(input) { var a = input.split(\"\"); var l, r = a.length - 1; for (l = 0; l < r; l++, r--) { var temp = a[l]; a[l] = a[r]; a[r] = temp; } return a.join(\"\"); } // Driver Code var X = \"adcbef\", Y = \"abcdef\"; // Function Call checkString(X, Y); </script>", "e": 34899, "s": 33035, "text": null }, { "code": null, "e": 34903, "s": 34899, "text": "Yes" }, { "code": null, "e": 34948, "s": 34905, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 34960, "s": 34948, "text": "29AjayKumar" }, { "code": null, "e": 34975, "s": 34960, "text": "amit143katiyar" }, { "code": null, "e": 34983, "s": 34975, "text": "ankthon" }, { "code": null, "e": 35000, "s": 34983, "text": "khushboogoyal499" }, { "code": null, "e": 35007, "s": 35000, "text": "rdtank" }, { "code": null, "e": 35015, "s": 35007, "text": "Reverse" }, { "code": null, "e": 35025, "s": 35015, "text": "substring" }, { "code": null, "e": 35047, "s": 35025, "text": "two-pointer-algorithm" }, { "code": null, "e": 35057, "s": 35047, "text": "Searching" }, { "code": null, "e": 35065, "s": 35057, "text": "Strings" }, { "code": null, "e": 35087, "s": 35065, "text": "two-pointer-algorithm" }, { "code": null, "e": 35097, "s": 35087, "text": "Searching" }, { "code": null, "e": 35105, "s": 35097, "text": "Strings" }, { "code": null, "e": 35113, "s": 35105, "text": "Reverse" }, { "code": null, "e": 35211, "s": 35113, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35247, "s": 35211, "text": "Best First Search (Informed Search)" }, { "code": null, "e": 35286, "s": 35247, "text": "Program to remove vowels from a String" }, { "code": null, "e": 35352, "s": 35286, "text": "Find whether an array is subset of another array | Added Method 5" }, { "code": null, "e": 35396, "s": 35352, "text": "Find common elements in three sorted arrays" }, { "code": null, "e": 35447, "s": 35396, "text": "3 Different ways to print Fibonacci series in Java" }, { "code": null, "e": 35493, "s": 35447, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 35518, "s": 35493, "text": "Reverse a string in Java" }, { "code": null, "e": 35552, "s": 35518, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 35612, "s": 35552, "text": "Write a program to print all permutations of a given string" } ]
How do I display the indexes of a collection in MongoDB?
In order to display the indexes of a collection, you can use getIndexes(). The syntax is as follows − db.yourCollectionName.getIndexes(); To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows − > db.indexDemo.insertOne({"StudentName":"Larry","StudentAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5c8f7c4f2f684a30fbdfd599") } > db.indexDemo.insertOne({"StudentName":"Mike","StudentAge":24}); { "acknowledged" : true, "insertedId" : ObjectId("5c8f7c552f684a30fbdfd59a") } Display all documents from a collection with the help of find() method. The query is as follows − > db.indexDemo.insertOne({"StudentName":"Carol","StudentAge":20}); The following is the output − { "acknowledged" : true, "insertedId" : ObjectId("5c8f7c5e2f684a30fbdfd59b") } > db.indexDemo.find().pretty(); { "_id" : ObjectId("5c8f7c4f2f684a30fbdfd599"), "StudentName" : "Larry", "StudentAge" : 21 } { "_id" : ObjectId("5c8f7c552f684a30fbdfd59a"), "StudentName" : "Mike", "StudentAge" : 24 } { "_id" : ObjectId("5c8f7c5e2f684a30fbdfd59b"), "StudentName" : "Carol", "StudentAge" : 20 } Here is the query to create indexes − > db.indexDemo.createIndex({"StudentName":-1,"StudentAge":-1}); The following is the output: { "createdCollectionAutomatically" : false, "numIndexesBefore" : 2, "numIndexesAfter" : 3, "ok" : 1 } Here is the query to display the indexes of a collection. The collection name is “indexDemo” − > db.indexDemo.getIndexes(); The following is the output − [ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "test.indexDemo" }, { "v" : 2, "key" : { "StudentName" : -1 }, "name" : "StudentName_-1", "ns" : "test.indexDemo" }, { "v" : 2, "key" : { "StudentName" : -1, "StudentAge" : -1 }, "name" : "StudentName_-1_StudentAge_-1", "ns" : "test.indexDemo" } ]
[ { "code": null, "e": 1164, "s": 1062, "text": "In order to display the indexes of a collection, you can use getIndexes(). The syntax is as follows −" }, { "code": null, "e": 1200, "s": 1164, "text": "db.yourCollectionName.getIndexes();" }, { "code": null, "e": 1338, "s": 1200, "text": "To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −" }, { "code": null, "e": 1641, "s": 1338, "text": "> db.indexDemo.insertOne({\"StudentName\":\"Larry\",\"StudentAge\":21});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8f7c4f2f684a30fbdfd599\")\n}\n> db.indexDemo.insertOne({\"StudentName\":\"Mike\",\"StudentAge\":24});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8f7c552f684a30fbdfd59a\")\n}" }, { "code": null, "e": 1739, "s": 1641, "text": "Display all documents from a collection with the help of find() method. The query is as follows −" }, { "code": null, "e": 1806, "s": 1739, "text": "> db.indexDemo.insertOne({\"StudentName\":\"Carol\",\"StudentAge\":20});" }, { "code": null, "e": 1836, "s": 1806, "text": "The following is the output −" }, { "code": null, "e": 2258, "s": 1836, "text": "{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8f7c5e2f684a30fbdfd59b\")\n}\n> db.indexDemo.find().pretty();\n{\n \"_id\" : ObjectId(\"5c8f7c4f2f684a30fbdfd599\"),\n \"StudentName\" : \"Larry\",\n \"StudentAge\" : 21\n}\n{\n \"_id\" : ObjectId(\"5c8f7c552f684a30fbdfd59a\"),\n \"StudentName\" : \"Mike\",\n \"StudentAge\" : 24\n}\n{\n \"_id\" : ObjectId(\"5c8f7c5e2f684a30fbdfd59b\"),\n \"StudentName\" : \"Carol\",\n \"StudentAge\" : 20\n}" }, { "code": null, "e": 2296, "s": 2258, "text": "Here is the query to create indexes −" }, { "code": null, "e": 2360, "s": 2296, "text": "> db.indexDemo.createIndex({\"StudentName\":-1,\"StudentAge\":-1});" }, { "code": null, "e": 2389, "s": 2360, "text": "The following is the output:" }, { "code": null, "e": 2503, "s": 2389, "text": "{\n \"createdCollectionAutomatically\" : false,\n \"numIndexesBefore\" : 2,\n \"numIndexesAfter\" : 3,\n \"ok\" : 1\n}" }, { "code": null, "e": 2598, "s": 2503, "text": "Here is the query to display the indexes of a collection. The collection name is “indexDemo” −" }, { "code": null, "e": 2627, "s": 2598, "text": "> db.indexDemo.getIndexes();" }, { "code": null, "e": 2657, "s": 2627, "text": "The following is the output −" }, { "code": null, "e": 3109, "s": 2657, "text": "[\n {\n \"v\" : 2,\n \"key\" : {\n \"_id\" : 1\n },\n \"name\" : \"_id_\",\n \"ns\" : \"test.indexDemo\"\n },\n {\n \"v\" : 2,\n \"key\" : {\n \"StudentName\" : -1\n },\n \"name\" : \"StudentName_-1\",\n \"ns\" : \"test.indexDemo\"\n },\n {\n \"v\" : 2,\n \"key\" : {\n \"StudentName\" : -1,\n \"StudentAge\" : -1\n },\n \"name\" : \"StudentName_-1_StudentAge_-1\",\n \"ns\" : \"test.indexDemo\"\n }\n]" } ]
BabylonJS - Dynamic Texture
The Dynamic Texture of BabylonJS creates a canvas and you can easily write text on the texture. It also allows you to work with canvas and use all the features available with html5 canvas to be used with dynamic texture. We will work on an example, which will show how to write text on the texture and will also draw a bezier Curve on the mesh we create. Following is the syntax to create Dynamic texture − var myDynamicTexture = new BABYLON.DynamicTexture(name, option, scene); Following are the required parameters to create dynamic texture − name − name of the dynamic texture name − name of the dynamic texture option − will have the width and height of the dynamic texture option − will have the width and height of the dynamic texture scene − scene created scene − scene created Following is the syntax to write text on the texture − myDynamicTexture.drawText(text, x, y, font, color, canvas color, invertY, update); Following are the required parameters to write text on the texture − text − text to be written; text − text to be written; x − distance from the left-hand edge; x − distance from the left-hand edge; Y − distance from the top or bottom edge, depending on invertY; Y − distance from the top or bottom edge, depending on invertY; font − font definition in the form font-style, font-size, font_name; font − font definition in the form font-style, font-size, font_name; invertY − true by default in which case y is the distance from the top, when false, y is distance from the bottom and the letters reversed; invertY − true by default in which case y is the distance from the top, when false, y is distance from the bottom and the letters reversed; update − true by default, the dynamic texture will immediately be updated. update − true by default, the dynamic texture will immediately be updated. <!doctype html> <html> <head> <meta charset = "utf-8"> <title>MDN Games: Babylon.js demo - shapes</title> <script src = "https://end3r.github.io/MDN-Games-3D/Babylon.js/js/babylon.js"></script> <style> html,body,canvas { margin: 0; padding: 0; width: 100%; height: 100%; font-size: 0; } </style> </head> <body> <canvas id = "renderCanvas"></canvas> <script type = "text/javascript"> var canvas = document.getElementById("renderCanvas"); var engine = new BABYLON.Engine(canvas, true); var createScene = function() { var scene = new BABYLON.Scene(engine); var camera = new BABYLON.ArcRotateCamera("Camera", -Math.PI/2, Math.PI / 3, 25, BABYLON.Vector3.Zero(), scene); camera.attachControl(canvas, true); var light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 1, 0), scene); light.intensity = 0.7; var box = BABYLON.Mesh.CreateBox("box", 3.0, scene); box.position = new BABYLON.Vector3(0, 0, -5); //Create dynamic texture var textureGround = new BABYLON.DynamicTexture("dynamic texture", {width:512, height:256}, scene); var textureContext = textureGround.getContext(); var materialGround = new BABYLON.StandardMaterial("Mat", scene); materialGround.diffuseTexture = textureGround; box.material = materialGround; //Add text to dynamic texture var font = "bold 60px Arial"; textureGround.drawText("Box", 200, 150, font, "green", "white", true, true); return scene; }; var scene = createScene(); engine.runRenderLoop(function() { scene.render(); }); </script> </body> </html> Dynamic texture also allows to work with html5 canvas methods and properties on dynamic texture as follows − var ctx = myDynamicTexture.getContext(); <!doctype html> <html> <head> <meta charset = "utf-8"> <title> Babylon.JS : Demo2</title> <script src = "babylon.js"></script> <style> canvas { width: 100%; height: 100%;} </style> </head> <body> <canvas id = "renderCanvas"></canvas> <script type = "text/javascript"> var canvas = document.getElementById("renderCanvas"); var engine = new BABYLON.Engine(canvas, true); var createScene = function () { var scene = new BABYLON.Scene(engine); var camera = new BABYLON.ArcRotateCamera("Camera", -Math.PI/2, Math.PI / 3, 25, BABYLON.Vector3.Zero(), scene); camera.attachControl(canvas, true); var light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 1, 0), scene); light.intensity = 0.7; var ground = BABYLON.MeshBuilder.CreateGround("ground1", {width: 20, height: 10, subdivisions: 25}, scene); //Create dynamic texture var textureGround = new BABYLON.DynamicTexture("dynamic texture", 512, scene); var textureContext = textureGround.getContext(); var materialGround = new BABYLON.StandardMaterial("Mat", scene); materialGround.diffuseTexture = textureGround; ground.material = materialGround; //Draw on canvas textureContext.beginPath(); textureContext.moveTo(75,40); textureContext.bezierCurveTo(75,37,70,25,50,25); textureContext.bezierCurveTo(20,25,20,62.5,20,62.5); textureContext.bezierCurveTo(20,80,40,102,75,120); textureContext.bezierCurveTo(110,102,130,80,130,62.5); textureContext.bezierCurveTo(130,62.5,130,25,100,25); textureContext.bezierCurveTo(85,25,75,37,75,40); textureContext.fillStyle = "red"; textureContext.fill(); textureGround.update(); return scene; }; var scene = createScene(); engine.runRenderLoop(function() { scene.render(); }); </script> </body> </html> We have created ground mesh and added dynamic texture to it. //ground mesh var ground = BABYLON.MeshBuilder.CreateGround("ground1", {width: 20, height: 10, subdivisions: 25}, scene); //Create dynamic texture var textureGround = new BABYLON.DynamicTexture("dynamic texture", 512, scene); //adding dynamic texture to ground using standard material var materialGround = new BABYLON.StandardMaterial("Mat", scene); materialGround.diffuseTexture = textureGround; ground.material = materialGround; To work with canvas on dynamic texture, we need to call canvas method first − var textureContext = textureGround.getContext() To the canvas, we will add the bezierCurve as follows − textureContext.beginPath(); textureContext.moveTo(75,40); textureContext.bezierCurveTo(75,37,70,25,50,25); textureContext.bezierCurveTo(20,25,20,62.5,20,62.5); textureContext.bezierCurveTo(20,80,40,102,75,120); textureContext.bezierCurveTo(110,102,130,80,130,62.5); textureContext.bezierCurveTo(130,62.5,130,25,100,25); textureContext.bezierCurveTo(85,25,75,37,75,40); textureContext.fillStyle = "red"; textureContext.fill(); textureGround.update(); Print Add Notes Bookmark this page
[ { "code": null, "e": 2404, "s": 2183, "text": "The Dynamic Texture of BabylonJS creates a canvas and you can easily write text on the texture. It also allows you to work with canvas and use all the features available with html5 canvas to be used with dynamic texture." }, { "code": null, "e": 2538, "s": 2404, "text": "We will work on an example, which will show how to write text on the texture and will also draw a bezier Curve on the mesh we create." }, { "code": null, "e": 2590, "s": 2538, "text": "Following is the syntax to create Dynamic texture −" }, { "code": null, "e": 2663, "s": 2590, "text": "var myDynamicTexture = new BABYLON.DynamicTexture(name, option, scene);\n" }, { "code": null, "e": 2729, "s": 2663, "text": "Following are the required parameters to create dynamic texture −" }, { "code": null, "e": 2764, "s": 2729, "text": "name − name of the dynamic texture" }, { "code": null, "e": 2799, "s": 2764, "text": "name − name of the dynamic texture" }, { "code": null, "e": 2862, "s": 2799, "text": "option − will have the width and height of the dynamic texture" }, { "code": null, "e": 2925, "s": 2862, "text": "option − will have the width and height of the dynamic texture" }, { "code": null, "e": 2947, "s": 2925, "text": "scene − scene created" }, { "code": null, "e": 2969, "s": 2947, "text": "scene − scene created" }, { "code": null, "e": 3024, "s": 2969, "text": "Following is the syntax to write text on the texture −" }, { "code": null, "e": 3108, "s": 3024, "text": "myDynamicTexture.drawText(text, x, y, font, color, canvas color, invertY, update);\n" }, { "code": null, "e": 3177, "s": 3108, "text": "Following are the required parameters to write text on the texture −" }, { "code": null, "e": 3204, "s": 3177, "text": "text − text to be written;" }, { "code": null, "e": 3231, "s": 3204, "text": "text − text to be written;" }, { "code": null, "e": 3269, "s": 3231, "text": "x − distance from the left-hand edge;" }, { "code": null, "e": 3307, "s": 3269, "text": "x − distance from the left-hand edge;" }, { "code": null, "e": 3371, "s": 3307, "text": "Y − distance from the top or bottom edge, depending on invertY;" }, { "code": null, "e": 3435, "s": 3371, "text": "Y − distance from the top or bottom edge, depending on invertY;" }, { "code": null, "e": 3504, "s": 3435, "text": "font − font definition in the form font-style, font-size, font_name;" }, { "code": null, "e": 3573, "s": 3504, "text": "font − font definition in the form font-style, font-size, font_name;" }, { "code": null, "e": 3713, "s": 3573, "text": "invertY − true by default in which case y is the distance from the top, when false, y is distance from the bottom and the letters reversed;" }, { "code": null, "e": 3853, "s": 3713, "text": "invertY − true by default in which case y is the distance from the top, when false, y is distance from the bottom and the letters reversed;" }, { "code": null, "e": 3928, "s": 3853, "text": "update − true by default, the dynamic texture will immediately be updated." }, { "code": null, "e": 4003, "s": 3928, "text": "update − true by default, the dynamic texture will immediately be updated." }, { "code": null, "e": 5878, "s": 4003, "text": "<!doctype html>\n<html>\n <head>\n <meta charset = \"utf-8\">\n <title>MDN Games: Babylon.js demo - shapes</title>\n <script src = \"https://end3r.github.io/MDN-Games-3D/Babylon.js/js/babylon.js\"></script> \n <style>\n html,body,canvas { margin: 0; padding: 0; width: 100%; height: 100%; font-size: 0; }\n </style>\n </head>\n\n <body>\n <canvas id = \"renderCanvas\"></canvas>\n <script type = \"text/javascript\">\n var canvas = document.getElementById(\"renderCanvas\");\n \n var engine = new BABYLON.Engine(canvas, true);\n var createScene = function() {\n var scene = new BABYLON.Scene(engine);\n\n var camera = new BABYLON.ArcRotateCamera(\"Camera\", -Math.PI/2, Math.PI / 3, 25, BABYLON.Vector3.Zero(), scene);\n camera.attachControl(canvas, true);\n\n var light = new BABYLON.HemisphericLight(\"light1\", new BABYLON.Vector3(0, 1, 0), scene);\n light.intensity = 0.7;\t\n\n var box = BABYLON.Mesh.CreateBox(\"box\", 3.0, scene);\n box.position = new BABYLON.Vector3(0, 0, -5); \n\n //Create dynamic texture\t\t\n var textureGround = new BABYLON.DynamicTexture(\"dynamic texture\", {width:512, height:256}, scene); \n var textureContext = textureGround.getContext();\n\n var materialGround = new BABYLON.StandardMaterial(\"Mat\", scene); \t\t\t\t\n materialGround.diffuseTexture = textureGround;\n box.material = materialGround;\n\n //Add text to dynamic texture\n var font = \"bold 60px Arial\";\n textureGround.drawText(\"Box\", 200, 150, font, \"green\", \"white\", true, true);\n return scene;\n };\n var scene = createScene();\n engine.runRenderLoop(function() {\n scene.render();\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 5987, "s": 5878, "text": "Dynamic texture also allows to work with html5 canvas methods and properties on dynamic texture as follows −" }, { "code": null, "e": 6029, "s": 5987, "text": "var ctx = myDynamicTexture.getContext();\n" }, { "code": null, "e": 8214, "s": 6029, "text": "<!doctype html>\n<html>\n <head>\n <meta charset = \"utf-8\">\n <title> Babylon.JS : Demo2</title>\n <script src = \"babylon.js\"></script> \n <style>\n canvas { width: 100%; height: 100%;}\n </style>\n </head>\n \n <body>\n <canvas id = \"renderCanvas\"></canvas>\n <script type = \"text/javascript\">\n var canvas = document.getElementById(\"renderCanvas\");\n var engine = new BABYLON.Engine(canvas, true);\t\n var createScene = function () {\n var scene = new BABYLON.Scene(engine);\n\n var camera = new BABYLON.ArcRotateCamera(\"Camera\", -Math.PI/2, Math.PI / 3, 25, BABYLON.Vector3.Zero(), scene);\n camera.attachControl(canvas, true);\n\n var light = new BABYLON.HemisphericLight(\"light1\", new BABYLON.Vector3(0, 1, 0), scene);\n light.intensity = 0.7;\t\t\n\n var ground = BABYLON.MeshBuilder.CreateGround(\"ground1\", {width: 20, height: 10, subdivisions: 25}, scene);\n\n //Create dynamic texture\n var textureGround = new BABYLON.DynamicTexture(\"dynamic texture\", 512, scene); \n var textureContext = textureGround.getContext();\n\n var materialGround = new BABYLON.StandardMaterial(\"Mat\", scene); \t\t\t\t\n materialGround.diffuseTexture = textureGround;\n ground.material = materialGround;\n\n //Draw on canvas\n textureContext.beginPath();\n textureContext.moveTo(75,40);\n textureContext.bezierCurveTo(75,37,70,25,50,25);\n textureContext.bezierCurveTo(20,25,20,62.5,20,62.5);\n textureContext.bezierCurveTo(20,80,40,102,75,120);\n textureContext.bezierCurveTo(110,102,130,80,130,62.5);\n textureContext.bezierCurveTo(130,62.5,130,25,100,25);\n textureContext.bezierCurveTo(85,25,75,37,75,40);\n textureContext.fillStyle = \"red\";\n textureContext.fill();\n textureGround.update();\n \n return scene;\n };\n var scene = createScene();\n engine.runRenderLoop(function() {\n scene.render();\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 8275, "s": 8214, "text": "We have created ground mesh and added dynamic texture to it." }, { "code": null, "e": 8718, "s": 8275, "text": "//ground mesh\nvar ground = BABYLON.MeshBuilder.CreateGround(\"ground1\", {width: 20, height: 10, subdivisions: 25}, scene);\n\n//Create dynamic texture\nvar textureGround = new BABYLON.DynamicTexture(\"dynamic texture\", 512, scene); \n\n//adding dynamic texture to ground using standard material\nvar materialGround = new BABYLON.StandardMaterial(\"Mat\", scene); \t\t\t\nmaterialGround.diffuseTexture = textureGround;\nground.material = materialGround;" }, { "code": null, "e": 8796, "s": 8718, "text": "To work with canvas on dynamic texture, we need to call canvas method first −" }, { "code": null, "e": 8845, "s": 8796, "text": "var textureContext = textureGround.getContext()\n" }, { "code": null, "e": 8901, "s": 8845, "text": "To the canvas, we will add the bezierCurve as follows −" }, { "code": null, "e": 9353, "s": 8901, "text": "textureContext.beginPath();\ntextureContext.moveTo(75,40);\n\ntextureContext.bezierCurveTo(75,37,70,25,50,25);\ntextureContext.bezierCurveTo(20,25,20,62.5,20,62.5);\ntextureContext.bezierCurveTo(20,80,40,102,75,120);\ntextureContext.bezierCurveTo(110,102,130,80,130,62.5);\ntextureContext.bezierCurveTo(130,62.5,130,25,100,25);\ntextureContext.bezierCurveTo(85,25,75,37,75,40);\n\ntextureContext.fillStyle = \"red\";\ntextureContext.fill();\ntextureGround.update();" }, { "code": null, "e": 9360, "s": 9353, "text": " Print" }, { "code": null, "e": 9371, "s": 9360, "text": " Add Notes" } ]
AbstractSet Class in Java with Examples - GeeksforGeeks
17 Jan, 2022 AbstractSet class in Java is a part of the Java Collection Framework which implements the Collection interface and extends the AbstractCollection class. It provides a skeletal implementation of the Set interface. This class does not override any of the implementations from the AbstractCollection class, but merely adds implementations for the equals() and hashCode() method. The process of implementing a set by extending this class is identical to that of implementing a Collection by extending AbstractCollection, except that all of the methods and constructors in subclasses of this class must obey the additional constraints imposed by the Set interface (for instance, the add method must not permit the addition of multiple instances of an object to a set). From the class hierarchy diagram, it can be concluded that it implements Iterable<E>, Collection<E>, Set<E> interfaces. The direct subclasses are ConcurrentSkipListSet, CopyOnWriteArraySet, EnumSet, HashSet, TreeSet. As we already discussed above, AbstractSet is an abstract class, so it should be assigned an instance of its subclasses such as TreeSet, HashSet, or EnumSet. Syntax: Declaration public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> Where E is the type of elements maintained by this Set. 1. protected AbstractSet(): The default constructor, but being protected, it doesn’t allow the creation of an AbstractSet object. AbstractSet<E> as = new TreeSet<E>(); METHOD DESCRIPTION Example 1: Java // Java Program to Illustrate AbstractSet Class // Importing required classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) throws Exception { // Try block to check for exceptions try { // Creating an empty TreeSet of integer type by // creating object of AbstractSet AbstractSet<Integer> abs_set = new TreeSet<Integer>(); // Populating TreeSet // using add() method abs_set.add(1); abs_set.add(2); abs_set.add(3); abs_set.add(4); abs_set.add(5); // Printing the elements inside above TreeSet System.out.println("AbstractSet: " + abs_set); } // Catch block to handle the exceptions catch (Exception e) { // Display exception on console System.out.println(e); } }} AbstractSet: [1, 2, 3, 4, 5] Example 2: Java // Java Program to Illustrate Methods// of AbstractSet class // Importing required classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) throws Exception { // Try block to check for exceptions try { // Creating an empty TreeSet of integer type AbstractSet<Integer> abs_set = new TreeSet<Integer>(); // Populating above TreeSet // using add() method abs_set.add(1); abs_set.add(2); abs_set.add(3); abs_set.add(4); abs_set.add(5); // Printing the elements inside TreeSet System.out.println("AbstractSet before " + "removeAll() operation : " + abs_set); // Creating an ArrayList of integer type Collection<Integer> arrlist2 = new ArrayList<Integer>(); // Adding elements to above ArrayList arrlist2.add(1); arrlist2.add(2); arrlist2.add(3); // Printing the ArrayList elements System.out.println("Collection Elements" + " to be removed : " + arrlist2); // Removing elements from AbstractSet specified // using removeAll() method abs_set.removeAll(arrlist2); // Printing the elements of ArrayList System.out.println("AbstractSet after " + "removeAll() operation : " + abs_set); } // Catch block to handle the exceptions catch (NullPointerException e) { // Display exception on console System.out.println("Exception thrown : " + e); } }} Output: Some other methods of classes or interfaces are defined below that somehow helps us to get a better understanding of AbstractSet Class as follows: METHOD DESCRIPTION METHOD DESCRIPTION METHOD DESCRIPTION METHOD DESCRIPTION SachinShinde1 Akanksha_Rai Ganeshchowdharysadanala solankimayank surindertarika1234 anikakapoor simranarora5sos Java - util package Java-AbstractSet Java-Collections Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java HashMap in Java with Examples Interfaces in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples ArrayList in Java How to iterate any Map in Java
[ { "code": null, "e": 23748, "s": 23720, "text": "\n17 Jan, 2022" }, { "code": null, "e": 24124, "s": 23748, "text": "AbstractSet class in Java is a part of the Java Collection Framework which implements the Collection interface and extends the AbstractCollection class. It provides a skeletal implementation of the Set interface. This class does not override any of the implementations from the AbstractCollection class, but merely adds implementations for the equals() and hashCode() method." }, { "code": null, "e": 24512, "s": 24124, "text": "The process of implementing a set by extending this class is identical to that of implementing a Collection by extending AbstractCollection, except that all of the methods and constructors in subclasses of this class must obey the additional constraints imposed by the Set interface (for instance, the add method must not permit the addition of multiple instances of an object to a set)." }, { "code": null, "e": 24887, "s": 24512, "text": "From the class hierarchy diagram, it can be concluded that it implements Iterable<E>, Collection<E>, Set<E> interfaces. The direct subclasses are ConcurrentSkipListSet, CopyOnWriteArraySet, EnumSet, HashSet, TreeSet. As we already discussed above, AbstractSet is an abstract class, so it should be assigned an instance of its subclasses such as TreeSet, HashSet, or EnumSet." }, { "code": null, "e": 24908, "s": 24887, "text": "Syntax: Declaration " }, { "code": null, "e": 24993, "s": 24908, "text": "public abstract class AbstractSet<E>\nextends AbstractCollection<E>\nimplements Set<E>" }, { "code": null, "e": 25049, "s": 24993, "text": "Where E is the type of elements maintained by this Set." }, { "code": null, "e": 25179, "s": 25049, "text": "1. protected AbstractSet(): The default constructor, but being protected, it doesn’t allow the creation of an AbstractSet object." }, { "code": null, "e": 25217, "s": 25179, "text": "AbstractSet<E> as = new TreeSet<E>();" }, { "code": null, "e": 25224, "s": 25217, "text": "METHOD" }, { "code": null, "e": 25236, "s": 25224, "text": "DESCRIPTION" }, { "code": null, "e": 25247, "s": 25236, "text": "Example 1:" }, { "code": null, "e": 25252, "s": 25247, "text": "Java" }, { "code": "// Java Program to Illustrate AbstractSet Class // Importing required classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) throws Exception { // Try block to check for exceptions try { // Creating an empty TreeSet of integer type by // creating object of AbstractSet AbstractSet<Integer> abs_set = new TreeSet<Integer>(); // Populating TreeSet // using add() method abs_set.add(1); abs_set.add(2); abs_set.add(3); abs_set.add(4); abs_set.add(5); // Printing the elements inside above TreeSet System.out.println(\"AbstractSet: \" + abs_set); } // Catch block to handle the exceptions catch (Exception e) { // Display exception on console System.out.println(e); } }}", "e": 26211, "s": 25252, "text": null }, { "code": null, "e": 26240, "s": 26211, "text": "AbstractSet: [1, 2, 3, 4, 5]" }, { "code": null, "e": 26251, "s": 26240, "text": "Example 2:" }, { "code": null, "e": 26256, "s": 26251, "text": "Java" }, { "code": "// Java Program to Illustrate Methods// of AbstractSet class // Importing required classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) throws Exception { // Try block to check for exceptions try { // Creating an empty TreeSet of integer type AbstractSet<Integer> abs_set = new TreeSet<Integer>(); // Populating above TreeSet // using add() method abs_set.add(1); abs_set.add(2); abs_set.add(3); abs_set.add(4); abs_set.add(5); // Printing the elements inside TreeSet System.out.println(\"AbstractSet before \" + \"removeAll() operation : \" + abs_set); // Creating an ArrayList of integer type Collection<Integer> arrlist2 = new ArrayList<Integer>(); // Adding elements to above ArrayList arrlist2.add(1); arrlist2.add(2); arrlist2.add(3); // Printing the ArrayList elements System.out.println(\"Collection Elements\" + \" to be removed : \" + arrlist2); // Removing elements from AbstractSet specified // using removeAll() method abs_set.removeAll(arrlist2); // Printing the elements of ArrayList System.out.println(\"AbstractSet after \" + \"removeAll() operation : \" + abs_set); } // Catch block to handle the exceptions catch (NullPointerException e) { // Display exception on console System.out.println(\"Exception thrown : \" + e); } }}", "e": 28116, "s": 26256, "text": null }, { "code": null, "e": 28124, "s": 28116, "text": "Output:" }, { "code": null, "e": 28271, "s": 28124, "text": "Some other methods of classes or interfaces are defined below that somehow helps us to get a better understanding of AbstractSet Class as follows:" }, { "code": null, "e": 28278, "s": 28271, "text": "METHOD" }, { "code": null, "e": 28290, "s": 28278, "text": "DESCRIPTION" }, { "code": null, "e": 28297, "s": 28290, "text": "METHOD" }, { "code": null, "e": 28309, "s": 28297, "text": "DESCRIPTION" }, { "code": null, "e": 28316, "s": 28309, "text": "METHOD" }, { "code": null, "e": 28328, "s": 28316, "text": "DESCRIPTION" }, { "code": null, "e": 28335, "s": 28328, "text": "METHOD" }, { "code": null, "e": 28347, "s": 28335, "text": "DESCRIPTION" }, { "code": null, "e": 28361, "s": 28347, "text": "SachinShinde1" }, { "code": null, "e": 28374, "s": 28361, "text": "Akanksha_Rai" }, { "code": null, "e": 28398, "s": 28374, "text": "Ganeshchowdharysadanala" }, { "code": null, "e": 28412, "s": 28398, "text": "solankimayank" }, { "code": null, "e": 28431, "s": 28412, "text": "surindertarika1234" }, { "code": null, "e": 28443, "s": 28431, "text": "anikakapoor" }, { "code": null, "e": 28459, "s": 28443, "text": "simranarora5sos" }, { "code": null, "e": 28479, "s": 28459, "text": "Java - util package" }, { "code": null, "e": 28496, "s": 28479, "text": "Java-AbstractSet" }, { "code": null, "e": 28513, "s": 28496, "text": "Java-Collections" }, { "code": null, "e": 28518, "s": 28513, "text": "Java" }, { "code": null, "e": 28523, "s": 28518, "text": "Java" }, { "code": null, "e": 28540, "s": 28523, "text": "Java-Collections" }, { "code": null, "e": 28638, "s": 28540, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28647, "s": 28638, "text": "Comments" }, { "code": null, "e": 28660, "s": 28647, "text": "Old Comments" }, { "code": null, "e": 28675, "s": 28660, "text": "Arrays in Java" }, { "code": null, "e": 28719, "s": 28675, "text": "Split() String method in Java with examples" }, { "code": null, "e": 28741, "s": 28719, "text": "For-each loop in Java" }, { "code": null, "e": 28766, "s": 28741, "text": "Reverse a string in Java" }, { "code": null, "e": 28796, "s": 28766, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28815, "s": 28796, "text": "Interfaces in Java" }, { "code": null, "e": 28866, "s": 28815, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28902, "s": 28866, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 28920, "s": 28902, "text": "ArrayList in Java" } ]
How to use deleteOne() function in MongoDB?
The deleteOne() function in MongoDB deletes at most one matching document from a collection. Let us first create a collection with documents − > db.demo363.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e57d2c3d0ada61456dc9369") } > db.demo363.insertOne({"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e57d2c7d0ada61456dc936a") } > db.demo363.insertOne({"Name":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e57d2cad0ada61456dc936b") } > db.demo363.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e57d2d1d0ada61456dc936c") } Display all documents from a collection with the help of find() method − > db.demo363.find(); This will produce the following output − { "_id" : ObjectId("5e57d2c3d0ada61456dc9369"), "Name" : "Chris" } { "_id" : ObjectId("5e57d2c7d0ada61456dc936a"), "Name" : "David" } { "_id" : ObjectId("5e57d2cad0ada61456dc936b"), "Name" : "Bob" } { "_id" : ObjectId("5e57d2d1d0ada61456dc936c"), "Name" : "Chris" } Following is the query to work with deleteOne() in MongoDB − > db.demo363.deleteOne({Name:"Chris"}); { "acknowledged" : true, "deletedCount" : 1 } Display all documents from a collection with the help of find() method − > db.demo363.find(); This will produce the following output − { "_id" : ObjectId("5e57d2c7d0ada61456dc936a"), "Name" : "David" } { "_id" : ObjectId("5e57d2cad0ada61456dc936b"), "Name" : "Bob" } { "_id" : ObjectId("5e57d2d1d0ada61456dc936c"), "Name" : "Chris" }
[ { "code": null, "e": 1205, "s": 1062, "text": "The deleteOne() function in MongoDB deletes at most one matching document from a collection. Let us first create a collection with documents −" }, { "code": null, "e": 1711, "s": 1205, "text": "> db.demo363.insertOne({\"Name\":\"Chris\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e57d2c3d0ada61456dc9369\")\n}\n> db.demo363.insertOne({\"Name\":\"David\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e57d2c7d0ada61456dc936a\")\n}\n> db.demo363.insertOne({\"Name\":\"Bob\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e57d2cad0ada61456dc936b\")\n}\n> db.demo363.insertOne({\"Name\":\"Chris\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e57d2d1d0ada61456dc936c\")\n}" }, { "code": null, "e": 1784, "s": 1711, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1805, "s": 1784, "text": "> db.demo363.find();" }, { "code": null, "e": 1846, "s": 1805, "text": "This will produce the following output −" }, { "code": null, "e": 2112, "s": 1846, "text": "{ \"_id\" : ObjectId(\"5e57d2c3d0ada61456dc9369\"), \"Name\" : \"Chris\" }\n{ \"_id\" : ObjectId(\"5e57d2c7d0ada61456dc936a\"), \"Name\" : \"David\" }\n{ \"_id\" : ObjectId(\"5e57d2cad0ada61456dc936b\"), \"Name\" : \"Bob\" }\n{ \"_id\" : ObjectId(\"5e57d2d1d0ada61456dc936c\"), \"Name\" : \"Chris\" }" }, { "code": null, "e": 2173, "s": 2112, "text": "Following is the query to work with deleteOne() in MongoDB −" }, { "code": null, "e": 2259, "s": 2173, "text": "> db.demo363.deleteOne({Name:\"Chris\"});\n{ \"acknowledged\" : true, \"deletedCount\" : 1 }" }, { "code": null, "e": 2332, "s": 2259, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 2353, "s": 2332, "text": "> db.demo363.find();" }, { "code": null, "e": 2394, "s": 2353, "text": "This will produce the following output −" }, { "code": null, "e": 2593, "s": 2394, "text": "{ \"_id\" : ObjectId(\"5e57d2c7d0ada61456dc936a\"), \"Name\" : \"David\" }\n{ \"_id\" : ObjectId(\"5e57d2cad0ada61456dc936b\"), \"Name\" : \"Bob\" }\n{ \"_id\" : ObjectId(\"5e57d2d1d0ada61456dc936c\"), \"Name\" : \"Chris\" }" } ]
Amazon Web Services - CloudFront
CloudFront is a CDN (Content Delivery Network). It retrieves data from Amazon S3 bucket and distributes it to multiple datacenter locations. It delivers the data through a network of data centers called edge locations. The nearest edge location is routed when the user requests for data, resulting in lowest latency, low network traffic, fast access to data, etc. AWS CloudFront delivers the content in the following steps. Step 1 − The user accesses a website and requests an object to download like an image file. Step 2 − DNS routes your request to the nearest CloudFront edge location to serve the user request. Step 3 − At edge location, CloudFront checks its cache for the requested files. If found, then returns it to the user otherwise does the following − First CloudFront compares the request with the specifications and forwards it to the applicable origin server for the corresponding file type. First CloudFront compares the request with the specifications and forwards it to the applicable origin server for the corresponding file type. The origin servers send the files back to the CloudFront edge location. The origin servers send the files back to the CloudFront edge location. As soon as the first byte arrives from the origin, CloudFront starts forwarding it to the user and adds the files to the cache in the edge location for the next time when someone again requests for the same file. As soon as the first byte arrives from the origin, CloudFront starts forwarding it to the user and adds the files to the cache in the edge location for the next time when someone again requests for the same file. Step 4 − The object is now in an edge cache for 24 hours or for the provided duration in file headers. CloudFront does the following − CloudFront forwards the next request for the object to the user’s origin to check the edge location version is updated or not. CloudFront forwards the next request for the object to the user’s origin to check the edge location version is updated or not. If the edge location version is updated, then CloudFront delivers it to the user. If the edge location version is updated, then CloudFront delivers it to the user. If the edge location version is not updated, then origin sends the latest version to CloudFront. CloudFront delivers the object to the user and stores the latest version in the cache at that edge location. If the edge location version is not updated, then origin sends the latest version to CloudFront. CloudFront delivers the object to the user and stores the latest version in the cache at that edge location. Fast − The broad network of edge locations and CloudFront caches copies of content close to the end users that results in lowering latency, high data transfer rates and low network traffic. All these make CloudFront fast. Simple − It is easy to use. Can be used with other AWS Services − Amazon CloudFront is designed in such a way that it can be easily integrated with other AWS services, like Amazon S3, Amazon EC2. Cost-effective − Using Amazon CloudFront, we pay only for the content that you deliver through the network, without any hidden charges and no up-front fees. Elastic − Using Amazon CloudFront, we need not worry about maintenance. The service automatically responds if any action is needed, in case the demand increases or decreases. Reliable − Amazon CloudFront is built on Amazon’s highly reliable infrastructure, i.e. its edge locations will automatically re-route the end users to the next nearest location, if required in some situations. Global − Amazon CloudFront uses a global network of edge locations located in most of the regions. AWS CloudFront can be set up using the following steps. Step 1 − Sign in to AWS management console using the following link − https://console.aws.amazon.com/ Step 2 − Upload Amazon S3 and choose every permission public. (How to upload content to S3 bucket is discussed in chapter 14) Step 3 − Create a CloudFront Web Distribution using the following steps. Open CloudFront console using the following link − https://console.aws.amazon.com/cloudfront/ Open CloudFront console using the following link − https://console.aws.amazon.com/cloudfront/ Click the Get Started button in the web section of Select a delivery method for your content page. Click the Get Started button in the web section of Select a delivery method for your content page. Create Distribution page opens. Choose the Amazon S3 bucket created in the Origin Domain Name and leave the remaining fields as default. Create Distribution page opens. Choose the Amazon S3 bucket created in the Origin Domain Name and leave the remaining fields as default. Default Cache Behavior Settings page opens. Keep the values as default and move to the next page. Default Cache Behavior Settings page opens. Keep the values as default and move to the next page. A Distribution settings page opens. Fill the details as per your requirement and click the Create Distribution button. A Distribution settings page opens. Fill the details as per your requirement and click the Create Distribution button. The Status column changes from In Progress to Deployed. Enable your distribution by selecting the Enable option. It will take around 15 minutes for the domain name to be available in the Distributions list. The Status column changes from In Progress to Deployed. Enable your distribution by selecting the Enable option. It will take around 15 minutes for the domain name to be available in the Distributions list. After creating distribution, CloudFront knows the location of Amazon S3 server and the user knows the domain name associated with the distribution. However, we can also create a link to Amazon S3 bucket content with that domain name and have CloudFront serve it. This helps save a lot of time. Following are the steps to link an object − Step 1 − Copy the following HTML code to a new file and write the domain-name that CloudFront assigned to the distribution in the place of domain name. Write a file name of Amazon S3 bucket in the place of object-name. <html> <head>CloudFront Testing link</head> <body> <p>My Cludfront.</p> <p><img src = "http://domain-name/object-name" alt = "test image"/> </body> </html> Step 2 − Save the text in a file with .html extension. Step 3 − Open the web page in a browser to test the links to see if they are working correctly. If not, then crosscheck the settings. 24 Lectures 3 hours Syed Raza 43 Lectures 4 hours Theo McArthur 15 Lectures 51 mins John Shea 58 Lectures 4 hours John Shea 72 Lectures 6.5 hours Pranjal Srivastava 15 Lectures 1.5 hours Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2655, "s": 2291, "text": "CloudFront is a CDN (Content Delivery Network). It retrieves data from Amazon S3 bucket and distributes it to multiple datacenter locations. It delivers the data through a network of data centers called edge locations. The nearest edge location is routed when the user requests for data, resulting in lowest latency, low network traffic, fast access to data, etc." }, { "code": null, "e": 2715, "s": 2655, "text": "AWS CloudFront delivers the content in the following steps." }, { "code": null, "e": 2807, "s": 2715, "text": "Step 1 − The user accesses a website and requests an object to download like an image file." }, { "code": null, "e": 2907, "s": 2807, "text": "Step 2 − DNS routes your request to the nearest CloudFront edge location to serve the user request." }, { "code": null, "e": 3056, "s": 2907, "text": "Step 3 − At edge location, CloudFront checks its cache for the requested files. If found, then returns it to the user otherwise does the following −" }, { "code": null, "e": 3199, "s": 3056, "text": "First CloudFront compares the request with the specifications and forwards it to the applicable origin server for the corresponding file type." }, { "code": null, "e": 3342, "s": 3199, "text": "First CloudFront compares the request with the specifications and forwards it to the applicable origin server for the corresponding file type." }, { "code": null, "e": 3414, "s": 3342, "text": "The origin servers send the files back to the CloudFront edge location." }, { "code": null, "e": 3486, "s": 3414, "text": "The origin servers send the files back to the CloudFront edge location." }, { "code": null, "e": 3699, "s": 3486, "text": "As soon as the first byte arrives from the origin, CloudFront starts forwarding it to the user and adds the files to the cache in the edge location for the next time when someone again requests for the same file." }, { "code": null, "e": 3912, "s": 3699, "text": "As soon as the first byte arrives from the origin, CloudFront starts forwarding it to the user and adds the files to the cache in the edge location for the next time when someone again requests for the same file." }, { "code": null, "e": 4047, "s": 3912, "text": "Step 4 − The object is now in an edge cache for 24 hours or for the provided duration in file headers. CloudFront does the following −" }, { "code": null, "e": 4174, "s": 4047, "text": "CloudFront forwards the next request for the object to the user’s origin to check the edge location version is updated or not." }, { "code": null, "e": 4301, "s": 4174, "text": "CloudFront forwards the next request for the object to the user’s origin to check the edge location version is updated or not." }, { "code": null, "e": 4383, "s": 4301, "text": "If the edge location version is updated, then CloudFront delivers it to the user." }, { "code": null, "e": 4465, "s": 4383, "text": "If the edge location version is updated, then CloudFront delivers it to the user." }, { "code": null, "e": 4671, "s": 4465, "text": "If the edge location version is not updated, then origin sends the latest version to CloudFront. CloudFront delivers the object to the user and stores the latest version in the cache at that edge location." }, { "code": null, "e": 4877, "s": 4671, "text": "If the edge location version is not updated, then origin sends the latest version to CloudFront. CloudFront delivers the object to the user and stores the latest version in the cache at that edge location." }, { "code": null, "e": 5099, "s": 4877, "text": "Fast − The broad network of edge locations and CloudFront caches copies of content close to the end users that results in lowering latency, high data transfer rates and low network traffic. All these make CloudFront fast." }, { "code": null, "e": 5127, "s": 5099, "text": "Simple − It is easy to use." }, { "code": null, "e": 5295, "s": 5127, "text": "Can be used with other AWS Services − Amazon CloudFront is designed in such a way that it can be easily integrated with other AWS services, like Amazon S3, Amazon EC2." }, { "code": null, "e": 5452, "s": 5295, "text": "Cost-effective − Using Amazon CloudFront, we pay only for the content that you deliver through the network, without any hidden charges and no up-front fees." }, { "code": null, "e": 5627, "s": 5452, "text": "Elastic − Using Amazon CloudFront, we need not worry about maintenance. The service automatically responds if any action is needed, in case the demand increases or decreases." }, { "code": null, "e": 5837, "s": 5627, "text": "Reliable − Amazon CloudFront is built on Amazon’s highly reliable infrastructure, i.e. its edge locations will automatically re-route the end users to the next nearest location, if required in some situations." }, { "code": null, "e": 5936, "s": 5837, "text": "Global − Amazon CloudFront uses a global network of edge locations located in most of the regions." }, { "code": null, "e": 5992, "s": 5936, "text": "AWS CloudFront can be set up using the following steps." }, { "code": null, "e": 6094, "s": 5992, "text": "Step 1 − Sign in to AWS management console using the following link − https://console.aws.amazon.com/" }, { "code": null, "e": 6220, "s": 6094, "text": "Step 2 − Upload Amazon S3 and choose every permission public. (How to upload content to S3 bucket is discussed in chapter 14)" }, { "code": null, "e": 6293, "s": 6220, "text": "Step 3 − Create a CloudFront Web Distribution using the following steps." }, { "code": null, "e": 6387, "s": 6293, "text": "Open CloudFront console using the following link − https://console.aws.amazon.com/cloudfront/" }, { "code": null, "e": 6481, "s": 6387, "text": "Open CloudFront console using the following link − https://console.aws.amazon.com/cloudfront/" }, { "code": null, "e": 6580, "s": 6481, "text": "Click the Get Started button in the web section of Select a delivery method for your content page." }, { "code": null, "e": 6679, "s": 6580, "text": "Click the Get Started button in the web section of Select a delivery method for your content page." }, { "code": null, "e": 6816, "s": 6679, "text": "Create Distribution page opens. Choose the Amazon S3 bucket created in the Origin Domain Name and leave the remaining fields as default." }, { "code": null, "e": 6953, "s": 6816, "text": "Create Distribution page opens. Choose the Amazon S3 bucket created in the Origin Domain Name and leave the remaining fields as default." }, { "code": null, "e": 7051, "s": 6953, "text": "Default Cache Behavior Settings page opens. Keep the values as default and move to the next page." }, { "code": null, "e": 7149, "s": 7051, "text": "Default Cache Behavior Settings page opens. Keep the values as default and move to the next page." }, { "code": null, "e": 7268, "s": 7149, "text": "A Distribution settings page opens. Fill the details as per your requirement and click the Create Distribution button." }, { "code": null, "e": 7387, "s": 7268, "text": "A Distribution settings page opens. Fill the details as per your requirement and click the Create Distribution button." }, { "code": null, "e": 7594, "s": 7387, "text": "The Status column changes from In Progress to Deployed. Enable your distribution by selecting the Enable option. It will take around 15 minutes for the domain name to be available in the Distributions list." }, { "code": null, "e": 7801, "s": 7594, "text": "The Status column changes from In Progress to Deployed. Enable your distribution by selecting the Enable option. It will take around 15 minutes for the domain name to be available in the Distributions list." }, { "code": null, "e": 8095, "s": 7801, "text": "After creating distribution, CloudFront knows the location of Amazon S3 server and the user knows the domain name associated with the distribution. However, we can also create a link to Amazon S3 bucket content with that domain name and have CloudFront serve it. This helps save a lot of time." }, { "code": null, "e": 8139, "s": 8095, "text": "Following are the steps to link an object −" }, { "code": null, "e": 8358, "s": 8139, "text": "Step 1 − Copy the following HTML code to a new file and write the domain-name that CloudFront assigned to the distribution in the place of domain name. Write a file name of Amazon S3 bucket in the place of object-name." }, { "code": null, "e": 8541, "s": 8358, "text": "<html> \n <head>CloudFront Testing link</head> \n <body> \n <p>My Cludfront.</p> \n <p><img src = \"http://domain-name/object-name\" alt = \"test image\"/> \n </body> \n</html>" }, { "code": null, "e": 8596, "s": 8541, "text": "Step 2 − Save the text in a file with .html extension." }, { "code": null, "e": 8730, "s": 8596, "text": "Step 3 − Open the web page in a browser to test the links to see if they are working correctly. If not, then crosscheck the settings." }, { "code": null, "e": 8763, "s": 8730, "text": "\n 24 Lectures \n 3 hours \n" }, { "code": null, "e": 8774, "s": 8763, "text": " Syed Raza" }, { "code": null, "e": 8807, "s": 8774, "text": "\n 43 Lectures \n 4 hours \n" }, { "code": null, "e": 8822, "s": 8807, "text": " Theo McArthur" }, { "code": null, "e": 8854, "s": 8822, "text": "\n 15 Lectures \n 51 mins\n" }, { "code": null, "e": 8865, "s": 8854, "text": " John Shea" }, { "code": null, "e": 8898, "s": 8865, "text": "\n 58 Lectures \n 4 hours \n" }, { "code": null, "e": 8909, "s": 8898, "text": " John Shea" }, { "code": null, "e": 8944, "s": 8909, "text": "\n 72 Lectures \n 6.5 hours \n" }, { "code": null, "e": 8964, "s": 8944, "text": " Pranjal Srivastava" }, { "code": null, "e": 8999, "s": 8964, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9019, "s": 8999, "text": " Harshit Srivastava" }, { "code": null, "e": 9026, "s": 9019, "text": " Print" }, { "code": null, "e": 9037, "s": 9026, "text": " Add Notes" } ]
Add a background color to the form input with CSS
To add background color to the form input, use the background-color property. You can try to run the following code to implement the background color property to form Live Demo <!DOCTYPE html> <html> <head> <style> input[type=text] { width: 100%; padding: 10px 15px; margin: 5px 0; box-sizing: border-box; background-color: gray; } </style> </head> <body> <p>Fill the below form,</p> <form> <label for = "subject">Subject</label> <input type = "text" id = "subject" name = "sub"> <label for = "student">Student</label> <input type = "text" id = "student" name = "stu"> </form> </body> </html>
[ { "code": null, "e": 1140, "s": 1062, "text": "To add background color to the form input, use the background-color property." }, { "code": null, "e": 1229, "s": 1140, "text": "You can try to run the following code to implement the background color property to form" }, { "code": null, "e": 1239, "s": 1229, "text": "Live Demo" }, { "code": null, "e": 1811, "s": 1239, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n input[type=text] {\n width: 100%;\n padding: 10px 15px;\n margin: 5px 0;\n box-sizing: border-box;\n background-color: gray;\n }\n </style>\n </head>\n <body>\n <p>Fill the below form,</p>\n <form>\n <label for = \"subject\">Subject</label>\n <input type = \"text\" id = \"subject\" name = \"sub\">\n <label for = \"student\">Student</label>\n <input type = \"text\" id = \"student\" name = \"stu\">\n </form>\n </body>\n</html>" } ]
Count of same length Strings that exists lexicographically in between two given Strings - GeeksforGeeks
06 May, 2021 Given two string S1 and S2 of length L, the task is to count the number of strings of length L, that exists in between S1 and S2, which are lexicographically greater than S1 but smaller than S2. Examples: Input: S1 = “b”, S2 = “f” Output: 3 Explaination: These are 3 strings which come lexicographically in between S1 and S2 i.e. “c”, “d” & “e”Input: S1 = “aby”, S2 = “ace” Output: 5 Explaination: These are 5 strings which come lexicographically in between S1 and S2 i.e. “abz”, “aca”, “acb”, “acc” & “acd”. Approach: First, find out the number of strings lexicographically smaller than the first string S1, as:Let the String S1 of length L be represented as c0c1c2...cL-1 where ci is the character in S1 at index i Therefore, To get the number of strings less than S1, we will calculate it as N(S1) = (number of letters less than c0 * 26L-1) + (number of letters less than c1 * 26L-2) + (number of letters less than c2 * 26L-3) + ... + (number of letters less than cL-2 * 26) + (number of letters less than cL-1)For example:Let S1 = "cbd" Number of strings less than S1 N(S1) = (number of letters less than 'c' * 262) + (number of letters less than 'b' * 26) + (number of letters less than 'd') N(S1) = (2 * 26 * 26) + (1 * 26) + (3) = 1352 + 26 + 3 = 1381.Similarly, find out the number of string lexicographically smaller than S2.Then just find out the difference between the above two values to get the number of string lexicographically greater than S1 but smaller than S2. First, find out the number of strings lexicographically smaller than the first string S1, as:Let the String S1 of length L be represented as c0c1c2...cL-1 where ci is the character in S1 at index i Therefore, To get the number of strings less than S1, we will calculate it as N(S1) = (number of letters less than c0 * 26L-1) + (number of letters less than c1 * 26L-2) + (number of letters less than c2 * 26L-3) + ... + (number of letters less than cL-2 * 26) + (number of letters less than cL-1)For example:Let S1 = "cbd" Number of strings less than S1 N(S1) = (number of letters less than 'c' * 262) + (number of letters less than 'b' * 26) + (number of letters less than 'd') N(S1) = (2 * 26 * 26) + (1 * 26) + (3) = 1352 + 26 + 3 = 1381. Let the String S1 of length L be represented as c0c1c2...cL-1 where ci is the character in S1 at index i Therefore, To get the number of strings less than S1, we will calculate it as N(S1) = (number of letters less than c0 * 26L-1) + (number of letters less than c1 * 26L-2) + (number of letters less than c2 * 26L-3) + ... + (number of letters less than cL-2 * 26) + (number of letters less than cL-1) For example: Let S1 = "cbd" Number of strings less than S1 N(S1) = (number of letters less than 'c' * 262) + (number of letters less than 'b' * 26) + (number of letters less than 'd') N(S1) = (2 * 26 * 26) + (1 * 26) + (3) = 1352 + 26 + 3 = 1381. Similarly, find out the number of string lexicographically smaller than S2. Then just find out the difference between the above two values to get the number of string lexicographically greater than S1 but smaller than S2. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find the count of// same length Strings that exists lexicographically// in between two given Strings #include <bits/stdc++.h>using namespace std; // Function to find the count of strings less// than given string lexicographicallyint LexicoLesserStrings(string s){ int count = 0; int len; // Find length of string s len = s.size(); // Looping over the string characters and // finding strings less than that character for (int i = 0; i < len; i++) { count += (s[i] - 'a') * pow(26, len - i - 1); } return count;} // Function to find the count of// same length Strings that exists// lexicographically in between two given Stringsint countString(string S1, string S2){ int countS1, countS2, totalString; // Count string less than S1 countS1 = LexicoLesserStrings(S1); // Count string less than S2 countS2 = LexicoLesserStrings(S2); // Total strings between S1 and S2 would // be difference between the counts - 1 totalString = countS2 - countS1 - 1; // If S1 is lexicographically greater // than S2 then return 0, otherwise return // the value of totalString return (totalString < 0 ? 0 : totalString);} // Driver codeint main(){ string S1, S2; S1 = "cda"; S2 = "cef"; cout << countString(S1, S2); return 0;} // Java program to find the count of same length// Strings that exists lexicographically// in between two given Stringsimport java.util.*; class GFG{ // Function to find the count of strings less// than given string lexicographicallystatic int LexicoLesserStrings(String s){ int count = 0; int len; // Find length of string s len = s.length(); // Looping over the string characters and // finding strings less than that character for(int i = 0; i < len; i++) { count += (s.charAt(i) - 'a') * Math.pow(26, len - i - 1); } return count;} // Function to find the count of// same length Strings that exists// lexicographically in between two// given Stringsstatic int countString(String S1, String S2){ int countS1, countS2, totalString; // Count string less than S1 countS1 = LexicoLesserStrings(S1); // Count string less than S2 countS2 = LexicoLesserStrings(S2); // Total strings between S1 and S2 would // be difference between the counts - 1 totalString = countS2 - countS1 - 1; // If S1 is lexicographically greater // than S2 then return 0, otherwise return // the value of totalString return (totalString < 0 ? 0 : totalString);} // Driver codepublic static void main(String args[]){ String S1, S2; S1 = "cda"; S2 = "cef"; System.out.println(countString(S1, S2));}} // This code is contributed by apurva raj # Python3 program to find the count of same# length Strings that exists lexicographically# in between two given Strings # Function to find the count of strings less# than given string lexicographicallydef LexicoLesserStrings(s): count = 0 # Find length of string s length = len(s) # Looping over the string characters and # finding strings less than that character for i in range(length): count += ((ord(s[i]) - ord('a')) * pow(26, length - i - 1)) return count # Function to find the count of# same length Strings that exists# lexicographically in between two# given Stringsdef countString(S1, S2): # Count string less than S1 countS1 = LexicoLesserStrings(S1) # Count string less than S2 countS2 = LexicoLesserStrings(S2) # Total strings between S1 and S2 would # be difference between the counts - 1 totalString = countS2 - countS1 - 1; # If S1 is lexicographically greater # than S2 then return 0, otherwise return # the value of totalString return (0 if totalString < 0 else totalString) # Driver codeS1 = "cda";S2 = "cef"; print(countString(S1, S2)) # This code is contributed by apurva raj // C# program to find the count of same length// Strings that exists lexicographically// in between two given Stringsusing System; class GFG{ // Function to find the count of strings less// than given string lexicographicallystatic int LexicoLesserStrings(String s){ int count = 0; int len; // Find length of string s len = s.Length; // Looping over the string characters and // finding strings less than that character for(int i = 0; i < len; i++) { count += ((s[i] - 'a') * (int)Math.Pow(26, len - i - 1)); } return count;} // Function to find the count of// same length Strings that exists// lexicographically in between two// given Stringsstatic int countString(String S1, String S2){ int countS1, countS2, totalString; // Count string less than S1 countS1 = LexicoLesserStrings(S1); // Count string less than S2 countS2 = LexicoLesserStrings(S2); // Total strings between S1 and S2 would // be difference between the counts - 1 totalString = countS2 - countS1 - 1; // If S1 is lexicographically greater // than S2 then return 0, otherwise return // the value of totalString return (totalString < 0 ? 0 : totalString);} // Driver codepublic static void Main(){ String S1, S2; S1 = "cda"; S2 = "cef"; Console.Write(countString(S1, S2));}} // This code is contributed by chitranayal <script> // JavaScript program to find the count of // same length Strings that exists lexicographically // in between two given Strings // Function to find the count of strings less // than given string lexicographically function LexicoLesserStrings(s) { var count = 0; var len; // Find length of string s len = s.length; // Looping over the string characters and // finding strings less than that character for (var i = 0; i < len; i++) { count += (s[i].charCodeAt(0) - "a".charCodeAt(0)) * Math.pow(26, len - i - 1); } return count; } // Function to find the count of // same length Strings that exists // lexicographically in between two given Strings function countString(S1, S2) { var countS1, countS2, totalString; // Count string less than S1 countS1 = LexicoLesserStrings(S1); // Count string less than S2 countS2 = LexicoLesserStrings(S2); // Total strings between S1 and S2 would // be difference between the counts - 1 totalString = countS2 - countS1 - 1; // If S1 is lexicographically greater // than S2 then return 0, otherwise return // the value of totalString return totalString < 0 ? 0 : totalString; } // Driver code var S1, S2; S1 = "cda"; S2 = "cef"; document.write(countString(S1, S2));</script> 30 Performance Analysis:Time Complexity: In the above approach, we are looping over the two strings of length N, therefore it will take O(N) time where N is the length of each string.Auxiliary Space Complexity: As in the above approach there is no extra space used, therefore the Auxiliary Space complexity will be O(1). ApurvaRaj nidhi_biet ukasp rdtank lexicographic-ordering Mathematical Strings Strings Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Print all possible combinations of r elements in a given array of size n Write a program to reverse an array or string Reverse a string in Java Longest Common Subsequence | DP-4 Check for Balanced Brackets in an expression (well-formedness) using Stack Python program to check if a string is palindrome or not
[ { "code": null, "e": 26159, "s": 26131, "text": "\n06 May, 2021" }, { "code": null, "e": 26366, "s": 26159, "text": "Given two string S1 and S2 of length L, the task is to count the number of strings of length L, that exists in between S1 and S2, which are lexicographically greater than S1 but smaller than S2. Examples: " }, { "code": null, "e": 26672, "s": 26366, "text": "Input: S1 = “b”, S2 = “f” Output: 3 Explaination: These are 3 strings which come lexicographically in between S1 and S2 i.e. “c”, “d” & “e”Input: S1 = “aby”, S2 = “ace” Output: 5 Explaination: These are 5 strings which come lexicographically in between S1 and S2 i.e. “abz”, “aca”, “acb”, “acc” & “acd”. " }, { "code": null, "e": 26685, "s": 26674, "text": "Approach: " }, { "code": null, "e": 27702, "s": 26685, "text": "First, find out the number of strings lexicographically smaller than the first string S1, as:Let the String S1 of length L \nbe represented as c0c1c2...cL-1\nwhere ci is the character in S1 at index i\n\nTherefore, To get the number of strings less than S1,\nwe will calculate it as \nN(S1) = (number of letters less than c0 * 26L-1)\n + (number of letters less than c1 * 26L-2)\n + (number of letters less than c2 * 26L-3)\n + ... \n + (number of letters less than cL-2 * 26)\n + (number of letters less than cL-1)For example:Let S1 = \"cbd\"\n\nNumber of strings less than S1\nN(S1) = (number of letters less than 'c' * 262)\n + (number of letters less than 'b' * 26)\n + (number of letters less than 'd')\n\nN(S1) = (2 * 26 * 26) + (1 * 26) + (3) \n = 1352 + 26 + 3 = 1381.Similarly, find out the number of string lexicographically smaller than S2.Then just find out the difference between the above two values to get the number of string lexicographically greater than S1 but smaller than S2." }, { "code": null, "e": 28499, "s": 27702, "text": "First, find out the number of strings lexicographically smaller than the first string S1, as:Let the String S1 of length L \nbe represented as c0c1c2...cL-1\nwhere ci is the character in S1 at index i\n\nTherefore, To get the number of strings less than S1,\nwe will calculate it as \nN(S1) = (number of letters less than c0 * 26L-1)\n + (number of letters less than c1 * 26L-2)\n + (number of letters less than c2 * 26L-3)\n + ... \n + (number of letters less than cL-2 * 26)\n + (number of letters less than cL-1)For example:Let S1 = \"cbd\"\n\nNumber of strings less than S1\nN(S1) = (number of letters less than 'c' * 262)\n + (number of letters less than 'b' * 26)\n + (number of letters less than 'd')\n\nN(S1) = (2 * 26 * 26) + (1 * 26) + (3) \n = 1352 + 26 + 3 = 1381." }, { "code": null, "e": 28937, "s": 28499, "text": "Let the String S1 of length L \nbe represented as c0c1c2...cL-1\nwhere ci is the character in S1 at index i\n\nTherefore, To get the number of strings less than S1,\nwe will calculate it as \nN(S1) = (number of letters less than c0 * 26L-1)\n + (number of letters less than c1 * 26L-2)\n + (number of letters less than c2 * 26L-3)\n + ... \n + (number of letters less than cL-2 * 26)\n + (number of letters less than cL-1)" }, { "code": null, "e": 28950, "s": 28937, "text": "For example:" }, { "code": null, "e": 29205, "s": 28950, "text": "Let S1 = \"cbd\"\n\nNumber of strings less than S1\nN(S1) = (number of letters less than 'c' * 262)\n + (number of letters less than 'b' * 26)\n + (number of letters less than 'd')\n\nN(S1) = (2 * 26 * 26) + (1 * 26) + (3) \n = 1352 + 26 + 3 = 1381." }, { "code": null, "e": 29281, "s": 29205, "text": "Similarly, find out the number of string lexicographically smaller than S2." }, { "code": null, "e": 29427, "s": 29281, "text": "Then just find out the difference between the above two values to get the number of string lexicographically greater than S1 but smaller than S2." }, { "code": null, "e": 29480, "s": 29427, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 29484, "s": 29480, "text": "C++" }, { "code": null, "e": 29489, "s": 29484, "text": "Java" }, { "code": null, "e": 29497, "s": 29489, "text": "Python3" }, { "code": null, "e": 29500, "s": 29497, "text": "C#" }, { "code": null, "e": 29511, "s": 29500, "text": "Javascript" }, { "code": " // C++ program to find the count of// same length Strings that exists lexicographically// in between two given Strings #include <bits/stdc++.h>using namespace std; // Function to find the count of strings less// than given string lexicographicallyint LexicoLesserStrings(string s){ int count = 0; int len; // Find length of string s len = s.size(); // Looping over the string characters and // finding strings less than that character for (int i = 0; i < len; i++) { count += (s[i] - 'a') * pow(26, len - i - 1); } return count;} // Function to find the count of// same length Strings that exists// lexicographically in between two given Stringsint countString(string S1, string S2){ int countS1, countS2, totalString; // Count string less than S1 countS1 = LexicoLesserStrings(S1); // Count string less than S2 countS2 = LexicoLesserStrings(S2); // Total strings between S1 and S2 would // be difference between the counts - 1 totalString = countS2 - countS1 - 1; // If S1 is lexicographically greater // than S2 then return 0, otherwise return // the value of totalString return (totalString < 0 ? 0 : totalString);} // Driver codeint main(){ string S1, S2; S1 = \"cda\"; S2 = \"cef\"; cout << countString(S1, S2); return 0;}", "e": 30861, "s": 29511, "text": null }, { "code": "// Java program to find the count of same length// Strings that exists lexicographically// in between two given Stringsimport java.util.*; class GFG{ // Function to find the count of strings less// than given string lexicographicallystatic int LexicoLesserStrings(String s){ int count = 0; int len; // Find length of string s len = s.length(); // Looping over the string characters and // finding strings less than that character for(int i = 0; i < len; i++) { count += (s.charAt(i) - 'a') * Math.pow(26, len - i - 1); } return count;} // Function to find the count of// same length Strings that exists// lexicographically in between two// given Stringsstatic int countString(String S1, String S2){ int countS1, countS2, totalString; // Count string less than S1 countS1 = LexicoLesserStrings(S1); // Count string less than S2 countS2 = LexicoLesserStrings(S2); // Total strings between S1 and S2 would // be difference between the counts - 1 totalString = countS2 - countS1 - 1; // If S1 is lexicographically greater // than S2 then return 0, otherwise return // the value of totalString return (totalString < 0 ? 0 : totalString);} // Driver codepublic static void main(String args[]){ String S1, S2; S1 = \"cda\"; S2 = \"cef\"; System.out.println(countString(S1, S2));}} // This code is contributed by apurva raj", "e": 32292, "s": 30861, "text": null }, { "code": "# Python3 program to find the count of same# length Strings that exists lexicographically# in between two given Strings # Function to find the count of strings less# than given string lexicographicallydef LexicoLesserStrings(s): count = 0 # Find length of string s length = len(s) # Looping over the string characters and # finding strings less than that character for i in range(length): count += ((ord(s[i]) - ord('a')) * pow(26, length - i - 1)) return count # Function to find the count of# same length Strings that exists# lexicographically in between two# given Stringsdef countString(S1, S2): # Count string less than S1 countS1 = LexicoLesserStrings(S1) # Count string less than S2 countS2 = LexicoLesserStrings(S2) # Total strings between S1 and S2 would # be difference between the counts - 1 totalString = countS2 - countS1 - 1; # If S1 is lexicographically greater # than S2 then return 0, otherwise return # the value of totalString return (0 if totalString < 0 else totalString) # Driver codeS1 = \"cda\";S2 = \"cef\"; print(countString(S1, S2)) # This code is contributed by apurva raj", "e": 33510, "s": 32292, "text": null }, { "code": "// C# program to find the count of same length// Strings that exists lexicographically// in between two given Stringsusing System; class GFG{ // Function to find the count of strings less// than given string lexicographicallystatic int LexicoLesserStrings(String s){ int count = 0; int len; // Find length of string s len = s.Length; // Looping over the string characters and // finding strings less than that character for(int i = 0; i < len; i++) { count += ((s[i] - 'a') * (int)Math.Pow(26, len - i - 1)); } return count;} // Function to find the count of// same length Strings that exists// lexicographically in between two// given Stringsstatic int countString(String S1, String S2){ int countS1, countS2, totalString; // Count string less than S1 countS1 = LexicoLesserStrings(S1); // Count string less than S2 countS2 = LexicoLesserStrings(S2); // Total strings between S1 and S2 would // be difference between the counts - 1 totalString = countS2 - countS1 - 1; // If S1 is lexicographically greater // than S2 then return 0, otherwise return // the value of totalString return (totalString < 0 ? 0 : totalString);} // Driver codepublic static void Main(){ String S1, S2; S1 = \"cda\"; S2 = \"cef\"; Console.Write(countString(S1, S2));}} // This code is contributed by chitranayal", "e": 34914, "s": 33510, "text": null }, { "code": "<script> // JavaScript program to find the count of // same length Strings that exists lexicographically // in between two given Strings // Function to find the count of strings less // than given string lexicographically function LexicoLesserStrings(s) { var count = 0; var len; // Find length of string s len = s.length; // Looping over the string characters and // finding strings less than that character for (var i = 0; i < len; i++) { count += (s[i].charCodeAt(0) - \"a\".charCodeAt(0)) * Math.pow(26, len - i - 1); } return count; } // Function to find the count of // same length Strings that exists // lexicographically in between two given Strings function countString(S1, S2) { var countS1, countS2, totalString; // Count string less than S1 countS1 = LexicoLesserStrings(S1); // Count string less than S2 countS2 = LexicoLesserStrings(S2); // Total strings between S1 and S2 would // be difference between the counts - 1 totalString = countS2 - countS1 - 1; // If S1 is lexicographically greater // than S2 then return 0, otherwise return // the value of totalString return totalString < 0 ? 0 : totalString; } // Driver code var S1, S2; S1 = \"cda\"; S2 = \"cef\"; document.write(countString(S1, S2));</script> ", "e": 36422, "s": 34914, "text": null }, { "code": null, "e": 36425, "s": 36422, "text": "30" }, { "code": null, "e": 36746, "s": 36427, "text": "Performance Analysis:Time Complexity: In the above approach, we are looping over the two strings of length N, therefore it will take O(N) time where N is the length of each string.Auxiliary Space Complexity: As in the above approach there is no extra space used, therefore the Auxiliary Space complexity will be O(1). " }, { "code": null, "e": 36756, "s": 36746, "text": "ApurvaRaj" }, { "code": null, "e": 36767, "s": 36756, "text": "nidhi_biet" }, { "code": null, "e": 36773, "s": 36767, "text": "ukasp" }, { "code": null, "e": 36780, "s": 36773, "text": "rdtank" }, { "code": null, "e": 36803, "s": 36780, "text": "lexicographic-ordering" }, { "code": null, "e": 36816, "s": 36803, "text": "Mathematical" }, { "code": null, "e": 36824, "s": 36816, "text": "Strings" }, { "code": null, "e": 36832, "s": 36824, "text": "Strings" }, { "code": null, "e": 36845, "s": 36832, "text": "Mathematical" }, { "code": null, "e": 36943, "s": 36845, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36967, "s": 36943, "text": "Merge two sorted arrays" }, { "code": null, "e": 37010, "s": 36967, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 37024, "s": 37010, "text": "Prime Numbers" }, { "code": null, "e": 37066, "s": 37024, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 37139, "s": 37066, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 37185, "s": 37139, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 37210, "s": 37185, "text": "Reverse a string in Java" }, { "code": null, "e": 37244, "s": 37210, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 37319, "s": 37244, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
Calculate Volume and Surface area Of Sphere - GeeksforGeeks
24 Nov, 2021 Given radius of sphere, calculate the volume and surface area of sphere.Sphere: Just like a circle, which geometrically is a two-dimensional object, a sphere is defined mathematically as the set of points that are all at the same distance r from a given point, but in three-dimensional space. This distance r is the radius of the sphere, and the given point is the center of the sphere. For a given surface area, the sphere is the one solid that has the greatest volume. This why it appears in nature so much, such as water drops, bubbles and planets etc.Volume Of Sphere: The number of cubic units that will exactly fill a sphere or the storage capacity of sphere. We can calculate the volume of sphere by using formula: Surface Area Of Sphere: The surface area of a sphere object is a measure of the total area that the surface of the sphere occupies. We can calculate the volume of sphere by using formula: Examples : Input : Radius Of Sphere = 5 Output : Volume Of Sphere : 523.5987755982989 Surface Area Of Sphere : 314.1592653589793 Explanation: Volume =( 4/3 ) * 3.14159 * 5 * 5 * 5 = 523.598 Surface Area = 4 * 3.14159 * 5 * 5 =314.159 Input : Radius Of Sphere = 12 Output : Volume Of Sphere : 7238.229473870883 Surface Area Of Sphere : 1809.5573684677208 C++ Java Python3 C# PHP Javascript // CPP program to calculate Volume and // Surface area of Sphere#include<bits/stdc++.h>using namespace std; // Initializing Value Of PIfloat pi = 3.14159; // Function To Calculate Volume Of Spherefloat volume(float r){ float vol; vol = (float(4) / float(3)) * pi * r * r * r; return vol; } // Function To Calculate Surface Area of Spherefloat surface_area(float r){ float sur_ar; sur_ar = 4 * pi * r * r; return sur_ar;} // Driver Functionint main(){ float radius = 12; float vol, sur_area; // Function Call vol = volume(radius); sur_area = surface_area(radius); // Printing Value Of Volume And Surface Area cout << "Volume Of Sphere :" << vol << endl; cout << "Surface Area Of Sphere :" << sur_area << endl; return 0;} // Java program to calculate Volume and// Surface area of Sphereclass GFG { // Initializing Value Of PIstatic float pi = 3.14159f; // Function To Calculate Volume Of Spherestatic float volume(float r){ float vol; vol = ((float)4 / (float)3) * (pi * r * r * r); return vol;} // Function To Calculate Surface Area of Spherestatic float surface_area(float r) { float sur_ar; sur_ar = 4 * pi * r * r; return sur_ar;} // Driver Functionpublic static void main(String[] args) { float radius = 12; float vol, sur_area; // Function Call vol = volume(radius); sur_area = surface_area(radius); // Printing Value Of Volume And Surface Area System.out.println("Volume Of Sphere :" + vol); System.out.println("Surface Area Of Sphere :" + sur_area);}} // This code is contributed by Anant Agarwal. ''' Python3 program to calculate Volume and Surface area of Sphere'''# Importing Math library for value Of PIimport mathpi = math.pi # Function to calculate Volume of Spheredef volume(r): vol = (4 / 3) * pi * r * r * r return vol # Function To Calculate Surface Area of Spheredef surfacearea(r): sur_ar = 4 * pi * r * r return sur_ar # Driver Coderadius = float(12)print( "Volume Of Sphere : ", volume(radius) )print( "Surface Area Of Sphere : ", surfacearea(radius) ) // C# program to calculate Volume and// Surface area of Sphereusing System; class GFG { // Initializing Value Of PI static float pi = 3.14159f; // Function To Calculate Volume // Of Sphere static float volume(float r) { float vol; vol = ((float)4 / (float)3) * (pi * r * r * r); return vol; } // Function To Calculate Surface Area // of Sphere static float surface_area(float r) { float sur_ar; sur_ar = 4 * pi * r * r; return sur_ar; } // Driver Function public static void Main() { float radius = 12; float vol, sur_area; // Function Call vol = volume(radius); sur_area = surface_area(radius); // Printing Value Of Volume And // Surface Area Console.WriteLine("Volume Of Sphere :" + vol); Console.WriteLine("Surface Area Of " + "Sphere :" + sur_area); }} // This code is contributed by vt_m. <?php// PHP program to calculate Volume // and Surface area of Sphere // Function To Calculate // Volume Of Spherefunction volume( $r){ $pi = 3.14159; $vol = (4 / 3) * $pi * $r * $r * $r; return $vol; } // Function To Calculate // Surface Area of Spherefunction surface_area( $r){ $pi = 3.14159; $sur_ar = 4 * $pi * $r * $r; return $sur_ar;} // Driver Code$radius = 12;$vol; $sur_area; // Function Call$vol = volume($radius);$sur_area = surface_area($radius); // Printing Value Of // Volume And Surface Areaecho ("Volume Of Sphere : " );echo($vol);echo( " \nSurface Area Of Sphere :");echo( $sur_area); // This code is contributed by vt_m.?> <script>// javascript program to calculate Volume and // Surface area of Sphere // Initializing Value Of PIconst pi = 3.14159; // Function To Calculate Volume Of Spherefunction volume( r){ let vol; vol = ((4) / (3)) * pi * r * r * r; return vol;} // Function To Calculate Surface Area of Spherefunction surface_area( r){ let sur_ar; sur_ar = 4 * pi * r * r; return sur_ar;} // Driver Function let radius = 12; let vol, sur_area; // Function Call vol = volume(radius).toFixed(2); sur_area = surface_area(radius).toFixed(2); // Printing Value Of Volume And Surface Area document.write( "Volume Of Sphere :" + vol +"<br/>"); document.write( "Surface Area Of Sphere :" + sur_area + "<br/>"); // This code is contributed by Rajput-Ji </script> Output : Volume Of Sphere :7238.22 Surface Area Of Sphere :1809.56 vt_m Rajput-Ji bunnyram19 area-volume-programs Geometric School Programming Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program for distance between two points on earth Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Closest Pair of Points | O(nlogn) Implementation Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Given n line segments, find if any two segments intersect Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 25336, "s": 25308, "text": "\n24 Nov, 2021" }, { "code": null, "e": 26060, "s": 25336, "text": "Given radius of sphere, calculate the volume and surface area of sphere.Sphere: Just like a circle, which geometrically is a two-dimensional object, a sphere is defined mathematically as the set of points that are all at the same distance r from a given point, but in three-dimensional space. This distance r is the radius of the sphere, and the given point is the center of the sphere. For a given surface area, the sphere is the one solid that has the greatest volume. This why it appears in nature so much, such as water drops, bubbles and planets etc.Volume Of Sphere: The number of cubic units that will exactly fill a sphere or the storage capacity of sphere. We can calculate the volume of sphere by using formula: " }, { "code": null, "e": 26250, "s": 26060, "text": "Surface Area Of Sphere: The surface area of a sphere object is a measure of the total area that the surface of the sphere occupies. We can calculate the volume of sphere by using formula: " }, { "code": null, "e": 26263, "s": 26250, "text": "Examples : " }, { "code": null, "e": 26669, "s": 26263, "text": "Input : Radius Of Sphere = 5\nOutput : Volume Of Sphere : 523.5987755982989\n Surface Area Of Sphere : 314.1592653589793\nExplanation:\n Volume =( 4/3 ) * 3.14159 * 5 * 5 * 5 = 523.598\n Surface Area = 4 * 3.14159 * 5 * 5 =314.159\n \n\nInput : Radius Of Sphere = 12\nOutput : Volume Of Sphere : 7238.229473870883\n Surface Area Of Sphere : 1809.5573684677208" }, { "code": null, "e": 26677, "s": 26673, "text": "C++" }, { "code": null, "e": 26682, "s": 26677, "text": "Java" }, { "code": null, "e": 26690, "s": 26682, "text": "Python3" }, { "code": null, "e": 26693, "s": 26690, "text": "C#" }, { "code": null, "e": 26697, "s": 26693, "text": "PHP" }, { "code": null, "e": 26708, "s": 26697, "text": "Javascript" }, { "code": "// CPP program to calculate Volume and // Surface area of Sphere#include<bits/stdc++.h>using namespace std; // Initializing Value Of PIfloat pi = 3.14159; // Function To Calculate Volume Of Spherefloat volume(float r){ float vol; vol = (float(4) / float(3)) * pi * r * r * r; return vol; } // Function To Calculate Surface Area of Spherefloat surface_area(float r){ float sur_ar; sur_ar = 4 * pi * r * r; return sur_ar;} // Driver Functionint main(){ float radius = 12; float vol, sur_area; // Function Call vol = volume(radius); sur_area = surface_area(radius); // Printing Value Of Volume And Surface Area cout << \"Volume Of Sphere :\" << vol << endl; cout << \"Surface Area Of Sphere :\" << sur_area << endl; return 0;}", "e": 27486, "s": 26708, "text": null }, { "code": "// Java program to calculate Volume and// Surface area of Sphereclass GFG { // Initializing Value Of PIstatic float pi = 3.14159f; // Function To Calculate Volume Of Spherestatic float volume(float r){ float vol; vol = ((float)4 / (float)3) * (pi * r * r * r); return vol;} // Function To Calculate Surface Area of Spherestatic float surface_area(float r) { float sur_ar; sur_ar = 4 * pi * r * r; return sur_ar;} // Driver Functionpublic static void main(String[] args) { float radius = 12; float vol, sur_area; // Function Call vol = volume(radius); sur_area = surface_area(radius); // Printing Value Of Volume And Surface Area System.out.println(\"Volume Of Sphere :\" + vol); System.out.println(\"Surface Area Of Sphere :\" + sur_area);}} // This code is contributed by Anant Agarwal.", "e": 28329, "s": 27486, "text": null }, { "code": "''' Python3 program to calculate Volume and Surface area of Sphere'''# Importing Math library for value Of PIimport mathpi = math.pi # Function to calculate Volume of Spheredef volume(r): vol = (4 / 3) * pi * r * r * r return vol # Function To Calculate Surface Area of Spheredef surfacearea(r): sur_ar = 4 * pi * r * r return sur_ar # Driver Coderadius = float(12)print( \"Volume Of Sphere : \", volume(radius) )print( \"Surface Area Of Sphere : \", surfacearea(radius) )", "e": 28813, "s": 28329, "text": null }, { "code": "// C# program to calculate Volume and// Surface area of Sphereusing System; class GFG { // Initializing Value Of PI static float pi = 3.14159f; // Function To Calculate Volume // Of Sphere static float volume(float r) { float vol; vol = ((float)4 / (float)3) * (pi * r * r * r); return vol; } // Function To Calculate Surface Area // of Sphere static float surface_area(float r) { float sur_ar; sur_ar = 4 * pi * r * r; return sur_ar; } // Driver Function public static void Main() { float radius = 12; float vol, sur_area; // Function Call vol = volume(radius); sur_area = surface_area(radius); // Printing Value Of Volume And // Surface Area Console.WriteLine(\"Volume Of Sphere :\" + vol); Console.WriteLine(\"Surface Area Of \" + \"Sphere :\" + sur_area); }} // This code is contributed by vt_m.", "e": 29890, "s": 28813, "text": null }, { "code": "<?php// PHP program to calculate Volume // and Surface area of Sphere // Function To Calculate // Volume Of Spherefunction volume( $r){ $pi = 3.14159; $vol = (4 / 3) * $pi * $r * $r * $r; return $vol; } // Function To Calculate // Surface Area of Spherefunction surface_area( $r){ $pi = 3.14159; $sur_ar = 4 * $pi * $r * $r; return $sur_ar;} // Driver Code$radius = 12;$vol; $sur_area; // Function Call$vol = volume($radius);$sur_area = surface_area($radius); // Printing Value Of // Volume And Surface Areaecho (\"Volume Of Sphere : \" );echo($vol);echo( \" \\nSurface Area Of Sphere :\");echo( $sur_area); // This code is contributed by vt_m.?>", "e": 30567, "s": 29890, "text": null }, { "code": "<script>// javascript program to calculate Volume and // Surface area of Sphere // Initializing Value Of PIconst pi = 3.14159; // Function To Calculate Volume Of Spherefunction volume( r){ let vol; vol = ((4) / (3)) * pi * r * r * r; return vol;} // Function To Calculate Surface Area of Spherefunction surface_area( r){ let sur_ar; sur_ar = 4 * pi * r * r; return sur_ar;} // Driver Function let radius = 12; let vol, sur_area; // Function Call vol = volume(radius).toFixed(2); sur_area = surface_area(radius).toFixed(2); // Printing Value Of Volume And Surface Area document.write( \"Volume Of Sphere :\" + vol +\"<br/>\"); document.write( \"Surface Area Of Sphere :\" + sur_area + \"<br/>\"); // This code is contributed by Rajput-Ji </script>", "e": 31371, "s": 30567, "text": null }, { "code": null, "e": 31382, "s": 31371, "text": "Output : " }, { "code": null, "e": 31440, "s": 31382, "text": "Volume Of Sphere :7238.22\nSurface Area Of Sphere :1809.56" }, { "code": null, "e": 31447, "s": 31442, "text": "vt_m" }, { "code": null, "e": 31457, "s": 31447, "text": "Rajput-Ji" }, { "code": null, "e": 31468, "s": 31457, "text": "bunnyram19" }, { "code": null, "e": 31489, "s": 31468, "text": "area-volume-programs" }, { "code": null, "e": 31499, "s": 31489, "text": "Geometric" }, { "code": null, "e": 31518, "s": 31499, "text": "School Programming" }, { "code": null, "e": 31528, "s": 31518, "text": "Geometric" }, { "code": null, "e": 31626, "s": 31528, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31635, "s": 31626, "text": "Comments" }, { "code": null, "e": 31648, "s": 31635, "text": "Old Comments" }, { "code": null, "e": 31697, "s": 31648, "text": "Program for distance between two points on earth" }, { "code": null, "e": 31750, "s": 31697, "text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)" }, { "code": null, "e": 31799, "s": 31750, "text": "Closest Pair of Points | O(nlogn) Implementation" }, { "code": null, "e": 31850, "s": 31799, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 31908, "s": 31850, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 31926, "s": 31908, "text": "Python Dictionary" }, { "code": null, "e": 31942, "s": 31926, "text": "Arrays in C/C++" }, { "code": null, "e": 31961, "s": 31942, "text": "Inheritance in C++" }, { "code": null, "e": 31986, "s": 31961, "text": "Reverse a string in Java" } ]
How to bind the spacebar key to a certain method in Tkinter?
Tkinter methods can be bound with the Keys or Mouse to perform certain operations or events in an application. Let us suppose for a particular application, we want to bind the <Space> Key such that it will perform a certain operation. We can bind any key to a particular operation or event by defining the bind(<key>, callback) method. In this example, we will create rectangles of random width and height by using random Module in Python. So, whenever we will press the Key, it will generate some random shapes on the screen. #Import the required Libraries from tkinter import * import random #Create an instance of Tkinter frame win= Tk() #Crate a canvas canvas=Canvas(win,width=500,height=250,bg='white') def draw_shapes(e): canvas.delete(ALL) canvas.create_rectangle(random.randint(5,300), random.randint(1,300), 25, 25, fill='khaki3') canvas.pack() #Bind the spacebar Key to a function win.bind("<space>", draw_shapes) win.mainloop() Run the above code to display a window that generates random shapes while pressing the <Space> Key on the Keyboard.
[ { "code": null, "e": 1398, "s": 1062, "text": "Tkinter methods can be bound with the Keys or Mouse to perform certain operations or events in an application. Let us suppose for a particular application, we want to bind the <Space> Key such that it will perform a certain operation. We can bind any key to a particular operation or event by defining the bind(<key>, callback) method." }, { "code": null, "e": 1589, "s": 1398, "text": "In this example, we will create rectangles of random width and height by using random Module in Python. So, whenever we will press the Key, it will generate some random shapes on the screen." }, { "code": null, "e": 2008, "s": 1589, "text": "#Import the required Libraries\nfrom tkinter import *\nimport random\n\n#Create an instance of Tkinter frame\nwin= Tk()\n\n#Crate a canvas\ncanvas=Canvas(win,width=500,height=250,bg='white')\ndef draw_shapes(e):\n canvas.delete(ALL)\n\ncanvas.create_rectangle(random.randint(5,300), random.randint(1,300), 25, 25, fill='khaki3')\ncanvas.pack()\n\n#Bind the spacebar Key to a function\nwin.bind(\"<space>\", draw_shapes)\nwin.mainloop()" }, { "code": null, "e": 2124, "s": 2008, "text": "Run the above code to display a window that generates random shapes while pressing the <Space> Key on the Keyboard." } ]
Uploading Large Files to GitHub. 3 ways to avoid getting error messages... | by Eden Au | Towards Data Science
GitHub has a strict file limit of 100MB. If you are just uploading lines of codes, this is not something that you need to worry about. However, if you want to upload a bit of data, or something in binary, this is a limit that you might want to cross. Here are three different ways to overcome the 100MB limit. Originally published on my blog edenau.github.io. Create a file .gitignore in the parent directory of the repository, and store all the file directories that you want Git to ignore. Use * for wildcard so that you do not need to add file directories manually each time you create a new large file. Here is an example: *.nc*.DS_store These ignored files will be automatically ignored by Git and will not be uploaded to GitHub. No more error messages. If you have accidentally committed files locally that exceeds 100MB, you would have a hard time trying to push it to GitHub. It cannot be solved by removing the large files and committing again. This is because GitHub keeps track of every commit, not just the latest one. You are technically pushing files in your entire commit record. While you could technically resolve it by branching, it is by no means straightforward. Fortunately, you can run a repository cleaner and it automatically cleans all the large file commits. Download BFG Repo-Cleaner bfg.jar and run the following command: java -jar bfg.jar --strip-blobs-bigger-than 100M <your_repo> It automatically cleans your commits and produces a new commit with the comment ‘remove large files’. Push it and you are good to go. You might have noticed that the abovementioned methods both avoid uploading the large files. What if you really want to upload them so that you could gain access to them on another device? Git Large File Storage lets you store them on a remote server such as GitHub. Download and install git-lfs by placing it into your $PATH. You will then need to run the following command once per local repository: git lfs install Large files are selected by: git lfs track '*.nc'git lfs track '*.csv' This will create a file named .gitattributes, and voilà! You can perform add and commit operations as normal. Then, you will first need to a) push the files to the LFS, then b) push the pointers to GitHub. Here are the commands: git lfs push --all origin mastergit push -u origin master Files on Git LFS are then available on GitHub with the following label. In order to pull the repository on another device, simply install git-lfs on that device (per local repository). Thank you for reading! If you are interested in data science, check out the following articles: towardsdatascience.com towardsdatascience.com Originally published on my blog edenau.github.io.
[ { "code": null, "e": 482, "s": 172, "text": "GitHub has a strict file limit of 100MB. If you are just uploading lines of codes, this is not something that you need to worry about. However, if you want to upload a bit of data, or something in binary, this is a limit that you might want to cross. Here are three different ways to overcome the 100MB limit." }, { "code": null, "e": 532, "s": 482, "text": "Originally published on my blog edenau.github.io." }, { "code": null, "e": 799, "s": 532, "text": "Create a file .gitignore in the parent directory of the repository, and store all the file directories that you want Git to ignore. Use * for wildcard so that you do not need to add file directories manually each time you create a new large file. Here is an example:" }, { "code": null, "e": 814, "s": 799, "text": "*.nc*.DS_store" }, { "code": null, "e": 931, "s": 814, "text": "These ignored files will be automatically ignored by Git and will not be uploaded to GitHub. No more error messages." }, { "code": null, "e": 1267, "s": 931, "text": "If you have accidentally committed files locally that exceeds 100MB, you would have a hard time trying to push it to GitHub. It cannot be solved by removing the large files and committing again. This is because GitHub keeps track of every commit, not just the latest one. You are technically pushing files in your entire commit record." }, { "code": null, "e": 1457, "s": 1267, "text": "While you could technically resolve it by branching, it is by no means straightforward. Fortunately, you can run a repository cleaner and it automatically cleans all the large file commits." }, { "code": null, "e": 1522, "s": 1457, "text": "Download BFG Repo-Cleaner bfg.jar and run the following command:" }, { "code": null, "e": 1583, "s": 1522, "text": "java -jar bfg.jar --strip-blobs-bigger-than 100M <your_repo>" }, { "code": null, "e": 1717, "s": 1583, "text": "It automatically cleans your commits and produces a new commit with the comment ‘remove large files’. Push it and you are good to go." }, { "code": null, "e": 1906, "s": 1717, "text": "You might have noticed that the abovementioned methods both avoid uploading the large files. What if you really want to upload them so that you could gain access to them on another device?" }, { "code": null, "e": 2119, "s": 1906, "text": "Git Large File Storage lets you store them on a remote server such as GitHub. Download and install git-lfs by placing it into your $PATH. You will then need to run the following command once per local repository:" }, { "code": null, "e": 2135, "s": 2119, "text": "git lfs install" }, { "code": null, "e": 2164, "s": 2135, "text": "Large files are selected by:" }, { "code": null, "e": 2206, "s": 2164, "text": "git lfs track '*.nc'git lfs track '*.csv'" }, { "code": null, "e": 2436, "s": 2206, "text": "This will create a file named .gitattributes, and voilà! You can perform add and commit operations as normal. Then, you will first need to a) push the files to the LFS, then b) push the pointers to GitHub. Here are the commands:" }, { "code": null, "e": 2494, "s": 2436, "text": "git lfs push --all origin mastergit push -u origin master" }, { "code": null, "e": 2566, "s": 2494, "text": "Files on Git LFS are then available on GitHub with the following label." }, { "code": null, "e": 2679, "s": 2566, "text": "In order to pull the repository on another device, simply install git-lfs on that device (per local repository)." }, { "code": null, "e": 2775, "s": 2679, "text": "Thank you for reading! If you are interested in data science, check out the following articles:" }, { "code": null, "e": 2798, "s": 2775, "text": "towardsdatascience.com" }, { "code": null, "e": 2821, "s": 2798, "text": "towardsdatascience.com" } ]
Count of smaller or equal elements in the sorted array in C++
We are given an array of integers. The goal is to find the count of elements of an array which are less than or equal to the given value K. Input Arr[]= { 1, 2, 3, 14, 50, 69, 90 } K=12 Output Numbers smaller or equal to K: 3 Explanation Numbers 1,2,3 is smaller or equal to 12. Input Arr[]= { 12, 13, 13, 13, 14, 50, 54, 100 } K=14 Output Numbers smaller or equal to K: 5 Explanation Numbers 12, 13, 14 are smaller or equal to 14. We take the integer array Arr[] and K. We take the integer array Arr[] and K. Function smallorEqual(int arr[],int k,int len) returns the count of elements of arr[] that are small or equal to K Function smallorEqual(int arr[],int k,int len) returns the count of elements of arr[] that are small or equal to K Take the initial variable count as 0 for such numbers. Take the initial variable count as 0 for such numbers. Traverse array of numbers using for loop. i=0 to i<len Traverse array of numbers using for loop. i=0 to i<len Now for each number arr[i], if it is <=k, increment count. Now for each number arr[i], if it is <=k, increment count. At the end loop count will have a total number which satisfies the condition. At the end loop count will have a total number which satisfies the condition. Return the count as result. Return the count as result. Live Demo #include <bits/stdc++.h> using namespace std; int smallorEqual(int arr[],int k,int len){ int count = 0; for (int i = 0; i < len; i++){ if(arr[i]<=k) { count++; } else { break; } } return count; } int main(){ int Arr[] = { 1,5,11,12,19,21,32,53,70,100 }; int K = 21; int Length= sizeof(Arr)/sizeof(Arr[0]); cout <<"Numbers smaller or equal to K: "<<smallorEqual(Arr,K,Length); return 0; } If we run the above code it will generate the following output − Numbers smaller or equal to K: 6 We take the integer array Arr[] and K. We take the integer array Arr[] and K. Function binarySearch(int arr[],int k,int len) returns the count of elements of arr[] that are small or equal to K Function binarySearch(int arr[],int k,int len) returns the count of elements of arr[] that are small or equal to K Take indexes low=0, high=len-1 and mid=(low+high)/2;/p> Take indexes low=0, high=len-1 and mid=(low+high)/2;/p> Take variable index=-1; Take variable index=-1; Using while loop, till low<=high Using while loop, till low<=high Check value of arr[mid]. If it is <= k. Then index=mid. New low=mid+1 Check value of arr[mid]. If it is <= k. Then index=mid. New low=mid+1 Otherwise new high=mid-1. Otherwise new high=mid-1. At the end of the while loop index will index of last number<=k. At the end of the while loop index will index of last number<=k. Return the index+1 as result because array indexing starts from 0 and all numbers from index 0 to index are less than k. Return the index+1 as result because array indexing starts from 0 and all numbers from index 0 to index are less than k. Live Demo #include <bits/stdc++.h> using namespace std; int binarySearch(int arr[],int k,int len){ int low = 0; int high = len -1; int mid = (high+low)/2; int index = -1; while(low <= high){ mid =( low + high ) / 2; if(arr[mid] <= k){ index = mid; low = mid+1; } else{ high=mid-1; } } return (index+1); } int main(){ int Arr[] = { 1,5,11,12,19,21,32,53,70,100 }; int K = 21; int Length= sizeof(Arr)/sizeof(Arr[0]); cout <<"Numbers smaller or equal to K: "<<binarySearch(Arr,K,Length); return 0; } If we run the above code it will generate the following output − Numbers smaller or equal to K: 6
[ { "code": null, "e": 1202, "s": 1062, "text": "We are given an array of integers. The goal is to find the count of elements of an array which are less than or equal to the given value K." }, { "code": null, "e": 1209, "s": 1202, "text": "Input " }, { "code": null, "e": 1249, "s": 1209, "text": "Arr[]= { 1, 2, 3, 14, 50, 69, 90 } K=12" }, { "code": null, "e": 1257, "s": 1249, "text": "Output " }, { "code": null, "e": 1290, "s": 1257, "text": "Numbers smaller or equal to K: 3" }, { "code": null, "e": 1303, "s": 1290, "text": "Explanation " }, { "code": null, "e": 1344, "s": 1303, "text": "Numbers 1,2,3 is smaller or equal to 12." }, { "code": null, "e": 1351, "s": 1344, "text": "Input " }, { "code": null, "e": 1399, "s": 1351, "text": "Arr[]= { 12, 13, 13, 13, 14, 50, 54, 100 } K=14" }, { "code": null, "e": 1407, "s": 1399, "text": "Output " }, { "code": null, "e": 1440, "s": 1407, "text": "Numbers smaller or equal to K: 5" }, { "code": null, "e": 1453, "s": 1440, "text": "Explanation " }, { "code": null, "e": 1500, "s": 1453, "text": "Numbers 12, 13, 14 are smaller or equal to 14." }, { "code": null, "e": 1539, "s": 1500, "text": "We take the integer array Arr[] and K." }, { "code": null, "e": 1578, "s": 1539, "text": "We take the integer array Arr[] and K." }, { "code": null, "e": 1693, "s": 1578, "text": "Function smallorEqual(int arr[],int k,int len) returns the count of elements of arr[] that are small or equal to K" }, { "code": null, "e": 1808, "s": 1693, "text": "Function smallorEqual(int arr[],int k,int len) returns the count of elements of arr[] that are small or equal to K" }, { "code": null, "e": 1863, "s": 1808, "text": "Take the initial variable count as 0 for such numbers." }, { "code": null, "e": 1918, "s": 1863, "text": "Take the initial variable count as 0 for such numbers." }, { "code": null, "e": 1973, "s": 1918, "text": "Traverse array of numbers using for loop. i=0 to i<len" }, { "code": null, "e": 2028, "s": 1973, "text": "Traverse array of numbers using for loop. i=0 to i<len" }, { "code": null, "e": 2087, "s": 2028, "text": "Now for each number arr[i], if it is <=k, increment count." }, { "code": null, "e": 2146, "s": 2087, "text": "Now for each number arr[i], if it is <=k, increment count." }, { "code": null, "e": 2224, "s": 2146, "text": "At the end loop count will have a total number which satisfies the condition." }, { "code": null, "e": 2302, "s": 2224, "text": "At the end loop count will have a total number which satisfies the condition." }, { "code": null, "e": 2330, "s": 2302, "text": "Return the count as result." }, { "code": null, "e": 2358, "s": 2330, "text": "Return the count as result." }, { "code": null, "e": 2369, "s": 2358, "text": " Live Demo" }, { "code": null, "e": 2814, "s": 2369, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint smallorEqual(int arr[],int k,int len){\n int count = 0;\n for (int i = 0; i < len; i++){\n if(arr[i]<=k)\n { count++; }\n else\n { break; }\n }\n return count;\n}\nint main(){\n int Arr[] = { 1,5,11,12,19,21,32,53,70,100 };\n int K = 21;\n int Length= sizeof(Arr)/sizeof(Arr[0]);\n cout <<\"Numbers smaller or equal to K: \"<<smallorEqual(Arr,K,Length);\n return 0;\n}" }, { "code": null, "e": 2879, "s": 2814, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 2912, "s": 2879, "text": "Numbers smaller or equal to K: 6" }, { "code": null, "e": 2951, "s": 2912, "text": "We take the integer array Arr[] and K." }, { "code": null, "e": 2990, "s": 2951, "text": "We take the integer array Arr[] and K." }, { "code": null, "e": 3105, "s": 2990, "text": "Function binarySearch(int arr[],int k,int len) returns the count of elements of arr[] that are small or equal to K" }, { "code": null, "e": 3220, "s": 3105, "text": "Function binarySearch(int arr[],int k,int len) returns the count of elements of arr[] that are small or equal to K" }, { "code": null, "e": 3276, "s": 3220, "text": "Take indexes low=0, high=len-1 and mid=(low+high)/2;/p>" }, { "code": null, "e": 3332, "s": 3276, "text": "Take indexes low=0, high=len-1 and mid=(low+high)/2;/p>" }, { "code": null, "e": 3356, "s": 3332, "text": "Take variable index=-1;" }, { "code": null, "e": 3380, "s": 3356, "text": "Take variable index=-1;" }, { "code": null, "e": 3413, "s": 3380, "text": "Using while loop, till low<=high" }, { "code": null, "e": 3446, "s": 3413, "text": "Using while loop, till low<=high" }, { "code": null, "e": 3516, "s": 3446, "text": "Check value of arr[mid]. If it is <= k. Then index=mid. New low=mid+1" }, { "code": null, "e": 3586, "s": 3516, "text": "Check value of arr[mid]. If it is <= k. Then index=mid. New low=mid+1" }, { "code": null, "e": 3612, "s": 3586, "text": "Otherwise new high=mid-1." }, { "code": null, "e": 3638, "s": 3612, "text": "Otherwise new high=mid-1." }, { "code": null, "e": 3703, "s": 3638, "text": "At the end of the while loop index will index of last number<=k." }, { "code": null, "e": 3768, "s": 3703, "text": "At the end of the while loop index will index of last number<=k." }, { "code": null, "e": 3889, "s": 3768, "text": "Return the index+1 as result because array indexing starts from 0 and all numbers from index 0 to index are less than k." }, { "code": null, "e": 4010, "s": 3889, "text": "Return the index+1 as result because array indexing starts from 0 and all numbers from index 0 to index are less than k." }, { "code": null, "e": 4021, "s": 4010, "text": " Live Demo" }, { "code": null, "e": 4601, "s": 4021, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint binarySearch(int arr[],int k,int len){\n int low = 0;\n int high = len -1;\n int mid = (high+low)/2;\n int index = -1;\n while(low <= high){\n mid =( low + high ) / 2;\n if(arr[mid] <= k){\n index = mid;\n low = mid+1;\n }\n else{\n high=mid-1;\n }\n }\n return (index+1);\n}\nint main(){\n int Arr[] = { 1,5,11,12,19,21,32,53,70,100 };\n int K = 21;\n int Length= sizeof(Arr)/sizeof(Arr[0]);\n cout <<\"Numbers smaller or equal to K: \"<<binarySearch(Arr,K,Length);\n return 0;\n}" }, { "code": null, "e": 4666, "s": 4601, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 4699, "s": 4666, "text": "Numbers smaller or equal to K: 6" } ]
Single dimensional array vs multidimensional array in JavaScript.
Following is the code for single and multidimentsional array in 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; } .result,.sample { font-size: 18px; font-weight: 500; color: rebeccapurple; } .result { color: red; } </style> </head> <body> <h1>Single dimensional array vs multidimensional array</h1> <div class="sample">Single dimensional Array<br /></div> <div class="result">Multidimensional Array<br /></div> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to display single and multidimensional array</h3> <script> let resEle = document.querySelector(".result"); let sampleEle = document.querySelector(".sample"); let BtnEle = document.querySelector(".Btn"); let arr = [1, 2, 3, 4, 5]; let arr1 = [ [1, 2, 3], ["A", "B", "C"], [5, "D", 6], ]; BtnEle.addEventListener("click", () => { sampleEle.innerHTML += arr + ""; arr1.forEach((item, index) => { resEle.innerHTML += "Index : " + index + " array = " + item + ""; }); }); </script> </body> </html> The above code will produce the following output − On clicking the ‘CLICK HERE’ button −
[ { "code": null, "e": 1139, "s": 1062, "text": "Following is the code for single and multidimentsional array in JavaScript −" }, { "code": null, "e": 1150, "s": 1139, "text": " Live Demo" }, { "code": null, "e": 2368, "s": 1150, "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 .result,.sample {\n font-size: 18px;\n font-weight: 500;\n color: rebeccapurple;\n }\n .result {\n color: red;\n }\n</style>\n</head>\n<body>\n<h1>Single dimensional array vs multidimensional array</h1>\n<div class=\"sample\">Single dimensional Array<br /></div>\n<div class=\"result\">Multidimensional Array<br /></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>Click on the above button to display single and multidimensional array</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n let sampleEle = document.querySelector(\".sample\");\n let BtnEle = document.querySelector(\".Btn\");\n let arr = [1, 2, 3, 4, 5];\n let arr1 = [\n [1, 2, 3],\n [\"A\", \"B\", \"C\"],\n [5, \"D\", 6],\n ];\n BtnEle.addEventListener(\"click\", () => {\n sampleEle.innerHTML += arr + \"\";\n arr1.forEach((item, index) => {\n resEle.innerHTML += \"Index : \" + index + \" array = \" + item + \"\";\n });\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2419, "s": 2368, "text": "The above code will produce the following output −" }, { "code": null, "e": 2457, "s": 2419, "text": "On clicking the ‘CLICK HERE’ button −" } ]
clear command in Linux with examples - GeeksforGeeks
26 Aug, 2020 clear is a standard Unix computer operating system command that is used to clear the terminal screen. This command first looks for a terminal type in the environment and after that, it figures out the terminfo database for how to clear the screen. And this command will ignore any command-line parameters that may be present. Also, the clear command doesn’t take any argument and it is almost similar to cls command on a number of other Operating Systems. Syntax: $clear Terminal Before Executing clear command: Terminal after Executing clear command: Note:- In order to clear the terminal press [ctrl+l] and for GNOME terminal in ubuntu 18.04 press [shift + ctrl + alt + c] manav014 linux-command Linux-system-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Thread functions in C/C++ nohup Command in Linux with Examples scp command in Linux with Examples mv command in Linux with examples SED command in Linux | Set 2 chown command in Linux with Examples Array Basics in Shell Scripting | Set 1 Docker - COPY Instruction nslookup command in Linux with Examples Basic Operators in Shell Scripting
[ { "code": null, "e": 24431, "s": 24403, "text": "\n26 Aug, 2020" }, { "code": null, "e": 24887, "s": 24431, "text": "clear is a standard Unix computer operating system command that is used to clear the terminal screen. This command first looks for a terminal type in the environment and after that, it figures out the terminfo database for how to clear the screen. And this command will ignore any command-line parameters that may be present. Also, the clear command doesn’t take any argument and it is almost similar to cls command on a number of other Operating Systems." }, { "code": null, "e": 24895, "s": 24887, "text": "Syntax:" }, { "code": null, "e": 24902, "s": 24895, "text": "$clear" }, { "code": null, "e": 24943, "s": 24902, "text": "Terminal Before Executing clear command:" }, { "code": null, "e": 24983, "s": 24943, "text": "Terminal after Executing clear command:" }, { "code": null, "e": 25106, "s": 24983, "text": "Note:- In order to clear the terminal press [ctrl+l] and for GNOME terminal in ubuntu 18.04 press [shift + ctrl + alt + c]" }, { "code": null, "e": 25115, "s": 25106, "text": "manav014" }, { "code": null, "e": 25129, "s": 25115, "text": "linux-command" }, { "code": null, "e": 25151, "s": 25129, "text": "Linux-system-commands" }, { "code": null, "e": 25158, "s": 25151, "text": "Picked" }, { "code": null, "e": 25169, "s": 25158, "text": "Linux-Unix" }, { "code": null, "e": 25267, "s": 25169, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25293, "s": 25267, "text": "Thread functions in C/C++" }, { "code": null, "e": 25330, "s": 25293, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 25365, "s": 25330, "text": "scp command in Linux with Examples" }, { "code": null, "e": 25399, "s": 25365, "text": "mv command in Linux with examples" }, { "code": null, "e": 25428, "s": 25399, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 25465, "s": 25428, "text": "chown command in Linux with Examples" }, { "code": null, "e": 25505, "s": 25465, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 25531, "s": 25505, "text": "Docker - COPY Instruction" }, { "code": null, "e": 25571, "s": 25531, "text": "nslookup command in Linux with Examples" } ]
Automate Reports in Google Sheets Using Data from Google BigQuery | by Marie Sharapa | Towards Data Science
Before we talk about settings, a few words about the features and benefits of Google BigQuery for those who aren’t familiar with this cloud storage service. Advantages of Google BigQuery: A fast cloud solution that allows you to process terabytes of data in seconds Suitable for both small and large companies Cost-effective and easy to scale Doesn’t require servers, capacity reservation, and maintenance Transparent pricing policy — pay only for the data processed, with no hidden fees Flexibility in data processing — access tables with data in SQL, and it’s also possible to use JavaScript functions Reliability and safety is confirmed by numerous certificates — PCI DSS, ISO 27001, SOC 2 & SOC 3 Type II — so you can safely store your customers’ credit card numbers, email addresses, and other personal information Another feature of Google BigQuery that’s worth highlighting, is its convenient integration with external services. The repository has a large number of ready-made libraries and connectors that make it easy to automate data exchange. For example, with OWOX BI, you can import data from Google Analytics, advertising sources, call tracking services, email newsletters, etc. into BigQuery: Here are some more useful tools for working with BigQuery: Rest API Third-party tools SDK JDBC ODBC command-line tool BigQuery recently introduced a Data Transfer Service tool that automatically delivers data from Google’s advertising services. It currently works with these services: Google Ads Campaign Manager Google Ad Manager YouTube You can set up the integration in a couple of clicks, after which all information from these services is automatically available to you in BigQuery. To build reports based on complete data and then automate them, you need to combine data from different sources in BigQuery. Here’s an example of how this can be done: First, collect data from your site in Google Analytics.Complement it with information from other sources using Google Sheets.Add cost data from advertising services – for example, through OWOX BI.Import all this data into BigQuery. If you’re a Google Analytics 360 customer, you can do this using the BigQuery Export feature. If you don’t have Google Analytics 360, you can connect OWOX BI and use it to import data from Google Analytics into Google BigQuery.Transfer information from your CRM and ERP systems to BigQuery to combine it with the data from your site.Also in BigQuery, download more information from Google Sheets of any kindIf you use call tracking, upload call and chat data to BigQuery. OWOX BI has integrations for five call/chat services.Do the same for email newsletters.Finally, use the Data Transfer Service, which imports data from Google and YouTube advertising services First, collect data from your site in Google Analytics. Complement it with information from other sources using Google Sheets. Add cost data from advertising services – for example, through OWOX BI. Import all this data into BigQuery. If you’re a Google Analytics 360 customer, you can do this using the BigQuery Export feature. If you don’t have Google Analytics 360, you can connect OWOX BI and use it to import data from Google Analytics into Google BigQuery. Transfer information from your CRM and ERP systems to BigQuery to combine it with the data from your site. Also in BigQuery, download more information from Google Sheets of any kind If you use call tracking, upload call and chat data to BigQuery. OWOX BI has integrations for five call/chat services. Do the same for email newsletters. Finally, use the Data Transfer Service, which imports data from Google and YouTube advertising services After you’ve combined all the data in Google BigQuery, linked it by a key parameter, and built the necessary reports, you can automate the uploading of these reports to Google Sheets. To do this, use the OWOX BI BigQuery Reports Add-on. It’s similar to the Google Analytics Sheets Add-on but requires knowledge of SQL syntax. To access data in BigQuery, you need to build an SQL query, after which you’ll see the data in the desired structure in Google Sheets. First, install the BigQuery Reports Add-on in your Chrome browser. To do this, open a Google Sheets document, go to the OWOX BI BigQuery Reports tab, and select Add a new report. If this is your first time working with this add-on, you’ll need to provide access to your Google BigQuery account. After that, specify the project whose data you want to see in the report. Then select an SQL query from the drop-down list (if you created queries earlier) or add a new query by clicking Add new query. You can immediately add dynamic parameters that you previously specified to the report in the SQL query. Select the dates for the report and run the query by clicking the Add & Run button. At this point, the add-on will access your data in BigQuery and perform calculations. Then, in your table, a separate sheet will appear with the query results. Now you can visualize this data, create pivot tables, and so on. To avoid having to run a query manually every time you need data, you can set up a scheduled report. To do this, go to Add-ons –> OWOX BI BigQuery Reports –> Schedule reports. Select the frequency with which the report will be updated (once per hour, day, week, or month). Then specify the time to start the SQL query. If necessary, activate an email alert to update the report. Save the settings. Done. Now your report will automatically be updated according to the set schedule. Finally, in order not to miss important changes in your KPIs, you can configure sending of reports by email using Google App Script. To get started, ask your developers to prepare a script with the email addresses and conditions for sending messages, either regularly or in response to critical changes to specified metrics. You can use this code as a template: // Send an email with two attachments: a file from Google Drive (as a PDF) and an HTML file. var file = DriveApp.getFileById('abcdefghijklmnopqrstuvwxyz'); var blob = Utilities.newBlob('Insert any HTML content here', 'text/html', 'my_document.html'); MailApp.sendEmail('[email protected]', 'Attachment example', 'Two files are attached.', { name: 'Automatic Emailer Script', attachments: [file.getAs(MimeType.PDF), blob] }); You can read the developer guidelines in Google Help for more on how to structure this code. Then open the report you need in the table and go to Tools –> Script Editor. A new window will open in which you need to paste your script. Click on the clock icon to set the schedule according to which the script will be launched. Now click the + Add Trigger button in the lower right corner. Then select the event source — Time Trigger and select from the list the frequency with which to email the report. Finally, click Save. Done! Now reports will come to your email, you won’t miss anything, and you’ll be able to make changes to your marketing activities in time.
[ { "code": null, "e": 328, "s": 171, "text": "Before we talk about settings, a few words about the features and benefits of Google BigQuery for those who aren’t familiar with this cloud storage service." }, { "code": null, "e": 359, "s": 328, "text": "Advantages of Google BigQuery:" }, { "code": null, "e": 437, "s": 359, "text": "A fast cloud solution that allows you to process terabytes of data in seconds" }, { "code": null, "e": 481, "s": 437, "text": "Suitable for both small and large companies" }, { "code": null, "e": 514, "s": 481, "text": "Cost-effective and easy to scale" }, { "code": null, "e": 577, "s": 514, "text": "Doesn’t require servers, capacity reservation, and maintenance" }, { "code": null, "e": 659, "s": 577, "text": "Transparent pricing policy — pay only for the data processed, with no hidden fees" }, { "code": null, "e": 775, "s": 659, "text": "Flexibility in data processing — access tables with data in SQL, and it’s also possible to use JavaScript functions" }, { "code": null, "e": 991, "s": 775, "text": "Reliability and safety is confirmed by numerous certificates — PCI DSS, ISO 27001, SOC 2 & SOC 3 Type II — so you can safely store your customers’ credit card numbers, email addresses, and other personal information" }, { "code": null, "e": 1379, "s": 991, "text": "Another feature of Google BigQuery that’s worth highlighting, is its convenient integration with external services. The repository has a large number of ready-made libraries and connectors that make it easy to automate data exchange. For example, with OWOX BI, you can import data from Google Analytics, advertising sources, call tracking services, email newsletters, etc. into BigQuery:" }, { "code": null, "e": 1438, "s": 1379, "text": "Here are some more useful tools for working with BigQuery:" }, { "code": null, "e": 1447, "s": 1438, "text": "Rest API" }, { "code": null, "e": 1465, "s": 1447, "text": "Third-party tools" }, { "code": null, "e": 1469, "s": 1465, "text": "SDK" }, { "code": null, "e": 1474, "s": 1469, "text": "JDBC" }, { "code": null, "e": 1479, "s": 1474, "text": "ODBC" }, { "code": null, "e": 1497, "s": 1479, "text": "command-line tool" }, { "code": null, "e": 1664, "s": 1497, "text": "BigQuery recently introduced a Data Transfer Service tool that automatically delivers data from Google’s advertising services. It currently works with these services:" }, { "code": null, "e": 1675, "s": 1664, "text": "Google Ads" }, { "code": null, "e": 1692, "s": 1675, "text": "Campaign Manager" }, { "code": null, "e": 1710, "s": 1692, "text": "Google Ad Manager" }, { "code": null, "e": 1718, "s": 1710, "text": "YouTube" }, { "code": null, "e": 1867, "s": 1718, "text": "You can set up the integration in a couple of clicks, after which all information from these services is automatically available to you in BigQuery." }, { "code": null, "e": 2035, "s": 1867, "text": "To build reports based on complete data and then automate them, you need to combine data from different sources in BigQuery. Here’s an example of how this can be done:" }, { "code": null, "e": 2930, "s": 2035, "text": "First, collect data from your site in Google Analytics.Complement it with information from other sources using Google Sheets.Add cost data from advertising services – for example, through OWOX BI.Import all this data into BigQuery. If you’re a Google Analytics 360 customer, you can do this using the BigQuery Export feature. If you don’t have Google Analytics 360, you can connect OWOX BI and use it to import data from Google Analytics into Google BigQuery.Transfer information from your CRM and ERP systems to BigQuery to combine it with the data from your site.Also in BigQuery, download more information from Google Sheets of any kindIf you use call tracking, upload call and chat data to BigQuery. OWOX BI has integrations for five call/chat services.Do the same for email newsletters.Finally, use the Data Transfer Service, which imports data from Google and YouTube advertising services" }, { "code": null, "e": 2986, "s": 2930, "text": "First, collect data from your site in Google Analytics." }, { "code": null, "e": 3057, "s": 2986, "text": "Complement it with information from other sources using Google Sheets." }, { "code": null, "e": 3129, "s": 3057, "text": "Add cost data from advertising services – for example, through OWOX BI." }, { "code": null, "e": 3393, "s": 3129, "text": "Import all this data into BigQuery. If you’re a Google Analytics 360 customer, you can do this using the BigQuery Export feature. If you don’t have Google Analytics 360, you can connect OWOX BI and use it to import data from Google Analytics into Google BigQuery." }, { "code": null, "e": 3500, "s": 3393, "text": "Transfer information from your CRM and ERP systems to BigQuery to combine it with the data from your site." }, { "code": null, "e": 3575, "s": 3500, "text": "Also in BigQuery, download more information from Google Sheets of any kind" }, { "code": null, "e": 3694, "s": 3575, "text": "If you use call tracking, upload call and chat data to BigQuery. OWOX BI has integrations for five call/chat services." }, { "code": null, "e": 3729, "s": 3694, "text": "Do the same for email newsletters." }, { "code": null, "e": 3833, "s": 3729, "text": "Finally, use the Data Transfer Service, which imports data from Google and YouTube advertising services" }, { "code": null, "e": 4294, "s": 3833, "text": "After you’ve combined all the data in Google BigQuery, linked it by a key parameter, and built the necessary reports, you can automate the uploading of these reports to Google Sheets. To do this, use the OWOX BI BigQuery Reports Add-on. It’s similar to the Google Analytics Sheets Add-on but requires knowledge of SQL syntax. To access data in BigQuery, you need to build an SQL query, after which you’ll see the data in the desired structure in Google Sheets." }, { "code": null, "e": 4473, "s": 4294, "text": "First, install the BigQuery Reports Add-on in your Chrome browser. To do this, open a Google Sheets document, go to the OWOX BI BigQuery Reports tab, and select Add a new report." }, { "code": null, "e": 4589, "s": 4473, "text": "If this is your first time working with this add-on, you’ll need to provide access to your Google BigQuery account." }, { "code": null, "e": 4791, "s": 4589, "text": "After that, specify the project whose data you want to see in the report. Then select an SQL query from the drop-down list (if you created queries earlier) or add a new query by clicking Add new query." }, { "code": null, "e": 4980, "s": 4791, "text": "You can immediately add dynamic parameters that you previously specified to the report in the SQL query. Select the dates for the report and run the query by clicking the Add & Run button." }, { "code": null, "e": 5140, "s": 4980, "text": "At this point, the add-on will access your data in BigQuery and perform calculations. Then, in your table, a separate sheet will appear with the query results." }, { "code": null, "e": 5205, "s": 5140, "text": "Now you can visualize this data, create pivot tables, and so on." }, { "code": null, "e": 5381, "s": 5205, "text": "To avoid having to run a query manually every time you need data, you can set up a scheduled report. To do this, go to Add-ons –> OWOX BI BigQuery Reports –> Schedule reports." }, { "code": null, "e": 5603, "s": 5381, "text": "Select the frequency with which the report will be updated (once per hour, day, week, or month). Then specify the time to start the SQL query. If necessary, activate an email alert to update the report. Save the settings." }, { "code": null, "e": 5686, "s": 5603, "text": "Done. Now your report will automatically be updated according to the set schedule." }, { "code": null, "e": 5819, "s": 5686, "text": "Finally, in order not to miss important changes in your KPIs, you can configure sending of reports by email using Google App Script." }, { "code": null, "e": 6011, "s": 5819, "text": "To get started, ask your developers to prepare a script with the email addresses and conditions for sending messages, either regularly or in response to critical changes to specified metrics." }, { "code": null, "e": 6048, "s": 6011, "text": "You can use this code as a template:" }, { "code": null, "e": 6480, "s": 6048, "text": "// Send an email with two attachments: a file from Google Drive (as a PDF) and an HTML file. var file = DriveApp.getFileById('abcdefghijklmnopqrstuvwxyz'); var blob = Utilities.newBlob('Insert any HTML content here', 'text/html', 'my_document.html'); MailApp.sendEmail('[email protected]', 'Attachment example', 'Two files are attached.', { name: 'Automatic Emailer Script', attachments: [file.getAs(MimeType.PDF), blob] });" }, { "code": null, "e": 6573, "s": 6480, "text": "You can read the developer guidelines in Google Help for more on how to structure this code." }, { "code": null, "e": 6713, "s": 6573, "text": "Then open the report you need in the table and go to Tools –> Script Editor. A new window will open in which you need to paste your script." }, { "code": null, "e": 7003, "s": 6713, "text": "Click on the clock icon to set the schedule according to which the script will be launched. Now click the + Add Trigger button in the lower right corner. Then select the event source — Time Trigger and select from the list the frequency with which to email the report. Finally, click Save." } ]
How to change current country code in android?
This example demonstrate about How to change current country code in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:gravity="center" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/text" android:textSize="30sp" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> In the above code, we have taken a text view to show country code information. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.Manifest; import android.content.pm.PackageManager; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import java.io.IOException; import java.util.List; public class MainActivity extends AppCompatActivity { TextView textView; Location location; double describeContents; List<Address> addresses; Geocoder geocoder; @RequiresApi(api = Build.VERSION_CODES.P) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.text); LocationManager locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 101); } location = locationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); geocoder= new Geocoder(this); } @RequiresApi(api = Build.VERSION_CODES.O) @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case 101: if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } try { addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 10); Address address = addresses.get(0); address.setCountryCode("KR"); textView.setText("" + address.getCountryCode()); } catch (IOException e) { e.printStackTrace(); } } else { //not granted } break; default: super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } @RequiresApi(api = Build.VERSION_CODES.O) @Override protected void onResume() { super.onResume(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } try { addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 10); Address address = addresses.get(0); address.setCountryCode("KR"); textView.setText("" + address.getCountryCode()); } catch (IOException e) { 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="com.example.myapplication"> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code
[ { "code": null, "e": 1140, "s": 1062, "text": "This example demonstrate about How to change current country code in android." }, { "code": null, "e": 1269, "s": 1140, "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": 1334, "s": 1269, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1868, "s": 1334, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:gravity=\"center\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/text\"\n android:textSize=\"30sp\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" />\n</LinearLayout>" }, { "code": null, "e": 1947, "s": 1868, "text": "In the above code, we have taken a text view to show country code information." }, { "code": null, "e": 2004, "s": 1947, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 5473, "s": 2004, "text": "package com.example.myapplication;\n\nimport android.Manifest;\nimport android.content.pm.PackageManager;\nimport android.location.Address;\nimport android.location.Geocoder;\nimport android.location.Location;\nimport android.location.LocationManager;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v4.app.ActivityCompat;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.TextView;\n\nimport java.io.IOException;\nimport java.util.List;\n\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n Location location;\n double describeContents;\n List<Address> addresses;\n Geocoder geocoder;\n\n @RequiresApi(api = Build.VERSION_CODES.P)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n LocationManager locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);\n if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {\n ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 101);\n }\n location = locationManager\n .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);\n geocoder= new Geocoder(this);\n }\n\n @RequiresApi(api = Build.VERSION_CODES.O)\n @Override\n public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {\n switch (requestCode) {\n case 101:\n if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {\n if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {\n return;\n }\n try {\n addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 10);\n Address address = addresses.get(0);\n address.setCountryCode(\"KR\");\n textView.setText(\"\" + address.getCountryCode());\n } catch (IOException e) {\n e.printStackTrace();\n }\n } else {\n //not granted\n }\n break;\n default:\n super.onRequestPermissionsResult(requestCode, permissions, grantResults);\n }\n }\n\n @RequiresApi(api = Build.VERSION_CODES.O)\n @Override\n protected void onResume() {\n super.onResume();\n if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {\n return;\n }\n try {\n addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 10);\n Address address = addresses.get(0);\n address.setCountryCode(\"KR\");\n textView.setText(\"\" + address.getCountryCode());\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 5528, "s": 5473, "text": "Step 4 − Add the following code to AndroidManifest.xml" }, { "code": null, "e": 6428, "s": 5528, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\npackage=\"com.example.myapplication\">\n <uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\" />\n <uses-permission android:name=\"android.permission.INTERNET\"/>\n <uses-permission android:name=\"android.permission.READ_PHONE_STATE\" />\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": 6779, "s": 6428, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 6819, "s": 6779, "text": "Click here to download the project code" } ]
How to obtain the highest occurring character in a String using C#?
The highest occurring character in a string is one that occurs most number of times. This can be demonstrated using the following example. String: apples are red The highest occurring character in the above string is e as it occurs 3 times, which is more than the occurrence of any other character. A program that obtains the highest occurring character in a string using C# is given as follows. Live Demo using System; namespace charCountDemo { public class Example { public static void Main() { String str = "abracadabra"; int []charCount = new int[256]; int length = str.Length; for (int i = 0; i < length; i++) { charCount[str[i]]++; } int maxCount = -1; char character = ' '; for (int i = 0; i < length; i++) { if (maxCount < charCount[str[i]]) { maxCount = charCount[str[i]]; character = str[i]; } } Console.WriteLine("The string is: " + str); Console.WriteLine("The highest occurring character in the above string is: " + character); Console.WriteLine("Number of times this character occurs: " + maxCount); } } } The output of the above program is as follows. The string is: abracadabra The highest occurring character in the above string is: a Number of times this character occurs: 5 Now, let us understand the above program. The string str is abracadabra. A new array charCount is created which is of size 256 and shows all the characters in the ASCII table. Then the string str is traversed using a for loop and the value in charCount is incremented corresponding to the character in the string. This can be seen in the following code snippet. String str = "abracadabra"; int []charCount = new int[256]; int length = str.Length; for (int i = 0; i < length; i++) { charCount[str[i]]++; } The integer maxCount stores the maximum count and character is the char value that occurs the maximum times. The values of maxCount and character can be determined using a for loop. This can be seen in the following code snippet. int maxCount = -1; char character = ' '; for (int i = 0; i < length; i++) { if (maxCount < charCount[str[i]]) { maxCount = charCount[str[i]]; character = str[i]; } } Finally, the values of str, maxCount and character are displayed. This can be seen in the following code snippet. Console.WriteLine("The string is: " + str); Console.WriteLine("The highest occurring character in the above string is: " + character); Console.WriteLine("Number of times this character occurs: " + maxCount);
[ { "code": null, "e": 1201, "s": 1062, "text": "The highest occurring character in a string is one that occurs most number of times. This can be demonstrated using the following example." }, { "code": null, "e": 1361, "s": 1201, "text": "String: apples are red\nThe highest occurring character in the above string is e as it occurs 3 times, which is more than the occurrence of any other character." }, { "code": null, "e": 1458, "s": 1361, "text": "A program that obtains the highest occurring character in a string using C# is given as follows." }, { "code": null, "e": 1469, "s": 1458, "text": " Live Demo" }, { "code": null, "e": 2275, "s": 1469, "text": "using System;\nnamespace charCountDemo {\n public class Example {\n public static void Main() {\n String str = \"abracadabra\";\n int []charCount = new int[256];\n int length = str.Length;\n for (int i = 0; i < length; i++) {\n charCount[str[i]]++;\n }\n int maxCount = -1;\n char character = ' ';\n for (int i = 0; i < length; i++) {\n if (maxCount < charCount[str[i]]) {\n maxCount = charCount[str[i]];\n character = str[i];\n }\n }\n Console.WriteLine(\"The string is: \" + str);\n Console.WriteLine(\"The highest occurring character in the above string is: \" + character);\n Console.WriteLine(\"Number of times this character occurs: \" + maxCount);\n }\n }\n}" }, { "code": null, "e": 2322, "s": 2275, "text": "The output of the above program is as follows." }, { "code": null, "e": 2448, "s": 2322, "text": "The string is: abracadabra\nThe highest occurring character in the above string is: a\nNumber of times this character occurs: 5" }, { "code": null, "e": 2490, "s": 2448, "text": "Now, let us understand the above program." }, { "code": null, "e": 2810, "s": 2490, "text": "The string str is abracadabra. A new array charCount is created which is of size 256 and shows all the characters in the ASCII table. Then the string str is traversed using a for loop and the value in charCount is incremented corresponding to the character in the string. This can be seen in the following code snippet." }, { "code": null, "e": 2956, "s": 2810, "text": "String str = \"abracadabra\";\nint []charCount = new int[256];\nint length = str.Length;\nfor (int i = 0; i < length; i++) {\n charCount[str[i]]++;\n}" }, { "code": null, "e": 3186, "s": 2956, "text": "The integer maxCount stores the maximum count and character is the char value that occurs the maximum times. The values of maxCount and character can be determined using a for loop. This can be seen in the following code snippet." }, { "code": null, "e": 3370, "s": 3186, "text": "int maxCount = -1;\nchar character = ' ';\nfor (int i = 0; i < length; i++) {\n if (maxCount < charCount[str[i]]) {\n maxCount = charCount[str[i]];\n character = str[i];\n }\n}" }, { "code": null, "e": 3484, "s": 3370, "text": "Finally, the values of str, maxCount and character are displayed. This can be seen in the following code snippet." }, { "code": null, "e": 3692, "s": 3484, "text": "Console.WriteLine(\"The string is: \" + str);\nConsole.WriteLine(\"The highest occurring character in the above string is: \" + character);\nConsole.WriteLine(\"Number of times this character occurs: \" + maxCount);" } ]
NamedParameterJdbcTemplate Class
The org.springframework.jdbc.core.NamedParameterJdbcTemplate class is a template class with a basic set of JDBC operations, allowing the use of named parameters rather than traditional '?' placeholders. This class delegates to a wrapped JdbcTemplate once the substitution from named parameters to JDBC style '?' placeholders is done at execution time. It also allows to expand a list of values to the appropriate number of placeholders. Following is the declaration for org.springframework.jdbc.core.NamedParameterJdbcTemplate class − public class NamedParameterJdbcTemplate extends Object implements NamedParameterJdbcOperations MapSqlParameterSource in = new MapSqlParameterSource(); in.addValue("id", id); in.addValue("description", new SqlLobValue(description, new DefaultLobHandler()), Types.CLOB); String SQL = "update Student set description = :description where id = :id"; NamedParameterJdbcTemplate jdbcTemplateObject = new NamedParameterJdbcTemplate(dataSource); jdbcTemplateObject.update(SQL, in); Where, in − SqlParameterSource object to pass a parameter to update a query. in − SqlParameterSource object to pass a parameter to update a query. SqlLobValue − Object to represent an SQL BLOB/CLOB value parameter. SqlLobValue − Object to represent an SQL BLOB/CLOB value parameter. jdbcTemplateObject − NamedParameterJdbcTemplate object to update student object in the database. jdbcTemplateObject − NamedParameterJdbcTemplate object to update student object in the database. To understand the above-mentioned concepts related to Spring JDBC, let us write an example which will update a query. To write our example, let us have a working Eclipse IDE in place and use the following steps to create a Spring application. Following is the content of the Data Access Object interface file StudentDAO.java. package com.tutorialspoint; import java.util.List; import javax.sql.DataSource; public interface StudentDAO { /** * This is the method to be used to initialize * database resources ie. connection. */ public void setDataSource(DataSource ds); /** * This is the method to be used to update * a record into the Student table. */ public void updateDescription(Integer id, String description); } Following is the content of the Student.java file. package com.tutorialspoint; public class Student { private Integer age; private String name; private Integer id; private String description; public void setAge(Integer age) { this.age = age; } public Integer getAge() { return age; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setId(Integer id) { this.id = id; } public Integer getId() { return id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } Following is the content of the StudentMapper.java file. package com.tutorialspoint; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; public class StudentMapper implements RowMapper<Student> { public Student mapRow(ResultSet rs, int rowNum) throws SQLException { Student student = new Student(); student.setId(rs.getInt("id")); student.setName(rs.getString("name")); student.setAge(rs.getInt("age")); student.setDescription(rs.getString("description")); return student; } } Following is the implementation class file StudentJDBCTemplate.java for the defined DAO interface StudentDAO. package com.tutorialspoint; import java.util.List; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.simple.SimpleJdbcCall; import org.springframework.jdbc.core.support.SqlLobValue; import org.springframework.jdbc.support.lob.DefaultLobHandler; import java.io.ByteArrayInputStream; import java.sql.Types; public class StudentJDBCTemplate implements StudentDAO { private DataSource dataSource; private JdbcTemplate jdbcTemplateObject; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public void updateDescription(Integer id, String description) { MapSqlParameterSource in = new MapSqlParameterSource(); in.addValue("id", id); in.addValue("description", new SqlLobValue(description, new DefaultLobHandler()), Types.CLOB); String SQL = "update Student set description = :description where id = :id"; NamedParameterJdbcTemplate jdbcTemplateObject = new NamedParameterJdbcTemplate(dataSource); jdbcTemplateObject.update(SQL, in); System.out.println("Updated Record with ID = " + id ); } } Following is the content of the MainApp.java file. package com.tutorialspoint; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.tutorialspoint.StudentJDBCTemplate; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate)context.getBean("studentJDBCTemplate"); studentJDBCTemplate.updateDescription(1, "This can be a very long text upto 4 GB of size."); } } Following is the configuration file Beans.xml. <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd "> <!-- Initialization for data source --> <bean id = "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name = "driverClassName" value = "com.mysql.jdbc.Driver"/> <property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/> <property name = "username" value = "root"/> <property name = "password" value = "admin"/> </bean> <!-- Definition for studentJDBCTemplate bean --> <bean id = "studentJDBCTemplate" class = "com.tutorialspoint.StudentJDBCTemplate"> <property name = "dataSource" ref = "dataSource" /> </bean> </beans> Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message. Updated Record with ID = 1 You can check the description stored by querying the database. Print Add Notes Bookmark this page
[ { "code": null, "e": 2833, "s": 2396, "text": "The org.springframework.jdbc.core.NamedParameterJdbcTemplate class is a template class with a basic set of JDBC operations, allowing the use of named parameters rather than traditional '?' placeholders. This class delegates to a wrapped JdbcTemplate once the substitution from named parameters to JDBC style '?' placeholders is done at execution time. It also allows to expand a list of values to the appropriate number of placeholders." }, { "code": null, "e": 2931, "s": 2833, "text": "Following is the declaration for org.springframework.jdbc.core.NamedParameterJdbcTemplate class −" }, { "code": null, "e": 3036, "s": 2931, "text": "public class NamedParameterJdbcTemplate\n extends Object\n implements NamedParameterJdbcOperations\n" }, { "code": null, "e": 3417, "s": 3036, "text": "MapSqlParameterSource in = new MapSqlParameterSource();\nin.addValue(\"id\", id);\nin.addValue(\"description\", new SqlLobValue(description, new DefaultLobHandler()), Types.CLOB);\n\nString SQL = \"update Student set description = :description where id = :id\";\nNamedParameterJdbcTemplate jdbcTemplateObject = new NamedParameterJdbcTemplate(dataSource);\njdbcTemplateObject.update(SQL, in);" }, { "code": null, "e": 3424, "s": 3417, "text": "Where," }, { "code": null, "e": 3494, "s": 3424, "text": "in − SqlParameterSource object to pass a parameter to update a query." }, { "code": null, "e": 3564, "s": 3494, "text": "in − SqlParameterSource object to pass a parameter to update a query." }, { "code": null, "e": 3632, "s": 3564, "text": "SqlLobValue − Object to represent an SQL BLOB/CLOB value parameter." }, { "code": null, "e": 3700, "s": 3632, "text": "SqlLobValue − Object to represent an SQL BLOB/CLOB value parameter." }, { "code": null, "e": 3797, "s": 3700, "text": "jdbcTemplateObject − NamedParameterJdbcTemplate object to update student object in the database." }, { "code": null, "e": 3894, "s": 3797, "text": "jdbcTemplateObject − NamedParameterJdbcTemplate object to update student object in the database." }, { "code": null, "e": 4137, "s": 3894, "text": "To understand the above-mentioned concepts related to Spring JDBC, let us write an example which will update a query. To write our example, let us have a working Eclipse IDE in place and use the following steps to create a Spring application." }, { "code": null, "e": 4220, "s": 4137, "text": "Following is the content of the Data Access Object interface file StudentDAO.java." }, { "code": null, "e": 4661, "s": 4220, "text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport javax.sql.DataSource;\n\npublic interface StudentDAO {\n /** \n * This is the method to be used to initialize\n * database resources ie. connection.\n */\n public void setDataSource(DataSource ds);\n \n /** \n * This is the method to be used to update\n * a record into the Student table.\n */\n public void updateDescription(Integer id, String description);\n}" }, { "code": null, "e": 4712, "s": 4661, "text": "Following is the content of the Student.java file." }, { "code": null, "e": 5377, "s": 4712, "text": "package com.tutorialspoint;\n\npublic class Student {\n private Integer age;\n private String name;\n private Integer id;\n private String description;\n\n public void setAge(Integer age) {\n this.age = age;\n }\n public Integer getAge() {\n return age;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getName() {\n return name;\n }\n public void setId(Integer id) {\n this.id = id;\n }\n public Integer getId() {\n return id;\n }\n public String getDescription() {\n return description;\n }\n public void setDescription(String description) {\n this.description = description;\n }\n}" }, { "code": null, "e": 5434, "s": 5377, "text": "Following is the content of the StudentMapper.java file." }, { "code": null, "e": 5951, "s": 5434, "text": "package com.tutorialspoint;\n\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport org.springframework.jdbc.core.RowMapper;\n\npublic class StudentMapper implements RowMapper<Student> {\n public Student mapRow(ResultSet rs, int rowNum) throws SQLException {\n Student student = new Student();\n student.setId(rs.getInt(\"id\"));\n student.setName(rs.getString(\"name\"));\n student.setAge(rs.getInt(\"age\"));\n student.setDescription(rs.getString(\"description\"));\n return student;\n }\n}" }, { "code": null, "e": 6061, "s": 5951, "text": "Following is the implementation class file StudentJDBCTemplate.java for the defined DAO interface StudentDAO." }, { "code": null, "e": 7443, "s": 6061, "text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport javax.sql.DataSource;\nimport org.springframework.jdbc.core.JdbcTemplate;\nimport org.springframework.jdbc.core.namedparam.MapSqlParameterSource;\nimport org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;\nimport org.springframework.jdbc.core.namedparam.SqlParameterSource;\nimport org.springframework.jdbc.core.simple.SimpleJdbcCall;\nimport org.springframework.jdbc.core.support.SqlLobValue;\nimport org.springframework.jdbc.support.lob.DefaultLobHandler;\nimport java.io.ByteArrayInputStream;\nimport java.sql.Types;\n\npublic class StudentJDBCTemplate implements StudentDAO {\n private DataSource dataSource;\n private JdbcTemplate jdbcTemplateObject;\n \n public void setDataSource(DataSource dataSource) {\n this.dataSource = dataSource;\n }\n public void updateDescription(Integer id, String description) {\n MapSqlParameterSource in = new MapSqlParameterSource();\n in.addValue(\"id\", id);\n in.addValue(\"description\", new SqlLobValue(description, new DefaultLobHandler()), Types.CLOB);\n\n String SQL = \"update Student set description = :description where id = :id\";\n NamedParameterJdbcTemplate jdbcTemplateObject = new NamedParameterJdbcTemplate(dataSource);\n \n jdbcTemplateObject.update(SQL, in);\n System.out.println(\"Updated Record with ID = \" + id );\n }\n}" }, { "code": null, "e": 7494, "s": 7443, "text": "Following is the content of the MainApp.java file." }, { "code": null, "e": 8092, "s": 7494, "text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\nimport com.tutorialspoint.StudentJDBCTemplate;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n\n StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate)context.getBean(\"studentJDBCTemplate\");\n studentJDBCTemplate.updateDescription(1, \"This can be a very long text upto 4 GB of size.\"); \n }\n}" }, { "code": null, "e": 8139, "s": 8092, "text": "Following is the configuration file Beans.xml." }, { "code": null, "e": 9089, "s": 8139, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd \">\n\n <!-- Initialization for data source -->\n <bean id = \"dataSource\" \n class = \"org.springframework.jdbc.datasource.DriverManagerDataSource\">\n <property name = \"driverClassName\" value = \"com.mysql.jdbc.Driver\"/>\n <property name = \"url\" value = \"jdbc:mysql://localhost:3306/TEST\"/>\n <property name = \"username\" value = \"root\"/>\n <property name = \"password\" value = \"admin\"/>\n </bean>\n\n <!-- Definition for studentJDBCTemplate bean -->\n <bean id = \"studentJDBCTemplate\" \n class = \"com.tutorialspoint.StudentJDBCTemplate\">\n <property name = \"dataSource\" ref = \"dataSource\" /> \n </bean> \n</beans>" }, { "code": null, "e": 9267, "s": 9089, "text": "Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message." }, { "code": null, "e": 9295, "s": 9267, "text": "Updated Record with ID = 1\n" }, { "code": null, "e": 9358, "s": 9295, "text": "You can check the description stored by querying the database." }, { "code": null, "e": 9365, "s": 9358, "text": " Print" }, { "code": null, "e": 9376, "s": 9365, "text": " Add Notes" } ]
CSS - content
The content property defines content to be inserted in generated content operations. This property is used along with :before or :after pseudo elements. string − Any permitted string value. This is always enclosed in quotation marks. string − Any permitted string value. This is always enclosed in quotation marks. URI − A pointer to an external resource such as an image. URI − A pointer to an external resource such as an image. counter − There are two possible forms of this value: counter(name, style?) and counters(name, string,? style?). In both cases, the content will be the value of the named counter at that point in the document, rendered in the optional style value (decimal by default). In the case of counters(...), the optional string value indicates a string to follow each instance of the named counter. counter − There are two possible forms of this value: counter(name, style?) and counters(name, string,? style?). In both cases, the content will be the value of the named counter at that point in the document, rendered in the optional style value (decimal by default). In the case of counters(...), the optional string value indicates a string to follow each instance of the named counter. attr(X) − Causes the insertion of the value of attribute X for the selector's subject. For example, it is possible to display the value of the alt attribute of an image using this value. attr(X) − Causes the insertion of the value of attribute X for the selector's subject. For example, it is possible to display the value of the alt attribute of an image using this value. open-quote − Causes the insertion of the appropriate string specified using the property quotes. open-quote − Causes the insertion of the appropriate string specified using the property quotes. close-quote − Causes the insertion of the appropriate string specified using the property quotes. close-quote − Causes the insertion of the appropriate string specified using the property quotes. no-open-quote − Prevents the insertion of the appropriate string specified using the property quotes. However, the nesting level of the quotation marks is still increased. no-open-quote − Prevents the insertion of the appropriate string specified using the property quotes. However, the nesting level of the quotation marks is still increased. no-close-quote − Prevents the insertion of the appropriate string specified using the property quotes. However, the nesting level of the quotation marks is still decreased. no-close-quote − Prevents the insertion of the appropriate string specified using the property quotes. However, the nesting level of the quotation marks is still decreased. :before and :after pseudo-elements. object.style.content = "url(home.avi)" Following is the example which demonstrates how to use :before element to add some content before any element. <html> <head> <style type = "text/css"> p:before { content: url(/images/bullet.gif) } </style> </head> <body> <p> This line will be preceded by a bullet.</p> <p> This line will be preceded by a bullet.</p> <p> This line will be preceded by a bullet.</p> </body> </html> This will produce following black link − This line will be preceded by a bullet. This line will be preceded by a bullet. This line will be preceded by a bullet. Following is the example which demonstrates how to use :after element to add some content after any element. <html> <head> <style type = "text/css"> p:after { content: url(/images/bullet.gif) } </style> </head> <body> <p> This line will be succeeded by a bullet.</p> <p> This line will be succeeded by a bullet.</p> <p> This line will be succeeded by a bullet.</p> </body> </html> This will produce following black link − This line will be succeeded by a bullet. This line will be succeeded by a bullet. This line will be succeeded by a bullet. 33 Lectures 2.5 hours Anadi Sharma 26 Lectures 2.5 hours Frahaan Hussain 44 Lectures 4.5 hours DigiFisk (Programming Is Fun) 21 Lectures 2.5 hours DigiFisk (Programming Is Fun) 51 Lectures 7.5 hours DigiFisk (Programming Is Fun) 52 Lectures 4 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2779, "s": 2626, "text": "The content property defines content to be inserted in generated content operations. This property is used along with :before or :after pseudo elements." }, { "code": null, "e": 2860, "s": 2779, "text": "string − Any permitted string value. This is always enclosed in quotation marks." }, { "code": null, "e": 2941, "s": 2860, "text": "string − Any permitted string value. This is always enclosed in quotation marks." }, { "code": null, "e": 2999, "s": 2941, "text": "URI − A pointer to an external resource such as an image." }, { "code": null, "e": 3057, "s": 2999, "text": "URI − A pointer to an external resource such as an image." }, { "code": null, "e": 3447, "s": 3057, "text": "counter − There are two possible forms of this value: counter(name, style?) and counters(name, string,? style?). In both cases, the content will be the value of the named counter at that point in the document, rendered in the optional style value (decimal by default). In the case of counters(...), the optional string value indicates a string to follow each instance of the named counter." }, { "code": null, "e": 3837, "s": 3447, "text": "counter − There are two possible forms of this value: counter(name, style?) and counters(name, string,? style?). In both cases, the content will be the value of the named counter at that point in the document, rendered in the optional style value (decimal by default). In the case of counters(...), the optional string value indicates a string to follow each instance of the named counter." }, { "code": null, "e": 4024, "s": 3837, "text": "attr(X) − Causes the insertion of the value of attribute X for the selector's subject. For example, it is possible to display the value of the alt attribute of an image using this value." }, { "code": null, "e": 4211, "s": 4024, "text": "attr(X) − Causes the insertion of the value of attribute X for the selector's subject. For example, it is possible to display the value of the alt attribute of an image using this value." }, { "code": null, "e": 4308, "s": 4211, "text": "open-quote − Causes the insertion of the appropriate string specified using the property quotes." }, { "code": null, "e": 4405, "s": 4308, "text": "open-quote − Causes the insertion of the appropriate string specified using the property quotes." }, { "code": null, "e": 4503, "s": 4405, "text": "close-quote − Causes the insertion of the appropriate string specified using the property quotes." }, { "code": null, "e": 4601, "s": 4503, "text": "close-quote − Causes the insertion of the appropriate string specified using the property quotes." }, { "code": null, "e": 4773, "s": 4601, "text": "no-open-quote − Prevents the insertion of the appropriate string specified using the property quotes. However, the nesting level of the quotation marks is still increased." }, { "code": null, "e": 4945, "s": 4773, "text": "no-open-quote − Prevents the insertion of the appropriate string specified using the property quotes. However, the nesting level of the quotation marks is still increased." }, { "code": null, "e": 5118, "s": 4945, "text": "no-close-quote − Prevents the insertion of the appropriate string specified using the property quotes. However, the nesting level of the quotation marks is still decreased." }, { "code": null, "e": 5291, "s": 5118, "text": "no-close-quote − Prevents the insertion of the appropriate string specified using the property quotes. However, the nesting level of the quotation marks is still decreased." }, { "code": null, "e": 5327, "s": 5291, "text": ":before and :after pseudo-elements." }, { "code": null, "e": 5367, "s": 5327, "text": "object.style.content = \"url(home.avi)\"\n" }, { "code": null, "e": 5478, "s": 5367, "text": "Following is the example which demonstrates how to use :before element to add some content before any element." }, { "code": null, "e": 5822, "s": 5478, "text": "<html>\n <head>\n <style type = \"text/css\">\n p:before {\n content: url(/images/bullet.gif)\n }\n </style>\n </head>\n\n <body>\n <p> This line will be preceded by a bullet.</p>\n <p> This line will be preceded by a bullet.</p>\n <p> This line will be preceded by a bullet.</p>\n </body>\n</html> " }, { "code": null, "e": 5863, "s": 5822, "text": "This will produce following black link −" }, { "code": null, "e": 5904, "s": 5863, "text": " This line will be preceded by a bullet." }, { "code": null, "e": 5945, "s": 5904, "text": " This line will be preceded by a bullet." }, { "code": null, "e": 5986, "s": 5945, "text": " This line will be preceded by a bullet." }, { "code": null, "e": 6095, "s": 5986, "text": "Following is the example which demonstrates how to use :after element to add some content after any element." }, { "code": null, "e": 6441, "s": 6095, "text": "<html>\n <head>\n <style type = \"text/css\">\n p:after {\n content: url(/images/bullet.gif)\n }\n </style>\n </head>\n\n <body>\n <p> This line will be succeeded by a bullet.</p>\n <p> This line will be succeeded by a bullet.</p>\n <p> This line will be succeeded by a bullet.</p>\n </body>\n</html> " }, { "code": null, "e": 6482, "s": 6441, "text": "This will produce following black link −" }, { "code": null, "e": 6524, "s": 6482, "text": " This line will be succeeded by a bullet." }, { "code": null, "e": 6566, "s": 6524, "text": " This line will be succeeded by a bullet." }, { "code": null, "e": 6608, "s": 6566, "text": " This line will be succeeded by a bullet." }, { "code": null, "e": 6643, "s": 6608, "text": "\n 33 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6657, "s": 6643, "text": " Anadi Sharma" }, { "code": null, "e": 6692, "s": 6657, "text": "\n 26 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6709, "s": 6692, "text": " Frahaan Hussain" }, { "code": null, "e": 6744, "s": 6709, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6775, "s": 6744, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 6810, "s": 6775, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6841, "s": 6810, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 6876, "s": 6841, "text": "\n 51 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6907, "s": 6876, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 6940, "s": 6907, "text": "\n 52 Lectures \n 4 hours \n" }, { "code": null, "e": 6971, "s": 6940, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 6978, "s": 6971, "text": " Print" }, { "code": null, "e": 6989, "s": 6978, "text": " Add Notes" } ]
Find the mean vector of a Matrix
13 Apr, 2021 Given a matrix of size M x N, the task is to find the Mean Vector of the given matrix. Examples: Input : mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} Output : Mean Vector is [4 5 6] Mean of column 1 is (1 + 4 + 7) / 3 = 4 Mean of column 2 is (2 + 5 + 8) / 3 = 5 Mean of column 3 is (3 + 6 + 9) / 3 = 6 Input : mat[][] = {{2, 4}, {6, 8}} Output : Mean Vector is [4 6] Mean of column 1 is (2 + 6) / 2 = 4 Mean of column 2 is (4 + 8) / 2 = 6 Approach: Lets take a matrix mat of dimension 5×3 representing lengths, breadths, heights of 5 objects. Now, the resulting mean vector will be a row vector of the following format : [mean(length) mean(breadth) mean(height)] Note: If we have a matrix of dimension M x N, then the resulting row vector will be having dimension 1 x N Now, simply calculate the mean of each column of the matrix which will give the required mean vector . C++ Java Python3 C# PHP Javascript // C++ program to find mean vector// of given matrix#include <bits/stdc++.h>using namespace std;#define rows 3#define cols 3 // Function to find mean vectorvoid meanVector(int mat[rows][cols]){ cout << "[ "; // loop to traverse each column for (int i = 0; i < rows; i++) { // to calculate mean of each row double mean = 0.00; // to store sum of elements of a column int sum = 0; for (int j = 0; j < cols; j++) sum += mat[j][i]; mean = sum / rows; cout << mean << " "; } cout << "]";} // Drivers codeint main(){ int mat[rows][cols] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; meanVector(mat); return 0;} // Java program to find// mean vector of given matriximport java.io.*; class GFG{static int rows = 3;static int cols = 3; // Function to// find mean vectorstatic void meanVector(int mat[][]){ System.out.print("[ "); // loop to traverse // each column for (int i = 0; i < rows; i++) { // to calculate mean // of each row double mean = 0.00; // to store sum of // elements of a column int sum = 0; for (int j = 0; j < cols; j++) sum += mat[j][i]; mean = sum / rows; System.out.print((int)mean + " "); } System.out.print("]");} // Driver codepublic static void main (String[] args){ int mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; meanVector(mat);}} // This code is contributed// by anuj_67. # Python3 program to find# mean vector of given# matrixrows = 3;cols = 3; # Function to# find mean vectordef meanVector(mat): print("[ ", end = ""); # loop to traverse # each column for i in range(rows): # to calculate # mean of each row mean = 0.00; # to store sum of # elements of a column sum = 0; for j in range(cols): sum = sum + mat[j][i]; mean = int(sum /rows); print(mean, end = " "); print("]"); # Driver Codemat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; meanVector(mat); # This code is contributed# by mits // C# program to find// mean vector of given matrixusing System; class GFG{static int rows = 3;static int cols = 3; // Function to// find mean vectorstatic void meanVector(int [,]mat){ Console.Write("[ "); // loop to traverse // each column for (int i = 0; i < rows; i++) { // to calculate mean // of each row double mean = 0.00; // to store sum of // elements of a column int sum = 0; for (int j = 0; j < cols; j++) sum += mat[j, i]; mean = sum / rows; Console.Write((int)mean + " "); } Console.Write("]");} // Driver codepublic static void Main (){ int[,] mat = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; meanVector(mat);}} // This code is contributed// by anuj_67. <?php// PHP program to find mean// vector of given matrix$rows = 3;$cols = 3; // Function to find mean vectorfunction meanVector($mat){ global $rows ,$cols; echo "[ "; // loop to traverse // each column for ($i = 0; $i < $rows; $i++) { // to calculate // mean of each row $mean = 0.00; // to store sum of // elements of a column $sum = 0; for ($j = 0; $j < $cols; $j++) $sum += $mat[$j][$i]; $mean = $sum /$rows; echo $mean , " "; } echo "]";} // Driver Code$mat = array(array(1, 2, 3), array(4, 5, 6), array(7, 8, 9)); meanVector($mat); // This code is contributed// by anuj_6?> <script> // Javascript program to find// mean vector of given matrixvar rows = 3;var cols = 3; // Function to find mean vectorfunction meanVector(mat){ document.write("[ "); // Loop to traverse // each column for (var i = 0; i < rows; i++) { // To calculate mean // of each row var mean = 0.00; // to store sum of // elements of a column var sum = 0; for (var j = 0; j < cols; j++) sum += mat[j][i]; mean = sum / rows; document.write(mean + " "); } document.write("]");} // Driver codevar mat = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]; meanVector(mat); // This code is contributed by Kirti </script> [ 4 5 6 ] Time Complexity: O(rows * cols) vt_m Mithun Kumar Kirti_Mangal Mathematical Matrix Mathematical Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n13 Apr, 2021" }, { "code": null, "e": 152, "s": 53, "text": "Given a matrix of size M x N, the task is to find the Mean Vector of the given matrix. Examples: " }, { "code": null, "e": 560, "s": 152, "text": "Input : mat[][] = {{1, 2, 3},\n {4, 5, 6},\n {7, 8, 9}} \nOutput : Mean Vector is [4 5 6]\nMean of column 1 is (1 + 4 + 7) / 3 = 4\nMean of column 2 is (2 + 5 + 8) / 3 = 5\nMean of column 3 is (3 + 6 + 9) / 3 = 6\n\nInput : mat[][] = {{2, 4},\n {6, 8}}\nOutput : Mean Vector is [4 6]\nMean of column 1 is (2 + 6) / 2 = 4\nMean of column 2 is (4 + 8) / 2 = 6" }, { "code": null, "e": 744, "s": 560, "text": "Approach: Lets take a matrix mat of dimension 5×3 representing lengths, breadths, heights of 5 objects. Now, the resulting mean vector will be a row vector of the following format : " }, { "code": null, "e": 787, "s": 744, "text": "[mean(length) mean(breadth) mean(height)]" }, { "code": null, "e": 998, "s": 787, "text": "Note: If we have a matrix of dimension M x N, then the resulting row vector will be having dimension 1 x N Now, simply calculate the mean of each column of the matrix which will give the required mean vector . " }, { "code": null, "e": 1002, "s": 998, "text": "C++" }, { "code": null, "e": 1007, "s": 1002, "text": "Java" }, { "code": null, "e": 1015, "s": 1007, "text": "Python3" }, { "code": null, "e": 1018, "s": 1015, "text": "C#" }, { "code": null, "e": 1022, "s": 1018, "text": "PHP" }, { "code": null, "e": 1033, "s": 1022, "text": "Javascript" }, { "code": "// C++ program to find mean vector// of given matrix#include <bits/stdc++.h>using namespace std;#define rows 3#define cols 3 // Function to find mean vectorvoid meanVector(int mat[rows][cols]){ cout << \"[ \"; // loop to traverse each column for (int i = 0; i < rows; i++) { // to calculate mean of each row double mean = 0.00; // to store sum of elements of a column int sum = 0; for (int j = 0; j < cols; j++) sum += mat[j][i]; mean = sum / rows; cout << mean << \" \"; } cout << \"]\";} // Drivers codeint main(){ int mat[rows][cols] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; meanVector(mat); return 0;}", "e": 1784, "s": 1033, "text": null }, { "code": "// Java program to find// mean vector of given matriximport java.io.*; class GFG{static int rows = 3;static int cols = 3; // Function to// find mean vectorstatic void meanVector(int mat[][]){ System.out.print(\"[ \"); // loop to traverse // each column for (int i = 0; i < rows; i++) { // to calculate mean // of each row double mean = 0.00; // to store sum of // elements of a column int sum = 0; for (int j = 0; j < cols; j++) sum += mat[j][i]; mean = sum / rows; System.out.print((int)mean + \" \"); } System.out.print(\"]\");} // Driver codepublic static void main (String[] args){ int mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; meanVector(mat);}} // This code is contributed// by anuj_67.", "e": 2618, "s": 1784, "text": null }, { "code": "# Python3 program to find# mean vector of given# matrixrows = 3;cols = 3; # Function to# find mean vectordef meanVector(mat): print(\"[ \", end = \"\"); # loop to traverse # each column for i in range(rows): # to calculate # mean of each row mean = 0.00; # to store sum of # elements of a column sum = 0; for j in range(cols): sum = sum + mat[j][i]; mean = int(sum /rows); print(mean, end = \" \"); print(\"]\"); # Driver Codemat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; meanVector(mat); # This code is contributed# by mits", "e": 3245, "s": 2618, "text": null }, { "code": "// C# program to find// mean vector of given matrixusing System; class GFG{static int rows = 3;static int cols = 3; // Function to// find mean vectorstatic void meanVector(int [,]mat){ Console.Write(\"[ \"); // loop to traverse // each column for (int i = 0; i < rows; i++) { // to calculate mean // of each row double mean = 0.00; // to store sum of // elements of a column int sum = 0; for (int j = 0; j < cols; j++) sum += mat[j, i]; mean = sum / rows; Console.Write((int)mean + \" \"); } Console.Write(\"]\");} // Driver codepublic static void Main (){ int[,] mat = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; meanVector(mat);}} // This code is contributed// by anuj_67.", "e": 4047, "s": 3245, "text": null }, { "code": "<?php// PHP program to find mean// vector of given matrix$rows = 3;$cols = 3; // Function to find mean vectorfunction meanVector($mat){ global $rows ,$cols; echo \"[ \"; // loop to traverse // each column for ($i = 0; $i < $rows; $i++) { // to calculate // mean of each row $mean = 0.00; // to store sum of // elements of a column $sum = 0; for ($j = 0; $j < $cols; $j++) $sum += $mat[$j][$i]; $mean = $sum /$rows; echo $mean , \" \"; } echo \"]\";} // Driver Code$mat = array(array(1, 2, 3), array(4, 5, 6), array(7, 8, 9)); meanVector($mat); // This code is contributed// by anuj_6?>", "e": 4755, "s": 4047, "text": null }, { "code": "<script> // Javascript program to find// mean vector of given matrixvar rows = 3;var cols = 3; // Function to find mean vectorfunction meanVector(mat){ document.write(\"[ \"); // Loop to traverse // each column for (var i = 0; i < rows; i++) { // To calculate mean // of each row var mean = 0.00; // to store sum of // elements of a column var sum = 0; for (var j = 0; j < cols; j++) sum += mat[j][i]; mean = sum / rows; document.write(mean + \" \"); } document.write(\"]\");} // Driver codevar mat = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]; meanVector(mat); // This code is contributed by Kirti </script>", "e": 5499, "s": 4755, "text": null }, { "code": null, "e": 5509, "s": 5499, "text": "[ 4 5 6 ]" }, { "code": null, "e": 5544, "s": 5511, "text": "Time Complexity: O(rows * cols) " }, { "code": null, "e": 5549, "s": 5544, "text": "vt_m" }, { "code": null, "e": 5562, "s": 5549, "text": "Mithun Kumar" }, { "code": null, "e": 5575, "s": 5562, "text": "Kirti_Mangal" }, { "code": null, "e": 5588, "s": 5575, "text": "Mathematical" }, { "code": null, "e": 5595, "s": 5588, "text": "Matrix" }, { "code": null, "e": 5608, "s": 5595, "text": "Mathematical" }, { "code": null, "e": 5615, "s": 5608, "text": "Matrix" } ]
Python Tkinter – Checkbutton Widget
26 Mar, 2020 Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task. Note: For more information, refer to Python GUI – tkinter The Checkbutton widget is a standard Tkinter widget that is used to implement on/off selections. Checkbuttons can contain text or images. When the button is pressed, Tkinter calls that function or method. Syntax:The syntax to use the checkbutton is given below. w = Checkbutton ( master, options) Parameters: master: This parameter is used to represents the parent window. options:There are many options which are available and they can be used as key-value pairs separated by commas. Options:Following are commonly used Option can be used with this widget :- activebackground: This option used to represent the background color when the checkbutton is under the cursor. activeforeground: This option used to represent the foreground color when the checkbutton is under the cursor. bg: This option used to represent the normal background color displayed behind the label and indicator. bitmap: This option used to display a monochrome image on a button. bd: This option used to represent the size of the border around the indicator and the default value is 2 pixels. command: This option is associated with a function to be called when the state of the checkbutton is changed. cursor: By using this option, the mouse cursor will change to that pattern when it is over the checkbutton. disabledforeground: The foreground color used to render the text of a disabled checkbutton. The default is a stippled version of the default foreground color. font: This option used to represent the font used for the text. fg: This option used to represent the color used to render the text. height: This option used to represent the number of lines of text on the checkbutton and it’s default value is 1. highlightcolor: This option used to represent the color of the focus highlight when the checkbutton has the focus. image: This option used to display a graphic image on the button. justify: This option used to control how the text is justified: CENTER, LEFT, or RIGHT. offvalue: The associated control variable is set to 0 by default if the button is unchecked. We can change the state of an unchecked variable to some other one. onvalue: The associated control variable is set to 1 by default if the button is checked. We can change the state of the checked variable to some other one. padx: This option used to represent how much space to leave to the left and right of the checkbutton and text. It’s default value is 1 pixel. pady: This option used to represent how much space to leave above and below the checkbutton and text. It’s default value is 1 pixel. relief: The type of the border of the checkbutton. It’s default value is set to FLAT. selectcolor: This option used to represent the color of the checkbutton when it is set. The Default is selectcolor=”red”. selectimage: The image is shown on the checkbutton when it is set. state: It represents the state of the checkbutton. By default, it is set to normal. We can change it to DISABLED to make the checkbutton unresponsive. The state of the checkbutton is ACTIVE when it is under focus. text: This option used use newlines (“\n”) to display multiple lines of text. underline: This option used to represent the index of the character in the text which is to be underlined. The indexing starts with zero in the text. variable: This option used to represents the associated variable that tracks the state of the checkbutton. width: This option used to represents the width of the checkbutton. and also represented in the number of characters that are represented in the form of texts. wraplength: This option will be broken text into the number of pieces. Methods:Methods used in this widgets are as follows: deselect(): This method is called to turn off the checkbutton. flash(): The checkbutton is flashed between the active and normal colors. invoke(): This method will invoke the method associated with the checkbutton. select(): This method is called to turn on the checkbutton. toggle(): This method is used to toggle between the different Checkbuttons. Example: from tkinter import * root = Tk()root.geometry("300x200") w = Label(root, text ='GeeksForGeeks', font = "50") w.pack() Checkbutton1 = IntVar() Checkbutton2 = IntVar() Checkbutton3 = IntVar() Button1 = Checkbutton(root, text = "Tutorial", variable = Checkbutton1, onvalue = 1, offvalue = 0, height = 2, width = 10) Button2 = Checkbutton(root, text = "Student", variable = Checkbutton2, onvalue = 1, offvalue = 0, height = 2, width = 10) Button3 = Checkbutton(root, text = "Courses", variable = Checkbutton3, onvalue = 1, offvalue = 0, height = 2, width = 10) Button1.pack() Button2.pack() Button3.pack() mainloop() Output: Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Enumerate() in Python Different ways to create Pandas Dataframe Read a file line by line in Python How to Install PIP on Windows ? Python String | replace() Python OOPs Concepts
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Mar, 2020" }, { "code": null, "e": 404, "s": 52, "text": "Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task." }, { "code": null, "e": 462, "s": 404, "text": "Note: For more information, refer to Python GUI – tkinter" }, { "code": null, "e": 667, "s": 462, "text": "The Checkbutton widget is a standard Tkinter widget that is used to implement on/off selections. Checkbuttons can contain text or images. When the button is pressed, Tkinter calls that function or method." }, { "code": null, "e": 724, "s": 667, "text": "Syntax:The syntax to use the checkbutton is given below." }, { "code": null, "e": 759, "s": 724, "text": "w = Checkbutton ( master, options)" }, { "code": null, "e": 771, "s": 759, "text": "Parameters:" }, { "code": null, "e": 835, "s": 771, "text": "master: This parameter is used to represents the parent window." }, { "code": null, "e": 947, "s": 835, "text": "options:There are many options which are available and they can be used as key-value pairs separated by commas." }, { "code": null, "e": 1022, "s": 947, "text": "Options:Following are commonly used Option can be used with this widget :-" }, { "code": null, "e": 1133, "s": 1022, "text": "activebackground: This option used to represent the background color when the checkbutton is under the cursor." }, { "code": null, "e": 1244, "s": 1133, "text": "activeforeground: This option used to represent the foreground color when the checkbutton is under the cursor." }, { "code": null, "e": 1348, "s": 1244, "text": "bg: This option used to represent the normal background color displayed behind the label and indicator." }, { "code": null, "e": 1416, "s": 1348, "text": "bitmap: This option used to display a monochrome image on a button." }, { "code": null, "e": 1529, "s": 1416, "text": "bd: This option used to represent the size of the border around the indicator and the default value is 2 pixels." }, { "code": null, "e": 1639, "s": 1529, "text": "command: This option is associated with a function to be called when the state of the checkbutton is changed." }, { "code": null, "e": 1747, "s": 1639, "text": "cursor: By using this option, the mouse cursor will change to that pattern when it is over the checkbutton." }, { "code": null, "e": 1906, "s": 1747, "text": "disabledforeground: The foreground color used to render the text of a disabled checkbutton. The default is a stippled version of the default foreground color." }, { "code": null, "e": 1970, "s": 1906, "text": "font: This option used to represent the font used for the text." }, { "code": null, "e": 2039, "s": 1970, "text": "fg: This option used to represent the color used to render the text." }, { "code": null, "e": 2153, "s": 2039, "text": "height: This option used to represent the number of lines of text on the checkbutton and it’s default value is 1." }, { "code": null, "e": 2268, "s": 2153, "text": "highlightcolor: This option used to represent the color of the focus highlight when the checkbutton has the focus." }, { "code": null, "e": 2334, "s": 2268, "text": "image: This option used to display a graphic image on the button." }, { "code": null, "e": 2422, "s": 2334, "text": "justify: This option used to control how the text is justified: CENTER, LEFT, or RIGHT." }, { "code": null, "e": 2583, "s": 2422, "text": "offvalue: The associated control variable is set to 0 by default if the button is unchecked. We can change the state of an unchecked variable to some other one." }, { "code": null, "e": 2740, "s": 2583, "text": "onvalue: The associated control variable is set to 1 by default if the button is checked. We can change the state of the checked variable to some other one." }, { "code": null, "e": 2882, "s": 2740, "text": "padx: This option used to represent how much space to leave to the left and right of the checkbutton and text. It’s default value is 1 pixel." }, { "code": null, "e": 3015, "s": 2882, "text": "pady: This option used to represent how much space to leave above and below the checkbutton and text. It’s default value is 1 pixel." }, { "code": null, "e": 3101, "s": 3015, "text": "relief: The type of the border of the checkbutton. It’s default value is set to FLAT." }, { "code": null, "e": 3223, "s": 3101, "text": "selectcolor: This option used to represent the color of the checkbutton when it is set. The Default is selectcolor=”red”." }, { "code": null, "e": 3290, "s": 3223, "text": "selectimage: The image is shown on the checkbutton when it is set." }, { "code": null, "e": 3504, "s": 3290, "text": "state: It represents the state of the checkbutton. By default, it is set to normal. We can change it to DISABLED to make the checkbutton unresponsive. The state of the checkbutton is ACTIVE when it is under focus." }, { "code": null, "e": 3582, "s": 3504, "text": "text: This option used use newlines (“\\n”) to display multiple lines of text." }, { "code": null, "e": 3732, "s": 3582, "text": "underline: This option used to represent the index of the character in the text which is to be underlined. The indexing starts with zero in the text." }, { "code": null, "e": 3839, "s": 3732, "text": "variable: This option used to represents the associated variable that tracks the state of the checkbutton." }, { "code": null, "e": 3999, "s": 3839, "text": "width: This option used to represents the width of the checkbutton. and also represented in the number of characters that are represented in the form of texts." }, { "code": null, "e": 4070, "s": 3999, "text": "wraplength: This option will be broken text into the number of pieces." }, { "code": null, "e": 4123, "s": 4070, "text": "Methods:Methods used in this widgets are as follows:" }, { "code": null, "e": 4186, "s": 4123, "text": "deselect(): This method is called to turn off the checkbutton." }, { "code": null, "e": 4260, "s": 4186, "text": "flash(): The checkbutton is flashed between the active and normal colors." }, { "code": null, "e": 4338, "s": 4260, "text": "invoke(): This method will invoke the method associated with the checkbutton." }, { "code": null, "e": 4398, "s": 4338, "text": "select(): This method is called to turn on the checkbutton." }, { "code": null, "e": 4474, "s": 4398, "text": "toggle(): This method is used to toggle between the different Checkbuttons." }, { "code": null, "e": 4483, "s": 4474, "text": "Example:" }, { "code": "from tkinter import * root = Tk()root.geometry(\"300x200\") w = Label(root, text ='GeeksForGeeks', font = \"50\") w.pack() Checkbutton1 = IntVar() Checkbutton2 = IntVar() Checkbutton3 = IntVar() Button1 = Checkbutton(root, text = \"Tutorial\", variable = Checkbutton1, onvalue = 1, offvalue = 0, height = 2, width = 10) Button2 = Checkbutton(root, text = \"Student\", variable = Checkbutton2, onvalue = 1, offvalue = 0, height = 2, width = 10) Button3 = Checkbutton(root, text = \"Courses\", variable = Checkbutton3, onvalue = 1, offvalue = 0, height = 2, width = 10) Button1.pack() Button2.pack() Button3.pack() mainloop() ", "e": 5431, "s": 4483, "text": null }, { "code": null, "e": 5439, "s": 5431, "text": "Output:" }, { "code": null, "e": 5454, "s": 5439, "text": "Python-tkinter" }, { "code": null, "e": 5461, "s": 5454, "text": "Python" }, { "code": null, "e": 5559, "s": 5461, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5587, "s": 5559, "text": "Read JSON file using Python" }, { "code": null, "e": 5637, "s": 5587, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 5659, "s": 5637, "text": "Python map() function" }, { "code": null, "e": 5703, "s": 5659, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 5725, "s": 5703, "text": "Enumerate() in Python" }, { "code": null, "e": 5767, "s": 5725, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5802, "s": 5767, "text": "Read a file line by line in Python" }, { "code": null, "e": 5834, "s": 5802, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5860, "s": 5834, "text": "Python String | replace()" } ]
Project Idea | Jal Sanrakshan
26 Jul, 2018 Project Title: Jal Sanrakshan One Line Idea: Gamify water conservation IntroductionIndian households water use involves a water storage system called a ‘tank’ which stores water from where water is consumed. And its also the fact that we are in the midst of severe water crises, thanks to global warming and other contributing factors. Its high time everybody starts preserving water, one of the way of doing which is ‘better and conscious consumption of water’. My idea is an attempt to do just this. SolutionTo build an Arduino based app which notes down the water flow(water that came out of the tank) and sends it to the app. The app will then ask the user to tell the activity he consumed water for. The current water reading will then be compared with earlier readings to check if the water consumed was less or more than before. If less, it will be updated as the best reading yet, else the user will be shown ways to better water consumption right on the app. Different readings will be maintained for different chores(activities like washing dishes, washing fruits, bathing, restroom use) and will be regularly updated to the best reading yet. This system will have a game like implementation, thus GAMIFYING(through a leaderboard system) the whole experience. Best consumptions will be encouraged through POSITIVE REINFORCEMENT(human psychology) techniques(like giving cash backs, reimbursement of water bills, media recognition, and the likes). Note: Increasing the sensitivity of the water flow sensor can also help in detecting WATER LEAKS. User control flow user control flow Features An interface to show best consumptions in all choresjal sanrakshan home jal sanrakshan home Easy UI to identify activity.identify activity identify activity Easy and secure autheasy and secure auth easy and secure auth Strong boxing and installation of hardware system to protect from tough weather. Future:Intelligent auto selection of activities depending on the water consumption amount, time of consumption and user’s habits. Methods compareCurrentWithBest compareCurrentWithBest(int currentReading, char chore[]){ int bestReading = min(currentReading, best reading for "chore") ; update best reading for "chore" with bestReading ; } listAllReading listAllReading(char chore[]){ forEach(reading in readings){ prepend to readingList; } show readingList to user; } identifyActivity : function called to ask user to identify chore or activity in which water was used. identifyActivity(int currentReading, choreList[String]){ show user the list of chores and activity ; if(newActivity) { record current reading as best for that chore; list new activity to choreList; } else { user selects activity; compareCurrentWithBest(currentReading, chore/activity); } } Tools used JavaScript Water Flow Sensor / Fluid FLowmeter Control Switch YF-S201 Firebase Arduino Uno MongoDB Applications In Indian water storage systems to analyze water storage and improve water conservation practices. Future plans Tie ups with digital payment services like, payTM, freecharge for cash back schemes and easy bill payments. Improving the system for better and more consistent reading. Use AI to automatically detect the type of domestic activity from the water consumption reading and then work forward. This will lead to a self-sustaining system in which user has to make no effort other than improving his practices, of course . Resources: https://robu.in/product/water-flow-sensor-fluid-flowmeter-control-switch-yf-s201/ Note: This project idea is contributed by Parikshit Hooda for ProGeek Cup 2.0- A project competition by GeeksforGeeks. ProGeek 2.0 Project Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 10 Best Web Development Projects For Your Resume E-commerce Website using Django Banking Transaction System using Java Voting System Project Using Django Framework Student record management system using linked list Setup Sending Email in Django Project Browser Automation Using Selenium Handling Ajax request in Django College Management System using Django - Python Project JWT Authentication with Django REST Framework
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jul, 2018" }, { "code": null, "e": 58, "s": 28, "text": "Project Title: Jal Sanrakshan" }, { "code": null, "e": 99, "s": 58, "text": "One Line Idea: Gamify water conservation" }, { "code": null, "e": 530, "s": 99, "text": "IntroductionIndian households water use involves a water storage system called a ‘tank’ which stores water from where water is consumed. And its also the fact that we are in the midst of severe water crises, thanks to global warming and other contributing factors. Its high time everybody starts preserving water, one of the way of doing which is ‘better and conscious consumption of water’. My idea is an attempt to do just this." }, { "code": null, "e": 658, "s": 530, "text": "SolutionTo build an Arduino based app which notes down the water flow(water that came out of the tank) and sends it to the app." }, { "code": null, "e": 996, "s": 658, "text": "The app will then ask the user to tell the activity he consumed water for. The current water reading will then be compared with earlier readings to check if the water consumed was less or more than before. If less, it will be updated as the best reading yet, else the user will be shown ways to better water consumption right on the app." }, { "code": null, "e": 1181, "s": 996, "text": "Different readings will be maintained for different chores(activities like washing dishes, washing fruits, bathing, restroom use) and will be regularly updated to the best reading yet." }, { "code": null, "e": 1484, "s": 1181, "text": "This system will have a game like implementation, thus GAMIFYING(through a leaderboard system) the whole experience. Best consumptions will be encouraged through POSITIVE REINFORCEMENT(human psychology) techniques(like giving cash backs, reimbursement of water bills, media recognition, and the likes)." }, { "code": null, "e": 1582, "s": 1484, "text": "Note: Increasing the sensitivity of the water flow sensor can also help in detecting WATER LEAKS." }, { "code": null, "e": 1600, "s": 1582, "text": "User control flow" }, { "code": null, "e": 1618, "s": 1600, "text": "user control flow" }, { "code": null, "e": 1627, "s": 1618, "text": "Features" }, { "code": null, "e": 1699, "s": 1627, "text": "An interface to show best consumptions in all choresjal sanrakshan home" }, { "code": null, "e": 1719, "s": 1699, "text": "jal sanrakshan home" }, { "code": null, "e": 1766, "s": 1719, "text": "Easy UI to identify activity.identify activity" }, { "code": null, "e": 1784, "s": 1766, "text": "identify activity" }, { "code": null, "e": 1825, "s": 1784, "text": "Easy and secure autheasy and secure auth" }, { "code": null, "e": 1846, "s": 1825, "text": "easy and secure auth" }, { "code": null, "e": 1927, "s": 1846, "text": "Strong boxing and installation of hardware system to protect from tough weather." }, { "code": null, "e": 2057, "s": 1927, "text": "Future:Intelligent auto selection of activities depending on the water consumption amount, time of consumption and user’s habits." }, { "code": null, "e": 2065, "s": 2057, "text": "Methods" }, { "code": null, "e": 2088, "s": 2065, "text": "compareCurrentWithBest" }, { "code": null, "e": 2269, "s": 2088, "text": "compareCurrentWithBest(int currentReading, char chore[]){\n int bestReading = min(currentReading, best reading for \"chore\") ;\n update best reading for \"chore\" with bestReading ; \n}\n" }, { "code": null, "e": 2284, "s": 2269, "text": "listAllReading" }, { "code": null, "e": 2409, "s": 2284, "text": "listAllReading(char chore[]){\n forEach(reading in readings){\n prepend to readingList;\n }\n show readingList to user;\n}\n" }, { "code": null, "e": 2511, "s": 2409, "text": "identifyActivity : function called to ask user to identify chore or activity in which water was used." }, { "code": null, "e": 2829, "s": 2511, "text": "identifyActivity(int currentReading, choreList[String]){\n show user the list of chores and activity ;\n if(newActivity)\n {\n record current reading as best for that chore;\n list new activity to choreList;\n } else {\n user selects activity;\n compareCurrentWithBest(currentReading, chore/activity);\n }\n}\n" }, { "code": null, "e": 2840, "s": 2829, "text": "Tools used" }, { "code": null, "e": 2851, "s": 2840, "text": "JavaScript" }, { "code": null, "e": 2910, "s": 2851, "text": "Water Flow Sensor / Fluid FLowmeter Control Switch YF-S201" }, { "code": null, "e": 2919, "s": 2910, "text": "Firebase" }, { "code": null, "e": 2931, "s": 2919, "text": "Arduino Uno" }, { "code": null, "e": 2939, "s": 2931, "text": "MongoDB" }, { "code": null, "e": 2952, "s": 2939, "text": "Applications" }, { "code": null, "e": 3051, "s": 2952, "text": "In Indian water storage systems to analyze water storage and improve water conservation practices." }, { "code": null, "e": 3064, "s": 3051, "text": "Future plans" }, { "code": null, "e": 3172, "s": 3064, "text": "Tie ups with digital payment services like, payTM, freecharge for cash back schemes and easy bill payments." }, { "code": null, "e": 3233, "s": 3172, "text": "Improving the system for better and more consistent reading." }, { "code": null, "e": 3480, "s": 3233, "text": "Use AI to automatically detect the type of domestic activity from the water consumption reading and then work forward. This will lead to a self-sustaining system in which user has to make no effort other than improving his practices, of course ." }, { "code": null, "e": 3491, "s": 3480, "text": "Resources:" }, { "code": null, "e": 3573, "s": 3491, "text": "https://robu.in/product/water-flow-sensor-fluid-flowmeter-control-switch-yf-s201/" }, { "code": null, "e": 3692, "s": 3573, "text": "Note: This project idea is contributed by Parikshit Hooda for ProGeek Cup 2.0- A project competition by GeeksforGeeks." }, { "code": null, "e": 3704, "s": 3692, "text": "ProGeek 2.0" }, { "code": null, "e": 3712, "s": 3704, "text": "Project" }, { "code": null, "e": 3810, "s": 3712, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3859, "s": 3810, "text": "10 Best Web Development Projects For Your Resume" }, { "code": null, "e": 3891, "s": 3859, "text": "E-commerce Website using Django" }, { "code": null, "e": 3929, "s": 3891, "text": "Banking Transaction System using Java" }, { "code": null, "e": 3974, "s": 3929, "text": "Voting System Project Using Django Framework" }, { "code": null, "e": 4025, "s": 3974, "text": "Student record management system using linked list" }, { "code": null, "e": 4063, "s": 4025, "text": "Setup Sending Email in Django Project" }, { "code": null, "e": 4097, "s": 4063, "text": "Browser Automation Using Selenium" }, { "code": null, "e": 4129, "s": 4097, "text": "Handling Ajax request in Django" }, { "code": null, "e": 4185, "s": 4129, "text": "College Management System using Django - Python Project" } ]
What are increment (++) and decrement (--) operators in C#?
To increment a value in C#, you can use the increment operators i.e. Pre-Increment and Post-Increment Operators. The following is an example − using System; class Demo { static void Main() { int a = 250; Console.WriteLine(a); a++; Console.WriteLine(a); ++a; Console.WriteLine(a); int b = 0; b = a++; Console.WriteLine(b); Console.WriteLine(a); b = ++a; Console.WriteLine(b); Console.WriteLine(a); } } To decrement a value in C#, you can use the decrement operators i.e. Pre-Decrement and Post-Decrement Operators. The following is an example − using System; class Demo { static void Main() { int a = 250; Console.WriteLine(a); a--; Console.WriteLine(a); --a; Console.WriteLine(a); int b = 0; b = a--; Console.WriteLine(b); Console.WriteLine(a); b = --a; Console.WriteLine(b); Console.WriteLine(a); } }
[ { "code": null, "e": 1175, "s": 1062, "text": "To increment a value in C#, you can use the increment operators i.e. Pre-Increment and Post-Increment Operators." }, { "code": null, "e": 1205, "s": 1175, "text": "The following is an example −" }, { "code": null, "e": 1552, "s": 1205, "text": "using System;\n\nclass Demo {\n static void Main() {\n int a = 250;\n Console.WriteLine(a);\n\n a++;\n Console.WriteLine(a);\n\n ++a;\n Console.WriteLine(a);\n\n int b = 0;\n b = a++;\n Console.WriteLine(b);\n Console.WriteLine(a);\n\n b = ++a;\n Console.WriteLine(b);\n Console.WriteLine(a);\n }\n}" }, { "code": null, "e": 1665, "s": 1552, "text": "To decrement a value in C#, you can use the decrement operators i.e. Pre-Decrement and Post-Decrement Operators." }, { "code": null, "e": 1695, "s": 1665, "text": "The following is an example −" }, { "code": null, "e": 2042, "s": 1695, "text": "using System;\n\nclass Demo {\n static void Main() {\n int a = 250;\n Console.WriteLine(a);\n\n a--;\n Console.WriteLine(a);\n\n --a;\n Console.WriteLine(a);\n\n int b = 0;\n b = a--;\n Console.WriteLine(b);\n Console.WriteLine(a);\n\n b = --a;\n Console.WriteLine(b);\n Console.WriteLine(a);\n }\n}" } ]
Topic Modelling in Python with spaCy and Gensim | by Tarek Ghanoum | Towards Data Science
Hackers recently attacked an international company. They copied several thousand documents and published the data on the dark web. The company reached out to my employer and asked if we could go through the data to assess the type of information contained in the documents. My first thought was: Topic Modelling. Topic Modelling is a technique to extract hidden topics from large volumes of text. The technique I will be introducing is categorized as an unsupervised machine learning algorithm. The algorithm's name is Latent Dirichlet Allocation (LDA) and is part of Python's Gensim package. LDA was first developed by Blei et al. in 2003. LDA is a generative probabilistic model similar to Naive Bayes. It represents topics as word probabilities and allows for uncovering latent or hidden topics as it clusters the words based on their co-occurrence in a respective document. Using the most advanced tools on the market (i.e. PowerPoint), I created the image below depicting the overall process. I will start the process by collecting the documents (Step 1); afterwards, I will do some data cleaning and break down all the documents into tokens (Step 2). From the tokens, I can build a dictionary that gives each token a unique ID number, which can then be used to create a corpus or Bag of Words representing the frequency of the tokens (Step 3). I use my dictionary and corpus to build a range of topics and try to find the optimal number of topics (Step 4). The last step is to find the distribution of topics in each document (Step 5). Before we dive into the above-visualized steps, I will ask you to go through the code below and ensure everything is installed and imported. !pip install pyLDAvis -qq!pip install -qq -U gensim!pip install spacy -qq!pip install matplotlib -qq!pip install seaborn -qq!python -m spacy download en_core_web_md -qqimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snssns.set()import spacyimport pyLDAvis.gensim_modelspyLDAvis.enable_notebook()# Visualise inside a notebookimport en_core_web_mdfrom gensim.corpora.dictionary import Dictionaryfrom gensim.models import LdaMulticorefrom gensim.models import CoherenceModel The data I will be using contains an overview of 500 different reports, including their summaries. I have made the data available on my GitHub so feel free to follow along or download the data and edit the URL. reports = pd.read_csv('https://github.com/sg-tarek/Python/raw/main/cordis-h2020reports.gz')reports.head() The snippet above only shows the first six columns, although the data contains a total of fifteen columns. reports.info() In the field of Natural Language Processing (NLP), text preprocessing is the practice of cleaning and preparing text data. I will be using an open-source software library called spaCy to prepare the data for analysis, but other libraries such as NLTK can also be used. I told you earlier to import and download something called 'en_core_web_md' which is spaCy's pre-trained model. The model, which I will call 'nlp', can be thought of as a pipeline. When you call 'nlp' on a text or word, the text runs through a processing pipeline, which is depicted below. It means that if the text isn't tokenized, it will then be tokenized, and afterwards, different components (tagger, parser, ner etc.) will be activated. To tokenize text means turning a string or document into smaller chunks (tokens). The model is specially trained on English text (notice the 'en' in the model name), making it capable of detecting different English words. Other language models are also supported. The most interesting component in the pipeline is the tagger which assigns Part-Of-Speech (POS) tags based on SpaCy's English language model to gain a variety of annotations. A POS tag (or part-of-speech tag) is a special label assigned to each token in a text corpus to indicate the type of token (is it an adjective? Punctuation? A verb? etc.) and often also other grammatical categories such as tense, number (plural/singular), symbols etc. POS tags are used in corpus searches and in-text analysis tools and algorithms. Some of the POS tags are listed below: We can use the POS tags to preprocess the data by removing unwanted tags. Assuming we want to remove all numbers in our text, we can then point at a specific tag and remove it. I will focus on the 'summary' column, where I will tokenize, lemmatize and remove stopwords: # Our spaCy model:nlp = en_core_web_md.load()# Tags I want to remove from the textremoval= ['ADV','PRON','CCONJ','PUNCT','PART','DET','ADP','SPACE', 'NUM', 'SYM']tokens = []for summary in nlp.pipe(reports['summary']): proj_tok = [token.lemma_.lower() for token in summary if token.pos_ not in removal and not token.is_stop and token.is_alpha] tokens.append(proj_tok) Notes to expand your knowledge: You might notice the 'is_alpha' and 'is_stop', which are attributes connected to specific tokens; you can look at the full list here: https://spacy.io/api/token Another point is 'nlp.pipe', which is specifically used to process text as a sequence of strings. This is much more efficient than processing text one by one. If you're only processing a single text, simply remove the '.pipe' extension. Source: https://spacy.io/usage/processing-pipelines Let's bring the tokens back into the report by creating a new column: reports[‘tokens’] = tokensreports[‘tokens’] The two main inputs to the LDA topic model are the dictionary and the corpus: Dictionary: The idea of the dictionary is to give each token a unique ID. Corpus: Having assigned a unique ID to each token, the corpus simply contains each ID and its frequency (if you wanna dive into it, then search for Bag of Word (BoW) which will introduce you to word embedding). # I will apply the Dictionary Object from Gensim, which maps each word to their unique ID:dictionary = Dictionary(reports['tokens']) You can print the dictionary which will tell you that 8848 unique ID’s were found. We can look at some of the IDs assigned to the tokens: print(dictionary.token2id){‘available’: 0, ‘capability’: 1, ‘cea’: 2, ‘challenge’: 3, ‘chemistry’: 4, ‘chimie’: 5, ‘coating’: 6, ‘commercial’: 7, ‘company’: 8, ‘compliant’: 9, ‘concentrated’: 10, ‘conductive’: 11, ‘conductivity’: 12, ‘cost’: 13, ‘demand’: 14, ‘design’: 15, ‘dispersion’: 16, ‘easily’: 17,... I will filter out low-frequency and high-frequency tokens, also limit the vocabulary to a max of 1000 words: dictionary.filter_extremes(no_below=5, no_above=0.5, keep_n=1000) No_below: Tokens that appear in less than 5 documents are filtered out. No_above: Tokens that appear in more than 50% of the total corpus are also removed as default. Keep_n: We limit ourselves to the top 1000 most frequent tokens (default is 100.000). Set to ‘None’ if you want to keep all. We are now ready to construct the corpus using the dictionary from above and the doc2bow function. The function doc2bow() simply counts the number of occurrences of each distinct word, converts the word to its integer word id and returns the result as a sparse vector: corpus = [dictionary.doc2bow(doc) for doc in reports['tokens']] The next step is to train the unsupervised machine learning model on the data. I choose to work with the LdaMulticore, which uses all CPU cores to parallelize and speed up model training. If this doesn’t work for you for some reason, try the gensim.models.ldamodel.LdaModel class which is an equivalent, but more straightforward and single-core implementation. When inserting our corpus into the topic modelling algorithm, the corpus gets analyzed in order to find the distribution of words in each topic and the distribution of topics in each document. lda_model = LdaMulticore(corpus=corpus, id2word=dictionary, iterations=50, num_topics=10, workers = 4, passes=10) As input, I give the model our corpus and dictionary from before; besides, I choose to iterate over the corpus 50 times to optimize the model parameters (this is the default value). I select the number of topics to be ten and the workers to be 4 (find the number of cores on your PC by pressing the ctr+shift+esc keys). The pass is 10, which means the model will pass through the corpus ten times during training. Having trained the model, the next natural step is to evaluate it. After having constructed the topics, a coherence score can be computed. The score measures the degree of semantic similarity between high scoring words in each topic. In this fashion, a coherence score can be computed for each iteration by inserting a varying number of topics. A range of algorithms has been introduced to calculate the coherence score (C_v, C_p, C_uci, C_umass, C_npmi, C_a, ...). Working with the gensim library makes computing these coherence measures for topic models fairly simple. I personally choose to implement C_v and C_umass. The coherence score for C_v ranges from 0 (complete incoherence) to 1 (complete coherence). Values above 0.5 are fairly good, according to John McLevey (source: Doing Computational Social Science: A Practical Introduction By John McLevey). On the other hand, C_umass returns negative values. Below I simply iterate through a different number of topics and save the coherence score in a list. Afterwards, I plot using seaborn. Calculating the coherence score using C_umass: topics = []score = []for i in range(1,20,1): lda_model = LdaMulticore(corpus=corpus, id2word=dictionary, iterations=10, num_topics=i, workers = 4, passes=10, random_state=100) cm = CoherenceModel(model=lda_model, corpus=corpus, dictionary=dictionary, coherence='u_mass') topics.append(i) score.append(cm.get_coherence())_=plt.plot(topics, score)_=plt.xlabel('Number of Topics')_=plt.ylabel('Coherence Score')plt.show() Calculating the coherence score using C_v: topics = []score = []for i in range(1,20,1): lda_model = LdaMulticore(corpus=corpus, id2word=dictionary, iterations=10, num_topics=i, workers = 4, passes=10, random_state=100) cm = CoherenceModel(model=lda_model, texts = reports['tokens'], corpus=corpus, dictionary=dictionary, coherence='c_v') topics.append(i) score.append(cm.get_coherence())_=plt.plot(topics, score)_=plt.xlabel('Number of Topics')_=plt.ylabel('Coherence Score')plt.show() When looking at the coherence using the C_umass or C_v algorithm, the best is usually the max. Looking at the graphs I choose to go with 5 topics, although no certain answer can be given. lda_model = LdaMulticore(corpus=corpus, id2word=dictionary, iterations=100, num_topics=5, workers = 4, passes=100) We can now print out the five topics and the related words: lda_model.print_topics(-1) [(0, ‘0.015*”datum” + 0.013*”service” + 0.010*”research” + 0.010*”support” + 0.009*”european” + 0.009*”network” + 0.009*”social” + 0.009*”people” + 0.008*”provide” + 0.008*”platform”’), (1, ‘0.021*”disease” + 0.016*”patient” + 0.015*”health” + 0.015*”clinical” + 0.012*”treatment” + 0.012*”study” + 0.010*”drug” + 0.010*”cancer” + 0.009*”system” + 0.009*”care”’), (2, ‘0.021*”system” + 0.015*”technology” + 0.013*”market” + 0.013*”energy” + 0.012*”high” + 0.012*”cost” + 0.010*”product” + 0.010*”process” + 0.009*”base” + 0.009*”solution”’), (3, ‘0.034*”cell” + 0.013*”study” + 0.013*”plant” + 0.012*”new” + 0.012*”understand” + 0.010*”mechanism” + 0.009*”process” + 0.009*”human” + 0.008*”development” + 0.008*”aim”’), (4, ‘0.026*”research” + 0.024*”innovation” + 0.016*”sme” + 0.015*”market” + 0.013*”new” + 0.012*”business” + 0.011*”plan” + 0.011*”partner” + 0.011*”support” + 0.010*”development”’)] Let’s look at our first report summary: reports['summary'][0]“Polyaniline has historically been one of the most promising conductive polymers from a cost/performance perspective, but processing issues have limited its uptake. Building upon seminal work on polyaniline performed at the CEA, RESCOLL (an independent research company based in France specialized in chemistry materials) has developed and patented a new electrically conductive polyaniline formulation under the trade name of PANIPLASTTM....” According to our LDA model, the above text belongs to Topic 2 and 4. The article is 87% belonging to topic 2 (index 1) and 12% belonging to topic 4 (index 3). lda_model[corpus][0][(2, 0.870234), (4, 0.122931786)] Let’s Visualize the topics and the words in each topic. Just like we saw above, but notice that the numbers in the circles do not align with the numbers from ‘print_topics’ above: lda_display = pyLDAvis.gensim_models.prepare(lda_model, corpus, dictionary)pyLDAvis.display(lda_display) The above chart represents our five topics as circles. They have been drawn using a dimensionality reduction technique called PCA. The goal is to have a distance in order to avoid overlapping and make each circle unique. When I hover over a circle different words are displayed on the right, showing word frequency (blue) and estimated term frequency within the selected topic (red). Topics closer to each other are more related. We can create a new column in the dataframe which has the most probable topic that each article belong to. We can add the most probable topic by running through each summary text: reports['topic'] = [sorted(lda_model[corpus][text])[0][0] for text in range(len(reports['summary']))] Let’s count the frequency of each topic: reports.topic.value_counts() The count shows: Topic 1: 320 Topic 2: 86 Topic 3: 57 Topic 4: 19 Topic 5: 18 This aligns well with the visualization from before. We can share our topic visualization by uploading it to GitHub pages. Click here to see my topics and interact with them. The first step is to download the visualization we created earlier in an HTML format. It’s essential to keep the name as index.html since the GitHub pages will be looking for a file with this name: pyLDAvis.save_html(lda_display, ‘index.html’) You will need to edit the index file to make it work properly. The file contains a lot of HTML code, regardless of the content copy the lines below and add them to your file. Notice that some code is at the top, while </body> and </html> goes at the bottom: <!DOCTYPE html> <html lang="en"> <body>LDA CODE GOES HERE! </body> </html> The next step is to create a new repository on GitHub and use the following naming convention for the repo: <username>.github.io Afterwards, drop your index.html file in the repo and visit the Topic Modelling visualization on the same name as the repo: <username>.github.io. I hope you enjoyed this article as much as I have enjoyed writing it. Leave a comment if you have any difficulties understanding my code. The Data Science community has given me a lot, so I am always open to giving back. Feel free to connect with me on Linkedin and follow me on Medium to receive more articles.
[ { "code": null, "e": 485, "s": 172, "text": "Hackers recently attacked an international company. They copied several thousand documents and published the data on the dark web. The company reached out to my employer and asked if we could go through the data to assess the type of information contained in the documents. My first thought was: Topic Modelling." }, { "code": null, "e": 765, "s": 485, "text": "Topic Modelling is a technique to extract hidden topics from large volumes of text. The technique I will be introducing is categorized as an unsupervised machine learning algorithm. The algorithm's name is Latent Dirichlet Allocation (LDA) and is part of Python's Gensim package." }, { "code": null, "e": 1050, "s": 765, "text": "LDA was first developed by Blei et al. in 2003. LDA is a generative probabilistic model similar to Naive Bayes. It represents topics as word probabilities and allows for uncovering latent or hidden topics as it clusters the words based on their co-occurrence in a respective document." }, { "code": null, "e": 1714, "s": 1050, "text": "Using the most advanced tools on the market (i.e. PowerPoint), I created the image below depicting the overall process. I will start the process by collecting the documents (Step 1); afterwards, I will do some data cleaning and break down all the documents into tokens (Step 2). From the tokens, I can build a dictionary that gives each token a unique ID number, which can then be used to create a corpus or Bag of Words representing the frequency of the tokens (Step 3). I use my dictionary and corpus to build a range of topics and try to find the optimal number of topics (Step 4). The last step is to find the distribution of topics in each document (Step 5)." }, { "code": null, "e": 1855, "s": 1714, "text": "Before we dive into the above-visualized steps, I will ask you to go through the code below and ensure everything is installed and imported." }, { "code": null, "e": 2347, "s": 1855, "text": "!pip install pyLDAvis -qq!pip install -qq -U gensim!pip install spacy -qq!pip install matplotlib -qq!pip install seaborn -qq!python -m spacy download en_core_web_md -qqimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snssns.set()import spacyimport pyLDAvis.gensim_modelspyLDAvis.enable_notebook()# Visualise inside a notebookimport en_core_web_mdfrom gensim.corpora.dictionary import Dictionaryfrom gensim.models import LdaMulticorefrom gensim.models import CoherenceModel" }, { "code": null, "e": 2558, "s": 2347, "text": "The data I will be using contains an overview of 500 different reports, including their summaries. I have made the data available on my GitHub so feel free to follow along or download the data and edit the URL." }, { "code": null, "e": 2664, "s": 2558, "text": "reports = pd.read_csv('https://github.com/sg-tarek/Python/raw/main/cordis-h2020reports.gz')reports.head()" }, { "code": null, "e": 2771, "s": 2664, "text": "The snippet above only shows the first six columns, although the data contains a total of fifteen columns." }, { "code": null, "e": 2786, "s": 2771, "text": "reports.info()" }, { "code": null, "e": 3055, "s": 2786, "text": "In the field of Natural Language Processing (NLP), text preprocessing is the practice of cleaning and preparing text data. I will be using an open-source software library called spaCy to prepare the data for analysis, but other libraries such as NLTK can also be used." }, { "code": null, "e": 3580, "s": 3055, "text": "I told you earlier to import and download something called 'en_core_web_md' which is spaCy's pre-trained model. The model, which I will call 'nlp', can be thought of as a pipeline. When you call 'nlp' on a text or word, the text runs through a processing pipeline, which is depicted below. It means that if the text isn't tokenized, it will then be tokenized, and afterwards, different components (tagger, parser, ner etc.) will be activated. To tokenize text means turning a string or document into smaller chunks (tokens)." }, { "code": null, "e": 3762, "s": 3580, "text": "The model is specially trained on English text (notice the 'en' in the model name), making it capable of detecting different English words. Other language models are also supported." }, { "code": null, "e": 4286, "s": 3762, "text": "The most interesting component in the pipeline is the tagger which assigns Part-Of-Speech (POS) tags based on SpaCy's English language model to gain a variety of annotations. A POS tag (or part-of-speech tag) is a special label assigned to each token in a text corpus to indicate the type of token (is it an adjective? Punctuation? A verb? etc.) and often also other grammatical categories such as tense, number (plural/singular), symbols etc. POS tags are used in corpus searches and in-text analysis tools and algorithms." }, { "code": null, "e": 4325, "s": 4286, "text": "Some of the POS tags are listed below:" }, { "code": null, "e": 4502, "s": 4325, "text": "We can use the POS tags to preprocess the data by removing unwanted tags. Assuming we want to remove all numbers in our text, we can then point at a specific tag and remove it." }, { "code": null, "e": 4595, "s": 4502, "text": "I will focus on the 'summary' column, where I will tokenize, lemmatize and remove stopwords:" }, { "code": null, "e": 4966, "s": 4595, "text": "# Our spaCy model:nlp = en_core_web_md.load()# Tags I want to remove from the textremoval= ['ADV','PRON','CCONJ','PUNCT','PART','DET','ADP','SPACE', 'NUM', 'SYM']tokens = []for summary in nlp.pipe(reports['summary']): proj_tok = [token.lemma_.lower() for token in summary if token.pos_ not in removal and not token.is_stop and token.is_alpha] tokens.append(proj_tok)" }, { "code": null, "e": 4998, "s": 4966, "text": "Notes to expand your knowledge:" }, { "code": null, "e": 5159, "s": 4998, "text": "You might notice the 'is_alpha' and 'is_stop', which are attributes connected to specific tokens; you can look at the full list here: https://spacy.io/api/token" }, { "code": null, "e": 5448, "s": 5159, "text": "Another point is 'nlp.pipe', which is specifically used to process text as a sequence of strings. This is much more efficient than processing text one by one. If you're only processing a single text, simply remove the '.pipe' extension. Source: https://spacy.io/usage/processing-pipelines" }, { "code": null, "e": 5518, "s": 5448, "text": "Let's bring the tokens back into the report by creating a new column:" }, { "code": null, "e": 5562, "s": 5518, "text": "reports[‘tokens’] = tokensreports[‘tokens’]" }, { "code": null, "e": 5640, "s": 5562, "text": "The two main inputs to the LDA topic model are the dictionary and the corpus:" }, { "code": null, "e": 5714, "s": 5640, "text": "Dictionary: The idea of the dictionary is to give each token a unique ID." }, { "code": null, "e": 5925, "s": 5714, "text": "Corpus: Having assigned a unique ID to each token, the corpus simply contains each ID and its frequency (if you wanna dive into it, then search for Bag of Word (BoW) which will introduce you to word embedding)." }, { "code": null, "e": 6058, "s": 5925, "text": "# I will apply the Dictionary Object from Gensim, which maps each word to their unique ID:dictionary = Dictionary(reports['tokens'])" }, { "code": null, "e": 6196, "s": 6058, "text": "You can print the dictionary which will tell you that 8848 unique ID’s were found. We can look at some of the IDs assigned to the tokens:" }, { "code": null, "e": 6505, "s": 6196, "text": "print(dictionary.token2id){‘available’: 0, ‘capability’: 1, ‘cea’: 2, ‘challenge’: 3, ‘chemistry’: 4, ‘chimie’: 5, ‘coating’: 6, ‘commercial’: 7, ‘company’: 8, ‘compliant’: 9, ‘concentrated’: 10, ‘conductive’: 11, ‘conductivity’: 12, ‘cost’: 13, ‘demand’: 14, ‘design’: 15, ‘dispersion’: 16, ‘easily’: 17,..." }, { "code": null, "e": 6614, "s": 6505, "text": "I will filter out low-frequency and high-frequency tokens, also limit the vocabulary to a max of 1000 words:" }, { "code": null, "e": 6680, "s": 6614, "text": "dictionary.filter_extremes(no_below=5, no_above=0.5, keep_n=1000)" }, { "code": null, "e": 6752, "s": 6680, "text": "No_below: Tokens that appear in less than 5 documents are filtered out." }, { "code": null, "e": 6847, "s": 6752, "text": "No_above: Tokens that appear in more than 50% of the total corpus are also removed as default." }, { "code": null, "e": 6972, "s": 6847, "text": "Keep_n: We limit ourselves to the top 1000 most frequent tokens (default is 100.000). Set to ‘None’ if you want to keep all." }, { "code": null, "e": 7241, "s": 6972, "text": "We are now ready to construct the corpus using the dictionary from above and the doc2bow function. The function doc2bow() simply counts the number of occurrences of each distinct word, converts the word to its integer word id and returns the result as a sparse vector:" }, { "code": null, "e": 7305, "s": 7241, "text": "corpus = [dictionary.doc2bow(doc) for doc in reports['tokens']]" }, { "code": null, "e": 7666, "s": 7305, "text": "The next step is to train the unsupervised machine learning model on the data. I choose to work with the LdaMulticore, which uses all CPU cores to parallelize and speed up model training. If this doesn’t work for you for some reason, try the gensim.models.ldamodel.LdaModel class which is an equivalent, but more straightforward and single-core implementation." }, { "code": null, "e": 7859, "s": 7666, "text": "When inserting our corpus into the topic modelling algorithm, the corpus gets analyzed in order to find the distribution of words in each topic and the distribution of topics in each document." }, { "code": null, "e": 7973, "s": 7859, "text": "lda_model = LdaMulticore(corpus=corpus, id2word=dictionary, iterations=50, num_topics=10, workers = 4, passes=10)" }, { "code": null, "e": 8387, "s": 7973, "text": "As input, I give the model our corpus and dictionary from before; besides, I choose to iterate over the corpus 50 times to optimize the model parameters (this is the default value). I select the number of topics to be ten and the workers to be 4 (find the number of cores on your PC by pressing the ctr+shift+esc keys). The pass is 10, which means the model will pass through the corpus ten times during training." }, { "code": null, "e": 8732, "s": 8387, "text": "Having trained the model, the next natural step is to evaluate it. After having constructed the topics, a coherence score can be computed. The score measures the degree of semantic similarity between high scoring words in each topic. In this fashion, a coherence score can be computed for each iteration by inserting a varying number of topics." }, { "code": null, "e": 9300, "s": 8732, "text": "A range of algorithms has been introduced to calculate the coherence score (C_v, C_p, C_uci, C_umass, C_npmi, C_a, ...). Working with the gensim library makes computing these coherence measures for topic models fairly simple. I personally choose to implement C_v and C_umass. The coherence score for C_v ranges from 0 (complete incoherence) to 1 (complete coherence). Values above 0.5 are fairly good, according to John McLevey (source: Doing Computational Social Science: A Practical Introduction By John McLevey). On the other hand, C_umass returns negative values." }, { "code": null, "e": 9434, "s": 9300, "text": "Below I simply iterate through a different number of topics and save the coherence score in a list. Afterwards, I plot using seaborn." }, { "code": null, "e": 9481, "s": 9434, "text": "Calculating the coherence score using C_umass:" }, { "code": null, "e": 9908, "s": 9481, "text": "topics = []score = []for i in range(1,20,1): lda_model = LdaMulticore(corpus=corpus, id2word=dictionary, iterations=10, num_topics=i, workers = 4, passes=10, random_state=100) cm = CoherenceModel(model=lda_model, corpus=corpus, dictionary=dictionary, coherence='u_mass') topics.append(i) score.append(cm.get_coherence())_=plt.plot(topics, score)_=plt.xlabel('Number of Topics')_=plt.ylabel('Coherence Score')plt.show()" }, { "code": null, "e": 9951, "s": 9908, "text": "Calculating the coherence score using C_v:" }, { "code": null, "e": 10402, "s": 9951, "text": "topics = []score = []for i in range(1,20,1): lda_model = LdaMulticore(corpus=corpus, id2word=dictionary, iterations=10, num_topics=i, workers = 4, passes=10, random_state=100) cm = CoherenceModel(model=lda_model, texts = reports['tokens'], corpus=corpus, dictionary=dictionary, coherence='c_v') topics.append(i) score.append(cm.get_coherence())_=plt.plot(topics, score)_=plt.xlabel('Number of Topics')_=plt.ylabel('Coherence Score')plt.show()" }, { "code": null, "e": 10590, "s": 10402, "text": "When looking at the coherence using the C_umass or C_v algorithm, the best is usually the max. Looking at the graphs I choose to go with 5 topics, although no certain answer can be given." }, { "code": null, "e": 10705, "s": 10590, "text": "lda_model = LdaMulticore(corpus=corpus, id2word=dictionary, iterations=100, num_topics=5, workers = 4, passes=100)" }, { "code": null, "e": 10765, "s": 10705, "text": "We can now print out the five topics and the related words:" }, { "code": null, "e": 10792, "s": 10765, "text": "lda_model.print_topics(-1)" }, { "code": null, "e": 10978, "s": 10792, "text": "[(0, ‘0.015*”datum” + 0.013*”service” + 0.010*”research” + 0.010*”support” + 0.009*”european” + 0.009*”network” + 0.009*”social” + 0.009*”people” + 0.008*”provide” + 0.008*”platform”’)," }, { "code": null, "e": 11156, "s": 10978, "text": "(1, ‘0.021*”disease” + 0.016*”patient” + 0.015*”health” + 0.015*”clinical” + 0.012*”treatment” + 0.012*”study” + 0.010*”drug” + 0.010*”cancer” + 0.009*”system” + 0.009*”care”’)," }, { "code": null, "e": 11334, "s": 11156, "text": "(2, ‘0.021*”system” + 0.015*”technology” + 0.013*”market” + 0.013*”energy” + 0.012*”high” + 0.012*”cost” + 0.010*”product” + 0.010*”process” + 0.009*”base” + 0.009*”solution”’)," }, { "code": null, "e": 11512, "s": 11334, "text": "(3, ‘0.034*”cell” + 0.013*”study” + 0.013*”plant” + 0.012*”new” + 0.012*”understand” + 0.010*”mechanism” + 0.009*”process” + 0.009*”human” + 0.008*”development” + 0.008*”aim”’)," }, { "code": null, "e": 11695, "s": 11512, "text": "(4, ‘0.026*”research” + 0.024*”innovation” + 0.016*”sme” + 0.015*”market” + 0.013*”new” + 0.012*”business” + 0.011*”plan” + 0.011*”partner” + 0.011*”support” + 0.010*”development”’)]" }, { "code": null, "e": 11735, "s": 11695, "text": "Let’s look at our first report summary:" }, { "code": null, "e": 12200, "s": 11735, "text": "reports['summary'][0]“Polyaniline has historically been one of the most promising conductive polymers from a cost/performance perspective, but processing issues have limited its uptake. Building upon seminal work on polyaniline performed at the CEA, RESCOLL (an independent research company based in France specialized in chemistry materials) has developed and patented a new electrically conductive polyaniline formulation under the trade name of PANIPLASTTM....”" }, { "code": null, "e": 12359, "s": 12200, "text": "According to our LDA model, the above text belongs to Topic 2 and 4. The article is 87% belonging to topic 2 (index 1) and 12% belonging to topic 4 (index 3)." }, { "code": null, "e": 12413, "s": 12359, "text": "lda_model[corpus][0][(2, 0.870234), (4, 0.122931786)]" }, { "code": null, "e": 12593, "s": 12413, "text": "Let’s Visualize the topics and the words in each topic. Just like we saw above, but notice that the numbers in the circles do not align with the numbers from ‘print_topics’ above:" }, { "code": null, "e": 12698, "s": 12593, "text": "lda_display = pyLDAvis.gensim_models.prepare(lda_model, corpus, dictionary)pyLDAvis.display(lda_display)" }, { "code": null, "e": 13128, "s": 12698, "text": "The above chart represents our five topics as circles. They have been drawn using a dimensionality reduction technique called PCA. The goal is to have a distance in order to avoid overlapping and make each circle unique. When I hover over a circle different words are displayed on the right, showing word frequency (blue) and estimated term frequency within the selected topic (red). Topics closer to each other are more related." }, { "code": null, "e": 13308, "s": 13128, "text": "We can create a new column in the dataframe which has the most probable topic that each article belong to. We can add the most probable topic by running through each summary text:" }, { "code": null, "e": 13410, "s": 13308, "text": "reports['topic'] = [sorted(lda_model[corpus][text])[0][0] for text in range(len(reports['summary']))]" }, { "code": null, "e": 13451, "s": 13410, "text": "Let’s count the frequency of each topic:" }, { "code": null, "e": 13480, "s": 13451, "text": "reports.topic.value_counts()" }, { "code": null, "e": 13497, "s": 13480, "text": "The count shows:" }, { "code": null, "e": 13510, "s": 13497, "text": "Topic 1: 320" }, { "code": null, "e": 13522, "s": 13510, "text": "Topic 2: 86" }, { "code": null, "e": 13534, "s": 13522, "text": "Topic 3: 57" }, { "code": null, "e": 13546, "s": 13534, "text": "Topic 4: 19" }, { "code": null, "e": 13558, "s": 13546, "text": "Topic 5: 18" }, { "code": null, "e": 13611, "s": 13558, "text": "This aligns well with the visualization from before." }, { "code": null, "e": 13733, "s": 13611, "text": "We can share our topic visualization by uploading it to GitHub pages. Click here to see my topics and interact with them." }, { "code": null, "e": 13931, "s": 13733, "text": "The first step is to download the visualization we created earlier in an HTML format. It’s essential to keep the name as index.html since the GitHub pages will be looking for a file with this name:" }, { "code": null, "e": 13977, "s": 13931, "text": "pyLDAvis.save_html(lda_display, ‘index.html’)" }, { "code": null, "e": 14235, "s": 13977, "text": "You will need to edit the index file to make it work properly. The file contains a lot of HTML code, regardless of the content copy the lines below and add them to your file. Notice that some code is at the top, while </body> and </html> goes at the bottom:" }, { "code": null, "e": 14321, "s": 14235, "text": "<!DOCTYPE html> <html lang=\"en\"> <body>LDA CODE GOES HERE! </body> </html>" }, { "code": null, "e": 14429, "s": 14321, "text": "The next step is to create a new repository on GitHub and use the following naming convention for the repo:" }, { "code": null, "e": 14450, "s": 14429, "text": "<username>.github.io" }, { "code": null, "e": 14596, "s": 14450, "text": "Afterwards, drop your index.html file in the repo and visit the Topic Modelling visualization on the same name as the repo: <username>.github.io." }, { "code": null, "e": 14817, "s": 14596, "text": "I hope you enjoyed this article as much as I have enjoyed writing it. Leave a comment if you have any difficulties understanding my code. The Data Science community has given me a lot, so I am always open to giving back." } ]
Running chrome browser in inconginto Mode in Selenium
We can run Chrome browser Incognito mode with Selenium webdriver. Incognito mode is a safe mode of opening a browser. This can be done with the help of the DesiredCapabilities and ChromeOptions class. We shall create an object of the ChromeOptions class and apply addArguments method on it. Then pass −−incognito as a parameter to that method. We shall then create an object of the DesiredCapabilities class. We shall apply setCapability method on the object of the DesiredCapabilities class and pass the ChromeOptions.CAPABILITY and the object of ChromeOptions class as parameters to that method. Finally, this browser chrome profile shall be fed to the webdriver object. ChromeOptions o= new ChromeOptions(); o.addArguments("−−incognito"); DesiredCapabilities c = DesiredCapabilities.chrome(); c.setCapability(ChromeOptions.CAPABILITY, o); WebDriver driver = new ChromeDriver(o); import org.openqa.selenium.WebDriver; import org.openqa.selenium.Capabilities; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; public class BrwIncognt{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); // configure options parameter to Chrome driver ChromeOptions o= new ChromeOptions(); // add Incognito parameter o.addArguments("--incognito"); // DesiredCapabilities object DesiredCapabilities c = DesiredCapabilities.chrome(); //set capability to browser c.setCapability(ChromeOptions.CAPABILITY, o); WebDriver driver = new ChromeDriver(o); driver.get("https://www.tutorialspoint.com/index.htm "); } }
[ { "code": null, "e": 1263, "s": 1062, "text": "We can run Chrome browser Incognito mode with Selenium webdriver. Incognito mode is a safe mode of opening a browser. This can be done with the help of the DesiredCapabilities and ChromeOptions class." }, { "code": null, "e": 1471, "s": 1263, "text": "We shall create an object of the ChromeOptions class and apply addArguments method on it. Then pass −−incognito as a parameter to that method. We shall then create an object of the DesiredCapabilities class." }, { "code": null, "e": 1660, "s": 1471, "text": "We shall apply setCapability method on the object of the DesiredCapabilities class and pass the ChromeOptions.CAPABILITY and the object of ChromeOptions class as parameters to that method." }, { "code": null, "e": 1735, "s": 1660, "text": "Finally, this browser chrome profile shall be fed to the webdriver object." }, { "code": null, "e": 1944, "s": 1735, "text": "ChromeOptions o= new ChromeOptions();\no.addArguments(\"−−incognito\");\nDesiredCapabilities c = DesiredCapabilities.chrome();\nc.setCapability(ChromeOptions.CAPABILITY, o);\nWebDriver driver = new ChromeDriver(o);" }, { "code": null, "e": 2874, "s": 1944, "text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.Capabilities;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.chrome.ChromeOptions;\nimport org.openqa.selenium.remote.CapabilityType;\nimport org.openqa.selenium.remote.DesiredCapabilities;\npublic class BrwIncognt{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n // configure options parameter to Chrome driver\n ChromeOptions o= new ChromeOptions();\n // add Incognito parameter\n o.addArguments(\"--incognito\");\n // DesiredCapabilities object\n DesiredCapabilities c = DesiredCapabilities.chrome();\n //set capability to browser\n c.setCapability(ChromeOptions.CAPABILITY, o);\n WebDriver driver = new ChromeDriver(o);\n driver.get(\"https://www.tutorialspoint.com/index.htm \");\n }\n}" } ]
How to format date and time in android?
This example demonstrates how do I format date and time 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" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAlignment="center" android:textSize="16sp" android:textStyle="bold|italic" android:layout_centerInParent="true" /> </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.SimpleDateFormat; import java.util.Calendar; public class MainActivity extends AppCompatActivity { TextView textView; String dateTime; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); Calendar calendar = Calendar.getInstance(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE, dd-MMM-yyyy hh-mm-ss a"); dateTime = simpleDateFormat.format(calendar.getTime()); textView.setText(dateTime); } } 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 – Click here to download the project code.
[ { "code": null, "e": 1130, "s": 1062, "text": "This example demonstrates how do I format date and time in android." }, { "code": null, "e": 1259, "s": 1130, "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": 1324, "s": 1259, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1901, "s": 1324, "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 tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:textAlignment=\"center\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold|italic\"\n android:layout_centerInParent=\"true\" />\n</RelativeLayout>" }, { "code": null, "e": 1958, "s": 1901, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2675, "s": 1958, "text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.TextView;\nimport java.text.SimpleDateFormat;\nimport java.util.Calendar;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n String dateTime;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.textView);\n Calendar calendar = Calendar.getInstance();\n SimpleDateFormat simpleDateFormat = new SimpleDateFormat(\"EEEE, dd-MMM-yyyy hh-mm-ss a\");\n dateTime = simpleDateFormat.format(calendar.getTime());\n textView.setText(dateTime);\n }\n}" }, { "code": null, "e": 2730, "s": 2675, "text": "Step 4 - Add the following code to androidManifest.xml" }, { "code": null, "e": 3400, "s": 2730, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 3747, "s": 3400, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 3788, "s": 3747, "text": "Click here to download the project code." } ]
Sentence classification using Bi-LSTM | by akshay uppal | Towards Data Science
So there are various ways for sentence classification like a bag of words approach or neural networks etc. In this article, I would be discussing mainly the sentence classification task using deep learning model (specifically Bi-LSTM) This article mainly is concerned with some basic introduction and jumps right into implementation. If you need in-depth information, I have included the links in the references. I have organized the articles in various categories, introductionimplementation: (preprocessing and baseline model)Bi-LSTM modelresults and conclusion introduction implementation: (preprocessing and baseline model) Bi-LSTM model results and conclusion Feel free to jump in a specific category. I. INTRODUCTION For sentence classification we have mainly two ways: Bag of words model (BOW)Deep neural network models Bag of words model (BOW) Deep neural network models The BOW model works by treating each word separately and encoding each of the words. For BOW approach we can use TF-IDF methods but it doesn’t preserve the context of each word in the sentences. So to achieve better performance for the task like named entity extraction, sentiment analysis, we use deep neural networks. Dataset: In this article I have used the Reddit -dataset[2] which is based on four emotion categories like rage, happy, gore and creepy. For the deep neural models, we need embeddings for the text. Embeddings capture the representation of the word in higher dimensional plane. Through embeddings, we create a vector representation of the word which is learned by understanding the context of words. We can either use pre-trained embeddings like the glove, fasttext which are trained on billion of documents or we can create our own embeddings (trained on our own corpus) using gensim package etc. In this article, I have used pre-trained glove-twitter embeddings which is suitable in our context of the social network data. Also, I choose 100-Dimensional embeddings which performs pretty good without taking too much time to train. You can choose other (25, 50, 300 D as well). embedding_path = "~/glove.twitter.27B.100d.txt" ## change # create the word2vec dict from the dictionarydef get_word2vec(file_path): file = open(embedding_path, "r") if (file): word2vec = dict() split = file.read().splitlines() for line in split: key = line.split(' ',1)[0] # the first word is the key value = np.array([float(val) for val in line.split(' ')[1:]]) word2vec[key] = value return (word2vec) else: print("invalid fiel path")w2v = get_word2vec(embedding_path) Preprocessing the text: So their data has four files representing four different emotions so we need to merge the files for the multi-category classification task. df_rage = pd.read_csv(os.path.join(dir_path,'processed_rage.csv'))df_happy = pd.read_csv(os.path.join(dir_path,'processed_happy.csv'))df_gore = pd.read_csv(os.path.join(dir_path,'processed_gore.csv'))df_creepy = pd.read_csv(os.path.join(dir_path,'processed_creepy.csv'))# create a random balances dataset of all of the categorieslength = np.min([len(df_rage),len(df_happy),len(df_creepy),len(df_gore)])df_final = pd.concat([df_rage[:length], df_happy[:length], df_gore[:length], df_creepy[:length]], ignore_index=True) Tokenizing : To break the sentences into simpler tokens or words we tokenize the text. In here we will be using nltk Tweet tokenizer as it works great with social network data. import nltkfrom nltk.corpus import stopwordsstopwords = set(stopwords.words('english'))nltk.download('wordnet')nltk.download('stopwords')from nltk.tokenize import TweetTokenizerfrom nltk.corpus import wordnet as wntknzr = TweetTokenizer()def get_tokens(sentence):# tokens = nltk.word_tokenize(sentence) # now using tweet tokenizer tokens = tknzr.tokenize(sentence) tokens = [token for token in tokens if (token not in stopwords and len(token) > 1)] tokens = [get_lemma(token) for token in tokens] return (tokens)def get_lemma(word): lemma = wn.morphy(word) if lemma is None: return word else: return lemmatoken_list = (df_final['title'].apply(get_tokens)) Preparing the input variable # integer encode the documentsencoded_docs = t.texts_to_sequences(sentences)# pad documents to a max length of 4 wordsmax_length = max_lenX = pad_sequences(encoded_docs, maxlen=max_length, padding='post') Output variable: from sklearn import preprocessingle = preprocessing.LabelEncoder()Y_new = df_final['subreddit']Y_new = le.fit_transform(Y_new) Splitting the data to training and testing ## now splitting into test and training datafrom sklearn.model_selection import train_test_splitX_train,X_test, Y_train, Y_test = train_test_split(X, y,test_size =0.20,random_state= 4 ) Baseline models Before getting the scores with the LSTM model I have got some metrics from our baseline models: For the baseline models, we can calculate simply the mean of the word2vec embeddings. # the object is a word2vec dictionary with value as array vector,# creates a mean of word vecotr for sentencesclass MeanVect(object): def __init__(self, word2vec): self.word2vec = word2vec # if a text is empty we should return a vector of zeros # with the same dimensionality as all the other vectors self.dim = len(next(iter(word2vec.values()))) # pass a word list def transform(self, X): return np.array([ np.mean([self.word2vec[w] for w in words if w in self.word2vec] or [np.zeros(self.dim)], axis=0) for words in (X) ]) SVM def svm_wrapper(X_train,Y_train): param_grid = [ {'C': [1, 10], 'kernel': ['linear']}, {'C': [1, 10], 'gamma': [0.1,0.01], 'kernel': ['rbf']},] svm = GridSearchCV(SVC(),param_grid) svm.fit(X_train, Y_train) return(svm) Metrics # svmsvm = svm_wrapper(X_train,Y_train)Y_pred = svm.predict(X_test)score = accuracy_score(Y_test,Y_pred)print("accuarcy :", score)0.70 For baselines, you can further apply other classifiers (like random forest etc)but I got the best F1 score with SVM. For the neural models in the language context, most popular are LSTMs (Long short term memory) which are a type of RNN (Recurrent neural network), which preserve the long term dependency of text. I have included the links in references which seem to explain LSTM’s in great detail. III. Bidirectional LSTM: For the bidirectional LSTM we have an embedding layer and instead of loading random weight we will load the weights from our glove embeddings # get the embedding matrix from the embedding layerfrom numpy import zerosembedding_matrix = zeros((vocab_size, 100))for word, i in t.word_index.items(): embedding_vector = w2v.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector We also want to calculate the vocab size for neural model. from keras.preprocessing.text import Tokenizerfrom keras.preprocessing.sequence import pad_sequences# prepare tokenizert = Tokenizer()t.fit_on_texts(token_list)vocab_size = len(t.word_index) + 1# integer encode the documentsencoded_docs = t.texts_to_sequences(sentences)# pad documents to a max length of 4 wordsmax_length = max_lenX = pad_sequences(encoded_docs, maxlen=max_length, padding='post')y = Y_new Final Model # main modelinput = Input(shape=(max_len,))model = Embedding(vocab_size,100,weights=[embedding_matrix],input_length=max_len)(input)model = Bidirectional (LSTM (100,return_sequences=True,dropout=0.50),merge_mode='concat')(model)model = TimeDistributed(Dense(100,activation='relu'))(model)model = Flatten()(model)model = Dense(100,activation='relu')(model)output = Dense(3,activation='softmax')(model)model = Model(input,output)model.compile(loss='sparse_categorical_crossentropy',optimizer='adam', metrics=['accuracy']) The max_len above have to be fixed for our neural model, which could be the sentence with max no of words or could be a static value. I defined it as 60. model summary — - Layer (type) Output Shape Param # =================================================================input_32 (InputLayer) (None, 60) 0 _________________________________________________________________embedding_34 (Embedding) (None, 60, 100) 284300 _________________________________________________________________bidirectional_29 (Bidirectio (None, 60, 200) 160800 _________________________________________________________________time_distributed_28 (TimeDis (None, 60, 100) 20100 _________________________________________________________________flatten_24 (Flatten) (None, 6000) 0 _________________________________________________________________dense_76 (Dense) (None, 100) 600100 _________________________________________________________________dense_77 (Dense) (None, 3) 303 =================================================================Total params: 1,065,603Trainable params: 1,065,603Non-trainable params: 0_________________________________________________________________ So in the paper for neral architecture for ner model [1] they use a CRF layer on top of Bi-LSTM but for simple multi categorical sentence classification, we can skip that. Fit the training data to the model: model.fit(X_train,Y_train,validation_split=0.25, nb_epoch = 10, verbose = 2) IV: RESULTS Evaluating the mode # evaluate the modelloss, accuracy = model.evaluate(X_test, Y_test, verbose=2)print('Accuracy: %f' % (accuracy*100))Accuracy: 74.593496 Classification report from sklearn.metrics import classification_report,confusion_matrixY_pred = model.predict(X_test)y_pred = np.array([np.argmax(pred) for pred in Y_pred])print(' Classification Report:\n',classification_report(Y_test,y_pred),'\n')Classification Report: precision recall f1-score support 0 0.74 0.72 0.73 129 1 0.75 0.64 0.69 106 2 0.76 0.89 0.82 127 3 0.73 0.72 0.72 130 micro avg 0.75 0.75 0.75 492 macro avg 0.75 0.74 0.74 492weighted avg 0.75 0.75 0.74 492 Conclusion: So we saw for the neural models that preserve the sequence of text and their context, we get better scores as compared BOW models but it depends on the context and application. So in some cases, it might be beneficial to have simple models as compared to complex neural models. Also, we had a smaller dataset so the training time was quite low but for larger datasets ( > 100k ), it might take more than 1 hour of training. Hope you enjoyed, if you have any doubts or comments please feel free to add to the comment section. Thanks. References: [1]: Lample, Guillaume, Miguel Ballesteros, Sandeep Subramanian, Kazuya Kawakami, and Chris Dyer. “Neural architectures for named entity recognition.” arXiv preprint arXiv:1603.01360 (2016). [2] Duong, Chi Thang, Remi Lebret, and Karl Aberer. “Multimodal Classification for Analysing Social Media.” The 27th European Conference on Machine Learning and Principles and Practice of Knowledge Discovery in Databases (ECML-PKDD), 2017
[ { "code": null, "e": 407, "s": 172, "text": "So there are various ways for sentence classification like a bag of words approach or neural networks etc. In this article, I would be discussing mainly the sentence classification task using deep learning model (specifically Bi-LSTM)" }, { "code": null, "e": 585, "s": 407, "text": "This article mainly is concerned with some basic introduction and jumps right into implementation. If you need in-depth information, I have included the links in the references." }, { "code": null, "e": 638, "s": 585, "text": "I have organized the articles in various categories," }, { "code": null, "e": 736, "s": 638, "text": "introductionimplementation: (preprocessing and baseline model)Bi-LSTM modelresults and conclusion" }, { "code": null, "e": 749, "s": 736, "text": "introduction" }, { "code": null, "e": 800, "s": 749, "text": "implementation: (preprocessing and baseline model)" }, { "code": null, "e": 814, "s": 800, "text": "Bi-LSTM model" }, { "code": null, "e": 837, "s": 814, "text": "results and conclusion" }, { "code": null, "e": 879, "s": 837, "text": "Feel free to jump in a specific category." }, { "code": null, "e": 895, "s": 879, "text": "I. INTRODUCTION" }, { "code": null, "e": 948, "s": 895, "text": "For sentence classification we have mainly two ways:" }, { "code": null, "e": 999, "s": 948, "text": "Bag of words model (BOW)Deep neural network models" }, { "code": null, "e": 1024, "s": 999, "text": "Bag of words model (BOW)" }, { "code": null, "e": 1051, "s": 1024, "text": "Deep neural network models" }, { "code": null, "e": 1246, "s": 1051, "text": "The BOW model works by treating each word separately and encoding each of the words. For BOW approach we can use TF-IDF methods but it doesn’t preserve the context of each word in the sentences." }, { "code": null, "e": 1371, "s": 1246, "text": "So to achieve better performance for the task like named entity extraction, sentiment analysis, we use deep neural networks." }, { "code": null, "e": 1380, "s": 1371, "text": "Dataset:" }, { "code": null, "e": 1508, "s": 1380, "text": "In this article I have used the Reddit -dataset[2] which is based on four emotion categories like rage, happy, gore and creepy." }, { "code": null, "e": 1968, "s": 1508, "text": "For the deep neural models, we need embeddings for the text. Embeddings capture the representation of the word in higher dimensional plane. Through embeddings, we create a vector representation of the word which is learned by understanding the context of words. We can either use pre-trained embeddings like the glove, fasttext which are trained on billion of documents or we can create our own embeddings (trained on our own corpus) using gensim package etc." }, { "code": null, "e": 2249, "s": 1968, "text": "In this article, I have used pre-trained glove-twitter embeddings which is suitable in our context of the social network data. Also, I choose 100-Dimensional embeddings which performs pretty good without taking too much time to train. You can choose other (25, 50, 300 D as well)." }, { "code": null, "e": 2797, "s": 2249, "text": "embedding_path = \"~/glove.twitter.27B.100d.txt\" ## change # create the word2vec dict from the dictionarydef get_word2vec(file_path): file = open(embedding_path, \"r\") if (file): word2vec = dict() split = file.read().splitlines() for line in split: key = line.split(' ',1)[0] # the first word is the key value = np.array([float(val) for val in line.split(' ')[1:]]) word2vec[key] = value return (word2vec) else: print(\"invalid fiel path\")w2v = get_word2vec(embedding_path)" }, { "code": null, "e": 2821, "s": 2797, "text": "Preprocessing the text:" }, { "code": null, "e": 2961, "s": 2821, "text": "So their data has four files representing four different emotions so we need to merge the files for the multi-category classification task." }, { "code": null, "e": 3483, "s": 2961, "text": "df_rage = pd.read_csv(os.path.join(dir_path,'processed_rage.csv'))df_happy = pd.read_csv(os.path.join(dir_path,'processed_happy.csv'))df_gore = pd.read_csv(os.path.join(dir_path,'processed_gore.csv'))df_creepy = pd.read_csv(os.path.join(dir_path,'processed_creepy.csv'))# create a random balances dataset of all of the categorieslength = np.min([len(df_rage),len(df_happy),len(df_creepy),len(df_gore)])df_final = pd.concat([df_rage[:length], df_happy[:length], df_gore[:length], df_creepy[:length]], ignore_index=True)" }, { "code": null, "e": 3496, "s": 3483, "text": "Tokenizing :" }, { "code": null, "e": 3660, "s": 3496, "text": "To break the sentences into simpler tokens or words we tokenize the text. In here we will be using nltk Tweet tokenizer as it works great with social network data." }, { "code": null, "e": 4356, "s": 3660, "text": "import nltkfrom nltk.corpus import stopwordsstopwords = set(stopwords.words('english'))nltk.download('wordnet')nltk.download('stopwords')from nltk.tokenize import TweetTokenizerfrom nltk.corpus import wordnet as wntknzr = TweetTokenizer()def get_tokens(sentence):# tokens = nltk.word_tokenize(sentence) # now using tweet tokenizer tokens = tknzr.tokenize(sentence) tokens = [token for token in tokens if (token not in stopwords and len(token) > 1)] tokens = [get_lemma(token) for token in tokens] return (tokens)def get_lemma(word): lemma = wn.morphy(word) if lemma is None: return word else: return lemmatoken_list = (df_final['title'].apply(get_tokens))" }, { "code": null, "e": 4385, "s": 4356, "text": "Preparing the input variable" }, { "code": null, "e": 4590, "s": 4385, "text": "# integer encode the documentsencoded_docs = t.texts_to_sequences(sentences)# pad documents to a max length of 4 wordsmax_length = max_lenX = pad_sequences(encoded_docs, maxlen=max_length, padding='post')" }, { "code": null, "e": 4607, "s": 4590, "text": "Output variable:" }, { "code": null, "e": 4734, "s": 4607, "text": "from sklearn import preprocessingle = preprocessing.LabelEncoder()Y_new = df_final['subreddit']Y_new = le.fit_transform(Y_new)" }, { "code": null, "e": 4777, "s": 4734, "text": "Splitting the data to training and testing" }, { "code": null, "e": 4964, "s": 4777, "text": "## now splitting into test and training datafrom sklearn.model_selection import train_test_splitX_train,X_test, Y_train, Y_test = train_test_split(X, y,test_size =0.20,random_state= 4 )" }, { "code": null, "e": 4980, "s": 4964, "text": "Baseline models" }, { "code": null, "e": 5076, "s": 4980, "text": "Before getting the scores with the LSTM model I have got some metrics from our baseline models:" }, { "code": null, "e": 5162, "s": 5076, "text": "For the baseline models, we can calculate simply the mean of the word2vec embeddings." }, { "code": null, "e": 5787, "s": 5162, "text": "# the object is a word2vec dictionary with value as array vector,# creates a mean of word vecotr for sentencesclass MeanVect(object): def __init__(self, word2vec): self.word2vec = word2vec # if a text is empty we should return a vector of zeros # with the same dimensionality as all the other vectors self.dim = len(next(iter(word2vec.values()))) # pass a word list def transform(self, X): return np.array([ np.mean([self.word2vec[w] for w in words if w in self.word2vec] or [np.zeros(self.dim)], axis=0) for words in (X) ])" }, { "code": null, "e": 5791, "s": 5787, "text": "SVM" }, { "code": null, "e": 6028, "s": 5791, "text": "def svm_wrapper(X_train,Y_train): param_grid = [ {'C': [1, 10], 'kernel': ['linear']}, {'C': [1, 10], 'gamma': [0.1,0.01], 'kernel': ['rbf']},] svm = GridSearchCV(SVC(),param_grid) svm.fit(X_train, Y_train) return(svm)" }, { "code": null, "e": 6036, "s": 6028, "text": "Metrics" }, { "code": null, "e": 6171, "s": 6036, "text": "# svmsvm = svm_wrapper(X_train,Y_train)Y_pred = svm.predict(X_test)score = accuracy_score(Y_test,Y_pred)print(\"accuarcy :\", score)0.70" }, { "code": null, "e": 6288, "s": 6171, "text": "For baselines, you can further apply other classifiers (like random forest etc)but I got the best F1 score with SVM." }, { "code": null, "e": 6570, "s": 6288, "text": "For the neural models in the language context, most popular are LSTMs (Long short term memory) which are a type of RNN (Recurrent neural network), which preserve the long term dependency of text. I have included the links in references which seem to explain LSTM’s in great detail." }, { "code": null, "e": 6595, "s": 6570, "text": "III. Bidirectional LSTM:" }, { "code": null, "e": 6737, "s": 6595, "text": "For the bidirectional LSTM we have an embedding layer and instead of loading random weight we will load the weights from our glove embeddings" }, { "code": null, "e": 6997, "s": 6737, "text": "# get the embedding matrix from the embedding layerfrom numpy import zerosembedding_matrix = zeros((vocab_size, 100))for word, i in t.word_index.items(): embedding_vector = w2v.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector" }, { "code": null, "e": 7056, "s": 6997, "text": "We also want to calculate the vocab size for neural model." }, { "code": null, "e": 7464, "s": 7056, "text": "from keras.preprocessing.text import Tokenizerfrom keras.preprocessing.sequence import pad_sequences# prepare tokenizert = Tokenizer()t.fit_on_texts(token_list)vocab_size = len(t.word_index) + 1# integer encode the documentsencoded_docs = t.texts_to_sequences(sentences)# pad documents to a max length of 4 wordsmax_length = max_lenX = pad_sequences(encoded_docs, maxlen=max_length, padding='post')y = Y_new" }, { "code": null, "e": 7476, "s": 7464, "text": "Final Model" }, { "code": null, "e": 7996, "s": 7476, "text": "# main modelinput = Input(shape=(max_len,))model = Embedding(vocab_size,100,weights=[embedding_matrix],input_length=max_len)(input)model = Bidirectional (LSTM (100,return_sequences=True,dropout=0.50),merge_mode='concat')(model)model = TimeDistributed(Dense(100,activation='relu'))(model)model = Flatten()(model)model = Dense(100,activation='relu')(model)output = Dense(3,activation='softmax')(model)model = Model(input,output)model.compile(loss='sparse_categorical_crossentropy',optimizer='adam', metrics=['accuracy'])" }, { "code": null, "e": 8150, "s": 7996, "text": "The max_len above have to be fixed for our neural model, which could be the sentence with max no of words or could be a static value. I defined it as 60." }, { "code": null, "e": 8168, "s": 8150, "text": "model summary — -" }, { "code": null, "e": 9347, "s": 8168, "text": "Layer (type) Output Shape Param # =================================================================input_32 (InputLayer) (None, 60) 0 _________________________________________________________________embedding_34 (Embedding) (None, 60, 100) 284300 _________________________________________________________________bidirectional_29 (Bidirectio (None, 60, 200) 160800 _________________________________________________________________time_distributed_28 (TimeDis (None, 60, 100) 20100 _________________________________________________________________flatten_24 (Flatten) (None, 6000) 0 _________________________________________________________________dense_76 (Dense) (None, 100) 600100 _________________________________________________________________dense_77 (Dense) (None, 3) 303 =================================================================Total params: 1,065,603Trainable params: 1,065,603Non-trainable params: 0_________________________________________________________________" }, { "code": null, "e": 9519, "s": 9347, "text": "So in the paper for neral architecture for ner model [1] they use a CRF layer on top of Bi-LSTM but for simple multi categorical sentence classification, we can skip that." }, { "code": null, "e": 9555, "s": 9519, "text": "Fit the training data to the model:" }, { "code": null, "e": 9632, "s": 9555, "text": "model.fit(X_train,Y_train,validation_split=0.25, nb_epoch = 10, verbose = 2)" }, { "code": null, "e": 9644, "s": 9632, "text": "IV: RESULTS" }, { "code": null, "e": 9664, "s": 9644, "text": "Evaluating the mode" }, { "code": null, "e": 9800, "s": 9664, "text": "# evaluate the modelloss, accuracy = model.evaluate(X_test, Y_test, verbose=2)print('Accuracy: %f' % (accuracy*100))Accuracy: 74.593496" }, { "code": null, "e": 9822, "s": 9800, "text": "Classification report" }, { "code": null, "e": 10498, "s": 9822, "text": "from sklearn.metrics import classification_report,confusion_matrixY_pred = model.predict(X_test)y_pred = np.array([np.argmax(pred) for pred in Y_pred])print(' Classification Report:\\n',classification_report(Y_test,y_pred),'\\n')Classification Report: precision recall f1-score support 0 0.74 0.72 0.73 129 1 0.75 0.64 0.69 106 2 0.76 0.89 0.82 127 3 0.73 0.72 0.72 130 micro avg 0.75 0.75 0.75 492 macro avg 0.75 0.74 0.74 492weighted avg 0.75 0.75 0.74 492" }, { "code": null, "e": 10510, "s": 10498, "text": "Conclusion:" }, { "code": null, "e": 10934, "s": 10510, "text": "So we saw for the neural models that preserve the sequence of text and their context, we get better scores as compared BOW models but it depends on the context and application. So in some cases, it might be beneficial to have simple models as compared to complex neural models. Also, we had a smaller dataset so the training time was quite low but for larger datasets ( > 100k ), it might take more than 1 hour of training." }, { "code": null, "e": 11043, "s": 10934, "text": "Hope you enjoyed, if you have any doubts or comments please feel free to add to the comment section. Thanks." }, { "code": null, "e": 11055, "s": 11043, "text": "References:" }, { "code": null, "e": 11246, "s": 11055, "text": "[1]: Lample, Guillaume, Miguel Ballesteros, Sandeep Subramanian, Kazuya Kawakami, and Chris Dyer. “Neural architectures for named entity recognition.” arXiv preprint arXiv:1603.01360 (2016)." } ]
SQLite - Useful Functions
SQLite has many built-in functions to perform processing on string or numeric data. Following is the list of few useful SQLite built-in functions and all are case in-sensitive which means you can use these functions either in lower-case form or in upper-case or in mixed form. For more details, you can check official documentation for SQLite. SQLite COUNT Function SQLite COUNT aggregate function is used to count the number of rows in a database table. SQLite MAX Function SQLite MAX aggregate function allows us to select the highest (maximum) value for a certain column. SQLite MIN Function SQLite MIN aggregate function allows us to select the lowest (minimum) value for a certain column. SQLite AVG Function SQLite AVG aggregate function selects the average value for certain table column. SQLite SUM Function SQLite SUM aggregate function allows selecting the total for a numeric column. SQLite RANDOM Function SQLite RANDOM function returns a pseudo-random integer between -9223372036854775808 and +9223372036854775807. SQLite ABS Function SQLite ABS function returns the absolute value of the numeric argument. SQLite UPPER Function SQLite UPPER function converts a string into upper-case letters. SQLite LOWER Function SQLite LOWER function converts a string into lower-case letters. SQLite LENGTH Function SQLite LENGTH function returns the length of a string. SQLite sqlite_version Function SQLite sqlite_version function returns the version of the SQLite library. Before we start giving examples on the above-mentioned functions, consider COMPANY table with the following records. ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 SQLite COUNT aggregate function is used to count the number of rows in a database table. Following is an example − sqlite> SELECT count(*) FROM COMPANY; The above SQLite SQL statement will produce the following. count(*) ---------- 7 SQLite MAX aggregate function allows us to select the highest (maximum) value for a certain column. Following is an example − sqlite> SELECT max(salary) FROM COMPANY; The above SQLite SQL statement will produce the following. max(salary) ----------- 85000.0 SQLite MIN aggregate function allows us to select the lowest (minimum) value for a certain column. Following is an example − sqlite> SELECT min(salary) FROM COMPANY; The above SQLite SQL statement will produce the following. min(salary) ----------- 10000.0 SQLite AVG aggregate function selects the average value for a certain table column. Following is an the example − sqlite> SELECT avg(salary) FROM COMPANY; The above SQLite SQL statement will produce the following. avg(salary) ---------------- 37142.8571428572 SQLite SUM aggregate function allows selecting the total for a numeric column. Following is an example − sqlite> SELECT sum(salary) FROM COMPANY; The above SQLite SQL statement will produce the following. sum(salary) ----------- 260000.0 SQLite RANDOM function returns a pseudo-random integer between -9223372036854775808 and +9223372036854775807. Following is an example − sqlite> SELECT random() AS Random; The above SQLite SQL statement will produce the following. Random ------------------- 5876796417670984050 SQLite ABS function returns the absolute value of the numeric argument. Following is an example − sqlite> SELECT abs(5), abs(-15), abs(NULL), abs(0), abs("ABC"); The above SQLite SQL statement will produce the following. abs(5) abs(-15) abs(NULL) abs(0) abs("ABC") ---------- ---------- ---------- ---------- ---------- 5 15 0 0.0 SQLite UPPER function converts a string into upper-case letters. Following is an example − sqlite> SELECT upper(name) FROM COMPANY; The above SQLite SQL statement will produce the following. upper(name) ----------- PAUL ALLEN TEDDY MARK DAVID KIM JAMES SQLite LOWER function converts a string into lower-case letters. Following is an example − sqlite> SELECT lower(name) FROM COMPANY; The above SQLite SQL statement will produce the following. lower(name) ----------- paul allen teddy mark david kim james SQLite LENGTH function returns the length of a string. Following is an example − sqlite> SELECT name, length(name) FROM COMPANY; The above SQLite SQL statement will produce the following. NAME length(name) ---------- ------------ Paul 4 Allen 5 Teddy 5 Mark 4 David 5 Kim 3 James 5 SQLite sqlite_version function returns the version of the SQLite library. Following is an example − sqlite> SELECT sqlite_version() AS 'SQLite Version'; The above SQLite SQL statement will produce the following. SQLite Version -------------- 3.6.20 25 Lectures 4.5 hours Sandip Bhattacharya 17 Lectures 1 hours Laurence Svekis 5 Lectures 51 mins Vinay Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 2982, "s": 2638, "text": "SQLite has many built-in functions to perform processing on string or numeric data. Following is the list of few useful SQLite built-in functions and all are case in-sensitive which means you can use these functions either in lower-case form or in upper-case or in mixed form. For more details, you can check official documentation for SQLite." }, { "code": null, "e": 3004, "s": 2982, "text": "SQLite COUNT Function" }, { "code": null, "e": 3093, "s": 3004, "text": "SQLite COUNT aggregate function is used to count the number of rows in a database table." }, { "code": null, "e": 3114, "s": 3093, "text": "SQLite MAX Function " }, { "code": null, "e": 3214, "s": 3114, "text": "SQLite MAX aggregate function allows us to select the highest (maximum) value for a certain column." }, { "code": null, "e": 3234, "s": 3214, "text": "SQLite MIN Function" }, { "code": null, "e": 3333, "s": 3234, "text": "SQLite MIN aggregate function allows us to select the lowest (minimum) value for a certain column." }, { "code": null, "e": 3354, "s": 3333, "text": "SQLite AVG Function " }, { "code": null, "e": 3436, "s": 3354, "text": "SQLite AVG aggregate function selects the average value for certain table column." }, { "code": null, "e": 3456, "s": 3436, "text": "SQLite SUM Function" }, { "code": null, "e": 3535, "s": 3456, "text": "SQLite SUM aggregate function allows selecting the total for a numeric column." }, { "code": null, "e": 3558, "s": 3535, "text": "SQLite RANDOM Function" }, { "code": null, "e": 3668, "s": 3558, "text": "SQLite RANDOM function returns a pseudo-random integer between -9223372036854775808 and +9223372036854775807." }, { "code": null, "e": 3688, "s": 3668, "text": "SQLite ABS Function" }, { "code": null, "e": 3760, "s": 3688, "text": "SQLite ABS function returns the absolute value of the numeric argument." }, { "code": null, "e": 3782, "s": 3760, "text": "SQLite UPPER Function" }, { "code": null, "e": 3847, "s": 3782, "text": "SQLite UPPER function converts a string into upper-case letters." }, { "code": null, "e": 3869, "s": 3847, "text": "SQLite LOWER Function" }, { "code": null, "e": 3934, "s": 3869, "text": "SQLite LOWER function converts a string into lower-case letters." }, { "code": null, "e": 3957, "s": 3934, "text": "SQLite LENGTH Function" }, { "code": null, "e": 4012, "s": 3957, "text": "SQLite LENGTH function returns the length of a string." }, { "code": null, "e": 4043, "s": 4012, "text": "SQLite sqlite_version Function" }, { "code": null, "e": 4117, "s": 4043, "text": "SQLite sqlite_version function returns the version of the SQLite library." }, { "code": null, "e": 4234, "s": 4117, "text": "Before we start giving examples on the above-mentioned functions, consider COMPANY table with the following records." }, { "code": null, "e": 4740, "s": 4234, "text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0" }, { "code": null, "e": 4855, "s": 4740, "text": "SQLite COUNT aggregate function is used to count the number of rows in a database table. Following is an example −" }, { "code": null, "e": 4893, "s": 4855, "text": "sqlite> SELECT count(*) FROM COMPANY;" }, { "code": null, "e": 4952, "s": 4893, "text": "The above SQLite SQL statement will produce the following." }, { "code": null, "e": 4975, "s": 4952, "text": "count(*)\n----------\n7\n" }, { "code": null, "e": 5101, "s": 4975, "text": "SQLite MAX aggregate function allows us to select the highest (maximum) value for a certain column. Following is an example −" }, { "code": null, "e": 5142, "s": 5101, "text": "sqlite> SELECT max(salary) FROM COMPANY;" }, { "code": null, "e": 5201, "s": 5142, "text": "The above SQLite SQL statement will produce the following." }, { "code": null, "e": 5234, "s": 5201, "text": "max(salary)\n-----------\n85000.0\n" }, { "code": null, "e": 5359, "s": 5234, "text": "SQLite MIN aggregate function allows us to select the lowest (minimum) value for a certain column. Following is an example −" }, { "code": null, "e": 5400, "s": 5359, "text": "sqlite> SELECT min(salary) FROM COMPANY;" }, { "code": null, "e": 5459, "s": 5400, "text": "The above SQLite SQL statement will produce the following." }, { "code": null, "e": 5492, "s": 5459, "text": "min(salary)\n-----------\n10000.0\n" }, { "code": null, "e": 5606, "s": 5492, "text": "SQLite AVG aggregate function selects the average value for a certain table column. Following is an the example −" }, { "code": null, "e": 5647, "s": 5606, "text": "sqlite> SELECT avg(salary) FROM COMPANY;" }, { "code": null, "e": 5706, "s": 5647, "text": "The above SQLite SQL statement will produce the following." }, { "code": null, "e": 5753, "s": 5706, "text": "avg(salary)\n----------------\n37142.8571428572\n" }, { "code": null, "e": 5858, "s": 5753, "text": "SQLite SUM aggregate function allows selecting the total for a numeric column. Following is an example −" }, { "code": null, "e": 5899, "s": 5858, "text": "sqlite> SELECT sum(salary) FROM COMPANY;" }, { "code": null, "e": 5958, "s": 5899, "text": "The above SQLite SQL statement will produce the following." }, { "code": null, "e": 5992, "s": 5958, "text": "sum(salary)\n-----------\n260000.0\n" }, { "code": null, "e": 6128, "s": 5992, "text": "SQLite RANDOM function returns a pseudo-random integer between -9223372036854775808 and +9223372036854775807. Following is an example −" }, { "code": null, "e": 6163, "s": 6128, "text": "sqlite> SELECT random() AS Random;" }, { "code": null, "e": 6222, "s": 6163, "text": "The above SQLite SQL statement will produce the following." }, { "code": null, "e": 6270, "s": 6222, "text": "Random\n-------------------\n5876796417670984050\n" }, { "code": null, "e": 6368, "s": 6270, "text": "SQLite ABS function returns the absolute value of the numeric argument. Following is an example −" }, { "code": null, "e": 6432, "s": 6368, "text": "sqlite> SELECT abs(5), abs(-15), abs(NULL), abs(0), abs(\"ABC\");" }, { "code": null, "e": 6491, "s": 6432, "text": "The above SQLite SQL statement will produce the following." }, { "code": null, "e": 6662, "s": 6491, "text": "abs(5) abs(-15) abs(NULL) abs(0) abs(\"ABC\")\n---------- ---------- ---------- ---------- ----------\n5 15 0 0.0\n" }, { "code": null, "e": 6753, "s": 6662, "text": "SQLite UPPER function converts a string into upper-case letters. Following is an example −" }, { "code": null, "e": 6794, "s": 6753, "text": "sqlite> SELECT upper(name) FROM COMPANY;" }, { "code": null, "e": 6853, "s": 6794, "text": "The above SQLite SQL statement will produce the following." }, { "code": null, "e": 6916, "s": 6853, "text": "upper(name)\n-----------\nPAUL\nALLEN\nTEDDY\nMARK\nDAVID\nKIM\nJAMES\n" }, { "code": null, "e": 7007, "s": 6916, "text": "SQLite LOWER function converts a string into lower-case letters. Following is an example −" }, { "code": null, "e": 7048, "s": 7007, "text": "sqlite> SELECT lower(name) FROM COMPANY;" }, { "code": null, "e": 7107, "s": 7048, "text": "The above SQLite SQL statement will produce the following." }, { "code": null, "e": 7170, "s": 7107, "text": "lower(name)\n-----------\npaul\nallen\nteddy\nmark\ndavid\nkim\njames\n" }, { "code": null, "e": 7251, "s": 7170, "text": "SQLite LENGTH function returns the length of a string. Following is an example −" }, { "code": null, "e": 7299, "s": 7251, "text": "sqlite> SELECT name, length(name) FROM COMPANY;" }, { "code": null, "e": 7358, "s": 7299, "text": "The above SQLite SQL statement will produce the following." }, { "code": null, "e": 7507, "s": 7358, "text": "NAME length(name)\n---------- ------------\nPaul 4\nAllen 5\nTeddy 5\nMark 4\nDavid 5\nKim 3\nJames 5\n" }, { "code": null, "e": 7607, "s": 7507, "text": "SQLite sqlite_version function returns the version of the SQLite library. Following is an example −" }, { "code": null, "e": 7660, "s": 7607, "text": "sqlite> SELECT sqlite_version() AS 'SQLite Version';" }, { "code": null, "e": 7719, "s": 7660, "text": "The above SQLite SQL statement will produce the following." }, { "code": null, "e": 7757, "s": 7719, "text": "SQLite Version\n--------------\n3.6.20\n" }, { "code": null, "e": 7792, "s": 7757, "text": "\n 25 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7813, "s": 7792, "text": " Sandip Bhattacharya" }, { "code": null, "e": 7846, "s": 7813, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 7863, "s": 7846, "text": " Laurence Svekis" }, { "code": null, "e": 7894, "s": 7863, "text": "\n 5 Lectures \n 51 mins\n" }, { "code": null, "e": 7907, "s": 7894, "text": " Vinay Kumar" }, { "code": null, "e": 7914, "s": 7907, "text": " Print" }, { "code": null, "e": 7925, "s": 7914, "text": " Add Notes" } ]
COBOL - Program Structure
A COBOL program structure consists of divisions as shown in the following image − A brief introduction of these divisions is given below − Sections are the logical subdivision of program logic. A section is a collection of paragraphs. Sections are the logical subdivision of program logic. A section is a collection of paragraphs. Paragraphs are the subdivision of a section or division. It is either a user-defined or a predefined name followed by a period, and consists of zero or more sentences/entries. Paragraphs are the subdivision of a section or division. It is either a user-defined or a predefined name followed by a period, and consists of zero or more sentences/entries. Sentences are the combination of one or more statements. Sentences appear only in the Procedure division. A sentence must end with a period. Sentences are the combination of one or more statements. Sentences appear only in the Procedure division. A sentence must end with a period. Statements are meaningful COBOL statements that perform some processing. Statements are meaningful COBOL statements that perform some processing. Characters are the lowest in the hierarchy and cannot be divisible. Characters are the lowest in the hierarchy and cannot be divisible. You can co-relate the above-mentioned terms with the COBOL program in the following example − PROCEDURE DIVISION. A0000-FIRST-PARA SECTION. FIRST-PARAGRAPH. ACCEPT WS-ID - Statement-1 -----| MOVE '10' TO WS-ID - Statement-2 |-- Sentence - 1 DISPLAY WS-ID - Statement-3 -----| . A COBOL program consists of four divisions. It is the first and only mandatory division of every COBOL program. The programmer and the compiler use this division to identify the program. In this division, PROGRAM-ID is the only mandatory paragraph. PROGRAM-ID specifies the program name that can consist 1 to 30 characters. Try the following example using the Live Demo option online. IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. PROCEDURE DIVISION. DISPLAY 'Welcome to Tutorialspoint'. STOP RUN. Given below is the JCL to execute the above COBOL program. //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO When you compile and execute the above program, it produces the following result − Welcome to Tutorialspoint Environment division is used to specify input and output files to the program. It consists of two sections − Configuration section provides information about the system on which the program is written and executed. It consists of two paragraphs − Source computer − System used to compile the program. Object computer − System used to execute the program. Configuration section provides information about the system on which the program is written and executed. It consists of two paragraphs − Source computer − System used to compile the program. Source computer − System used to compile the program. Object computer − System used to execute the program. Object computer − System used to execute the program. Input-Output section provides information about the files to be used in the program. It consists of two paragraphs − File control − Provides information of external data sets used in the program. I-O control − Provides information of files used in the program. Input-Output section provides information about the files to be used in the program. It consists of two paragraphs − File control − Provides information of external data sets used in the program. File control − Provides information of external data sets used in the program. I-O control − Provides information of files used in the program. I-O control − Provides information of files used in the program. ENVIRONMENT DIVISION. CONFIGURATION SECTION. SOURCE-COMPUTER. XXX-ZOS. OBJECT-COMPUTER. XXX-ZOS. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT FILEN ASSIGN TO DDNAME ORGANIZATION IS SEQUENTIAL. Data division is used to define the variables used in the program. It consists of four sections − File section is used to define the record structure of the file. File section is used to define the record structure of the file. Working-Storage section is used to declare temporary variables and file structures which are used in the program. Working-Storage section is used to declare temporary variables and file structures which are used in the program. Local-Storage section is similar to Working-Storage section. The only difference is that the variables will be allocated and initialized every time a program starts execution. Local-Storage section is similar to Working-Storage section. The only difference is that the variables will be allocated and initialized every time a program starts execution. Linkage section is used to describe the data names that are received from an external program. Linkage section is used to describe the data names that are received from an external program. COBOL Program IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT FILEN ASSIGN TO INPUT. ORGANIZATION IS SEQUENTIAL. ACCESS IS SEQUENTIAL. DATA DIVISION. FILE SECTION. FD FILEN 01 NAME PIC A(25). WORKING-STORAGE SECTION. 01 WS-STUDENT PIC A(30). 01 WS-ID PIC 9(5). LOCAL-STORAGE SECTION. 01 LS-CLASS PIC 9(3). LINKAGE SECTION. 01 LS-ID PIC 9(5). PROCEDURE DIVISION. DISPLAY 'Executing COBOL program using JCL'. STOP RUN. The JCL to execute the above COBOL program is as follows − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO //INPUT DD DSN = ABC.EFG.XYZ,DISP = SHR When you compile and execute the above program, it produces the following result − Executing COBOL program using JCL Procedure division is used to include the logic of the program. It consists of executable statements using variables defined in the data division. In this division, paragraph and section names are user-defined. There must be at least one statement in the procedure division. The last statement to end the execution in this division is either STOP RUN which is used in the calling programs or EXIT PROGRAM which is used in the called programs. IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-NAME PIC A(30). 01 WS-ID PIC 9(5) VALUE 12345. PROCEDURE DIVISION. A000-FIRST-PARA. DISPLAY 'Hello World'. MOVE 'TutorialsPoint' TO WS-NAME. DISPLAY "My name is : "WS-NAME. DISPLAY "My ID is : "WS-ID. STOP RUN. JCL to execute the above COBOL program − //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO When you compile and execute the above program, it produces the following result − Hello World My name is : TutorialsPoint My ID is : 12345 12 Lectures 2.5 hours Nishant Malik 33 Lectures 3.5 hours Craig Kenneth Kaercher Print Add Notes Bookmark this page
[ { "code": null, "e": 2104, "s": 2022, "text": "A COBOL program structure consists of divisions as shown in the following image −" }, { "code": null, "e": 2161, "s": 2104, "text": "A brief introduction of these divisions is given below −" }, { "code": null, "e": 2257, "s": 2161, "text": "Sections are the logical subdivision of program logic. A section is a collection of paragraphs." }, { "code": null, "e": 2353, "s": 2257, "text": "Sections are the logical subdivision of program logic. A section is a collection of paragraphs." }, { "code": null, "e": 2529, "s": 2353, "text": "Paragraphs are the subdivision of a section or division. It is either a user-defined or a predefined name followed by a period, and consists of zero or more sentences/entries." }, { "code": null, "e": 2705, "s": 2529, "text": "Paragraphs are the subdivision of a section or division. It is either a user-defined or a predefined name followed by a period, and consists of zero or more sentences/entries." }, { "code": null, "e": 2846, "s": 2705, "text": "Sentences are the combination of one or more statements. Sentences appear only in the Procedure division. A sentence must end with a period." }, { "code": null, "e": 2987, "s": 2846, "text": "Sentences are the combination of one or more statements. Sentences appear only in the Procedure division. A sentence must end with a period." }, { "code": null, "e": 3060, "s": 2987, "text": "Statements are meaningful COBOL statements that perform some processing." }, { "code": null, "e": 3133, "s": 3060, "text": "Statements are meaningful COBOL statements that perform some processing." }, { "code": null, "e": 3201, "s": 3133, "text": "Characters are the lowest in the hierarchy and cannot be divisible." }, { "code": null, "e": 3269, "s": 3201, "text": "Characters are the lowest in the hierarchy and cannot be divisible." }, { "code": null, "e": 3363, "s": 3269, "text": "You can co-relate the above-mentioned terms with the COBOL program in the following example −" }, { "code": null, "e": 3581, "s": 3363, "text": "PROCEDURE DIVISION.\nA0000-FIRST-PARA SECTION.\nFIRST-PARAGRAPH.\nACCEPT WS-ID - Statement-1 -----|\nMOVE '10' TO WS-ID - Statement-2 |-- Sentence - 1\nDISPLAY WS-ID - Statement-3 -----|\n." }, { "code": null, "e": 3625, "s": 3581, "text": "A COBOL program consists of four divisions." }, { "code": null, "e": 3905, "s": 3625, "text": "It is the first and only mandatory division of every COBOL program. The programmer and the compiler use this division to identify the program. In this division, PROGRAM-ID is the only mandatory paragraph. PROGRAM-ID specifies the program name that can consist 1 to 30 characters." }, { "code": null, "e": 3966, "s": 3905, "text": "Try the following example using the Live Demo option online." }, { "code": null, "e": 4077, "s": 3966, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\nPROCEDURE DIVISION.\nDISPLAY 'Welcome to Tutorialspoint'.\nSTOP RUN." }, { "code": null, "e": 4136, "s": 4077, "text": "Given below is the JCL to execute the above COBOL program." }, { "code": null, "e": 4213, "s": 4136, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO" }, { "code": null, "e": 4296, "s": 4213, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 4323, "s": 4296, "text": "Welcome to Tutorialspoint\n" }, { "code": null, "e": 4432, "s": 4323, "text": "Environment division is used to specify input and output files to the program. It consists of two sections −" }, { "code": null, "e": 4680, "s": 4432, "text": "Configuration section provides information about the system on which the program is written and executed. It consists of two paragraphs −\n\nSource computer − System used to compile the program.\nObject computer − System used to execute the program.\n" }, { "code": null, "e": 4818, "s": 4680, "text": "Configuration section provides information about the system on which the program is written and executed. It consists of two paragraphs −" }, { "code": null, "e": 4872, "s": 4818, "text": "Source computer − System used to compile the program." }, { "code": null, "e": 4926, "s": 4872, "text": "Source computer − System used to compile the program." }, { "code": null, "e": 4980, "s": 4926, "text": "Object computer − System used to execute the program." }, { "code": null, "e": 5034, "s": 4980, "text": "Object computer − System used to execute the program." }, { "code": null, "e": 5297, "s": 5034, "text": "Input-Output section provides information about the files to be used in the program. It consists of two paragraphs −\n\nFile control − Provides information of external data sets used in the program.\nI-O control − Provides information of files used in the program.\n" }, { "code": null, "e": 5414, "s": 5297, "text": "Input-Output section provides information about the files to be used in the program. It consists of two paragraphs −" }, { "code": null, "e": 5493, "s": 5414, "text": "File control − Provides information of external data sets used in the program." }, { "code": null, "e": 5572, "s": 5493, "text": "File control − Provides information of external data sets used in the program." }, { "code": null, "e": 5637, "s": 5572, "text": "I-O control − Provides information of files used in the program." }, { "code": null, "e": 5702, "s": 5637, "text": "I-O control − Provides information of files used in the program." }, { "code": null, "e": 5909, "s": 5702, "text": "ENVIRONMENT DIVISION.\nCONFIGURATION SECTION.\n SOURCE-COMPUTER. XXX-ZOS.\n OBJECT-COMPUTER. XXX-ZOS.\n\nINPUT-OUTPUT SECTION.\n FILE-CONTROL.\n SELECT FILEN ASSIGN TO DDNAME\n ORGANIZATION IS SEQUENTIAL." }, { "code": null, "e": 6007, "s": 5909, "text": "Data division is used to define the variables used in the program. It consists of four sections −" }, { "code": null, "e": 6072, "s": 6007, "text": "File section is used to define the record structure of the file." }, { "code": null, "e": 6137, "s": 6072, "text": "File section is used to define the record structure of the file." }, { "code": null, "e": 6251, "s": 6137, "text": "Working-Storage section is used to declare temporary variables and file structures which are used in the program." }, { "code": null, "e": 6365, "s": 6251, "text": "Working-Storage section is used to declare temporary variables and file structures which are used in the program." }, { "code": null, "e": 6541, "s": 6365, "text": "Local-Storage section is similar to Working-Storage section. The only difference is that the variables will be allocated and initialized every time a program starts execution." }, { "code": null, "e": 6717, "s": 6541, "text": "Local-Storage section is similar to Working-Storage section. The only difference is that the variables will be allocated and initialized every time a program starts execution." }, { "code": null, "e": 6812, "s": 6717, "text": "Linkage section is used to describe the data names that are received from an external program." }, { "code": null, "e": 6907, "s": 6812, "text": "Linkage section is used to describe the data names that are received from an external program." }, { "code": null, "e": 6921, "s": 6907, "text": "COBOL Program" }, { "code": null, "e": 7454, "s": 6921, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nENVIRONMENT DIVISION.\n INPUT-OUTPUT SECTION.\n FILE-CONTROL.\n SELECT FILEN ASSIGN TO INPUT.\n ORGANIZATION IS SEQUENTIAL.\n ACCESS IS SEQUENTIAL.\n\nDATA DIVISION.\n FILE SECTION.\n FD FILEN\n 01 NAME PIC A(25).\n \n WORKING-STORAGE SECTION.\n 01 WS-STUDENT PIC A(30).\n 01 WS-ID PIC 9(5).\n\n LOCAL-STORAGE SECTION.\n 01 LS-CLASS PIC 9(3).\n \n LINKAGE SECTION.\n 01 LS-ID PIC 9(5).\n \nPROCEDURE DIVISION.\n DISPLAY 'Executing COBOL program using JCL'.\nSTOP RUN." }, { "code": null, "e": 7513, "s": 7454, "text": "The JCL to execute the above COBOL program is as follows −" }, { "code": null, "e": 7630, "s": 7513, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO\n//INPUT DD DSN = ABC.EFG.XYZ,DISP = SHR" }, { "code": null, "e": 7713, "s": 7630, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 7748, "s": 7713, "text": "Executing COBOL program using JCL\n" }, { "code": null, "e": 7959, "s": 7748, "text": "Procedure division is used to include the logic of the program. It consists of executable statements using variables defined in the data division. In this division, paragraph and section names are user-defined." }, { "code": null, "e": 8191, "s": 7959, "text": "There must be at least one statement in the procedure division. The last statement to end the execution in this division is either STOP RUN which is used in the calling programs or EXIT PROGRAM which is used in the called programs." }, { "code": null, "e": 8518, "s": 8191, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 WS-NAME PIC A(30).\n 01 WS-ID PIC 9(5) VALUE 12345.\n\nPROCEDURE DIVISION.\n A000-FIRST-PARA.\n DISPLAY 'Hello World'.\n MOVE 'TutorialsPoint' TO WS-NAME.\n DISPLAY \"My name is : \"WS-NAME.\n DISPLAY \"My ID is : \"WS-ID.\nSTOP RUN." }, { "code": null, "e": 8559, "s": 8518, "text": "JCL to execute the above COBOL program −" }, { "code": null, "e": 8636, "s": 8559, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO" }, { "code": null, "e": 8719, "s": 8636, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 8777, "s": 8719, "text": "Hello World\nMy name is : TutorialsPoint\nMy ID is : 12345\n" }, { "code": null, "e": 8812, "s": 8777, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8827, "s": 8812, "text": " Nishant Malik" }, { "code": null, "e": 8862, "s": 8827, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8886, "s": 8862, "text": " Craig Kenneth Kaercher" }, { "code": null, "e": 8893, "s": 8886, "text": " Print" }, { "code": null, "e": 8904, "s": 8893, "text": " Add Notes" } ]
Cosine similarity: How does it measure the similarity, Maths behind and usage in Python | by Varun | Towards Data Science
What is cosine similarity? Cosine similarity measures the similarity between two vectors by calculating the cosine of the angle between the two vectors. Cosine similarity is one of the most widely used and powerful similarity measure in Data Science. It is used in multiple applications such as finding similar documents in NLP, information retrieval, finding similar sequence to a DNA in bioinformatics, detecting plagiarism and may more. Cosine similarity is calculated as follows, Why cosine of the angle between A and B gives us the similarity? If you look at the cosine function, it is 1 at theta = 0 and -1 at theta = 180, that means for two overlapping vectors cosine will be the highest and lowest for two exactly opposite vectors. You can consider 1-cosine as distance. How to calculate it in Python? The numerator of the formula is the dot product of the two vectors and denominator is the product of L2 norm of both the vectors. Dot product of two vectors is the sum of element wise multiplication of the vectors and L2 norm is the square root of sum of squares of elements of a vector. We can either use inbuilt functions in Numpy library to calculate dot product and L2 norm of the vectors and put it in the formula or directly use the cosine_similarity from sklearn.metrics.pairwise. Consider two vectors A and B in 2-D, following code calculates the cosine similarity, import numpy as npimport matplotlib.pyplot as plt# consider two vectors A and B in 2-DA=np.array([7,3])B=np.array([3,7])ax = plt.axes()ax.arrow(0.0, 0.0, A[0], A[1], head_width=0.4, head_length=0.5)plt.annotate(f"A({A[0]},{A[1]})", xy=(A[0], A[1]),xytext=(A[0]+0.5, A[1]))ax.arrow(0.0, 0.0, B[0], B[1], head_width=0.4, head_length=0.5)plt.annotate(f"B({B[0]},{B[1]})", xy=(B[0], B[1]),xytext=(B[0]+0.5, B[1]))plt.xlim(0,10)plt.ylim(0,10)plt.show()plt.close()# cosine similarity between A and Bcos_sim=np.dot(A,B)/(np.linalg.norm(A)*np.linalg.norm(B))print (f"Cosine Similarity between A and B:{cos_sim}")print (f"Cosine Distance between A and B:{1-cos_sim}") # using sklearn to calculate cosine similarityfrom sklearn.metrics.pairwise import cosine_similarity,cosine_distancescos_sim=cosine_similarity(A.reshape(1,-1),B.reshape(1,-1))print (f"Cosine Similarity between A and B:{cos_sim}")print (f"Cosine Distance between A and B:{1-cos_sim}") # using scipy, it calculates 1-cosinefrom scipy.spatial import distancedistance.cosine(A.reshape(1,-1),B.reshape(1,-1)) Proof of the formula Cosine similarity formula can be proved by using Law of cosines, Consider two vectors A and B in 2-dimensions, such as, Using Law of cosines, You can prove the same for 3-dimensions or any dimensions in general. It follows exactly same steps as above. Summary We saw how cosine similarity works, how to use it and why does it work. I hope this article helped in understanding the whole concept behind this powerful metric.
[ { "code": null, "e": 199, "s": 172, "text": "What is cosine similarity?" }, { "code": null, "e": 325, "s": 199, "text": "Cosine similarity measures the similarity between two vectors by calculating the cosine of the angle between the two vectors." }, { "code": null, "e": 612, "s": 325, "text": "Cosine similarity is one of the most widely used and powerful similarity measure in Data Science. It is used in multiple applications such as finding similar documents in NLP, information retrieval, finding similar sequence to a DNA in bioinformatics, detecting plagiarism and may more." }, { "code": null, "e": 656, "s": 612, "text": "Cosine similarity is calculated as follows," }, { "code": null, "e": 721, "s": 656, "text": "Why cosine of the angle between A and B gives us the similarity?" }, { "code": null, "e": 951, "s": 721, "text": "If you look at the cosine function, it is 1 at theta = 0 and -1 at theta = 180, that means for two overlapping vectors cosine will be the highest and lowest for two exactly opposite vectors. You can consider 1-cosine as distance." }, { "code": null, "e": 982, "s": 951, "text": "How to calculate it in Python?" }, { "code": null, "e": 1270, "s": 982, "text": "The numerator of the formula is the dot product of the two vectors and denominator is the product of L2 norm of both the vectors. Dot product of two vectors is the sum of element wise multiplication of the vectors and L2 norm is the square root of sum of squares of elements of a vector." }, { "code": null, "e": 1556, "s": 1270, "text": "We can either use inbuilt functions in Numpy library to calculate dot product and L2 norm of the vectors and put it in the formula or directly use the cosine_similarity from sklearn.metrics.pairwise. Consider two vectors A and B in 2-D, following code calculates the cosine similarity," }, { "code": null, "e": 2215, "s": 1556, "text": "import numpy as npimport matplotlib.pyplot as plt# consider two vectors A and B in 2-DA=np.array([7,3])B=np.array([3,7])ax = plt.axes()ax.arrow(0.0, 0.0, A[0], A[1], head_width=0.4, head_length=0.5)plt.annotate(f\"A({A[0]},{A[1]})\", xy=(A[0], A[1]),xytext=(A[0]+0.5, A[1]))ax.arrow(0.0, 0.0, B[0], B[1], head_width=0.4, head_length=0.5)plt.annotate(f\"B({B[0]},{B[1]})\", xy=(B[0], B[1]),xytext=(B[0]+0.5, B[1]))plt.xlim(0,10)plt.ylim(0,10)plt.show()plt.close()# cosine similarity between A and Bcos_sim=np.dot(A,B)/(np.linalg.norm(A)*np.linalg.norm(B))print (f\"Cosine Similarity between A and B:{cos_sim}\")print (f\"Cosine Distance between A and B:{1-cos_sim}\")" }, { "code": null, "e": 2499, "s": 2215, "text": "# using sklearn to calculate cosine similarityfrom sklearn.metrics.pairwise import cosine_similarity,cosine_distancescos_sim=cosine_similarity(A.reshape(1,-1),B.reshape(1,-1))print (f\"Cosine Similarity between A and B:{cos_sim}\")print (f\"Cosine Distance between A and B:{1-cos_sim}\")" }, { "code": null, "e": 2619, "s": 2499, "text": "# using scipy, it calculates 1-cosinefrom scipy.spatial import distancedistance.cosine(A.reshape(1,-1),B.reshape(1,-1))" }, { "code": null, "e": 2640, "s": 2619, "text": "Proof of the formula" }, { "code": null, "e": 2705, "s": 2640, "text": "Cosine similarity formula can be proved by using Law of cosines," }, { "code": null, "e": 2760, "s": 2705, "text": "Consider two vectors A and B in 2-dimensions, such as," }, { "code": null, "e": 2782, "s": 2760, "text": "Using Law of cosines," }, { "code": null, "e": 2892, "s": 2782, "text": "You can prove the same for 3-dimensions or any dimensions in general. It follows exactly same steps as above." }, { "code": null, "e": 2900, "s": 2892, "text": "Summary" } ]
Mode 1—strobed I/O
We call mode 1 as the strobed Input Output or handshake Input Output. We use this mode when the data is supplied by the input device to the microprocessor at irregular interval of time. A port which is functioned to program in mode uses three handshake signals. These handshake signals are provided by Port C. Only port A and B works in mode 1. The pins PC2, PC1, and PC0 provides handshake signals for port B when we configure it for Input port or Output port. Moreover, the pins PC7, PC6, and PC3 provides handshake signals for port A. The point to be noted that PC3 pin is a handshake line for Port A in the input terminal and also performing the output operations. If port A and B both works in mode 1 the remaining two pins of port C are used for performing the simple Input Output operations in mode 0. If either of Port A or B works in mode 1 then the rest 5 pins of port C are completely free. Example 1: Configure Port A as strobed input port, Port B as strobed output port, and PC7, PC6 as output lines. The required mode definition control word is shown in the figure below − It is to be noted that the LS bit is a don't care bit. This is because all the four lines of Port C lower are used for handshaking purposes some of which will be input pins and some others outputs. The 8255 will automatically configure these handshake pins, and so it is unimportant whether this LS bit is a 0 or a 1. Bit 3 must be a 0 to indicate that PC7 and PC6 are output lines. In this case it does not mean that the entire Port C upper is output, as PC5 and PC4 are used for handshaking purposes. The instructions to achieve this requirement assuming the chip select circuit are as follows. MVI A, B4H ; Treating X as 0 OUT 23H
[ { "code": null, "e": 1964, "s": 1062, "text": "We call mode 1 as the strobed Input Output or handshake Input Output. We use this mode when the data is supplied by the input device to the microprocessor at irregular interval of time. A port which is functioned to program in mode uses three handshake signals. These handshake signals are provided by Port C. Only port A and B works in mode 1. The pins PC2, PC1, and PC0 provides handshake signals for port B when we configure it for Input port or Output port. Moreover, the pins PC7, PC6, and PC3 provides handshake signals for port A. The point to be noted that PC3 pin is a handshake line for Port A in the input terminal and also performing the output operations. If port A and B both works in mode 1 the remaining two pins of port C are used for performing the simple Input Output operations in mode 0. If either of Port A or B works in mode 1 then the rest 5 pins of port C are completely free." }, { "code": null, "e": 2076, "s": 1964, "text": "Example 1: Configure Port A as strobed input port, Port B as strobed output port, and PC7, PC6 as output lines." }, { "code": null, "e": 2149, "s": 2076, "text": "The required mode definition control word is shown in the figure below −" }, { "code": null, "e": 2249, "s": 2149, "text": "It is to be noted that the LS bit is a don't care bit. This is because all the four lines of Port C" }, { "code": null, "e": 2467, "s": 2249, "text": "lower are used for handshaking purposes some of which will be input pins and some others outputs. The 8255 will automatically configure these handshake pins, and so it is unimportant whether this LS bit is a 0 or a 1." }, { "code": null, "e": 2567, "s": 2467, "text": "Bit 3 must be a 0 to indicate that PC7 and PC6 are output lines. In this case it does not mean that" }, { "code": null, "e": 2746, "s": 2567, "text": "the entire Port C upper is output, as PC5 and PC4 are used for handshaking purposes. The instructions to achieve this requirement assuming the chip select circuit are as follows." }, { "code": null, "e": 2783, "s": 2746, "text": "MVI A, B4H ; Treating X as 0\nOUT 23H" } ]
Design and Analysis Merge Sort
In this chapter, we will discuss merge sort and analyze its complexity. The problem of sorting a list of numbers lends itself immediately to a divide-and-conquer strategy: split the list into two halves, recursively sort each half, and then merge the two sorted sub-lists. In this algorithm, the numbers are stored in an array numbers[]. Here, p and q represents the start and end index of a sub-array. Algorithm: Merge-Sort (numbers[], p, r) if p < r then q = ⌊(p + r) / 2⌋ Merge-Sort (numbers[], p, q) Merge-Sort (numbers[], q + 1, r) Merge (numbers[], p, q, r) Function: Merge (numbers[], p, q, r) n1 = q – p + 1 n2 = r – q declare leftnums[1...n1 + 1] and rightnums[1...n2 + 1] temporary arrays for i = 1 to n1 leftnums[i] = numbers[p + i - 1] for j = 1 to n2 rightnums[j] = numbers[q+ j] leftnums[n1 + 1] = ∞ rightnums[n2 + 1] = ∞ i = 1 j = 1 for k = p to r if leftnums[i] ≤ rightnums[j] numbers[k] = leftnums[i] i = i + 1 else numbers[k] = rightnums[j] j = j + 1 Let us consider, the running time of Merge-Sort as T(n). Hence, T(n)={cifn⩽12xT(n2)+dxnotherwise where c and d are constants Therefore, using this recurrence relation, T(n)=2iT(n2i)+i.d.n As, i=logn,T(n)=2lognT(n2logn)+logn.d.n =c.n+d.n.logn Therefore, T(n)=O(nlogn) In the following example, we have shown Merge-Sort algorithm step by step. First, every iteration array is divided into two sub-arrays, until the sub-array contains only one element. When these sub-arrays cannot be divided further, then merge operations are performed. 102 Lectures 10 hours Arnab Chakraborty 30 Lectures 3 hours Arnab Chakraborty 31 Lectures 4 hours Arnab Chakraborty 43 Lectures 1.5 hours Manoj Kumar 7 Lectures 1 hours Zach Miller 54 Lectures 4 hours Sasha Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2671, "s": 2599, "text": "In this chapter, we will discuss merge sort and analyze its complexity." }, { "code": null, "e": 2872, "s": 2671, "text": "The problem of sorting a list of numbers lends itself immediately to a divide-and-conquer strategy: split the list into two halves, recursively sort each half, and then merge the two sorted sub-lists." }, { "code": null, "e": 3002, "s": 2872, "text": "In this algorithm, the numbers are stored in an array numbers[]. Here, p and q represents the start and end index of a sub-array." }, { "code": null, "e": 3179, "s": 3002, "text": "Algorithm: Merge-Sort (numbers[], p, r) \nif p < r then \nq = ⌊(p + r) / 2⌋ \nMerge-Sort (numbers[], p, q) \n Merge-Sort (numbers[], q + 1, r) \n Merge (numbers[], p, q, r) \n" }, { "code": null, "e": 3638, "s": 3179, "text": "Function: Merge (numbers[], p, q, r)\nn1 = q – p + 1 \nn2 = r – q \ndeclare leftnums[1...n1 + 1] and rightnums[1...n2 + 1] temporary arrays \nfor i = 1 to n1 \n leftnums[i] = numbers[p + i - 1] \nfor j = 1 to n2 \n rightnums[j] = numbers[q+ j] \nleftnums[n1 + 1] = ∞ \nrightnums[n2 + 1] = ∞ \ni = 1 \nj = 1 \nfor k = p to r \n if leftnums[i] ≤ rightnums[j] \n numbers[k] = leftnums[i] \n i = i + 1 \n else\n numbers[k] = rightnums[j] \n j = j + 1 \n" }, { "code": null, "e": 3702, "s": 3638, "text": "Let us consider, the running time of Merge-Sort as T(n). Hence," }, { "code": null, "e": 3763, "s": 3702, "text": "T(n)={cifn⩽12xT(n2)+dxnotherwise where c and d are constants" }, { "code": null, "e": 3806, "s": 3763, "text": "Therefore, using this recurrence relation," }, { "code": null, "e": 3826, "s": 3806, "text": "T(n)=2iT(n2i)+i.d.n" }, { "code": null, "e": 3866, "s": 3826, "text": "As, i=logn,T(n)=2lognT(n2logn)+logn.d.n" }, { "code": null, "e": 3880, "s": 3866, "text": "=c.n+d.n.logn" }, { "code": null, "e": 3905, "s": 3880, "text": "Therefore, T(n)=O(nlogn)" }, { "code": null, "e": 4174, "s": 3905, "text": "In the following example, we have shown Merge-Sort algorithm step by step. First, every iteration array is divided into two sub-arrays, until the sub-array contains only one element. When these sub-arrays cannot be divided further, then merge operations are performed." }, { "code": null, "e": 4209, "s": 4174, "text": "\n 102 Lectures \n 10 hours \n" }, { "code": null, "e": 4228, "s": 4209, "text": " Arnab Chakraborty" }, { "code": null, "e": 4261, "s": 4228, "text": "\n 30 Lectures \n 3 hours \n" }, { "code": null, "e": 4280, "s": 4261, "text": " Arnab Chakraborty" }, { "code": null, "e": 4313, "s": 4280, "text": "\n 31 Lectures \n 4 hours \n" }, { "code": null, "e": 4332, "s": 4313, "text": " Arnab Chakraborty" }, { "code": null, "e": 4367, "s": 4332, "text": "\n 43 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4380, "s": 4367, "text": " Manoj Kumar" }, { "code": null, "e": 4412, "s": 4380, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 4425, "s": 4412, "text": " Zach Miller" }, { "code": null, "e": 4458, "s": 4425, "text": "\n 54 Lectures \n 4 hours \n" }, { "code": null, "e": 4472, "s": 4458, "text": " Sasha Miller" }, { "code": null, "e": 4479, "s": 4472, "text": " Print" }, { "code": null, "e": 4490, "s": 4479, "text": " Add Notes" } ]
Monitoring and TroubleShooting using Cloudwatch
Functions created in AWS Lambda are monitored by Amazon CloudWatch. It helps in logging all the requests made to the Lambda function when it is triggered. Consider that the following code is uploaded in AWS Lambda with function name as lambda and cloudwatch. exports.handler = (event, context, callback) => { // TODO implement console.log("Lambda monitoring using amazon cloudwatch"); callback(null, 'Hello from Lambda'); }; When the function is tested or triggered, you should see an entry in Cloudwatch. For this purpose, go to AWS services and click CloudWatch. Select logs from left side. When you click Logs, it has the Log Groups of AWS Lambda function created in your account. Select anyAWS Lambda function and check the details. Here, we are referring to Lambda function with name:lambdaandcloudwatch. The logs added to the Lambda function are displayed here as shown below − Now, let us add S3 trigger to the Lambda function and see the logs details in CloudWatch as shown below − Let us update AWS Lambda code to display the file uploaded and bucket name as shown in the code given below − exports.handler = (event, context, callback) => { // TODO implement console.log("Lambda monitoring using amazon cloudwatch"); const bucket = event.Records[0].s3.bucket.name; const filename = event.Records[0].s3.object.key; const message = `File is uploaded in - ${bucket} -> ${filename}`; console.log(message); callback(null, 'Hello from Lambda'); }; Now, add file in s3storetestlambdaEventbucket as shown − When the file is uploaded, AWS Lambda functions will get triggered and the console log messages from Lambda code are displayed in CloudWatch as shown below − If there is any error, CloudWatch gives the error details as shown below − Note that we have referred to the bucket name wrongly in AWS Lambda code as shown − exports.handler = (event, context, callback) => { // TODO implement console.log("Lambda monitoring using amazon cloudwatch"); const bucket = event.Records[0].bucket.name; const filename = event.Records[0].s3.object.key; const message = `File is uploaded in - ${bucket} -> ${filename}`; console.log(message); callback(null, 'Hello from Lambda'); }; The bucket name reference from the event is wrong. Thus, we should see an error displayed in CloudWatch as shown below − The details of the Lambda function execution can be seen in the metrics. Click Metrics displayed in the left side. The graph details for the lambda function lambdaandcloudwatch are as shown below − It gives details such as the duration for which the Lambda function is executed, number of times it is invoked and the errors from the Lambda function. 35 Lectures 7.5 hours Mr. Pradeep Kshetrapal 30 Lectures 3.5 hours Priyanka Choudhary 44 Lectures 7.5 hours Eduonix Learning Solutions 51 Lectures 6 hours Manuj Aggarwal 41 Lectures 5 hours AR Shankar 14 Lectures 1 hours Zach Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2561, "s": 2406, "text": "Functions created in AWS Lambda are monitored by Amazon CloudWatch. It helps in logging all the requests made to the Lambda function when it is triggered." }, { "code": null, "e": 2665, "s": 2561, "text": "Consider that the following code is uploaded in AWS Lambda with function name as lambda and cloudwatch." }, { "code": null, "e": 2844, "s": 2665, "text": "exports.handler = (event, context, callback) => {\n // TODO implement\n console.log(\"Lambda monitoring using amazon cloudwatch\"); \n callback(null, 'Hello from Lambda');\n};" }, { "code": null, "e": 2985, "s": 2844, "text": "When the function is tested or triggered, you should see an entry in Cloudwatch. For this purpose, go to AWS services and click CloudWatch." }, { "code": null, "e": 3013, "s": 2985, "text": "Select logs from left side." }, { "code": null, "e": 3304, "s": 3013, "text": "When you click Logs, it has the Log Groups of AWS Lambda function created in your account. Select anyAWS Lambda function and check the details. Here, we are referring to Lambda function with name:lambdaandcloudwatch. The logs added to the Lambda function are displayed here as shown below −" }, { "code": null, "e": 3410, "s": 3304, "text": "Now, let us add S3 trigger to the Lambda function and see the logs details in CloudWatch as shown below −" }, { "code": null, "e": 3520, "s": 3410, "text": "Let us update AWS Lambda code to display the file uploaded and bucket name as shown in the code given below −" }, { "code": null, "e": 3892, "s": 3520, "text": "exports.handler = (event, context, callback) => {\n // TODO implement\n console.log(\"Lambda monitoring using amazon cloudwatch\");\n const bucket = event.Records[0].s3.bucket.name;\n const filename = event.Records[0].s3.object.key;\n const message = `File is uploaded in - ${bucket} -> ${filename}`;\n console.log(message);\n callback(null, 'Hello from Lambda');\n};" }, { "code": null, "e": 3949, "s": 3892, "text": "Now, add file in s3storetestlambdaEventbucket as shown −" }, { "code": null, "e": 4107, "s": 3949, "text": "When the file is uploaded, AWS Lambda functions will get triggered and the console log messages from Lambda code are displayed in CloudWatch as shown below −" }, { "code": null, "e": 4182, "s": 4107, "text": "If there is any error, CloudWatch gives the error details as shown below −" }, { "code": null, "e": 4266, "s": 4182, "text": "Note that we have referred to the bucket name wrongly in AWS Lambda code as shown −" }, { "code": null, "e": 4635, "s": 4266, "text": "exports.handler = (event, context, callback) => {\n // TODO implement\n console.log(\"Lambda monitoring using amazon cloudwatch\");\n const bucket = event.Records[0].bucket.name;\n const filename = event.Records[0].s3.object.key;\n const message = `File is uploaded in - ${bucket} -> ${filename}`;\n console.log(message);\n callback(null, 'Hello from Lambda');\n};" }, { "code": null, "e": 4756, "s": 4635, "text": "The bucket name reference from the event is wrong. Thus, we should see an error displayed in CloudWatch as shown below −" }, { "code": null, "e": 4871, "s": 4756, "text": "The details of the Lambda function execution can be seen in the metrics. Click Metrics displayed in the left side." }, { "code": null, "e": 4954, "s": 4871, "text": "The graph details for the lambda function lambdaandcloudwatch are as shown below −" }, { "code": null, "e": 5106, "s": 4954, "text": "It gives details such as the duration for which the Lambda function is executed, number of times it is invoked and the errors from the Lambda function." }, { "code": null, "e": 5141, "s": 5106, "text": "\n 35 Lectures \n 7.5 hours \n" }, { "code": null, "e": 5165, "s": 5141, "text": " Mr. Pradeep Kshetrapal" }, { "code": null, "e": 5200, "s": 5165, "text": "\n 30 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5220, "s": 5200, "text": " Priyanka Choudhary" }, { "code": null, "e": 5255, "s": 5220, "text": "\n 44 Lectures \n 7.5 hours \n" }, { "code": null, "e": 5283, "s": 5255, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5316, "s": 5283, "text": "\n 51 Lectures \n 6 hours \n" }, { "code": null, "e": 5332, "s": 5316, "text": " Manuj Aggarwal" }, { "code": null, "e": 5365, "s": 5332, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 5377, "s": 5365, "text": " AR Shankar" }, { "code": null, "e": 5410, "s": 5377, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 5423, "s": 5410, "text": " Zach Miller" }, { "code": null, "e": 5430, "s": 5423, "text": " Print" }, { "code": null, "e": 5441, "s": 5430, "text": " Add Notes" } ]
Data Science Fundamentals (R): Import & Export Data from Excel — xlsx | by Carrie Lo | Towards Data Science
Data science is a very broad topic, before entering into this enormous forest, you ought to know the most fundamental part which is importing and exporting data correctly. Without the data, you cannot perform all the machine learning techniques or draw insightful analysis. You may think that importing and exporting are very easy, just one simple code with the file name inside. I had the same feeling before, but later on, I realized that there are some key parameters that need to be changed (especially if the data involves text), otherwise, you will not get the data as the way that you want. You will see the examples below. This article would give you a summary of using an R package, xlsx. You will learn how to import and export the excel files with different functions and what the differences are between them. Other import and export packages are discussed in series. medium.com xlsx Read, write, format Excel 2007 and Excel 97/2000/XP/2003 files The xlsx package gives programmatic control of Excel files using R. A high-level API allows the user to read a sheet of an xlsx document into a data.frame and write a data.frame to a file. Lower level functionality permits the direct manipulation of sheets, rows, and cells. For example, the user has control to set colors, fonts, data formats, add borders, hide/unhide sheets, add/remove rows, add/remove sheets, etc. The input data involves English text, number, Traditional Chinese text, and Simplified Chinese text. At the end of this demonstration, you will know what options should be specified to import and export data with different formats of context in R. Function to test (default settings) read.xlsx (file, sheetIndex, sheetName=NULL, rowIndex=NULL, startRow=NULL, endRow=NULL, colIndex=NULL, as.data.frame=TRUE, header=TRUE, colClasses=NA, keepFormulas=FALSE, encoding=”unknown”, password=NULL, ...) read.xlsx2 (file, sheetIndex, sheetName=NULL, startRow=1, colIndex=NULL, endRow=NULL, as.data.frame=TRUE, header=TRUE, colClasses=”character”, password=NULL, ...) write.xlsx (x, file, sheetName=”Sheet1", col.names=TRUE, row.names=TRUE, append=FALSE, showNA=TRUE, password=NULL) write.xlsx2 (x, file, sheetName=”Sheet1",col.names=TRUE, row.names=TRUE, append=FALSE, password=NULL, ...) #############library(xlsx)############## read excel xlsx - method 1xlsx_df = read.xlsx(file="Reference_Sample.xlsx", sheetName="Sample_Sheet", header=T, stringsAsFactors=F, encoding="UTF-8") str(xlsx_df) header=T retrieves the title of xlsx file in R. stringsAsFactors=F is used instead of T as we do not want R to treat the character inputs as factors. You can find that as the encoding is set to “UTF-8”, so the Chinese characters are shown in UTF code. If encoding is not set, the garbled code is shown. If you want to display Chinese characters or specific characters in other languages, the locale should be set beforehand. In this example, local = “Chinese” should be specified. local = “cht” can only display traditional Chinese text while local = “Chinese” can display both Traditional and Simplified Chinese words. Sys.setlocale(category = "LC_ALL", locale = "Chinese")# read excel xlsx - method 1xlsx_df = read.xlsx(file="Reference_Sample.xlsx", sheetName="Sample_Sheet", header=T, stringsAsFactors=F, encoding="UTF-8") # read excel xlsx - method 2xlsx_df2 = read.xlsx2(file="Reference_Sample.xlsx", sheetName="Sample_Sheet", header=T, stringsAsFactors=F) You can find that both methods, i.e. read.xlsx and read.xlsx2, show data in the same format. As the default encoding is “UTF-8”, so if the locale is set properly, i.e. locale = “Chinese”, the same output should be shown. Yet, when you check the structure of xlsx_df2, you can find something different. str(xlsx_df2) The structure of all variables become character. It may cause inconvenience if you want to do calculations later. When using read.xlsx and read.xlsx2, if column names contain space, all the spaces are changed to “.” Thus, when you do a selection on columns by using column names, you need to use the new names, i.e. “Traditional.Chinese” and “Simplified.Chinese” in this case. The following section is the demonstration for writing excel output. # write excel xlsx - method 1write.xlsx(xlsx_df, file="Output1.xlsx", sheetName="Sample_Sheet", row.names=F, showNA=F) row.names = F is indicated to remove the row index used in R. showNA = F is used so blanks will remain as blanks instead of being replaced by “NA” in the output file. However, the column names remain as those shown in R if the column names are not defined again before exporting, so you will still find those “.” in the column names. # write excel xlsx - method 2write.xlsx2(xlsx_df2, file="Output2.xlsx", sheetName="Sample_Sheet", row.names=F, showNA=F) The output of using write.xlsx2 shows similar output, but the context of all columns of xlsx_df2 is char, so the output will retain the same structure, and you can see that the numbers on column B become characters. read.xlsx is recommended as the original data structure is not changed, but you need to define the encoding method. (encoding = “UTF-8” is commonly used.) For writing an excel file, the output files of both write.xlsx and write.xlsx2 are quite similar, so you can use either one. One limitation of using xlsx is that it only supports the file with .xlsx extension, if you want to read xls file, readxl can be used (will be talked about in the next article). You can find other articles of data import and export in R here. If you are interested to know more tricks and skills, you are welcome to browse our website: https://cydalytics.blogspot.com/ LinkedIn: Carrie Lo — https://www.linkedin.com/in/carrielsc/ Yeung Wong — https://www.linkedin.com/in/yeungwong/ Data Science Fundamentals (R): Import Data from Excel — readxlData Science Fundamentals (R): Import Data from text files — textreadr & readtextData Visualization Tips (Power BI) — Convert Categorical Variables to Dummy VariablesChinese Word Cloud with Different Shape (Python)Making a Game for Kids to Learn English and Have Fun with Python Data Science Fundamentals (R): Import Data from Excel — readxl Data Science Fundamentals (R): Import Data from text files — textreadr & readtext Data Visualization Tips (Power BI) — Convert Categorical Variables to Dummy Variables Chinese Word Cloud with Different Shape (Python) Making a Game for Kids to Learn English and Have Fun with Python
[ { "code": null, "e": 678, "s": 47, "text": "Data science is a very broad topic, before entering into this enormous forest, you ought to know the most fundamental part which is importing and exporting data correctly. Without the data, you cannot perform all the machine learning techniques or draw insightful analysis. You may think that importing and exporting are very easy, just one simple code with the file name inside. I had the same feeling before, but later on, I realized that there are some key parameters that need to be changed (especially if the data involves text), otherwise, you will not get the data as the way that you want. You will see the examples below." }, { "code": null, "e": 869, "s": 678, "text": "This article would give you a summary of using an R package, xlsx. You will learn how to import and export the excel files with different functions and what the differences are between them." }, { "code": null, "e": 927, "s": 869, "text": "Other import and export packages are discussed in series." }, { "code": null, "e": 938, "s": 927, "text": "medium.com" }, { "code": null, "e": 943, "s": 938, "text": "xlsx" }, { "code": null, "e": 1006, "s": 943, "text": "Read, write, format Excel 2007 and Excel 97/2000/XP/2003 files" }, { "code": null, "e": 1425, "s": 1006, "text": "The xlsx package gives programmatic control of Excel files using R. A high-level API allows the user to read a sheet of an xlsx document into a data.frame and write a data.frame to a file. Lower level functionality permits the direct manipulation of sheets, rows, and cells. For example, the user has control to set colors, fonts, data formats, add borders, hide/unhide sheets, add/remove rows, add/remove sheets, etc." }, { "code": null, "e": 1526, "s": 1425, "text": "The input data involves English text, number, Traditional Chinese text, and Simplified Chinese text." }, { "code": null, "e": 1673, "s": 1526, "text": "At the end of this demonstration, you will know what options should be specified to import and export data with different formats of context in R." }, { "code": null, "e": 1709, "s": 1673, "text": "Function to test (default settings)" }, { "code": null, "e": 1920, "s": 1709, "text": "read.xlsx (file, sheetIndex, sheetName=NULL, rowIndex=NULL, startRow=NULL, endRow=NULL, colIndex=NULL, as.data.frame=TRUE, header=TRUE, colClasses=NA, keepFormulas=FALSE, encoding=”unknown”, password=NULL, ...)" }, { "code": null, "e": 2083, "s": 1920, "text": "read.xlsx2 (file, sheetIndex, sheetName=NULL, startRow=1, colIndex=NULL, endRow=NULL, as.data.frame=TRUE, header=TRUE, colClasses=”character”, password=NULL, ...)" }, { "code": null, "e": 2198, "s": 2083, "text": "write.xlsx (x, file, sheetName=”Sheet1\", col.names=TRUE, row.names=TRUE, append=FALSE, showNA=TRUE, password=NULL)" }, { "code": null, "e": 2305, "s": 2198, "text": "write.xlsx2 (x, file, sheetName=”Sheet1\",col.names=TRUE, row.names=TRUE, append=FALSE, password=NULL, ...)" }, { "code": null, "e": 2496, "s": 2305, "text": "#############library(xlsx)############## read excel xlsx - method 1xlsx_df = read.xlsx(file=\"Reference_Sample.xlsx\", sheetName=\"Sample_Sheet\", header=T, stringsAsFactors=F, encoding=\"UTF-8\")" }, { "code": null, "e": 2509, "s": 2496, "text": "str(xlsx_df)" }, { "code": null, "e": 2557, "s": 2509, "text": "header=T retrieves the title of xlsx file in R." }, { "code": null, "e": 2659, "s": 2557, "text": "stringsAsFactors=F is used instead of T as we do not want R to treat the character inputs as factors." }, { "code": null, "e": 2812, "s": 2659, "text": "You can find that as the encoding is set to “UTF-8”, so the Chinese characters are shown in UTF code. If encoding is not set, the garbled code is shown." }, { "code": null, "e": 2990, "s": 2812, "text": "If you want to display Chinese characters or specific characters in other languages, the locale should be set beforehand. In this example, local = “Chinese” should be specified." }, { "code": null, "e": 3129, "s": 2990, "text": "local = “cht” can only display traditional Chinese text while local = “Chinese” can display both Traditional and Simplified Chinese words." }, { "code": null, "e": 3335, "s": 3129, "text": "Sys.setlocale(category = \"LC_ALL\", locale = \"Chinese\")# read excel xlsx - method 1xlsx_df = read.xlsx(file=\"Reference_Sample.xlsx\", sheetName=\"Sample_Sheet\", header=T, stringsAsFactors=F, encoding=\"UTF-8\")" }, { "code": null, "e": 3471, "s": 3335, "text": "# read excel xlsx - method 2xlsx_df2 = read.xlsx2(file=\"Reference_Sample.xlsx\", sheetName=\"Sample_Sheet\", header=T, stringsAsFactors=F)" }, { "code": null, "e": 3773, "s": 3471, "text": "You can find that both methods, i.e. read.xlsx and read.xlsx2, show data in the same format. As the default encoding is “UTF-8”, so if the locale is set properly, i.e. locale = “Chinese”, the same output should be shown. Yet, when you check the structure of xlsx_df2, you can find something different." }, { "code": null, "e": 3787, "s": 3773, "text": "str(xlsx_df2)" }, { "code": null, "e": 3901, "s": 3787, "text": "The structure of all variables become character. It may cause inconvenience if you want to do calculations later." }, { "code": null, "e": 4003, "s": 3901, "text": "When using read.xlsx and read.xlsx2, if column names contain space, all the spaces are changed to “.”" }, { "code": null, "e": 4164, "s": 4003, "text": "Thus, when you do a selection on columns by using column names, you need to use the new names, i.e. “Traditional.Chinese” and “Simplified.Chinese” in this case." }, { "code": null, "e": 4233, "s": 4164, "text": "The following section is the demonstration for writing excel output." }, { "code": null, "e": 4352, "s": 4233, "text": "# write excel xlsx - method 1write.xlsx(xlsx_df, file=\"Output1.xlsx\", sheetName=\"Sample_Sheet\", row.names=F, showNA=F)" }, { "code": null, "e": 4414, "s": 4352, "text": "row.names = F is indicated to remove the row index used in R." }, { "code": null, "e": 4519, "s": 4414, "text": "showNA = F is used so blanks will remain as blanks instead of being replaced by “NA” in the output file." }, { "code": null, "e": 4686, "s": 4519, "text": "However, the column names remain as those shown in R if the column names are not defined again before exporting, so you will still find those “.” in the column names." }, { "code": null, "e": 4807, "s": 4686, "text": "# write excel xlsx - method 2write.xlsx2(xlsx_df2, file=\"Output2.xlsx\", sheetName=\"Sample_Sheet\", row.names=F, showNA=F)" }, { "code": null, "e": 5023, "s": 4807, "text": "The output of using write.xlsx2 shows similar output, but the context of all columns of xlsx_df2 is char, so the output will retain the same structure, and you can see that the numbers on column B become characters." }, { "code": null, "e": 5178, "s": 5023, "text": "read.xlsx is recommended as the original data structure is not changed, but you need to define the encoding method. (encoding = “UTF-8” is commonly used.)" }, { "code": null, "e": 5303, "s": 5178, "text": "For writing an excel file, the output files of both write.xlsx and write.xlsx2 are quite similar, so you can use either one." }, { "code": null, "e": 5481, "s": 5303, "text": "One limitation of using xlsx is that it only supports the file with .xlsx extension, if you want to read xls file, readxl can be used (will be talked about in the next article)." }, { "code": null, "e": 5546, "s": 5481, "text": "You can find other articles of data import and export in R here." }, { "code": null, "e": 5672, "s": 5546, "text": "If you are interested to know more tricks and skills, you are welcome to browse our website: https://cydalytics.blogspot.com/" }, { "code": null, "e": 5682, "s": 5672, "text": "LinkedIn:" }, { "code": null, "e": 5733, "s": 5682, "text": "Carrie Lo — https://www.linkedin.com/in/carrielsc/" }, { "code": null, "e": 5785, "s": 5733, "text": "Yeung Wong — https://www.linkedin.com/in/yeungwong/" }, { "code": null, "e": 6126, "s": 5785, "text": "Data Science Fundamentals (R): Import Data from Excel — readxlData Science Fundamentals (R): Import Data from text files — textreadr & readtextData Visualization Tips (Power BI) — Convert Categorical Variables to Dummy VariablesChinese Word Cloud with Different Shape (Python)Making a Game for Kids to Learn English and Have Fun with Python" }, { "code": null, "e": 6189, "s": 6126, "text": "Data Science Fundamentals (R): Import Data from Excel — readxl" }, { "code": null, "e": 6271, "s": 6189, "text": "Data Science Fundamentals (R): Import Data from text files — textreadr & readtext" }, { "code": null, "e": 6357, "s": 6271, "text": "Data Visualization Tips (Power BI) — Convert Categorical Variables to Dummy Variables" }, { "code": null, "e": 6406, "s": 6357, "text": "Chinese Word Cloud with Different Shape (Python)" } ]
java.time.Duration.ofSeconds() Method Example
The java.time.Duration.ofSeconds(long seconds) method obtains a Duration representing a number of seconds and an adjustment in nanoseconds. Following is the declaration for java.time.Duration.ofSeconds(long seconds) method. public static Duration ofSeconds(long seconds, long nanoAdjustment) seconds − the number of seconds, positive or negative. seconds − the number of seconds, positive or negative. nanoAdjustment − the nanosecond adjustment to the number of seconds, positive or negative. nanoAdjustment − the nanosecond adjustment to the number of seconds, positive or negative. a Duration, not null. ArithmeticException − if the adjustment causes the seconds to exceed the capacity of Duration. The following example shows the usage of java.time.Duration.ofSeconds(long seconds, long nanoAdjustment) method. package com.tutorialspoint; import java.time.Duration; public class DurationDemo { public static void main(String[] args) { Duration duration = Duration.ofSeconds(2); Duration duration1 = duration.plus(Duration.ofSeconds(5)); System.out.println(duration1.toMillis()); } } Let us compile and run the above program, this will produce the following result − 7000 Print Add Notes Bookmark this page
[ { "code": null, "e": 2055, "s": 1915, "text": "The java.time.Duration.ofSeconds(long seconds) method obtains a Duration representing a number of seconds and an adjustment in nanoseconds." }, { "code": null, "e": 2139, "s": 2055, "text": "Following is the declaration for java.time.Duration.ofSeconds(long seconds) method." }, { "code": null, "e": 2208, "s": 2139, "text": "public static Duration ofSeconds(long seconds, long nanoAdjustment)\n" }, { "code": null, "e": 2263, "s": 2208, "text": "seconds − the number of seconds, positive or negative." }, { "code": null, "e": 2318, "s": 2263, "text": "seconds − the number of seconds, positive or negative." }, { "code": null, "e": 2409, "s": 2318, "text": "nanoAdjustment − the nanosecond adjustment to the number of seconds, positive or negative." }, { "code": null, "e": 2500, "s": 2409, "text": "nanoAdjustment − the nanosecond adjustment to the number of seconds, positive or negative." }, { "code": null, "e": 2522, "s": 2500, "text": "a Duration, not null." }, { "code": null, "e": 2617, "s": 2522, "text": "ArithmeticException − if the adjustment causes the seconds to exceed the capacity of Duration." }, { "code": null, "e": 2730, "s": 2617, "text": "The following example shows the usage of java.time.Duration.ofSeconds(long seconds, long nanoAdjustment) method." }, { "code": null, "e": 3029, "s": 2730, "text": "package com.tutorialspoint;\n\nimport java.time.Duration;\n\npublic class DurationDemo {\n public static void main(String[] args) {\n\n Duration duration = Duration.ofSeconds(2);\n Duration duration1 = duration.plus(Duration.ofSeconds(5));\n System.out.println(duration1.toMillis());\n }\n}" }, { "code": null, "e": 3112, "s": 3029, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3118, "s": 3112, "text": "7000\n" }, { "code": null, "e": 3125, "s": 3118, "text": " Print" }, { "code": null, "e": 3136, "s": 3125, "text": " Add Notes" } ]
How to use function Alias in PowerShell?
Like the Parameter alias, we can also set the function alias name to refer to the function as a different name. function Test-NewConnection{ [CmdletBinding()] [Alias("TC")] param( [Parameter(Mandatory=$true)] [String]$Server ) Write-Output "Testing $server connection" } Now, instead of the Test-NewConnection function name, you can directly use the function alias “TC” as shown below. PS C:\> Tc -Server "Test1-win2k16" Testing Test1-win2k16 connection
[ { "code": null, "e": 1174, "s": 1062, "text": "Like the Parameter alias, we can also set the function alias name to refer to the function as a different name." }, { "code": null, "e": 1360, "s": 1174, "text": "function Test-NewConnection{\n [CmdletBinding()]\n [Alias(\"TC\")]\n param(\n [Parameter(Mandatory=$true)]\n [String]$Server\n )\n Write-Output \"Testing $server connection\"\n}" }, { "code": null, "e": 1475, "s": 1360, "text": "Now, instead of the Test-NewConnection function name, you can directly use the function alias “TC” as shown below." }, { "code": null, "e": 1543, "s": 1475, "text": "PS C:\\> Tc -Server \"Test1-win2k16\"\nTesting Test1-win2k16 connection" } ]
What is an inline function in C language?
The inline function can be substituted at the place where the function call is happening. Function substitution is always compiler choice. In an inline function, a function call is replaced by the actual program code. In an inline function, a function call is replaced by the actual program code. Most of the Inline functions are used for small computations. They are not suitable for large computing. Most of the Inline functions are used for small computations. They are not suitable for large computing. An inline function is similar to a normal function. The only difference is that we place a keyword inline before the function name. An inline function is similar to a normal function. The only difference is that we place a keyword inline before the function name. Inline functions are created with the following syntax − inline function_name (){ //function definition } Following is the C program for inline functions − #include<stdio.h> inline int mul(int a, int b) //inline function declaration{ return(a*b); } int main(){ int c; c=mul(2,3); printf("Multiplication:%d\n",c); return 0; } When the above program is executed, it produces the following result − 6
[ { "code": null, "e": 1201, "s": 1062, "text": "The inline function can be substituted at the place where the function call is happening. Function substitution is always compiler choice." }, { "code": null, "e": 1280, "s": 1201, "text": "In an inline function, a function call is replaced by the actual program code." }, { "code": null, "e": 1359, "s": 1280, "text": "In an inline function, a function call is replaced by the actual program code." }, { "code": null, "e": 1464, "s": 1359, "text": "Most of the Inline functions are used for small computations. They are not suitable for large computing." }, { "code": null, "e": 1569, "s": 1464, "text": "Most of the Inline functions are used for small computations. They are not suitable for large computing." }, { "code": null, "e": 1701, "s": 1569, "text": "An inline function is similar to a normal function. The only difference is that we place a keyword inline before the function name." }, { "code": null, "e": 1833, "s": 1701, "text": "An inline function is similar to a normal function. The only difference is that we place a keyword inline before the function name." }, { "code": null, "e": 1890, "s": 1833, "text": "Inline functions are created with the following syntax −" }, { "code": null, "e": 1942, "s": 1890, "text": "inline function_name (){\n //function definition\n}" }, { "code": null, "e": 1992, "s": 1942, "text": "Following is the C program for inline functions −" }, { "code": null, "e": 2176, "s": 1992, "text": "#include<stdio.h>\ninline int mul(int a, int b) //inline function declaration{\n return(a*b);\n}\nint main(){\n int c;\n c=mul(2,3);\n printf(\"Multiplication:%d\\n\",c);\n return 0;\n}" }, { "code": null, "e": 2247, "s": 2176, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2249, "s": 2247, "text": "6" } ]
Angular PrimeNG Menu Component - GeeksforGeeks
08 Sep, 2021 Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Menu component in Angular PrimeNG. We will also learn about the properties, events, methods & styling along with their syntaxes that will be used in the code. Menu component: It is used to make a component that contains some information & supports either static or dynamic positioning. Properties: model: It is an array of menuitems. It accepts the array data type as input & the default value is null. popup: It is used to define if the menu would be displayed as a popup. It is of boolean data type & the default value is false. style: It is used to set the inline style of the component. It is of string data type & the default value is null. styleClass: It is used to set the style class of the component. It is of string data type & the default value is null. appendTo: It is the target element to attach the overlay. It accepts any data type & the default value is null. baseZIndex: It is used to set base zIndex value to use in layering. It is of number data type & the default value is 0. autoZIndex: It is used to specify whether to automatically manage the layering. It is of boolean data type & the default value is true. showTransitionOptions: It is used to show transition options of the show animation. It is of string data type & the default value is .12s cubic-bezier(0, 0, 0.2, 1). hideTransitionOptions: It is used to hide transition options of the hide animation. It is of string data type & the default value is .1s linear. Events: onShow: It is a callback that is fired when the overlay menu is shown. onHide: It is a callback that is fired when the overlay menu is hidden. Methods: toggle: It is used to toggles the visibility of the popup menu. show: It is used to displays the popup menu. hide: It is used to hides the popup menu. Styling: p-menu: it is a container element. p-menu-list: it is a list element. p-menuitem: it is a menuitem element. p-menuitem-text: it is a label of a menuitem. p-menuitem-icon: it is an icon of a menuitem. Creating Angular application & module installation: Step 1: Create an Angular application using the following command. ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command. cd appname Step 3: Install PrimeNG in your given directory. npm install primeng --save npm install primeicons --save Project Structure: It will look like the following: Example 1: This is the basic example that shows how to use the Menu component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG Menu Component</h5><p-menu [model]="gfg"></p-menu> app.module.ts import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { MenuModule } from 'primeng/menu';import { ButtonModule } from 'primeng/button'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, MenuModule, ButtonModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {} app.component.ts import { Component } from '@angular/core';import { MenuItem } from 'primeng/api'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { gfg: MenuItem[]; ngOnInit() { this.gfg = [ { label: 'HTML', items: [ { label: 'HTML 1' }, { label: 'HTML 2' } ] }, { label: 'Angular', items: [ { label: 'Angular 1' }, { label: 'Angular 2' } ] } ]; }} Output: Example 2: In this example, we are making a menu list using a button. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG Menu Component</h5><button type="button" pButton pRipple label="Click Here" (click)="menu.toggle($event)"></button><p-menu #menu [popup]="true" [model]="gfg"></p-menu> app.module.ts import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { MenuModule } from 'primeng/menu';import { ButtonModule } from 'primeng/button';import { RippleModule } from 'primeng/ripple'; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, MenuModule, RippleModule, ButtonModule ], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {} app.component.ts import { Component } from '@angular/core';import { MenuItem, MessageService, PrimeNGConfig } from 'primeng/api'; @Component({ selector: 'my-app', templateUrl: './app.component.html', providers: [MessageService]})export class AppComponent { gfg: MenuItem[]; constructor( private messageService: MessageService, private primengConfig: PrimeNGConfig ) {} ngOnInit() { this.primengConfig.ripple = true; this.gfg = [ { label: 'HTML', items: [ { label: 'HTML 1' }, { label: 'HTML 2' } ] }, { label: 'Angular', items: [ { label: 'Angular 1' }, { label: 'Angular 2' } ] } ]; }} Output: Reference: https://primefaces.org/primeng/showcase/#/menu Angular-PrimeNG AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Angular Libraries For Web Developers How to use <mat-chip-list> and <mat-chip> in Angular Material ? How to make a Bootstrap Modal Popup in Angular 9/8 ? How to create module with Routing in Angular 9 ? Angular PrimeNG Dropdown Component Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25109, "s": 25081, "text": "\n08 Sep, 2021" }, { "code": null, "e": 25514, "s": 25109, "text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Menu component in Angular PrimeNG. We will also learn about the properties, events, methods & styling along with their syntaxes that will be used in the code. " }, { "code": null, "e": 25641, "s": 25514, "text": "Menu component: It is used to make a component that contains some information & supports either static or dynamic positioning." }, { "code": null, "e": 25653, "s": 25641, "text": "Properties:" }, { "code": null, "e": 25758, "s": 25653, "text": "model: It is an array of menuitems. It accepts the array data type as input & the default value is null." }, { "code": null, "e": 25886, "s": 25758, "text": "popup: It is used to define if the menu would be displayed as a popup. It is of boolean data type & the default value is false." }, { "code": null, "e": 26001, "s": 25886, "text": "style: It is used to set the inline style of the component. It is of string data type & the default value is null." }, { "code": null, "e": 26120, "s": 26001, "text": "styleClass: It is used to set the style class of the component. It is of string data type & the default value is null." }, { "code": null, "e": 26232, "s": 26120, "text": "appendTo: It is the target element to attach the overlay. It accepts any data type & the default value is null." }, { "code": null, "e": 26353, "s": 26232, "text": "baseZIndex: It is used to set base zIndex value to use in layering. It is of number data type & the default value is 0." }, { "code": null, "e": 26489, "s": 26353, "text": "autoZIndex: It is used to specify whether to automatically manage the layering. It is of boolean data type & the default value is true." }, { "code": null, "e": 26655, "s": 26489, "text": "showTransitionOptions: It is used to show transition options of the show animation. It is of string data type & the default value is .12s cubic-bezier(0, 0, 0.2, 1)." }, { "code": null, "e": 26800, "s": 26655, "text": "hideTransitionOptions: It is used to hide transition options of the hide animation. It is of string data type & the default value is .1s linear." }, { "code": null, "e": 26808, "s": 26800, "text": "Events:" }, { "code": null, "e": 26879, "s": 26808, "text": "onShow: It is a callback that is fired when the overlay menu is shown." }, { "code": null, "e": 26951, "s": 26879, "text": "onHide: It is a callback that is fired when the overlay menu is hidden." }, { "code": null, "e": 26962, "s": 26953, "text": "Methods:" }, { "code": null, "e": 27026, "s": 26962, "text": "toggle: It is used to toggles the visibility of the popup menu." }, { "code": null, "e": 27071, "s": 27026, "text": "show: It is used to displays the popup menu." }, { "code": null, "e": 27113, "s": 27071, "text": "hide: It is used to hides the popup menu." }, { "code": null, "e": 27122, "s": 27113, "text": "Styling:" }, { "code": null, "e": 27157, "s": 27122, "text": "p-menu: it is a container element." }, { "code": null, "e": 27192, "s": 27157, "text": "p-menu-list: it is a list element." }, { "code": null, "e": 27230, "s": 27192, "text": "p-menuitem: it is a menuitem element." }, { "code": null, "e": 27276, "s": 27230, "text": "p-menuitem-text: it is a label of a menuitem." }, { "code": null, "e": 27322, "s": 27276, "text": "p-menuitem-icon: it is an icon of a menuitem." }, { "code": null, "e": 27374, "s": 27322, "text": "Creating Angular application & module installation:" }, { "code": null, "e": 27441, "s": 27374, "text": "Step 1: Create an Angular application using the following command." }, { "code": null, "e": 27456, "s": 27441, "text": "ng new appname" }, { "code": null, "e": 27553, "s": 27456, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command." }, { "code": null, "e": 27564, "s": 27553, "text": "cd appname" }, { "code": null, "e": 27613, "s": 27564, "text": "Step 3: Install PrimeNG in your given directory." }, { "code": null, "e": 27670, "s": 27613, "text": "npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 27722, "s": 27670, "text": "Project Structure: It will look like the following:" }, { "code": null, "e": 27801, "s": 27722, "text": "Example 1: This is the basic example that shows how to use the Menu component." }, { "code": null, "e": 27820, "s": 27801, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG Menu Component</h5><p-menu [model]=\"gfg\"></p-menu>", "e": 27905, "s": 27820, "text": null }, { "code": null, "e": 27921, "s": 27907, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { MenuModule } from 'primeng/menu';import { ButtonModule } from 'primeng/button'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, MenuModule, ButtonModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}", "e": 28443, "s": 27921, "text": null }, { "code": null, "e": 28460, "s": 28443, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core';import { MenuItem } from 'primeng/api'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { gfg: MenuItem[]; ngOnInit() { this.gfg = [ { label: 'HTML', items: [ { label: 'HTML 1' }, { label: 'HTML 2' } ] }, { label: 'Angular', items: [ { label: 'Angular 1' }, { label: 'Angular 2' } ] } ]; }}", "e": 29035, "s": 28460, "text": null }, { "code": null, "e": 29043, "s": 29035, "text": "Output:" }, { "code": null, "e": 29113, "s": 29043, "text": "Example 2: In this example, we are making a menu list using a button." }, { "code": null, "e": 29132, "s": 29113, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG Menu Component</h5><button type=\"button\" pButton pRipple label=\"Click Here\" (click)=\"menu.toggle($event)\"></button><p-menu #menu [popup]=\"true\" [model]=\"gfg\"></p-menu>", "e": 29341, "s": 29132, "text": null }, { "code": null, "e": 29355, "s": 29341, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { MenuModule } from 'primeng/menu';import { ButtonModule } from 'primeng/button';import { RippleModule } from 'primeng/ripple'; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, MenuModule, RippleModule, ButtonModule ], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}", "e": 29929, "s": 29355, "text": null }, { "code": null, "e": 29946, "s": 29929, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core';import { MenuItem, MessageService, PrimeNGConfig } from 'primeng/api'; @Component({ selector: 'my-app', templateUrl: './app.component.html', providers: [MessageService]})export class AppComponent { gfg: MenuItem[]; constructor( private messageService: MessageService, private primengConfig: PrimeNGConfig ) {} ngOnInit() { this.primengConfig.ripple = true; this.gfg = [ { label: 'HTML', items: [ { label: 'HTML 1' }, { label: 'HTML 2' } ] }, { label: 'Angular', items: [ { label: 'Angular 1' }, { label: 'Angular 2' } ] } ]; }}", "e": 30726, "s": 29946, "text": null }, { "code": null, "e": 30734, "s": 30726, "text": "Output:" }, { "code": null, "e": 30792, "s": 30734, "text": "Reference: https://primefaces.org/primeng/showcase/#/menu" }, { "code": null, "e": 30808, "s": 30792, "text": "Angular-PrimeNG" }, { "code": null, "e": 30818, "s": 30808, "text": "AngularJS" }, { "code": null, "e": 30835, "s": 30818, "text": "Web Technologies" }, { "code": null, "e": 30933, "s": 30835, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30942, "s": 30933, "text": "Comments" }, { "code": null, "e": 30955, "s": 30942, "text": "Old Comments" }, { "code": null, "e": 30999, "s": 30955, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 31063, "s": 30999, "text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?" }, { "code": null, "e": 31116, "s": 31063, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 31165, "s": 31116, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 31200, "s": 31165, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 31242, "s": 31200, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 31275, "s": 31242, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31337, "s": 31275, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31380, "s": 31337, "text": "How to fetch data from an API in ReactJS ?" } ]
How to get android application version name?
This example demonstrate about How to get android application version name. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:gravity = "center" android:layout_height = "match_parent" tools:context = ".MainActivity" android:orientation = "vertical"> <TextView android:id = "@+id/text" android:textSize = "30sp" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> </LinearLayout> In the above code, we have taken text view to show application version name. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.app.ActivityManager; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.telephony.TelephonyManager; import android.view.WindowManager; import android.widget.TextView; import java.util.List; public class MainActivity extends AppCompatActivity { TextView textView; @RequiresApi(api = Build.VERSION_CODES.P) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND); setContentView(R.layout.activity_main); textView = findViewById(R.id.text); PackageManager pm = getApplicationContext().getPackageManager(); String pkgName = getApplicationContext().getPackageName(); PackageInfo pkgInfo = null; try { pkgInfo = pm.getPackageInfo(pkgName, 0); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } String ver = pkgInfo.versionName; textView.setText("" +ver); } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code
[ { "code": null, "e": 1138, "s": 1062, "text": "This example demonstrate about How to get android application version name." }, { "code": null, "e": 1267, "s": 1138, "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": 1332, "s": 1267, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1928, "s": 1332, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <TextView\n android:id = \"@+id/text\"\n android:textSize = \"30sp\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2005, "s": 1928, "text": "In the above code, we have taken text view to show application version name." }, { "code": null, "e": 2062, "s": 2005, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3377, "s": 2062, "text": "package com.example.myapplication;\nimport android.app.ActivityManager;\nimport android.content.Context;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.telephony.TelephonyManager;\nimport android.view.WindowManager;\nimport android.widget.TextView;\nimport java.util.List;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @RequiresApi(api = Build.VERSION_CODES.P)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,\n WindowManager.LayoutParams.FLAG_BLUR_BEHIND);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n PackageManager pm = getApplicationContext().getPackageManager();\n String pkgName = getApplicationContext().getPackageName();\n PackageInfo pkgInfo = null;\n try {\n pkgInfo = pm.getPackageInfo(pkgName, 0);\n } catch (PackageManager.NameNotFoundException e) {\n e.printStackTrace();\n }\n String ver = pkgInfo.versionName;\n textView.setText(\"\" +ver);\n }\n}" }, { "code": null, "e": 3724, "s": 3377, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 3764, "s": 3724, "text": "Click here to download the project code" } ]
fseek() vs rewind() in C
fseek() in C language is used to move file pointer to a specific position. Offset and stream are the destination of pointer, given in the function parameters. If successful, it returns zero, else non-zero value is returned. Here is the syntax of fseek() in C language, int fseek(FILE *stream, long int offset, int whence) Here are the parameters used in fseek(), stream − This is the pointer to identify the stream. stream − This is the pointer to identify the stream. offset − This is the number of bytes from the position. offset − This is the number of bytes from the position. whence − This is the position from where offset is added. whence − This is the position from where offset is added. whence is specified by one of the following constants. SEEK_END − End of file. SEEK_END − End of file. SEEK_SET − Starting of file. SEEK_SET − Starting of file. SEEK_CUR − Current position of file pointer. SEEK_CUR − Current position of file pointer. Here is an example of fseek() in C language − Let’s say we have “demo.txt” file with the following content − This is demo text! This is demo text! This is demo text! This is demo text! Now let us see the code. #include<stdio.h> void main() { FILE *f; f = fopen("demo.txt", "r"); if(f == NULL) { printf("\n Can't open file or file doesn't exist."); exit(0); } fseek(f, 0, SEEK_END); printf("The size of file : %ld bytes", ftell(f)); getch(); } The size of file : 78 bytes In the above program, file “demo.txt” is opened using fopen() and fseek() function is used to move the pointer to the end of the file. f = fopen("demo.txt", "r"); if(f == NULL) { printf("\n Can't open file or file doesn't exist."); exit(0); } fseek(f, 0, SEEK_END); The function rewind() is used to set the position of file to the beginning of given stream. It does not return any value. Here is the syntax of rewind() in C language, void rewind(FILE *stream); Here is an example of rewind() in C language, Let’s say we have “new.txt” file with the following content − This is demo! This is demo! Now, let us see the example. #include<stdio.h> void main() { FILE *f; f = fopen("new.txt", "r"); if(f == NULL) { printf("\n Can't open file or file doesn't exist."); exit(0); } rewind(f); fseek(f, 0, SEEK_END); printf("The size of file : %ld bytes", ftell(f)); getch(); } The size of file : 28 bytes In the above program, file is opened by using fopen() and if pointer variable is null, it will display can’t open file or file doesn’t exist. The function rewind() is moving the pointer to the starting of file. f = fopen("new.txt", "r"); if(f == NULL) { printf("\n Can't open file or file doesn't exist."); exit(0); } rewind(f);
[ { "code": null, "e": 1286, "s": 1062, "text": "fseek() in C language is used to move file pointer to a specific position. Offset and stream are the destination of pointer, given in the function parameters. If successful, it returns zero, else non-zero value is returned." }, { "code": null, "e": 1331, "s": 1286, "text": "Here is the syntax of fseek() in C language," }, { "code": null, "e": 1384, "s": 1331, "text": "int fseek(FILE *stream, long int offset, int whence)" }, { "code": null, "e": 1425, "s": 1384, "text": "Here are the parameters used in fseek()," }, { "code": null, "e": 1478, "s": 1425, "text": "stream − This is the pointer to identify the stream." }, { "code": null, "e": 1531, "s": 1478, "text": "stream − This is the pointer to identify the stream." }, { "code": null, "e": 1587, "s": 1531, "text": "offset − This is the number of bytes from the position." }, { "code": null, "e": 1643, "s": 1587, "text": "offset − This is the number of bytes from the position." }, { "code": null, "e": 1701, "s": 1643, "text": "whence − This is the position from where offset is added." }, { "code": null, "e": 1759, "s": 1701, "text": "whence − This is the position from where offset is added." }, { "code": null, "e": 1814, "s": 1759, "text": "whence is specified by one of the following constants." }, { "code": null, "e": 1838, "s": 1814, "text": "SEEK_END − End of file." }, { "code": null, "e": 1862, "s": 1838, "text": "SEEK_END − End of file." }, { "code": null, "e": 1891, "s": 1862, "text": "SEEK_SET − Starting of file." }, { "code": null, "e": 1920, "s": 1891, "text": "SEEK_SET − Starting of file." }, { "code": null, "e": 1965, "s": 1920, "text": "SEEK_CUR − Current position of file pointer." }, { "code": null, "e": 2010, "s": 1965, "text": "SEEK_CUR − Current position of file pointer." }, { "code": null, "e": 2056, "s": 2010, "text": "Here is an example of fseek() in C language −" }, { "code": null, "e": 2119, "s": 2056, "text": "Let’s say we have “demo.txt” file with the following content −" }, { "code": null, "e": 2195, "s": 2119, "text": "This is demo text!\nThis is demo text!\nThis is demo text!\nThis is demo text!" }, { "code": null, "e": 2220, "s": 2195, "text": "Now let us see the code." }, { "code": null, "e": 2486, "s": 2220, "text": "#include<stdio.h>\nvoid main() {\n FILE *f;\n f = fopen(\"demo.txt\", \"r\");\n if(f == NULL) {\n printf(\"\\n Can't open file or file doesn't exist.\");\n exit(0);\n }\n fseek(f, 0, SEEK_END);\n printf(\"The size of file : %ld bytes\", ftell(f));\n getch();\n}" }, { "code": null, "e": 2514, "s": 2486, "text": "The size of file : 78 bytes" }, { "code": null, "e": 2649, "s": 2514, "text": "In the above program, file “demo.txt” is opened using fopen() and fseek() function is used to move the pointer to the end of the file." }, { "code": null, "e": 2786, "s": 2649, "text": "f = fopen(\"demo.txt\", \"r\");\nif(f == NULL) {\n printf(\"\\n Can't open file or file doesn't exist.\");\n exit(0);\n}\nfseek(f, 0, SEEK_END);" }, { "code": null, "e": 2908, "s": 2786, "text": "The function rewind() is used to set the position of file to the beginning of given stream. It does not return any value." }, { "code": null, "e": 2954, "s": 2908, "text": "Here is the syntax of rewind() in C language," }, { "code": null, "e": 2981, "s": 2954, "text": "void rewind(FILE *stream);" }, { "code": null, "e": 3027, "s": 2981, "text": "Here is an example of rewind() in C language," }, { "code": null, "e": 3089, "s": 3027, "text": "Let’s say we have “new.txt” file with the following content −" }, { "code": null, "e": 3117, "s": 3089, "text": "This is demo!\nThis is demo!" }, { "code": null, "e": 3146, "s": 3117, "text": "Now, let us see the example." }, { "code": null, "e": 3425, "s": 3146, "text": "#include<stdio.h>\nvoid main() {\n FILE *f;\n f = fopen(\"new.txt\", \"r\");\n if(f == NULL) {\n printf(\"\\n Can't open file or file doesn't exist.\");\n exit(0);\n }\n rewind(f);\n fseek(f, 0, SEEK_END);\n printf(\"The size of file : %ld bytes\", ftell(f));\n getch();\n}" }, { "code": null, "e": 3453, "s": 3425, "text": "The size of file : 28 bytes" }, { "code": null, "e": 3664, "s": 3453, "text": "In the above program, file is opened by using fopen() and if pointer variable is null, it will display can’t open file or file doesn’t exist. The function rewind() is moving the pointer to the starting of file." }, { "code": null, "e": 3788, "s": 3664, "text": "f = fopen(\"new.txt\", \"r\");\nif(f == NULL) {\n printf(\"\\n Can't open file or file doesn't exist.\");\n exit(0);\n}\nrewind(f);" } ]