title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Comparable vs Comparator in Java - GeeksforGeeks
|
29 May, 2021
Java provides two interfaces to sort objects using data members of the class:
ComparableComparator
Comparable
Comparator
Using Comparable Interface
A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface to compare its instances. Consider a Movie class that has members like, rating, name, year. Suppose we wish to sort a list of Movies based on year of release. We can implement the Comparable interface with the Movie class, and we override the method compareTo() of Comparable interface.
Java
// A Java program to demonstrate use of Comparableimport java.io.*;import java.util.*; // A class 'Movie' that implements Comparableclass Movie implements Comparable<Movie>{ private double rating; private String name; private int year; // Used to sort movies by year public int compareTo(Movie m) { return this.year - m.year; } // Constructor public Movie(String nm, double rt, int yr) { this.name = nm; this.rating = rt; this.year = yr; } // Getter methods for accessing private data public double getRating() { return rating; } public String getName() { return name; } public int getYear() { return year; }} // Driver classclass Main{ public static void main(String[] args) { ArrayList<Movie> list = new ArrayList<Movie>(); list.add(new Movie("Force Awakens", 8.3, 2015)); list.add(new Movie("Star Wars", 8.7, 1977)); list.add(new Movie("Empire Strikes Back", 8.8, 1980)); list.add(new Movie("Return of the Jedi", 8.4, 1983)); Collections.sort(list); System.out.println("Movies after sorting : "); for (Movie movie: list) { System.out.println(movie.getName() + " " + movie.getRating() + " " + movie.getYear()); } }}
Output:
Movies after sorting :
Star Wars 8.7 1977
Empire Strikes Back 8.8 1980
Return of the Jedi 8.4 1983
Force Awakens 8.3 2015
Now, suppose we want to sort movies by their rating and names as well. When we make a collection element comparable(by having it implement Comparable), we get only one chance to implement the compareTo() method. The solution is using Comparator.
Using Comparator
Unlike Comparable, Comparator is external to the element type we are comparing. It’s a separate class. We create multiple separate classes (that implement Comparator) to compare by different members.Collections class has a second sort() method and it takes Comparator. The sort() method invokes the compare() to sort objects.To compare movies by Rating, we need to do 3 things :
Create a class that implements Comparator (and thus the compare() method that does the work previously done by compareTo()).Make an instance of the Comparator class.Call the overloaded sort() method, giving it both the list and the instance of the class that implements Comparator.
Create a class that implements Comparator (and thus the compare() method that does the work previously done by compareTo()).
Make an instance of the Comparator class.
Call the overloaded sort() method, giving it both the list and the instance of the class that implements Comparator.
Java
//A Java program to demonstrate Comparator interfaceimport java.io.*;import java.util.*; // A class 'Movie' that implements Comparableclass Movie implements Comparable<Movie>{ private double rating; private String name; private int year; // Used to sort movies by year public int compareTo(Movie m) { return this.year - m.year; } // Constructor public Movie(String nm, double rt, int yr) { this.name = nm; this.rating = rt; this.year = yr; } // Getter methods for accessing private data public double getRating() { return rating; } public String getName() { return name; } public int getYear() { return year; }} // Class to compare Movies by ratingsclass RatingCompare implements Comparator<Movie>{ public int compare(Movie m1, Movie m2) { if (m1.getRating() < m2.getRating()) return -1; if (m1.getRating() > m2.getRating()) return 1; else return 0; }} // Class to compare Movies by nameclass NameCompare implements Comparator<Movie>{ public int compare(Movie m1, Movie m2) { return m1.getName().compareTo(m2.getName()); }} // Driver classclass Main{ public static void main(String[] args) { ArrayList<Movie> list = new ArrayList<Movie>(); list.add(new Movie("Force Awakens", 8.3, 2015)); list.add(new Movie("Star Wars", 8.7, 1977)); list.add(new Movie("Empire Strikes Back", 8.8, 1980)); list.add(new Movie("Return of the Jedi", 8.4, 1983)); // Sort by rating : (1) Create an object of ratingCompare // (2) Call Collections.sort // (3) Print Sorted list System.out.println("Sorted by rating"); RatingCompare ratingCompare = new RatingCompare(); Collections.sort(list, ratingCompare); for (Movie movie: list) System.out.println(movie.getRating() + " " + movie.getName() + " " + movie.getYear()); // Call overloaded sort method with RatingCompare // (Same three steps as above) System.out.println("\nSorted by name"); NameCompare nameCompare = new NameCompare(); Collections.sort(list, nameCompare); for (Movie movie: list) System.out.println(movie.getName() + " " + movie.getRating() + " " + movie.getYear()); // Uses Comparable to sort by year System.out.println("\nSorted by year"); Collections.sort(list); for (Movie movie: list) System.out.println(movie.getYear() + " " + movie.getRating() + " " + movie.getName()+" "); }}
Output :
Sorted by rating
8.3 Force Awakens 2015
8.4 Return of the Jedi 1983
8.7 Star Wars 1977
8.8 Empire Strikes Back 1980
Sorted by name
Empire Strikes Back 8.8 1980
Force Awakens 8.3 2015
Return of the Jedi 8.4 1983
Star Wars 8.7 1977
Sorted by year
1977 8.7 Star Wars
1980 8.8 Empire Strikes Back
1983 8.4 Return of the Jedi
2015 8.3 Force Awakens
Comparable is meant for objects with natural ordering which means the object itself must know how it is to be ordered. For example Roll Numbers of students. Whereas, Comparator interface sorting is done through a separate class.
Logically, Comparable interface compares “this” reference with the object specified and Comparator in Java compares two different class objects provided.
If any class implements Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Arrays.sort() method and objects will be sorted based on there natural order defined by CompareTo method.
A basic differentiating feature is that using comparable we can use only one comparison. Whereas, we can write more than one custom comparators as you want for a given type, all using different interpretations of what sorting means. Like in the comparable example we could just sort by only one attribute, i.e., year but in the comparator, we were able to use different attributes like rating, name, and year as well.
To summarize, if sorting of objects needs to be based on natural order then use Comparable whereas if you sorting needs to be done on attributes of different objects, then use Comparator in Java.
This article is contributed by Souradeep Barua. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
easeit
pianomastr64
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
Singleton Class in Java
Set in Java
Multithreading in Java
Collections in Java
Queue Interface In Java
Initializing a List in Java
Overriding in Java
LinkedList in Java
|
[
{
"code": null,
"e": 25511,
"s": 25483,
"text": "\n29 May, 2021"
},
{
"code": null,
"e": 25591,
"s": 25511,
"text": "Java provides two interfaces to sort objects using data members of the class: "
},
{
"code": null,
"e": 25612,
"s": 25591,
"text": "ComparableComparator"
},
{
"code": null,
"e": 25623,
"s": 25612,
"text": "Comparable"
},
{
"code": null,
"e": 25634,
"s": 25623,
"text": "Comparator"
},
{
"code": null,
"e": 25663,
"s": 25636,
"text": "Using Comparable Interface"
},
{
"code": null,
"e": 26092,
"s": 25663,
"text": "A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface to compare its instances. Consider a Movie class that has members like, rating, name, year. Suppose we wish to sort a list of Movies based on year of release. We can implement the Comparable interface with the Movie class, and we override the method compareTo() of Comparable interface. "
},
{
"code": null,
"e": 26099,
"s": 26094,
"text": "Java"
},
{
"code": "// A Java program to demonstrate use of Comparableimport java.io.*;import java.util.*; // A class 'Movie' that implements Comparableclass Movie implements Comparable<Movie>{ private double rating; private String name; private int year; // Used to sort movies by year public int compareTo(Movie m) { return this.year - m.year; } // Constructor public Movie(String nm, double rt, int yr) { this.name = nm; this.rating = rt; this.year = yr; } // Getter methods for accessing private data public double getRating() { return rating; } public String getName() { return name; } public int getYear() { return year; }} // Driver classclass Main{ public static void main(String[] args) { ArrayList<Movie> list = new ArrayList<Movie>(); list.add(new Movie(\"Force Awakens\", 8.3, 2015)); list.add(new Movie(\"Star Wars\", 8.7, 1977)); list.add(new Movie(\"Empire Strikes Back\", 8.8, 1980)); list.add(new Movie(\"Return of the Jedi\", 8.4, 1983)); Collections.sort(list); System.out.println(\"Movies after sorting : \"); for (Movie movie: list) { System.out.println(movie.getName() + \" \" + movie.getRating() + \" \" + movie.getYear()); } }}",
"e": 27455,
"s": 26099,
"text": null
},
{
"code": null,
"e": 27465,
"s": 27455,
"text": "Output: "
},
{
"code": null,
"e": 27592,
"s": 27465,
"text": "Movies after sorting : \n\nStar Wars 8.7 1977\n\nEmpire Strikes Back 8.8 1980\n\nReturn of the Jedi 8.4 1983\n\nForce Awakens 8.3 2015"
},
{
"code": null,
"e": 27840,
"s": 27592,
"text": "Now, suppose we want to sort movies by their rating and names as well. When we make a collection element comparable(by having it implement Comparable), we get only one chance to implement the compareTo() method. The solution is using Comparator. "
},
{
"code": null,
"e": 27857,
"s": 27840,
"text": "Using Comparator"
},
{
"code": null,
"e": 28238,
"s": 27857,
"text": "Unlike Comparable, Comparator is external to the element type we are comparing. It’s a separate class. We create multiple separate classes (that implement Comparator) to compare by different members.Collections class has a second sort() method and it takes Comparator. The sort() method invokes the compare() to sort objects.To compare movies by Rating, we need to do 3 things : "
},
{
"code": null,
"e": 28520,
"s": 28238,
"text": "Create a class that implements Comparator (and thus the compare() method that does the work previously done by compareTo()).Make an instance of the Comparator class.Call the overloaded sort() method, giving it both the list and the instance of the class that implements Comparator."
},
{
"code": null,
"e": 28645,
"s": 28520,
"text": "Create a class that implements Comparator (and thus the compare() method that does the work previously done by compareTo())."
},
{
"code": null,
"e": 28687,
"s": 28645,
"text": "Make an instance of the Comparator class."
},
{
"code": null,
"e": 28804,
"s": 28687,
"text": "Call the overloaded sort() method, giving it both the list and the instance of the class that implements Comparator."
},
{
"code": null,
"e": 28811,
"s": 28806,
"text": "Java"
},
{
"code": "//A Java program to demonstrate Comparator interfaceimport java.io.*;import java.util.*; // A class 'Movie' that implements Comparableclass Movie implements Comparable<Movie>{ private double rating; private String name; private int year; // Used to sort movies by year public int compareTo(Movie m) { return this.year - m.year; } // Constructor public Movie(String nm, double rt, int yr) { this.name = nm; this.rating = rt; this.year = yr; } // Getter methods for accessing private data public double getRating() { return rating; } public String getName() { return name; } public int getYear() { return year; }} // Class to compare Movies by ratingsclass RatingCompare implements Comparator<Movie>{ public int compare(Movie m1, Movie m2) { if (m1.getRating() < m2.getRating()) return -1; if (m1.getRating() > m2.getRating()) return 1; else return 0; }} // Class to compare Movies by nameclass NameCompare implements Comparator<Movie>{ public int compare(Movie m1, Movie m2) { return m1.getName().compareTo(m2.getName()); }} // Driver classclass Main{ public static void main(String[] args) { ArrayList<Movie> list = new ArrayList<Movie>(); list.add(new Movie(\"Force Awakens\", 8.3, 2015)); list.add(new Movie(\"Star Wars\", 8.7, 1977)); list.add(new Movie(\"Empire Strikes Back\", 8.8, 1980)); list.add(new Movie(\"Return of the Jedi\", 8.4, 1983)); // Sort by rating : (1) Create an object of ratingCompare // (2) Call Collections.sort // (3) Print Sorted list System.out.println(\"Sorted by rating\"); RatingCompare ratingCompare = new RatingCompare(); Collections.sort(list, ratingCompare); for (Movie movie: list) System.out.println(movie.getRating() + \" \" + movie.getName() + \" \" + movie.getYear()); // Call overloaded sort method with RatingCompare // (Same three steps as above) System.out.println(\"\\nSorted by name\"); NameCompare nameCompare = new NameCompare(); Collections.sort(list, nameCompare); for (Movie movie: list) System.out.println(movie.getName() + \" \" + movie.getRating() + \" \" + movie.getYear()); // Uses Comparable to sort by year System.out.println(\"\\nSorted by year\"); Collections.sort(list); for (Movie movie: list) System.out.println(movie.getYear() + \" \" + movie.getRating() + \" \" + movie.getName()+\" \"); }} ",
"e": 31585,
"s": 28811,
"text": null
},
{
"code": null,
"e": 31595,
"s": 31585,
"text": "Output : "
},
{
"code": null,
"e": 31944,
"s": 31595,
"text": "Sorted by rating\n8.3 Force Awakens 2015\n8.4 Return of the Jedi 1983\n8.7 Star Wars 1977\n8.8 Empire Strikes Back 1980\n\nSorted by name\nEmpire Strikes Back 8.8 1980\nForce Awakens 8.3 2015\nReturn of the Jedi 8.4 1983\nStar Wars 8.7 1977\n\nSorted by year\n1977 8.7 Star Wars \n1980 8.8 Empire Strikes Back \n1983 8.4 Return of the Jedi \n2015 8.3 Force Awakens"
},
{
"code": null,
"e": 32175,
"s": 31946,
"text": "Comparable is meant for objects with natural ordering which means the object itself must know how it is to be ordered. For example Roll Numbers of students. Whereas, Comparator interface sorting is done through a separate class."
},
{
"code": null,
"e": 32329,
"s": 32175,
"text": "Logically, Comparable interface compares “this” reference with the object specified and Comparator in Java compares two different class objects provided."
},
{
"code": null,
"e": 32599,
"s": 32329,
"text": "If any class implements Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Arrays.sort() method and objects will be sorted based on there natural order defined by CompareTo method."
},
{
"code": null,
"e": 33017,
"s": 32599,
"text": "A basic differentiating feature is that using comparable we can use only one comparison. Whereas, we can write more than one custom comparators as you want for a given type, all using different interpretations of what sorting means. Like in the comparable example we could just sort by only one attribute, i.e., year but in the comparator, we were able to use different attributes like rating, name, and year as well."
},
{
"code": null,
"e": 33215,
"s": 33019,
"text": "To summarize, if sorting of objects needs to be based on natural order then use Comparable whereas if you sorting needs to be done on attributes of different objects, then use Comparator in Java."
},
{
"code": null,
"e": 33389,
"s": 33215,
"text": " This article is contributed by Souradeep Barua. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 33396,
"s": 33389,
"text": "easeit"
},
{
"code": null,
"e": 33409,
"s": 33396,
"text": "pianomastr64"
},
{
"code": null,
"e": 33414,
"s": 33409,
"text": "Java"
},
{
"code": null,
"e": 33419,
"s": 33414,
"text": "Java"
},
{
"code": null,
"e": 33517,
"s": 33419,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33532,
"s": 33517,
"text": "Stream In Java"
},
{
"code": null,
"e": 33551,
"s": 33532,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 33575,
"s": 33551,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 33587,
"s": 33575,
"text": "Set in Java"
},
{
"code": null,
"e": 33610,
"s": 33587,
"text": "Multithreading in Java"
},
{
"code": null,
"e": 33630,
"s": 33610,
"text": "Collections in Java"
},
{
"code": null,
"e": 33654,
"s": 33630,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 33682,
"s": 33654,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 33701,
"s": 33682,
"text": "Overriding in Java"
}
] |
How to define a function Using the WITH clause in Oracle?
|
Problem:
You want to define a function in Oracle using WITH clause.
Solution
Starting with Oracle Database 12.1, you can define functions as well as procedures within the same SQL statement in which the SELECT statement appears. This allows the context switch between the PL/SQL and SQL engines by allowing both steps to take place in the SQL engine and, in turn, provides for a performance gain.
The function or procedure needs to be defined using the WITH clause. Remember, In previous versions of the Oracle platform, only subqueries could be defined in the WITH clause.
WITH FUNCTION func_amount(p_emailid IN VARCHAR2) RETURN NUMBER IS l_amt NUMBER;
BEGIN
SELECT SUM(oi.quantity*p.unit_price) AS AMT
INTO l_amt
FROM sample_customers C,
sample_orders O,
sample_order_items OI,
sample_products P
WHERE C.customer_id =o.customer_id
AND o.order_id = oi.order_id
AND oi.product_id = p.product_id
AND c.email_address = p_emailid;
RETURN l_amt;
END;
SELECT func_amount ('tammy.bryant@internalmail') AS TOTAL_AMOUNT FROM DUAL;
WITH FUNCTION func_amount(p_emailid IN VARCHAR2) RETURN NUMBER IS l_amt NUMBER;
BEGIN
SELECT SUM(oi.quantity*p.unit_price) AS AMT
INTO l_amt
FROM sample_customers C,
sample_orders O,
sample_order_items OI,
sample_products P
WHERE C.customer_id =o.customer_id
AND o.order_id = oi.order_id
AND oi.product_id = p.product_id
AND c.email_address = p_emailid;
RETURN l_amt;
END;
SELECT func_amount ('tammy.bryant@internalmail') AS TOTAL_AMOUNT FROM DUAL;
The WITH FUNCTION feature is useful in many different situations especially when you need to use a function for better once off performance.
The main downside that I see to this feature is that you lose the benefits of a reusable function in favor of obtaining improved performance through reduced context shifts between the SQL and PL/SQL engines. It is advisable to do a cost analysis and weigh the benefits against the possible need to reuse the function in other contexts.
DROP TABLE sample_customers;
DROP TABLE sample_orders;
DROP TABLE sample_order_items;
DROP TABLE sample_products;
create table sample_customers (
customer_id integer generated by default on null as identity,
email_address varchar2(255 char) not null,
full_name varchar2(255 char) not null)
;
insert into sample_customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (1,'tammy.bryant@internalmail','Tammy Bryant');
insert into sample_customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (2,'roy.white@internalmail','Roy White');
insert into sample_customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (3,'gary.jenkins@internalmail','Gary Jenkins');
insert into sample_customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (4,'victor.morris@internalmail','Victor Morris');
insert into sample_customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (5,'beverly.hughes@internalmail','Beverly Hughes');
insert into sample_customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (6,'evelyn.torres@internalmail','Evelyn Torres');
create table sample_products (
product_id integer generated by default on null as identity ,
product_name varchar2(255 char) not null,
unit_price number(10,2));
insert into sample_products (PRODUCT_ID,PRODUCT_NAME,UNIT_PRICE) values (1,'tennis raquet',29.55);
insert into sample_products (PRODUCT_ID,PRODUCT_NAME,UNIT_PRICE) values (2,'tennis net',16.67);
insert into sample_products (PRODUCT_ID,PRODUCT_NAME,UNIT_PRICE) values (3,'tennis ball',44.17);
insert into sample_products (PRODUCT_ID,PRODUCT_NAME,UNIT_PRICE) values (4,'tennis shoe',43.71);
insert into sample_products (PRODUCT_ID,PRODUCT_NAME,UNIT_PRICE) values (5,'tennis bag',38.28);
insert into sample_products (PRODUCT_ID,PRODUCT_NAME,UNIT_PRICE) values (6,'soccer ball',19.16);
insert into sample_products (PRODUCT_ID,PRODUCT_NAME,UNIT_PRICE) values (7,'soccer net',19.58);
create table sample_orders (
order_id integer
generated by default on null as identity,
customer_id integer not null,
store_id integer not null)
;
Insert into sample_orders (ORDER_ID,CUSTOMER_ID,STORE_ID) values (1,3,1);
Insert into sample_orders (ORDER_ID,CUSTOMER_ID,STORE_ID) values (2,45,1);
Insert into sample_orders (ORDER_ID,CUSTOMER_ID,STORE_ID) values (3,18,1);
Insert into sample_orders (ORDER_ID,CUSTOMER_ID,STORE_ID) values (4,45,1);
Insert into sample_orders (ORDER_ID,CUSTOMER_ID,STORE_ID) values (5,2,1);
Insert into sample_orders (ORDER_ID,CUSTOMER_ID,STORE_ID) values (6,74,1);
Insert into sample_orders (ORDER_ID,CUSTOMER_ID,STORE_ID) values (7,9,1);
Insert into sample_orders (ORDER_ID,CUSTOMER_ID,STORE_ID) values (8,109,1);
Insert into sample_orders (ORDER_ID,CUSTOMER_ID,STORE_ID) values (9,127,1);
create table sample_order_items (
order_id integer not null,
product_id integer not null,
unit_price number(10,2) not null,
quantity integer not null);
insert into sample_order_items (ORDER_ID,PRODUCT_ID,UNIT_PRICE,QUANTITY) values (1,33,37,4);
insert into sample_order_items (ORDER_ID,PRODUCT_ID,UNIT_PRICE,QUANTITY)values (1,11,30.69,2);
insert into sample_order_items (ORDER_ID,PRODUCT_ID,UNIT_PRICE,QUANTITY) values (2,41,8.66,3);
insert into sample_order_items (ORDER_ID,PRODUCT_ID,UNIT_PRICE,QUANTITY) values (2,32,5.65,5);
insert into sample_order_items (ORDER_ID,PRODUCT_ID,UNIT_PRICE,QUANTITY) values (3,41,8.66,5);
insert into sample_order_items (ORDER_ID,PRODUCT_ID,UNIT_PRICE,QUANTITY) values (4,20,28.21,2);
insert into sample_order_items (ORDER_ID,PRODUCT_ID,UNIT_PRICE,QUANTITY) values (4,38,22.98,4);
insert into sample_order_items (ORDER_ID,PRODUCT_ID,UNIT_PRICE,QUANTITY) values (4,46,39.16,4);
insert into sample_order_items (ORDER_ID,PRODUCT_ID,UNIT_PRICE,QUANTITY) values (5,40,34.06,4);
insert into sample_order_items (ORDER_ID,PRODUCT_ID,UNIT_PRICE,QUANTITY) values (5,32,5.65,3);
insert into sample_order_items (ORDER_ID,PRODUCT_ID,UNIT_PRICE,QUANTITY) values (6,6,38.28,3);
COMMIT;
|
[
{
"code": null,
"e": 1071,
"s": 1062,
"text": "Problem:"
},
{
"code": null,
"e": 1130,
"s": 1071,
"text": "You want to define a function in Oracle using WITH clause."
},
{
"code": null,
"e": 1139,
"s": 1130,
"text": "Solution"
},
{
"code": null,
"e": 1459,
"s": 1139,
"text": "Starting with Oracle Database 12.1, you can define functions as well as procedures within the same SQL statement in which the SELECT statement appears. This allows the context switch between the PL/SQL and SQL engines by allowing both steps to take place in the SQL engine and, in turn, provides for a performance gain."
},
{
"code": null,
"e": 1636,
"s": 1459,
"text": "The function or procedure needs to be defined using the WITH clause. Remember, In previous versions of the Oracle platform, only subqueries could be defined in the WITH clause."
},
{
"code": null,
"e": 2121,
"s": 1636,
"text": "WITH FUNCTION func_amount(p_emailid IN VARCHAR2) RETURN NUMBER IS l_amt NUMBER;\nBEGIN\n SELECT SUM(oi.quantity*p.unit_price) AS AMT\n INTO l_amt\n FROM sample_customers C,\n sample_orders O,\n sample_order_items OI,\n sample_products P\n WHERE C.customer_id =o.customer_id\n AND o.order_id = oi.order_id\n AND oi.product_id = p.product_id\n AND c.email_address = p_emailid;\n RETURN l_amt;\nEND;\n\nSELECT func_amount ('tammy.bryant@internalmail') AS TOTAL_AMOUNT FROM DUAL;"
},
{
"code": null,
"e": 2606,
"s": 2121,
"text": "WITH FUNCTION func_amount(p_emailid IN VARCHAR2) RETURN NUMBER IS l_amt NUMBER;\nBEGIN\n SELECT SUM(oi.quantity*p.unit_price) AS AMT\n INTO l_amt\n FROM sample_customers C,\n sample_orders O,\n sample_order_items OI,\n sample_products P\n WHERE C.customer_id =o.customer_id\n AND o.order_id = oi.order_id\n AND oi.product_id = p.product_id\n AND c.email_address = p_emailid;\n RETURN l_amt;\nEND;\n\nSELECT func_amount ('tammy.bryant@internalmail') AS TOTAL_AMOUNT FROM DUAL;"
},
{
"code": null,
"e": 2747,
"s": 2606,
"text": "The WITH FUNCTION feature is useful in many different situations especially when you need to use a function for better once off performance."
},
{
"code": null,
"e": 3083,
"s": 2747,
"text": "The main downside that I see to this feature is that you lose the benefits of a reusable function in favor of obtaining improved performance through reduced context shifts between the SQL and PL/SQL engines. It is advisable to do a cost analysis and weigh the benefits against the possible need to reuse the function in other contexts."
},
{
"code": null,
"e": 4147,
"s": 3083,
"text": "DROP TABLE sample_customers;\nDROP TABLE sample_orders;\nDROP TABLE sample_order_items;\nDROP TABLE sample_products;\n \ncreate table sample_customers (\n customer_id integer generated by default on null as identity,\n email_address varchar2(255 char) not null,\n full_name varchar2(255 char) not null)\n ;\n insert into sample_customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (1,'tammy.bryant@internalmail','Tammy Bryant');\n insert into sample_customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (2,'roy.white@internalmail','Roy White');\n insert into sample_customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (3,'gary.jenkins@internalmail','Gary Jenkins');\n insert into sample_customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (4,'victor.morris@internalmail','Victor Morris');\n insert into sample_customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (5,'beverly.hughes@internalmail','Beverly Hughes');\n insert into sample_customers (CUSTOMER_ID,EMAIL_ADDRESS,FULL_NAME) values (6,'evelyn.torres@internalmail','Evelyn Torres');\n "
},
{
"code": null,
"e": 5019,
"s": 4147,
"text": "create table sample_products (\n product_id integer generated by default on null as identity ,\n product_name varchar2(255 char) not null,\n unit_price number(10,2));\n \ninsert into sample_products (PRODUCT_ID,PRODUCT_NAME,UNIT_PRICE) values (1,'tennis raquet',29.55);\ninsert into sample_products (PRODUCT_ID,PRODUCT_NAME,UNIT_PRICE) values (2,'tennis net',16.67);\ninsert into sample_products (PRODUCT_ID,PRODUCT_NAME,UNIT_PRICE) values (3,'tennis ball',44.17);\ninsert into sample_products (PRODUCT_ID,PRODUCT_NAME,UNIT_PRICE) values (4,'tennis shoe',43.71);\ninsert into sample_products (PRODUCT_ID,PRODUCT_NAME,UNIT_PRICE) values (5,'tennis bag',38.28);\ninsert into sample_products (PRODUCT_ID,PRODUCT_NAME,UNIT_PRICE) values (6,'soccer ball',19.16);\ninsert into sample_products (PRODUCT_ID,PRODUCT_NAME,UNIT_PRICE) values (7,'soccer net',19.58);"
},
{
"code": null,
"e": 5890,
"s": 5019,
"text": " create table sample_orders (\n order_id integer\n generated by default on null as identity,\n customer_id integer not null,\n store_id integer not null)\n ;\n \nInsert into sample_orders (ORDER_ID,CUSTOMER_ID,STORE_ID) values (1,3,1);\nInsert into sample_orders (ORDER_ID,CUSTOMER_ID,STORE_ID) values (2,45,1);\nInsert into sample_orders (ORDER_ID,CUSTOMER_ID,STORE_ID) values (3,18,1);\nInsert into sample_orders (ORDER_ID,CUSTOMER_ID,STORE_ID) values (4,45,1);\nInsert into sample_orders (ORDER_ID,CUSTOMER_ID,STORE_ID) values (5,2,1);\nInsert into sample_orders (ORDER_ID,CUSTOMER_ID,STORE_ID) values (6,74,1);\nInsert into sample_orders (ORDER_ID,CUSTOMER_ID,STORE_ID) values (7,9,1);\nInsert into sample_orders (ORDER_ID,CUSTOMER_ID,STORE_ID) values (8,109,1);\nInsert into sample_orders (ORDER_ID,CUSTOMER_ID,STORE_ID) values (9,127,1);"
},
{
"code": null,
"e": 7180,
"s": 5890,
"text": " create table sample_order_items (\n order_id integer not null,\n product_id integer not null,\n unit_price number(10,2) not null,\n quantity integer not null);\n\ninsert into sample_order_items (ORDER_ID,PRODUCT_ID,UNIT_PRICE,QUANTITY) values (1,33,37,4);\ninsert into sample_order_items (ORDER_ID,PRODUCT_ID,UNIT_PRICE,QUANTITY)values (1,11,30.69,2);\ninsert into sample_order_items (ORDER_ID,PRODUCT_ID,UNIT_PRICE,QUANTITY) values (2,41,8.66,3);\ninsert into sample_order_items (ORDER_ID,PRODUCT_ID,UNIT_PRICE,QUANTITY) values (2,32,5.65,5);\ninsert into sample_order_items (ORDER_ID,PRODUCT_ID,UNIT_PRICE,QUANTITY) values (3,41,8.66,5);\ninsert into sample_order_items (ORDER_ID,PRODUCT_ID,UNIT_PRICE,QUANTITY) values (4,20,28.21,2);\ninsert into sample_order_items (ORDER_ID,PRODUCT_ID,UNIT_PRICE,QUANTITY) values (4,38,22.98,4);\ninsert into sample_order_items (ORDER_ID,PRODUCT_ID,UNIT_PRICE,QUANTITY) values (4,46,39.16,4);\ninsert into sample_order_items (ORDER_ID,PRODUCT_ID,UNIT_PRICE,QUANTITY) values (5,40,34.06,4);\ninsert into sample_order_items (ORDER_ID,PRODUCT_ID,UNIT_PRICE,QUANTITY) values (5,32,5.65,3);\ninsert into sample_order_items (ORDER_ID,PRODUCT_ID,UNIT_PRICE,QUANTITY) values (6,6,38.28,3);\n\nCOMMIT;"
}
] |
p5.js | print() function - GeeksforGeeks
|
12 Apr, 2019
The print() function in p5.js writes the content on console area of the web browser. It is helpful for looking at the data a program is producing which helps in debugging the code. The elements can be separated by using quotes (“”) and joined with the addition operator (+). Use print(‘\n’) to display blank line.
Syntax:
print(c)
Parameters: The function accepts single parameter c which stores the any combination of Number, String, Object, Boolean, Array to print.
Below program illustrates the print() function in p5.js:
Example 1: This example uses print() function to display the content on console.
function setup() { // Create canvas of given size createCanvas(400, 400); // print function call print("Hello GeeksForGeeks");} function draw() { // Set the background color background(220);}
Output:
Example 2: This example uses print() function to display the content on console.
function setup() { // Create canvas of given size createCanvas(400, 400); // print function call for(let i = 0; i < 4; i++) { for(let j = 0; j < i; j++) { print("*"); } print("\n"); }} function draw() { // Set the background color background(220);}
Output:
Reference: https://p5js.org/reference/#/p5/print
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 45047,
"s": 45019,
"text": "\n12 Apr, 2019"
},
{
"code": null,
"e": 45361,
"s": 45047,
"text": "The print() function in p5.js writes the content on console area of the web browser. It is helpful for looking at the data a program is producing which helps in debugging the code. The elements can be separated by using quotes (“”) and joined with the addition operator (+). Use print(‘\\n’) to display blank line."
},
{
"code": null,
"e": 45369,
"s": 45361,
"text": "Syntax:"
},
{
"code": null,
"e": 45378,
"s": 45369,
"text": "print(c)"
},
{
"code": null,
"e": 45515,
"s": 45378,
"text": "Parameters: The function accepts single parameter c which stores the any combination of Number, String, Object, Boolean, Array to print."
},
{
"code": null,
"e": 45572,
"s": 45515,
"text": "Below program illustrates the print() function in p5.js:"
},
{
"code": null,
"e": 45653,
"s": 45572,
"text": "Example 1: This example uses print() function to display the content on console."
},
{
"code": "function setup() { // Create canvas of given size createCanvas(400, 400); // print function call print(\"Hello GeeksForGeeks\");} function draw() { // Set the background color background(220);}",
"e": 45878,
"s": 45653,
"text": null
},
{
"code": null,
"e": 45886,
"s": 45878,
"text": "Output:"
},
{
"code": null,
"e": 45967,
"s": 45886,
"text": "Example 2: This example uses print() function to display the content on console."
},
{
"code": "function setup() { // Create canvas of given size createCanvas(400, 400); // print function call for(let i = 0; i < 4; i++) { for(let j = 0; j < i; j++) { print(\"*\"); } print(\"\\n\"); }} function draw() { // Set the background color background(220);}",
"e": 46284,
"s": 45967,
"text": null
},
{
"code": null,
"e": 46292,
"s": 46284,
"text": "Output:"
},
{
"code": null,
"e": 46341,
"s": 46292,
"text": "Reference: https://p5js.org/reference/#/p5/print"
},
{
"code": null,
"e": 46358,
"s": 46341,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 46369,
"s": 46358,
"text": "JavaScript"
},
{
"code": null,
"e": 46386,
"s": 46369,
"text": "Web Technologies"
},
{
"code": null,
"e": 46484,
"s": 46386,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 46524,
"s": 46484,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 46569,
"s": 46524,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 46630,
"s": 46569,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 46702,
"s": 46630,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 46771,
"s": 46702,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 46811,
"s": 46771,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 46844,
"s": 46811,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 46889,
"s": 46844,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 46932,
"s": 46889,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Read and Edit Image Metadata with Python | by Kenneth Leung | Towards Data Science
|
For every photo, there is more than meets the eye. The images taken with digital cameras and smartphones contain rich information (known as metadata) beyond the visible pixels.
This metadata can be helpful in many business cases. For instance, fraud detection systems for insurance claims analyze metadata of submitted photographs to check whether the claimant took them before the accident.
In this article, we explore how to use the exif library to read and edit metadata of digital images.
(1) What are Metadata and Exif?(2) Read Image Metadata(3) Modify Image Metadata(4) Save Modified Image Metadata(5) Wrapping It Up
Feel free to check out all the codes in the accompanying GitHub repo.
Metadata refers to the set of data describing the data, and you can think of it as data about the data. The metadata of photos consists of information such as camera model and date of capture.
This metadata is stored in Exif (Exchangeable image file format), a format standard for the various types of media (e.g. images, videos, audio) taken by devices such as digital cameras and smartphones.
The Python library used in this project is exif, which happens to be the namesake of the Exif format.
We start by installing exif with this command:
pip install exif
For this demo, here is the photo that we will be working on:
We instantiate an exif Image Class by reading the image in a binary format before checking whether it contains any metadata. If so, the has_exif method will return True.
Different photos have varying metadata attributes (aka Exif tags) due to the different devices used to capture them. We can view the existing attributes for an image with the list_all() method.
To read values of specific attributes, we can use the get() method. While there are other methods, I prefer get() as it gracefully handles cases where attributes do not exist by returning None (instead of throwing an error).
P.S. Check out the Image_Metadata_Extraction_EXIF.ipynb notebook for the function to extract all metadata of an image into a Pandas DataFrame.
Besides reading metadata, we can perform a series of modifications such as adding, updating, and deleting attributes.
New attributes not currently present can be added to further enrich the metadata.
One important thing to note is that the attribute added must be a recognized EXIF tag. Otherwise, the addition will not take place. You can find the complete list of recognized image attributes here.
For example, we can add the recognized copyright attribute. After assigning a value (Kenneth Leung 2021) to the copyright attribute, the get() method will give us this new value instead of None.
We can also update the existing values of the image metadata attributes.
If we want to delete specific attributes instead of updating them, we can do so with .delete().
After all the modifications, the final step is to save the image with the modified metadata as a new file.
With the above, we have saved the modified image using a filename with the prefix of ‘modified_’ so that the original image is not overwritten.
There are many other interesting attributes to explore, and you can find more details on the exif documentation page.
What we have done so far is process a single image. The value of the exif package is realized through batch processing, where the extraction and modification of metadata are done on a large set of images. To see batch processing in action, have a look at the batch_process_metadata.py script in the GitHub repo.
An important thing to keep in mind is to back up your photos before using this library to prevent any unexpected data loss.
I welcome you to join me on a data science learning journey! Follow this Medium page and check out my GitHub to stay in the loop of more exciting data science content. Meanwhile, have fun reading and modifying image metadata!
|
[
{
"code": null,
"e": 349,
"s": 172,
"text": "For every photo, there is more than meets the eye. The images taken with digital cameras and smartphones contain rich information (known as metadata) beyond the visible pixels."
},
{
"code": null,
"e": 564,
"s": 349,
"text": "This metadata can be helpful in many business cases. For instance, fraud detection systems for insurance claims analyze metadata of submitted photographs to check whether the claimant took them before the accident."
},
{
"code": null,
"e": 665,
"s": 564,
"text": "In this article, we explore how to use the exif library to read and edit metadata of digital images."
},
{
"code": null,
"e": 795,
"s": 665,
"text": "(1) What are Metadata and Exif?(2) Read Image Metadata(3) Modify Image Metadata(4) Save Modified Image Metadata(5) Wrapping It Up"
},
{
"code": null,
"e": 865,
"s": 795,
"text": "Feel free to check out all the codes in the accompanying GitHub repo."
},
{
"code": null,
"e": 1058,
"s": 865,
"text": "Metadata refers to the set of data describing the data, and you can think of it as data about the data. The metadata of photos consists of information such as camera model and date of capture."
},
{
"code": null,
"e": 1260,
"s": 1058,
"text": "This metadata is stored in Exif (Exchangeable image file format), a format standard for the various types of media (e.g. images, videos, audio) taken by devices such as digital cameras and smartphones."
},
{
"code": null,
"e": 1362,
"s": 1260,
"text": "The Python library used in this project is exif, which happens to be the namesake of the Exif format."
},
{
"code": null,
"e": 1409,
"s": 1362,
"text": "We start by installing exif with this command:"
},
{
"code": null,
"e": 1426,
"s": 1409,
"text": "pip install exif"
},
{
"code": null,
"e": 1487,
"s": 1426,
"text": "For this demo, here is the photo that we will be working on:"
},
{
"code": null,
"e": 1657,
"s": 1487,
"text": "We instantiate an exif Image Class by reading the image in a binary format before checking whether it contains any metadata. If so, the has_exif method will return True."
},
{
"code": null,
"e": 1851,
"s": 1657,
"text": "Different photos have varying metadata attributes (aka Exif tags) due to the different devices used to capture them. We can view the existing attributes for an image with the list_all() method."
},
{
"code": null,
"e": 2076,
"s": 1851,
"text": "To read values of specific attributes, we can use the get() method. While there are other methods, I prefer get() as it gracefully handles cases where attributes do not exist by returning None (instead of throwing an error)."
},
{
"code": null,
"e": 2219,
"s": 2076,
"text": "P.S. Check out the Image_Metadata_Extraction_EXIF.ipynb notebook for the function to extract all metadata of an image into a Pandas DataFrame."
},
{
"code": null,
"e": 2337,
"s": 2219,
"text": "Besides reading metadata, we can perform a series of modifications such as adding, updating, and deleting attributes."
},
{
"code": null,
"e": 2419,
"s": 2337,
"text": "New attributes not currently present can be added to further enrich the metadata."
},
{
"code": null,
"e": 2619,
"s": 2419,
"text": "One important thing to note is that the attribute added must be a recognized EXIF tag. Otherwise, the addition will not take place. You can find the complete list of recognized image attributes here."
},
{
"code": null,
"e": 2814,
"s": 2619,
"text": "For example, we can add the recognized copyright attribute. After assigning a value (Kenneth Leung 2021) to the copyright attribute, the get() method will give us this new value instead of None."
},
{
"code": null,
"e": 2887,
"s": 2814,
"text": "We can also update the existing values of the image metadata attributes."
},
{
"code": null,
"e": 2983,
"s": 2887,
"text": "If we want to delete specific attributes instead of updating them, we can do so with .delete()."
},
{
"code": null,
"e": 3090,
"s": 2983,
"text": "After all the modifications, the final step is to save the image with the modified metadata as a new file."
},
{
"code": null,
"e": 3234,
"s": 3090,
"text": "With the above, we have saved the modified image using a filename with the prefix of ‘modified_’ so that the original image is not overwritten."
},
{
"code": null,
"e": 3352,
"s": 3234,
"text": "There are many other interesting attributes to explore, and you can find more details on the exif documentation page."
},
{
"code": null,
"e": 3664,
"s": 3352,
"text": "What we have done so far is process a single image. The value of the exif package is realized through batch processing, where the extraction and modification of metadata are done on a large set of images. To see batch processing in action, have a look at the batch_process_metadata.py script in the GitHub repo."
},
{
"code": null,
"e": 3788,
"s": 3664,
"text": "An important thing to keep in mind is to back up your photos before using this library to prevent any unexpected data loss."
}
] |
copy in Python (Deep Copy and Shallow Copy) - GeeksforGeeks
|
10 Feb, 2020
In Python, Assignment statements do not copy objects, they create bindings between a target and an object. When we use = operator user thinks that this creates a new object; well, it doesn’t. It only creates a new variable that shares the reference of the original object. Sometimes a user wants to work with mutable objects, in order to do that user looks for a way to create “real copies” or “clones” of these objects. Or, sometimes a user wants copies that user can modify without automatically modifying the original at the same time, in order to do that we create copies of objects.
A copy is sometimes needed so one can change one copy without changing the other. In Python, there are two ways to create copies :
Deep copy
Shallow copy
In order to make these copy, we use copy module. We use copy module for shallow and deep copy operations. For Example
# importing copy moduleimport copy # initializing list 1 li1 = [1, 2, [3,5], 4] # using copy for shallow copy li2 = copy.copy(li1) # using deepcopy for deepcopy li3 = copy.deepcopy(li1)
In the above code, the copy() returns a shallow copy of list and deepcopy() return a deep copy of list.
Deep copy is a process in which the copying process occurs recursively. It means first constructing a new collection object and then recursively populating it with copies of the child objects found in the original. In case of deep copy, a copy of object is copied in other object. It means that any changes made to a copy of object do not reflect in the original object. In python, this is implemented using “deepcopy()” function.
# Python code to demonstrate copy operations # importing "copy" for copy operationsimport copy # initializing list 1li1 = [1, 2, [3,5], 4] # using deepcopy to deep copy li2 = copy.deepcopy(li1) # original elements of listprint ("The original elements before deep copying")for i in range(0,len(li1)): print (li1[i],end=" ") print("\r") # adding and element to new listli2[2][0] = 7 # Change is reflected in l2 print ("The new list of elements after deep copying ")for i in range(0,len( li1)): print (li2[i],end=" ") print("\r") # Change is NOT reflected in original list# as it is a deep copyprint ("The original elements after deep copying")for i in range(0,len( li1)): print (li1[i],end=" ")
Output:
The original elements before deep copying
1 2 [3, 5] 4
The new list of elements after deep copying
1 2 [7, 5] 4
The original elements after deep copying
1 2 [3, 5] 4
In the above example, the change made in the list did not effect in other lists, indicating the list is deep copied.
A shallow copy means constructing a new collection object and then populating it with references to the child objects found in the original. The copying process does not recurse and therefore won’t create copies of the child objects themselves. In case of shallow copy, a reference of object is copied in other object. It means that any changes made to a copy of object do reflect in the original object. In python, this is implemented using “copy()” function.
# Python code to demonstrate copy operations # importing "copy" for copy operationsimport copy # initializing list 1li1 = [1, 2, [3,5], 4] # using copy to shallow copy li2 = copy.copy(li1) # original elements of listprint ("The original elements before shallow copying")for i in range(0,len(li1)): print (li1[i],end=" ") print("\r") # adding and element to new listli2[2][0] = 7 # checking if change is reflectedprint ("The original elements after shallow copying")for i in range(0,len( li1)): print (li1[i],end=" ")
Output:
The original elements before shallow copying
1 2 [3, 5] 4
The original elements after shallow copying
1 2 [7, 5] 4
In the above example, the change made in the list did effect in other list, indicating the list is shallow copied.
Important Points:The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):
A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
YouTubeGeeksforGeeks507K subscribersPython Programming Tutorial | copy in Python (Deep Copy and Shallow Copy) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:04•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=aSR1IPh9kBs" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
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": 25397,
"s": 25369,
"text": "\n10 Feb, 2020"
},
{
"code": null,
"e": 25985,
"s": 25397,
"text": "In Python, Assignment statements do not copy objects, they create bindings between a target and an object. When we use = operator user thinks that this creates a new object; well, it doesn’t. It only creates a new variable that shares the reference of the original object. Sometimes a user wants to work with mutable objects, in order to do that user looks for a way to create “real copies” or “clones” of these objects. Or, sometimes a user wants copies that user can modify without automatically modifying the original at the same time, in order to do that we create copies of objects."
},
{
"code": null,
"e": 26116,
"s": 25985,
"text": "A copy is sometimes needed so one can change one copy without changing the other. In Python, there are two ways to create copies :"
},
{
"code": null,
"e": 26126,
"s": 26116,
"text": "Deep copy"
},
{
"code": null,
"e": 26139,
"s": 26126,
"text": "Shallow copy"
},
{
"code": null,
"e": 26257,
"s": 26139,
"text": "In order to make these copy, we use copy module. We use copy module for shallow and deep copy operations. For Example"
},
{
"code": "# importing copy moduleimport copy # initializing list 1 li1 = [1, 2, [3,5], 4] # using copy for shallow copy li2 = copy.copy(li1) # using deepcopy for deepcopy li3 = copy.deepcopy(li1) ",
"e": 26452,
"s": 26257,
"text": null
},
{
"code": null,
"e": 26556,
"s": 26452,
"text": "In the above code, the copy() returns a shallow copy of list and deepcopy() return a deep copy of list."
},
{
"code": null,
"e": 26987,
"s": 26556,
"text": "Deep copy is a process in which the copying process occurs recursively. It means first constructing a new collection object and then recursively populating it with copies of the child objects found in the original. In case of deep copy, a copy of object is copied in other object. It means that any changes made to a copy of object do not reflect in the original object. In python, this is implemented using “deepcopy()” function."
},
{
"code": "# Python code to demonstrate copy operations # importing \"copy\" for copy operationsimport copy # initializing list 1li1 = [1, 2, [3,5], 4] # using deepcopy to deep copy li2 = copy.deepcopy(li1) # original elements of listprint (\"The original elements before deep copying\")for i in range(0,len(li1)): print (li1[i],end=\" \") print(\"\\r\") # adding and element to new listli2[2][0] = 7 # Change is reflected in l2 print (\"The new list of elements after deep copying \")for i in range(0,len( li1)): print (li2[i],end=\" \") print(\"\\r\") # Change is NOT reflected in original list# as it is a deep copyprint (\"The original elements after deep copying\")for i in range(0,len( li1)): print (li1[i],end=\" \")",
"e": 27698,
"s": 26987,
"text": null
},
{
"code": null,
"e": 27706,
"s": 27698,
"text": "Output:"
},
{
"code": null,
"e": 27877,
"s": 27706,
"text": "The original elements before deep copying\n1 2 [3, 5] 4 \nThe new list of elements after deep copying \n1 2 [7, 5] 4 \nThe original elements after deep copying\n1 2 [3, 5] 4 \n"
},
{
"code": null,
"e": 27995,
"s": 27877,
"text": "In the above example, the change made in the list did not effect in other lists, indicating the list is deep copied. "
},
{
"code": null,
"e": 28456,
"s": 27995,
"text": "A shallow copy means constructing a new collection object and then populating it with references to the child objects found in the original. The copying process does not recurse and therefore won’t create copies of the child objects themselves. In case of shallow copy, a reference of object is copied in other object. It means that any changes made to a copy of object do reflect in the original object. In python, this is implemented using “copy()” function."
},
{
"code": "# Python code to demonstrate copy operations # importing \"copy\" for copy operationsimport copy # initializing list 1li1 = [1, 2, [3,5], 4] # using copy to shallow copy li2 = copy.copy(li1) # original elements of listprint (\"The original elements before shallow copying\")for i in range(0,len(li1)): print (li1[i],end=\" \") print(\"\\r\") # adding and element to new listli2[2][0] = 7 # checking if change is reflectedprint (\"The original elements after shallow copying\")for i in range(0,len( li1)): print (li1[i],end=\" \")",
"e": 28986,
"s": 28456,
"text": null
},
{
"code": null,
"e": 28994,
"s": 28986,
"text": "Output:"
},
{
"code": null,
"e": 29112,
"s": 28994,
"text": "The original elements before shallow copying\n1 2 [3, 5] 4 \nThe original elements after shallow copying\n1 2 [7, 5] 4 \n"
},
{
"code": null,
"e": 29227,
"s": 29112,
"text": "In the above example, the change made in the list did effect in other list, indicating the list is shallow copied."
},
{
"code": null,
"e": 29399,
"s": 29227,
"text": "Important Points:The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):"
},
{
"code": null,
"e": 29546,
"s": 29399,
"text": "A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original."
},
{
"code": null,
"e": 29675,
"s": 29546,
"text": "A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original."
},
{
"code": null,
"e": 30547,
"s": 29675,
"text": "YouTubeGeeksforGeeks507K subscribersPython Programming Tutorial | copy in Python (Deep Copy and Shallow Copy) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:04•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=aSR1IPh9kBs\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 30554,
"s": 30547,
"text": "Python"
},
{
"code": null,
"e": 30652,
"s": 30554,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30670,
"s": 30652,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30705,
"s": 30670,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 30737,
"s": 30705,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30759,
"s": 30737,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 30801,
"s": 30759,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 30831,
"s": 30801,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 30857,
"s": 30831,
"text": "Python String | replace()"
},
{
"code": null,
"e": 30886,
"s": 30857,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 30930,
"s": 30886,
"text": "Reading and Writing to text files in Python"
}
] |
Throwable getStackTrace() method in Java with Examples - GeeksforGeeks
|
19 Aug, 2019
The getStackTrace() method of Throwable class used to return an array of stack trace elements which is the stack trace information printed by printStackTrace(). In the array of stack trace elements(assuming the array’s length is non-zero), each element represents one stack frame. The first element of the array means zeroth index element of this array represents the top of the stack, which is the last method invoked in the sequence or we can say that this zeroth index element information is related to the point where throwable was created and thrown. The last element of this array represents the bottom of the stack, which is the first method invoked in the sequence.In Some cases one or more stack frames from the stack trace is returned. The array returned by this method will contain one element for every frame that would be printed by printStackTrace. Any changes to the returned array do not affect future calls to this method.
Syntax:
public StackTraceElement[] getStackTrace()
Returns: This method returns an array of stack trace elements representing the stack trace information.
Below programs illustrate the getStackTrace method of Throwable class:
Example 1:
// Java program to demonstrate// the getStackTrace() Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { // add the numbers addPositiveNumbers(2, -1); } catch (Throwable e) { // get StackTraceElements // using getStackTrace() StackTraceElement[] stktrace = e.getStackTrace(); // print element of stktrace for (int i = 0; i < stktrace.length; i++) { System.out.println("Index " + i + " of stack trace" + " array conatins = " + stktrace[i].toString()); } } } // method which adds two positive number public static void addPositiveNumbers(int a, int b) throws Exception { // if Numbers are Positive // than add or throw Exception if (a < 0 || b < 0) { throw new Exception( "Numbers are not Positive"); } else { System.out.println(a + b); } }}
Index 0 of stack trace array conatins = GFG.addPositiveNumbers(File.java:48)
Index 1 of stack trace array conatins = GFG.main(File.java:18)
Example 2:
// Java program to demonstrate// the getStackTrace() Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { testException1(); } catch (Throwable e) { // get StackTraceElements // using getStackTrace() StackTraceElement[] stktrace = e.getStackTrace(); // print element of stktrace for (int i = 0; i < stktrace.length; i++) { System.out.println("Index " + i + " of stack trace" + " array conatins = " + stktrace[i].toString()); } } } // method which throws Exception // calling other method testException2 public static void testException1() throws Exception { // This method second in series // of calling method which throw exception // so this will be second index element testException2(); } // method which throws Exception // calling other method testException3 public static void testException2() throws Exception { // This method calls a method // where exception is thrown // so this will be first index element testException3(); } // method which throws IndexOutOfBoundsException public static void testException3() throws IndexOutOfBoundsException { // here exception thrown // so this will be Zeroth element throw new IndexOutOfBoundsException( "Forcefully Generated Exception"); }}
Index 0 of stack trace array conatins = GFG.testException3(File.java:68)
Index 1 of stack trace array conatins = GFG.testException2(File.java:58)
Index 2 of stack trace array conatins = GFG.testException1(File.java:46)
Index 3 of stack trace array conatins = GFG.main(File.java:17)
References:https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#getStackTrace()
Akanksha_Rai
Java-Exception Handling
Java-Exceptions
Java-Functions
Java-lang package
java-Throwable
Java
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
Multidimensional Arrays in Java
Singleton Class in Java
|
[
{
"code": null,
"e": 25873,
"s": 25845,
"text": "\n19 Aug, 2019"
},
{
"code": null,
"e": 26813,
"s": 25873,
"text": "The getStackTrace() method of Throwable class used to return an array of stack trace elements which is the stack trace information printed by printStackTrace(). In the array of stack trace elements(assuming the array’s length is non-zero), each element represents one stack frame. The first element of the array means zeroth index element of this array represents the top of the stack, which is the last method invoked in the sequence or we can say that this zeroth index element information is related to the point where throwable was created and thrown. The last element of this array represents the bottom of the stack, which is the first method invoked in the sequence.In Some cases one or more stack frames from the stack trace is returned. The array returned by this method will contain one element for every frame that would be printed by printStackTrace. Any changes to the returned array do not affect future calls to this method."
},
{
"code": null,
"e": 26821,
"s": 26813,
"text": "Syntax:"
},
{
"code": null,
"e": 26864,
"s": 26821,
"text": "public StackTraceElement[] getStackTrace()"
},
{
"code": null,
"e": 26968,
"s": 26864,
"text": "Returns: This method returns an array of stack trace elements representing the stack trace information."
},
{
"code": null,
"e": 27039,
"s": 26968,
"text": "Below programs illustrate the getStackTrace method of Throwable class:"
},
{
"code": null,
"e": 27050,
"s": 27039,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// the getStackTrace() Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { // add the numbers addPositiveNumbers(2, -1); } catch (Throwable e) { // get StackTraceElements // using getStackTrace() StackTraceElement[] stktrace = e.getStackTrace(); // print element of stktrace for (int i = 0; i < stktrace.length; i++) { System.out.println(\"Index \" + i + \" of stack trace\" + \" array conatins = \" + stktrace[i].toString()); } } } // method which adds two positive number public static void addPositiveNumbers(int a, int b) throws Exception { // if Numbers are Positive // than add or throw Exception if (a < 0 || b < 0) { throw new Exception( \"Numbers are not Positive\"); } else { System.out.println(a + b); } }}",
"e": 28246,
"s": 27050,
"text": null
},
{
"code": null,
"e": 28387,
"s": 28246,
"text": "Index 0 of stack trace array conatins = GFG.addPositiveNumbers(File.java:48)\nIndex 1 of stack trace array conatins = GFG.main(File.java:18)\n"
},
{
"code": null,
"e": 28398,
"s": 28387,
"text": "Example 2:"
},
{
"code": "// Java program to demonstrate// the getStackTrace() Method. import java.io.*; class GFG { // Main Method public static void main(String[] args) throws Exception { try { testException1(); } catch (Throwable e) { // get StackTraceElements // using getStackTrace() StackTraceElement[] stktrace = e.getStackTrace(); // print element of stktrace for (int i = 0; i < stktrace.length; i++) { System.out.println(\"Index \" + i + \" of stack trace\" + \" array conatins = \" + stktrace[i].toString()); } } } // method which throws Exception // calling other method testException2 public static void testException1() throws Exception { // This method second in series // of calling method which throw exception // so this will be second index element testException2(); } // method which throws Exception // calling other method testException3 public static void testException2() throws Exception { // This method calls a method // where exception is thrown // so this will be first index element testException3(); } // method which throws IndexOutOfBoundsException public static void testException3() throws IndexOutOfBoundsException { // here exception thrown // so this will be Zeroth element throw new IndexOutOfBoundsException( \"Forcefully Generated Exception\"); }}",
"e": 30086,
"s": 28398,
"text": null
},
{
"code": null,
"e": 30369,
"s": 30086,
"text": "Index 0 of stack trace array conatins = GFG.testException3(File.java:68)\nIndex 1 of stack trace array conatins = GFG.testException2(File.java:58)\nIndex 2 of stack trace array conatins = GFG.testException1(File.java:46)\nIndex 3 of stack trace array conatins = GFG.main(File.java:17)\n"
},
{
"code": null,
"e": 30464,
"s": 30369,
"text": "References:https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#getStackTrace()"
},
{
"code": null,
"e": 30477,
"s": 30464,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 30501,
"s": 30477,
"text": "Java-Exception Handling"
},
{
"code": null,
"e": 30517,
"s": 30501,
"text": "Java-Exceptions"
},
{
"code": null,
"e": 30532,
"s": 30517,
"text": "Java-Functions"
},
{
"code": null,
"e": 30550,
"s": 30532,
"text": "Java-lang package"
},
{
"code": null,
"e": 30565,
"s": 30550,
"text": "java-Throwable"
},
{
"code": null,
"e": 30570,
"s": 30565,
"text": "Java"
},
{
"code": null,
"e": 30575,
"s": 30570,
"text": "Java"
},
{
"code": null,
"e": 30673,
"s": 30575,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30724,
"s": 30673,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 30754,
"s": 30724,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 30769,
"s": 30754,
"text": "Stream In Java"
},
{
"code": null,
"e": 30788,
"s": 30769,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 30819,
"s": 30788,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 30837,
"s": 30819,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 30869,
"s": 30837,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 30889,
"s": 30869,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 30921,
"s": 30889,
"text": "Multidimensional Arrays in Java"
}
] |
How to convert two-dimensional array into an object in JavaScript ? - GeeksforGeeks
|
16 Apr, 2021
In this article, we will learn how to convert a two-dimensional array to an object. A two-dimensional array can have any number of rows and two columns.
Example:
Input: [
["John", 12],
["Jack", 13],
["Matt", 14],
["Maxx", 15]
]
Output: {
"John": 12,
"Jack": 13,
"Matt": 14,
"Maxx": 15
}
The below approaches can be followed to solve the problem.
Approach 1: In this approach, we create an empty object and use the Array.forEach() method to iterate over the array. On every iteration, we insert the first item of the child array into the object as a key and the second item as the value. Then it returns the object after the iterations.
Example:
Javascript
function arr2obj(arr) { // Create an empty object let obj = {}; arr.forEach((v) => { // Extract the key and the value let key = v[0]; let value = v[1]; // Add the key and value to // the object obj[key] = value; }); // Return the object return obj;} console.log( arr2obj([ ["John", 12], ["Jack", 13], ["Matt", 14], ["Maxx", 15], ]));
Output:
{
Jack: 13,
John: 12,
Matt: 14,
Maxx: 15
}
Approach 2: In this approach, we will use the Array.reduce() method and initialize the accumulator with an empty object. On every iteration, we assign the current value as the key’s value of the accumulator and return the accumulator. Then it returns the object after the iterations.
Example:
Javascript
function arr2obj(arr) { return arr.reduce( (acc, curr) => { // Extract the key and the value let key = curr[0]; let value = curr[1]; // Assign key and value // to the accumulator acc[key] = value; // Return the accumulator return acc; }, // Initialize with an empty object {} );} console.log( arr2obj([ ["Eren", "Yeager"], ["Mikasa", "Ackermann"], ["Armin", "Arlelt"], ["Levi", "Ackermann"], ]));
Output:
{
Eren: 'Yeager',
Mikasa: 'Ackermann',
Armin: 'Arlelt',
Levi: 'Ackermann'
}
Approach 3: In this approach, we first flatten the array using the Array.flat() method so that we get a one-dimensional array. We can then create an empty object and iterate the array to assign evenly positioned values as the key of the object and oddly positioned values as the value.
Example:
Javascript
function arr2obj(arr) { // Flatten the array arr = arr.flat(); // Create an empty object let obj = {}; for (let i = 0; i < arr.length; i++) { if (i % 2 == 0) { // Extract the key and the value let key = arr[i]; let value = arr[i + 1]; // Assign the key and value obj[key] = value; } } return obj;} console.log( arr2obj([ ["Max", 19], ["Chloe", 20], ["Nathan", 22], ["Mark", 31], ]));
Output:
{
Max: 19,
Chloe: 20,
Nathan: 22,
Mark: 31
}
javascript-array
JavaScript-Methods
javascript-object
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 39215,
"s": 39187,
"text": "\n16 Apr, 2021"
},
{
"code": null,
"e": 39368,
"s": 39215,
"text": "In this article, we will learn how to convert a two-dimensional array to an object. A two-dimensional array can have any number of rows and two columns."
},
{
"code": null,
"e": 39377,
"s": 39368,
"text": "Example:"
},
{
"code": null,
"e": 39594,
"s": 39377,
"text": "Input: [\n [\"John\", 12],\n [\"Jack\", 13],\n [\"Matt\", 14],\n [\"Maxx\", 15]\n ]\n\nOutput: {\n \"John\": 12,\n \"Jack\": 13,\n \"Matt\": 14,\n \"Maxx\": 15\n }"
},
{
"code": null,
"e": 39653,
"s": 39594,
"text": "The below approaches can be followed to solve the problem."
},
{
"code": null,
"e": 39943,
"s": 39653,
"text": "Approach 1: In this approach, we create an empty object and use the Array.forEach() method to iterate over the array. On every iteration, we insert the first item of the child array into the object as a key and the second item as the value. Then it returns the object after the iterations."
},
{
"code": null,
"e": 39954,
"s": 39945,
"text": "Example:"
},
{
"code": null,
"e": 39965,
"s": 39954,
"text": "Javascript"
},
{
"code": "function arr2obj(arr) { // Create an empty object let obj = {}; arr.forEach((v) => { // Extract the key and the value let key = v[0]; let value = v[1]; // Add the key and value to // the object obj[key] = value; }); // Return the object return obj;} console.log( arr2obj([ [\"John\", 12], [\"Jack\", 13], [\"Matt\", 14], [\"Maxx\", 15], ]));",
"e": 40404,
"s": 39965,
"text": null
},
{
"code": null,
"e": 40412,
"s": 40404,
"text": "Output:"
},
{
"code": null,
"e": 40463,
"s": 40412,
"text": "{\n Jack: 13,\n John: 12,\n Matt: 14,\n Maxx: 15\n}"
},
{
"code": null,
"e": 40747,
"s": 40463,
"text": "Approach 2: In this approach, we will use the Array.reduce() method and initialize the accumulator with an empty object. On every iteration, we assign the current value as the key’s value of the accumulator and return the accumulator. Then it returns the object after the iterations."
},
{
"code": null,
"e": 40756,
"s": 40747,
"text": "Example:"
},
{
"code": null,
"e": 40767,
"s": 40756,
"text": "Javascript"
},
{
"code": "function arr2obj(arr) { return arr.reduce( (acc, curr) => { // Extract the key and the value let key = curr[0]; let value = curr[1]; // Assign key and value // to the accumulator acc[key] = value; // Return the accumulator return acc; }, // Initialize with an empty object {} );} console.log( arr2obj([ [\"Eren\", \"Yeager\"], [\"Mikasa\", \"Ackermann\"], [\"Armin\", \"Arlelt\"], [\"Levi\", \"Ackermann\"], ]));",
"e": 41341,
"s": 40767,
"text": null
},
{
"code": null,
"e": 41349,
"s": 41341,
"text": "Output:"
},
{
"code": null,
"e": 41433,
"s": 41349,
"text": "{\n Eren: 'Yeager',\n Mikasa: 'Ackermann',\n Armin: 'Arlelt',\n Levi: 'Ackermann'\n}"
},
{
"code": null,
"e": 41719,
"s": 41433,
"text": "Approach 3: In this approach, we first flatten the array using the Array.flat() method so that we get a one-dimensional array. We can then create an empty object and iterate the array to assign evenly positioned values as the key of the object and oddly positioned values as the value."
},
{
"code": null,
"e": 41728,
"s": 41719,
"text": "Example:"
},
{
"code": null,
"e": 41739,
"s": 41728,
"text": "Javascript"
},
{
"code": "function arr2obj(arr) { // Flatten the array arr = arr.flat(); // Create an empty object let obj = {}; for (let i = 0; i < arr.length; i++) { if (i % 2 == 0) { // Extract the key and the value let key = arr[i]; let value = arr[i + 1]; // Assign the key and value obj[key] = value; } } return obj;} console.log( arr2obj([ [\"Max\", 19], [\"Chloe\", 20], [\"Nathan\", 22], [\"Mark\", 31], ]));",
"e": 42260,
"s": 41739,
"text": null
},
{
"code": null,
"e": 42268,
"s": 42260,
"text": "Output:"
},
{
"code": null,
"e": 42325,
"s": 42268,
"text": "{ \n Max: 19,\n Chloe: 20, \n Nathan: 22, \n Mark: 31 \n}"
},
{
"code": null,
"e": 42342,
"s": 42325,
"text": "javascript-array"
},
{
"code": null,
"e": 42361,
"s": 42342,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 42379,
"s": 42361,
"text": "javascript-object"
},
{
"code": null,
"e": 42390,
"s": 42379,
"text": "JavaScript"
},
{
"code": null,
"e": 42407,
"s": 42390,
"text": "Web Technologies"
},
{
"code": null,
"e": 42505,
"s": 42407,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42545,
"s": 42505,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 42590,
"s": 42545,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 42651,
"s": 42590,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 42723,
"s": 42651,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 42792,
"s": 42723,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 42832,
"s": 42792,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 42865,
"s": 42832,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 42910,
"s": 42865,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 42953,
"s": 42910,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Getting last element of an array in Julia - last() Method - GeeksforGeeks
|
26 Mar, 2020
The last() is an inbuilt function in julia which is used to return the last element of the specified iterable collection.
Syntax: last(coll)
Parameters:
coll: Specified iterable collection.
Returns: It returns the last element of the specified iterable collection.
Example 1:
# Julia program to illustrate # the use of last() method # Getting the last element of # the specified iterable collection# or 1D arrayprintln(last(1:2:3))println(last(5:10))println(last([3, 5, 7, 9]))println(last([2, 4, 6, 8]))
Output:
3
10
9
8
Example 2:
# Julia program to illustrate # the use of last() method # Getting the last element of # the specified 2D and 3D arrayprintln(last([3 5; 7 9]))println(last(["a" "b"; "c" "d"]))println(last(cat([1 2; 3 4], [5 6; 7 8], [2 2; 3 4], dims = 3)))println(last(cat(["a" "b"; "c" "d"], ["e" "f"; "g" "h"], ["i" "j"; "k" "l"], dims = 3)))
Output:
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Storing Output on a File in Julia
Formatting of Strings in Julia
Reshaping array dimensions in Julia | Array reshape() Method
Manipulating matrices in Julia
Creating array with repeated elements in Julia - repeat() Method
while loop in Julia
Get array dimensions and size of a dimension in Julia - size() Method
|
[
{
"code": null,
"e": 25629,
"s": 25601,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 25751,
"s": 25629,
"text": "The last() is an inbuilt function in julia which is used to return the last element of the specified iterable collection."
},
{
"code": null,
"e": 25770,
"s": 25751,
"text": "Syntax: last(coll)"
},
{
"code": null,
"e": 25782,
"s": 25770,
"text": "Parameters:"
},
{
"code": null,
"e": 25819,
"s": 25782,
"text": "coll: Specified iterable collection."
},
{
"code": null,
"e": 25894,
"s": 25819,
"text": "Returns: It returns the last element of the specified iterable collection."
},
{
"code": null,
"e": 25905,
"s": 25894,
"text": "Example 1:"
},
{
"code": "# Julia program to illustrate # the use of last() method # Getting the last element of # the specified iterable collection# or 1D arrayprintln(last(1:2:3))println(last(5:10))println(last([3, 5, 7, 9]))println(last([2, 4, 6, 8]))",
"e": 26136,
"s": 25905,
"text": null
},
{
"code": null,
"e": 26144,
"s": 26136,
"text": "Output:"
},
{
"code": null,
"e": 26154,
"s": 26144,
"text": "3\n10\n9\n8\n"
},
{
"code": null,
"e": 26165,
"s": 26154,
"text": "Example 2:"
},
{
"code": "# Julia program to illustrate # the use of last() method # Getting the last element of # the specified 2D and 3D arrayprintln(last([3 5; 7 9]))println(last([\"a\" \"b\"; \"c\" \"d\"]))println(last(cat([1 2; 3 4], [5 6; 7 8], [2 2; 3 4], dims = 3)))println(last(cat([\"a\" \"b\"; \"c\" \"d\"], [\"e\" \"f\"; \"g\" \"h\"], [\"i\" \"j\"; \"k\" \"l\"], dims = 3)))",
"e": 26546,
"s": 26165,
"text": null
},
{
"code": null,
"e": 26554,
"s": 26546,
"text": "Output:"
},
{
"code": null,
"e": 26560,
"s": 26554,
"text": "Julia"
},
{
"code": null,
"e": 26658,
"s": 26560,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26675,
"s": 26658,
"text": "Vectors in Julia"
},
{
"code": null,
"e": 26735,
"s": 26675,
"text": "Getting rounded value of a number in Julia - round() Method"
},
{
"code": null,
"e": 26808,
"s": 26735,
"text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)"
},
{
"code": null,
"e": 26842,
"s": 26808,
"text": "Storing Output on a File in Julia"
},
{
"code": null,
"e": 26873,
"s": 26842,
"text": "Formatting of Strings in Julia"
},
{
"code": null,
"e": 26934,
"s": 26873,
"text": "Reshaping array dimensions in Julia | Array reshape() Method"
},
{
"code": null,
"e": 26965,
"s": 26934,
"text": "Manipulating matrices in Julia"
},
{
"code": null,
"e": 27030,
"s": 26965,
"text": "Creating array with repeated elements in Julia - repeat() Method"
},
{
"code": null,
"e": 27050,
"s": 27030,
"text": "while loop in Julia"
}
] |
Flipkart Interview Experience for SDE Internship | On-Campus 2021 - GeeksforGeeks
|
28 Sep, 2021
Flipkart recently visited our campus, hiring for SDE Internship for summer 2021. They were open only for students in CSE and had no CGPA criteria.
The hiring workflow consisted of 4 rounds in total ( 1 Coding Round, 2 Technical Interviews, and 1 HM Interview ).
Note: Everything, including the interviews, was online due to the COVID situation.
Round 1 ( Coding Round ): We were given 3 questions to solve within 90 mins.
Count of all nodes at even height from the given root in a General m-ary Tree.Similar tohttps://www.geeksforgeeks.org/print-nodes-odd-levels-tree/”> this article but for a general tree and even levels. Sort first k values in ascending order and remaining n-k values in descending order. Given a string A consisting of lowercase alphabets and a list of strings B find the number of strings in B that forms a substring after deleting at most k characters from A also these operations is allowed on strings in B :a. We can change character ‘o’ to ‘a’, ‘t’ to ‘i’, and vice-versa.b. We can delete one character from the current string.
Count of all nodes at even height from the given root in a General m-ary Tree.Similar tohttps://www.geeksforgeeks.org/print-nodes-odd-levels-tree/”> this article but for a general tree and even levels.
Sort first k values in ascending order and remaining n-k values in descending order.
Given a string A consisting of lowercase alphabets and a list of strings B find the number of strings in B that forms a substring after deleting at most k characters from A also these operations is allowed on strings in B :a. We can change character ‘o’ to ‘a’, ‘t’ to ‘i’, and vice-versa.b. We can delete one character from the current string.
The submitted codes were tested on multiple hidden test cases. 11 Students were shortlisted for further rounds.
Round 2 ( Technical Interview ): This round was held on the Aspiring Minds Codemeet platform which is a Live Coding Interview Platform. The interviewer asked to write only Pseudo Code for the following questions :
The minimum number of subarrays of a given array of numbers such that every subarray is either increasing or decreasing. Find if there is a rectangle in binary matrix with corners as 1
The minimum number of subarrays of a given array of numbers such that every subarray is either increasing or decreasing.
Find if there is a rectangle in binary matrix with corners as 1
Question 1 Example :
arr = [1,2,3,3,1,5,6,7,8,7,4]
Ans - 4 ( 1,2,3 | 3,1 | 5,6,7,8 | 7,4 )
( Inc , Dec , Inc , Dec )
Therefore we can have 4 subarrays such that they
are either all increasign or decreasig.
Note : We have just have to find alternating sequence
for increasing or decreasing from first index to last.
The questions were easy and I gave the correct solution for both. (Actually gave a Recursive DP approach for the first question initially but changed to simple iterative after I realized it’s just a basic array partition problem.)
After this 9/11 students were qualified for further rounds.
Round 3 ( Technical Interview ): This round was also held on the same Codemeet platform and the interviewer asked to write the pseudo-code for the 1st question and the 2nd question was only for discussion.
Given a Binary Tree you have to perform the given operation recursively :a. Print all Leaf nodes.b. Assume all Leaf nodes are deleted.c. Go to step aThe solution for this problem is similar to this article Count of leaf nodes required to be removed at each step to empty a given Binary Tree Given a Complete Binary Tree where each level is sorted in increasing order and the next level has elements greater than the maximum of the current level, discuss a method to implement searching of value in this tree. https://www.geeksforgeeks.org/check-if-value-exists-in-level-order-sorted-complete-binary-tree/
Given a Binary Tree you have to perform the given operation recursively :a. Print all Leaf nodes.b. Assume all Leaf nodes are deleted.c. Go to step aThe solution for this problem is similar to this article Count of leaf nodes required to be removed at each step to empty a given Binary Tree
Given a Complete Binary Tree where each level is sorted in increasing order and the next level has elements greater than the maximum of the current level, discuss a method to implement searching of value in this tree. https://www.geeksforgeeks.org/check-if-value-exists-in-level-order-sorted-complete-binary-tree/
Q 1 . Example :
1
/ \
2 3
/ \
4 5
For this the answer would be
First Time - 4,5,3
Second Time - 2
Third Time - 1
Note : The set in which a node will belong to is
the maximum distance from all leaf node in that subtree.
Q 2 . Example :
3
5 8
9 11 12 14
Note : If we need to search any element we have to
look if we get the range of nodes where that node
could be by having 2 pointers , one going only left
and the other only right.
Time Complexity would be O(log^2(n))
I answered both of them correctly. (Just messed up a bit for time complexity for 2nd question ).
After this 7/11 were qualified for the last round.
Round 4 ( Hiring Manager Interview ): This round was similar to any HR round but was conducted by a Senior Developer. The main focus was mostly on behavioral questions, my past experiences, and projects.
After a brief introduction, these questions were asked :
What is your past internship experience and what was your role? (Asked because I had mentioned that I had previous internship experience)What contribution did you make to opensource and what’s its use case? (Asked as I mentioned contribution to opensource.)Why is your CGPA low and how would you work on improving it? (I have 7.7/10 CGPA :D)Tell me about two of your weaknesses (One personal and one Technical)?Have you ever lead a team, and what was your takeaway?
What is your past internship experience and what was your role? (Asked because I had mentioned that I had previous internship experience)
What contribution did you make to opensource and what’s its use case? (Asked as I mentioned contribution to opensource.)
Why is your CGPA low and how would you work on improving it? (I have 7.7/10 CGPA :D)
Tell me about two of your weaknesses (One personal and one Technical)?
Have you ever lead a team, and what was your takeaway?
Apart from this, there were some more random questions were also asked. Finally, It was my time to ask any questions I had, and I had a lot of them. We both ended the interview on a positive note and soon after I got the email for selection.
A total of 3 students were selected for the Flipkart 2021 SDE Internship from my campus.
Some General Tips –
Be confident about your solution in the Technical Interviews
Always provide your interviewer with a non-efficient solution if you can not arrive at an optimal solution on the first try.
Make use of the whiteboard if there are any in your Interview IDE (It provides a better way to represent your thoughts).
Ask your interviewer questions at the end of every interview if they are open to it. ( Personal, Technical, or regarding Internship )
Flipkart
Marketing
On-Campus
Internship
Interview Experiences
Flipkart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus)
Zoho Interview Experience (Off-Campus ) 2022
HashedIn by Deloitte Interview Experience for SDE Intern+FTE | (Off-Campus) 2022
McKinsey Interview Experience for Software Associate Internship
Groww Interview Experience for SDE Intern (Web) Off-Campus
Amazon Interview Questions
Commonly Asked Java Programming Interview Questions | Set 2
Amazon Interview Experience for SDE-1 (Off-Campus)
Amazon AWS Interview Experience for SDE-1
Difference between ANN, CNN and RNN
|
[
{
"code": null,
"e": 26769,
"s": 26741,
"text": "\n28 Sep, 2021"
},
{
"code": null,
"e": 26917,
"s": 26769,
"text": "Flipkart recently visited our campus, hiring for SDE Internship for summer 2021. They were open only for students in CSE and had no CGPA criteria. "
},
{
"code": null,
"e": 27032,
"s": 26917,
"text": "The hiring workflow consisted of 4 rounds in total ( 1 Coding Round, 2 Technical Interviews, and 1 HM Interview )."
},
{
"code": null,
"e": 27115,
"s": 27032,
"text": "Note: Everything, including the interviews, was online due to the COVID situation."
},
{
"code": null,
"e": 27193,
"s": 27115,
"text": "Round 1 ( Coding Round ): We were given 3 questions to solve within 90 mins."
},
{
"code": null,
"e": 27825,
"s": 27193,
"text": "Count of all nodes at even height from the given root in a General m-ary Tree.Similar tohttps://www.geeksforgeeks.org/print-nodes-odd-levels-tree/”> this article but for a general tree and even levels. Sort first k values in ascending order and remaining n-k values in descending order. Given a string A consisting of lowercase alphabets and a list of strings B find the number of strings in B that forms a substring after deleting at most k characters from A also these operations is allowed on strings in B :a. We can change character ‘o’ to ‘a’, ‘t’ to ‘i’, and vice-versa.b. We can delete one character from the current string."
},
{
"code": null,
"e": 28028,
"s": 27825,
"text": "Count of all nodes at even height from the given root in a General m-ary Tree.Similar tohttps://www.geeksforgeeks.org/print-nodes-odd-levels-tree/”> this article but for a general tree and even levels. "
},
{
"code": null,
"e": 28114,
"s": 28028,
"text": "Sort first k values in ascending order and remaining n-k values in descending order. "
},
{
"code": null,
"e": 28459,
"s": 28114,
"text": "Given a string A consisting of lowercase alphabets and a list of strings B find the number of strings in B that forms a substring after deleting at most k characters from A also these operations is allowed on strings in B :a. We can change character ‘o’ to ‘a’, ‘t’ to ‘i’, and vice-versa.b. We can delete one character from the current string."
},
{
"code": null,
"e": 28571,
"s": 28459,
"text": "The submitted codes were tested on multiple hidden test cases. 11 Students were shortlisted for further rounds."
},
{
"code": null,
"e": 28785,
"s": 28571,
"text": "Round 2 ( Technical Interview ): This round was held on the Aspiring Minds Codemeet platform which is a Live Coding Interview Platform. The interviewer asked to write only Pseudo Code for the following questions :"
},
{
"code": null,
"e": 28970,
"s": 28785,
"text": "The minimum number of subarrays of a given array of numbers such that every subarray is either increasing or decreasing. Find if there is a rectangle in binary matrix with corners as 1"
},
{
"code": null,
"e": 29092,
"s": 28970,
"text": "The minimum number of subarrays of a given array of numbers such that every subarray is either increasing or decreasing. "
},
{
"code": null,
"e": 29156,
"s": 29092,
"text": "Find if there is a rectangle in binary matrix with corners as 1"
},
{
"code": null,
"e": 29484,
"s": 29156,
"text": "Question 1 Example :\narr = [1,2,3,3,1,5,6,7,8,7,4]\nAns - 4 ( 1,2,3 | 3,1 | 5,6,7,8 | 7,4 )\n ( Inc , Dec , Inc , Dec )\nTherefore we can have 4 subarrays such that they \nare either all increasign or decreasig.\nNote : We have just have to find alternating sequence\nfor increasing or decreasing from first index to last."
},
{
"code": null,
"e": 29715,
"s": 29484,
"text": "The questions were easy and I gave the correct solution for both. (Actually gave a Recursive DP approach for the first question initially but changed to simple iterative after I realized it’s just a basic array partition problem.)"
},
{
"code": null,
"e": 29776,
"s": 29715,
"text": "After this 9/11 students were qualified for further rounds. "
},
{
"code": null,
"e": 29982,
"s": 29776,
"text": "Round 3 ( Technical Interview ): This round was also held on the same Codemeet platform and the interviewer asked to write the pseudo-code for the 1st question and the 2nd question was only for discussion."
},
{
"code": null,
"e": 30588,
"s": 29982,
"text": "Given a Binary Tree you have to perform the given operation recursively :a. Print all Leaf nodes.b. Assume all Leaf nodes are deleted.c. Go to step aThe solution for this problem is similar to this article Count of leaf nodes required to be removed at each step to empty a given Binary Tree Given a Complete Binary Tree where each level is sorted in increasing order and the next level has elements greater than the maximum of the current level, discuss a method to implement searching of value in this tree. https://www.geeksforgeeks.org/check-if-value-exists-in-level-order-sorted-complete-binary-tree/"
},
{
"code": null,
"e": 30880,
"s": 30588,
"text": "Given a Binary Tree you have to perform the given operation recursively :a. Print all Leaf nodes.b. Assume all Leaf nodes are deleted.c. Go to step aThe solution for this problem is similar to this article Count of leaf nodes required to be removed at each step to empty a given Binary Tree "
},
{
"code": null,
"e": 31195,
"s": 30880,
"text": "Given a Complete Binary Tree where each level is sorted in increasing order and the next level has elements greater than the maximum of the current level, discuss a method to implement searching of value in this tree. https://www.geeksforgeeks.org/check-if-value-exists-in-level-order-sorted-complete-binary-tree/"
},
{
"code": null,
"e": 31852,
"s": 31195,
"text": "Q 1 . Example :\n 1\n / \\\n 2 3 \n / \\ \n 4 5 \n For this the answer would be \n First Time - 4,5,3\n Second Time - 2\n Third Time - 1\n Note : The set in which a node will belong to is \n the maximum distance from all leaf node in that subtree.\n \nQ 2 . Example :\n 3\n 5 8\n 9 11 12 14\n Note : If we need to search any element we have to \n look if we get the range of nodes where that node \n could be by having 2 pointers , one going only left \n and the other only right.\n \n Time Complexity would be O(log^2(n))"
},
{
"code": null,
"e": 31949,
"s": 31852,
"text": "I answered both of them correctly. (Just messed up a bit for time complexity for 2nd question )."
},
{
"code": null,
"e": 32001,
"s": 31949,
"text": "After this 7/11 were qualified for the last round. "
},
{
"code": null,
"e": 32205,
"s": 32001,
"text": "Round 4 ( Hiring Manager Interview ): This round was similar to any HR round but was conducted by a Senior Developer. The main focus was mostly on behavioral questions, my past experiences, and projects."
},
{
"code": null,
"e": 32262,
"s": 32205,
"text": "After a brief introduction, these questions were asked :"
},
{
"code": null,
"e": 32728,
"s": 32262,
"text": "What is your past internship experience and what was your role? (Asked because I had mentioned that I had previous internship experience)What contribution did you make to opensource and what’s its use case? (Asked as I mentioned contribution to opensource.)Why is your CGPA low and how would you work on improving it? (I have 7.7/10 CGPA :D)Tell me about two of your weaknesses (One personal and one Technical)?Have you ever lead a team, and what was your takeaway?"
},
{
"code": null,
"e": 32866,
"s": 32728,
"text": "What is your past internship experience and what was your role? (Asked because I had mentioned that I had previous internship experience)"
},
{
"code": null,
"e": 32987,
"s": 32866,
"text": "What contribution did you make to opensource and what’s its use case? (Asked as I mentioned contribution to opensource.)"
},
{
"code": null,
"e": 33072,
"s": 32987,
"text": "Why is your CGPA low and how would you work on improving it? (I have 7.7/10 CGPA :D)"
},
{
"code": null,
"e": 33143,
"s": 33072,
"text": "Tell me about two of your weaknesses (One personal and one Technical)?"
},
{
"code": null,
"e": 33198,
"s": 33143,
"text": "Have you ever lead a team, and what was your takeaway?"
},
{
"code": null,
"e": 33440,
"s": 33198,
"text": "Apart from this, there were some more random questions were also asked. Finally, It was my time to ask any questions I had, and I had a lot of them. We both ended the interview on a positive note and soon after I got the email for selection."
},
{
"code": null,
"e": 33529,
"s": 33440,
"text": "A total of 3 students were selected for the Flipkart 2021 SDE Internship from my campus."
},
{
"code": null,
"e": 33550,
"s": 33529,
"text": "Some General Tips – "
},
{
"code": null,
"e": 33611,
"s": 33550,
"text": "Be confident about your solution in the Technical Interviews"
},
{
"code": null,
"e": 33736,
"s": 33611,
"text": "Always provide your interviewer with a non-efficient solution if you can not arrive at an optimal solution on the first try."
},
{
"code": null,
"e": 33857,
"s": 33736,
"text": "Make use of the whiteboard if there are any in your Interview IDE (It provides a better way to represent your thoughts)."
},
{
"code": null,
"e": 33991,
"s": 33857,
"text": "Ask your interviewer questions at the end of every interview if they are open to it. ( Personal, Technical, or regarding Internship )"
},
{
"code": null,
"e": 34000,
"s": 33991,
"text": "Flipkart"
},
{
"code": null,
"e": 34010,
"s": 34000,
"text": "Marketing"
},
{
"code": null,
"e": 34020,
"s": 34010,
"text": "On-Campus"
},
{
"code": null,
"e": 34031,
"s": 34020,
"text": "Internship"
},
{
"code": null,
"e": 34053,
"s": 34031,
"text": "Interview Experiences"
},
{
"code": null,
"e": 34062,
"s": 34053,
"text": "Flipkart"
},
{
"code": null,
"e": 34160,
"s": 34062,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34237,
"s": 34160,
"text": "Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus)"
},
{
"code": null,
"e": 34282,
"s": 34237,
"text": "Zoho Interview Experience (Off-Campus ) 2022"
},
{
"code": null,
"e": 34363,
"s": 34282,
"text": "HashedIn by Deloitte Interview Experience for SDE Intern+FTE | (Off-Campus) 2022"
},
{
"code": null,
"e": 34427,
"s": 34363,
"text": "McKinsey Interview Experience for Software Associate Internship"
},
{
"code": null,
"e": 34486,
"s": 34427,
"text": "Groww Interview Experience for SDE Intern (Web) Off-Campus"
},
{
"code": null,
"e": 34513,
"s": 34486,
"text": "Amazon Interview Questions"
},
{
"code": null,
"e": 34573,
"s": 34513,
"text": "Commonly Asked Java Programming Interview Questions | Set 2"
},
{
"code": null,
"e": 34624,
"s": 34573,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus)"
},
{
"code": null,
"e": 34666,
"s": 34624,
"text": "Amazon AWS Interview Experience for SDE-1"
}
] |
JavaScript | template literals - GeeksforGeeks
|
23 Oct, 2019
Template Literal in ES6 provides new features to create a string that gives more control over dynamic strings. Traditionally, String is created using single quotes (‘) or double quotes (“) quotes. Template literal is created using the backtick (`) character.
Syntax:
var s=`some string`;
Multiline Strings: In-order to create a multiline string an escape sequence \n was used to give new line character. However, Template Literals there is no need to add \n string ends only when it gets backtick (`) character.
Example:<script>// Without template literalconsole.log('Some text that I want \non two lines!'); // With template literalconsole.log(`Some text that I wanton two lines!`);</script>
<script>// Without template literalconsole.log('Some text that I want \non two lines!'); // With template literalconsole.log(`Some text that I wanton two lines!`);</script>
Output:Some text that I want
on two lines!
Some text that I want
on two lines!
Some text that I want
on two lines!
Some text that I want
on two lines!
Expressions: To dynamically add values into new Template Literals expressions are used. The ${} syntax allows an expression in it that produces the value. This value can be a string stored in a variable or a computation operation.
${expression}
Example : The code below shows the use of expressions in template literals.<script>let principal = 1000;let noofyears = 1;let rateofinterest = 7; let SI = `Simple Interest is ${(principal * noofyears * rateofinterest)/100}`;alert("Simple Interest is" + SI);</script>
<script>let principal = 1000;let noofyears = 1;let rateofinterest = 7; let SI = `Simple Interest is ${(principal * noofyears * rateofinterest)/100}`;alert("Simple Interest is" + SI);</script>
Output:
Tagged Templates: One of the features of Template Literals is its ability to create Tagged Template Literals. Tagged Literal is written like a function definition, but the difference is when this literal is called. There is no parenthesis() to a literal call. An array of Strings are passed as a parameter to a literal.
Example 1:<script> function TaggedLiteralEg(strings) { document.write(strings);} TaggedLiteralEg `GeeksforGeeks`; </script>
<script> function TaggedLiteralEg(strings) { document.write(strings);} TaggedLiteralEg `GeeksforGeeks`; </script>
Output:GeeksforGeeks
GeeksforGeeks
Example 2: It is also possible to pass values to a tagged literal. This value can be a result of some expression or a value fetched from the variable. The code below shows the use of Tagged Literal.<script>function TaggedLiteralEg(strings, value, value2) { document.write(strings); document.write("<br>"+value2+" "+value); } let text = 'GeeksforGeeks';TaggedLiteralEg`test ${text} ${2+3}`; </script>
<script>function TaggedLiteralEg(strings, value, value2) { document.write(strings); document.write("<br>"+value2+" "+value); } let text = 'GeeksforGeeks';TaggedLiteralEg`test ${text} ${2+3}`; </script>
Output:test , ,
5 GeeksforGeeks
test , ,
5 GeeksforGeeks
Raw String: Raw method of template literal allows access of raw strings as they were entered, without processing escape sequences. In addition, the String.raw() method exists to create raw strings just like the default template function, and string concatenation would create.
Example:<script>var s=String.raw`Welcome to GeeksforGeeks Value of expression is ${2+3}`;document.write(s);</script>
<script>var s=String.raw`Welcome to GeeksforGeeks Value of expression is ${2+3}`;document.write(s);</script>
Output:Welcome to GeeksforGeeks Value of expression is 5
Welcome to GeeksforGeeks Value of expression is 5
Nested Templates: Templates can be nested if it contains multiple expression evaluation or multiple condition checking. Instead of using else if ladder this is readable and gives ease to the developer. The code below finds the maximum of three numbers using conditional operator and nested template literal.
Example:<script>function maximum(x, y, z) {var c = `value ${ (y>x && y>z) ? 'y is greater' :`${x>z ? 'x is greater' : 'z is greater'}` }`;return (c);}document.write(maximum(5, 11, 15)+"<br>");document.write(maximum(15, 11, 3)+"<br>");document.write(maximum(11, 33, 2)+"<br>");</script>
<script>function maximum(x, y, z) {var c = `value ${ (y>x && y>z) ? 'y is greater' :`${x>z ? 'x is greater' : 'z is greater'}` }`;return (c);}document.write(maximum(5, 11, 15)+"<br>");document.write(maximum(15, 11, 3)+"<br>");document.write(maximum(11, 33, 2)+"<br>");</script>
Output:value z is greater
value x is greater
value y is greater
value z is greater
value x is greater
value y is greater
javascript-basics
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab 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 ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25647,
"s": 25619,
"text": "\n23 Oct, 2019"
},
{
"code": null,
"e": 25906,
"s": 25647,
"text": "Template Literal in ES6 provides new features to create a string that gives more control over dynamic strings. Traditionally, String is created using single quotes (‘) or double quotes (“) quotes. Template literal is created using the backtick (`) character."
},
{
"code": null,
"e": 25914,
"s": 25906,
"text": "Syntax:"
},
{
"code": null,
"e": 25935,
"s": 25914,
"text": "var s=`some string`;"
},
{
"code": null,
"e": 26159,
"s": 25935,
"text": "Multiline Strings: In-order to create a multiline string an escape sequence \\n was used to give new line character. However, Template Literals there is no need to add \\n string ends only when it gets backtick (`) character."
},
{
"code": null,
"e": 26341,
"s": 26159,
"text": "Example:<script>// Without template literalconsole.log('Some text that I want \\non two lines!'); // With template literalconsole.log(`Some text that I wanton two lines!`);</script>"
},
{
"code": "<script>// Without template literalconsole.log('Some text that I want \\non two lines!'); // With template literalconsole.log(`Some text that I wanton two lines!`);</script>",
"e": 26515,
"s": 26341,
"text": null
},
{
"code": null,
"e": 26594,
"s": 26515,
"text": "Output:Some text that I want\non two lines!\nSome text that I want\non two lines!"
},
{
"code": null,
"e": 26666,
"s": 26594,
"text": "Some text that I want\non two lines!\nSome text that I want\non two lines!"
},
{
"code": null,
"e": 26897,
"s": 26666,
"text": "Expressions: To dynamically add values into new Template Literals expressions are used. The ${} syntax allows an expression in it that produces the value. This value can be a string stored in a variable or a computation operation."
},
{
"code": null,
"e": 26911,
"s": 26897,
"text": "${expression}"
},
{
"code": null,
"e": 27190,
"s": 26911,
"text": "Example : The code below shows the use of expressions in template literals.<script>let principal = 1000;let noofyears = 1;let rateofinterest = 7; let SI = `Simple Interest is ${(principal * noofyears * rateofinterest)/100}`;alert(\"Simple Interest is\" + SI);</script>"
},
{
"code": "<script>let principal = 1000;let noofyears = 1;let rateofinterest = 7; let SI = `Simple Interest is ${(principal * noofyears * rateofinterest)/100}`;alert(\"Simple Interest is\" + SI);</script>",
"e": 27394,
"s": 27190,
"text": null
},
{
"code": null,
"e": 27402,
"s": 27394,
"text": "Output:"
},
{
"code": null,
"e": 27722,
"s": 27402,
"text": "Tagged Templates: One of the features of Template Literals is its ability to create Tagged Template Literals. Tagged Literal is written like a function definition, but the difference is when this literal is called. There is no parenthesis() to a literal call. An array of Strings are passed as a parameter to a literal."
},
{
"code": null,
"e": 27855,
"s": 27722,
"text": "Example 1:<script> function TaggedLiteralEg(strings) { document.write(strings);} TaggedLiteralEg `GeeksforGeeks`; </script>"
},
{
"code": "<script> function TaggedLiteralEg(strings) { document.write(strings);} TaggedLiteralEg `GeeksforGeeks`; </script>",
"e": 27978,
"s": 27855,
"text": null
},
{
"code": null,
"e": 27999,
"s": 27978,
"text": "Output:GeeksforGeeks"
},
{
"code": null,
"e": 28013,
"s": 27999,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 28431,
"s": 28013,
"text": "Example 2: It is also possible to pass values to a tagged literal. This value can be a result of some expression or a value fetched from the variable. The code below shows the use of Tagged Literal.<script>function TaggedLiteralEg(strings, value, value2) { document.write(strings); document.write(\"<br>\"+value2+\" \"+value); } let text = 'GeeksforGeeks';TaggedLiteralEg`test ${text} ${2+3}`; </script>"
},
{
"code": "<script>function TaggedLiteralEg(strings, value, value2) { document.write(strings); document.write(\"<br>\"+value2+\" \"+value); } let text = 'GeeksforGeeks';TaggedLiteralEg`test ${text} ${2+3}`; </script>",
"e": 28651,
"s": 28431,
"text": null
},
{
"code": null,
"e": 28683,
"s": 28651,
"text": "Output:test , ,\n5 GeeksforGeeks"
},
{
"code": null,
"e": 28708,
"s": 28683,
"text": "test , ,\n5 GeeksforGeeks"
},
{
"code": null,
"e": 28985,
"s": 28708,
"text": "Raw String: Raw method of template literal allows access of raw strings as they were entered, without processing escape sequences. In addition, the String.raw() method exists to create raw strings just like the default template function, and string concatenation would create."
},
{
"code": null,
"e": 29102,
"s": 28985,
"text": "Example:<script>var s=String.raw`Welcome to GeeksforGeeks Value of expression is ${2+3}`;document.write(s);</script>"
},
{
"code": "<script>var s=String.raw`Welcome to GeeksforGeeks Value of expression is ${2+3}`;document.write(s);</script>",
"e": 29211,
"s": 29102,
"text": null
},
{
"code": null,
"e": 29268,
"s": 29211,
"text": "Output:Welcome to GeeksforGeeks Value of expression is 5"
},
{
"code": null,
"e": 29318,
"s": 29268,
"text": "Welcome to GeeksforGeeks Value of expression is 5"
},
{
"code": null,
"e": 29626,
"s": 29318,
"text": "Nested Templates: Templates can be nested if it contains multiple expression evaluation or multiple condition checking. Instead of using else if ladder this is readable and gives ease to the developer. The code below finds the maximum of three numbers using conditional operator and nested template literal."
},
{
"code": null,
"e": 29932,
"s": 29626,
"text": "Example:<script>function maximum(x, y, z) {var c = `value ${ (y>x && y>z) ? 'y is greater' :`${x>z ? 'x is greater' : 'z is greater'}` }`;return (c);}document.write(maximum(5, 11, 15)+\"<br>\");document.write(maximum(15, 11, 3)+\"<br>\");document.write(maximum(11, 33, 2)+\"<br>\");</script> "
},
{
"code": "<script>function maximum(x, y, z) {var c = `value ${ (y>x && y>z) ? 'y is greater' :`${x>z ? 'x is greater' : 'z is greater'}` }`;return (c);}document.write(maximum(5, 11, 15)+\"<br>\");document.write(maximum(15, 11, 3)+\"<br>\");document.write(maximum(11, 33, 2)+\"<br>\");</script> ",
"e": 30230,
"s": 29932,
"text": null
},
{
"code": null,
"e": 30294,
"s": 30230,
"text": "Output:value z is greater\nvalue x is greater\nvalue y is greater"
},
{
"code": null,
"e": 30351,
"s": 30294,
"text": "value z is greater\nvalue x is greater\nvalue y is greater"
},
{
"code": null,
"e": 30369,
"s": 30351,
"text": "javascript-basics"
},
{
"code": null,
"e": 30376,
"s": 30369,
"text": "Picked"
},
{
"code": null,
"e": 30387,
"s": 30376,
"text": "JavaScript"
},
{
"code": null,
"e": 30404,
"s": 30387,
"text": "Web Technologies"
},
{
"code": null,
"e": 30502,
"s": 30404,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30542,
"s": 30502,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30587,
"s": 30542,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30648,
"s": 30587,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30720,
"s": 30648,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 30766,
"s": 30720,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 30806,
"s": 30766,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30839,
"s": 30806,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30884,
"s": 30839,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30927,
"s": 30884,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Automate Instagram Messages using Python - GeeksforGeeks
|
01 Nov, 2020
In this article, we will see how to send a single message to any number of people. We just have to provide a list of users. We will use selenium for this task.
Selenium: It is an open-source tool that automates web browsers. It provides a single interface that lets you write test scripts in programming languages like Ruby, Java, NodeJS, PHP, Perl, Python, and C#, among others. I personally prefer Python as it’s very easy to write code in python. A browser-driver then executes these scripts on a browser-instance on your device. To install this module run this command into your terminal.
pip install selenium
webdriver-manager: It provides a way to automatically manage drivers for different browsers. To install this module run this command into your terminal.
pip install webdriver-manager
ChromeDriver: ChromeDriver is a separate executable that Selenium WebDriver uses to control Chrome.
Google Chrome
Step 1: Importing all the necessary libraries.
Python3
from selenium import webdriverimport osimport timefrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditionsfrom selenium.webdriver.common.keys import Keysfrom webdriver_manager.chrome import ChromeDriverManager
Step 2: Using chrome with this code will always work (no need to worry about updating chromedriver version)
Python3
driver = webdriver.Chrome(ChromeDriverManager().install())
Step 3: Before declaring a Class we will make a list of users( any no. of users in this code I am using three users.) in that list you have to send the username of the person you want to send a message to and the message we want to send to all the users.
Python3
# you can take any valid usernameaudience = [ 'sundarpichai','virat.kholi','rudymancuso']message = "testing of a bot"
Step 4: Here I am creating a class function all the code will be written inside this class so, In the end, we just have to just call this class. Let’s create an __init__ function that can be called when an object is created from the class,__init__ will provide the access that is required to initialize the attributes of the class.
Python3
class bot: def __init__(self, username, password, audience, message): # initializing the username self.username = username # initializing the password self.password = password # passing the list of user or initializing self.user = user # passing the message of user or initializing self.message = message # initializing the base url. self.base_url = 'https://www.instagram.com/' # here it calls the driver to open chrome web browser. self.bot = driver # initializing the login function we will create self.login()
Step 5: Creating a Login function where all the steps will be written
Python3
def login(self): self.bot.get(self.base_url) # ENTERING THE USERNAME FOR LOGIN INTO INSTAGRAM enter_username = WebDriverWait(self.bot, 20).until( expected_conditions.presence_of_element_located((By.NAME, 'username'))) enter_username.send_keys(self.username) # ENTERING THE PASSWORD FOR LOGIN INTO INSTAGRAM enter_password = WebDriverWait(self.bot, 20).until( expected_conditions.presence_of_element_located((By.NAME, 'password'))) enter_password.send_keys(self.password) # RETURNING THE PASSWORD and login into the account enter_password.send_keys(Keys.RETURN) time.sleep(5)
Note: for finding the XPath right-click on the element then you see the inspect option on a web browser.
Selecting xpath
Step 6: HANDLING POP-UP BOXES – When you log in to Instagram you will come across two pop-up boxes as shown in the images. The first one will be asking about do you want to save info or not it will click on not now. The second one will be asking you to turn off the notifications or not so we will again click on not now as shown in the given code.
Python3
# first pop-up boxself.bot.find_element_by_xpath( '//*[@id="react-root"]/section/main/div/div/div/div/button').click()time.sleep(3) # 2nd pop-up boxself.bot.find_element_by_xpath( '/html/body/div[4]/div/div/div/div[3]/button[2]').click() time.sleep(4)
1st pop-up box
2nd pop-up box
Step 7: Clicking on the message option on the right corner
Message button(Direct button)
Note: This will click on the message(direct) option.
Python3
# this will click on message(direct) option.self.bot.find_element_by_xpath( '//a[@class="xWeGp"]/*[name()="svg"][@aria-label="Direct"]').click() time.sleep(3)
Step 8: Clicking on the pencil option here we type the user’s name.
Python3
# This will click on the pencil icon as shown in the figure.self.bot.find_element_by_xpath( '//*[@id="react-root"]/section/div/div[2]/div/div/div[2]/div/button').click()time.sleep(2)
Step 9: Here is the main part of the code where we take a username from the list search for it and message that person. This process is in the loop to take username.
Python3
for i in user: # enter the username self.bot.find_element_by_xpath( '/html/body/div[4]/div/div/div[2]/div[1]/div/div[2]/input').send_keys(i) time.sleep(2) # click on the username self.bot.find_element_by_xpath( '/html/body/div[4]/div/div/div[2]/div[2]/div').click() time.sleep(2) # next button self.bot.find_element_by_xpath( '/html/body/div[4]/div/div/div[1]/div/div[2]/div/button').click() time.sleep(2) # click on message area send = self.bot.find_element_by_xpath( '/html/body/div[1]/section/div/div[2]/div/div/div[2]/div[2]/div/div[2]/div/div/div[2]/textarea') # types message send.send_keys(self.message) time.sleep(1) # send message send.send_keys(Keys.RETURN) time.sleep(2) # clicks on pencil icon self.bot.find_element_by_xpath( '/html/body/div[1]/section/div/div[2]/div/div/div[1]/div[1]/div/div[3]/button').click() time.sleep(2) # here will take the next username from the user's list.
Step 10: We have finally completed the code. It’s time to create a function where we will pass the username and the password of the account in which we want to login and call our class here.
Python3
def init(): # you can even enter your personal account. bot('username', 'password', user, message_) input("DONE")
Step 11: Let’s call our function
Python3
# calling this function will message everyone's# that is on your user's list...:)init()
Let’s put all the code together
Python3
# importing modulefrom selenium import webdriverimport osimport timefrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditionsfrom selenium.webdriver.common.keys import Keysfrom webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(ChromeDriverManager().install()) # enter receiver user nameuser = ['User_name', 'User_name ']message_ = ("final test") class bot: def __init__(self, username, password, user, message): self.username = username self.password = password self.user = user self.message = message self.base_url = 'https://www.instagram.com/' self.bot = driver self.login() def login(self): self.bot.get(self.base_url) enter_username = WebDriverWait(self.bot, 20).until( expected_conditions.presence_of_element_located((By.NAME, 'username'))) enter_username.send_keys(self.username) enter_password = WebDriverWait(self.bot, 20).until( expected_conditions.presence_of_element_located((By.NAME, 'password'))) enter_password.send_keys(self.password) enter_password.send_keys(Keys.RETURN) time.sleep(5) # first pop-up self.bot.find_element_by_xpath( '//*[@id="react-root"]/section/main/div/div/div/div/button').click() time.sleep(3) # 2nd pop-up self.bot.find_element_by_xpath( '/html/body/div[4]/div/div/div/div[3]/button[2]').click() time.sleep(4) # direct button self.bot.find_element_by_xpath( '//a[@class="xWeGp"]/*[name()="svg"][@aria-label="Direct"]').click() time.sleep(3) # clicks on pencil icon self.bot.find_element_by_xpath( '//*[@id="react-root"]/section/div/div[2]/div/div/div[2]/div/button').click() time.sleep(2) for i in user: # enter the username self.bot.find_element_by_xpath( '/html/body/div[4]/div/div/div[2]/div[1]/div/div[2]/input').send_keys(i) time.sleep(2) # click on the username self.bot.find_element_by_xpath( '/html/body/div[4]/div/div/div[2]/div[2]/div').click() time.sleep(2) # next button self.bot.find_element_by_xpath( '/html/body/div[4]/div/div/div[1]/div/div[2]/div/button').click() time.sleep(2) # click on message area send = self.bot.find_element_by_xpath( '/html/body/div[1]/section/div/div[2]/div/div/div[2]/div[2]/div/div[2]/div/div/div[2]/textarea') # types message send.send_keys(self.message) time.sleep(1) # send message send.send_keys(Keys.RETURN) time.sleep(2) # clicks on direct option or pencl icon self.bot.find_element_by_xpath( '/html/body/div[1]/section/div/div[2]/div/div/div[1]/div[1]/div/div[3]/button').click() time.sleep(2) def init(): bot('username', 'password', user, message_) # when our program ends it will show "done". input("DONE") # calling the functioninit()
python-utility
Technical Scripter 2020
Project
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
Simple Chat Room using Python
Java Swing | Simple User Registration Form
OpenCV C++ Program for Face Detection
Twitter Sentiment Analysis using Python
Banking Transaction System using Java
Face Detection using Python and OpenCV with webcam
Program for Employee Management System
Snake Game in C
Image Classifier using CNN
|
[
{
"code": null,
"e": 25889,
"s": 25861,
"text": "\n01 Nov, 2020"
},
{
"code": null,
"e": 26049,
"s": 25889,
"text": "In this article, we will see how to send a single message to any number of people. We just have to provide a list of users. We will use selenium for this task."
},
{
"code": null,
"e": 26482,
"s": 26049,
"text": "Selenium: It is an open-source tool that automates web browsers. It provides a single interface that lets you write test scripts in programming languages like Ruby, Java, NodeJS, PHP, Perl, Python, and C#, among others. I personally prefer Python as it’s very easy to write code in python. A browser-driver then executes these scripts on a browser-instance on your device. To install this module run this command into your terminal."
},
{
"code": null,
"e": 26504,
"s": 26482,
"text": "pip install selenium\n"
},
{
"code": null,
"e": 26657,
"s": 26504,
"text": "webdriver-manager: It provides a way to automatically manage drivers for different browsers. To install this module run this command into your terminal."
},
{
"code": null,
"e": 26688,
"s": 26657,
"text": "pip install webdriver-manager\n"
},
{
"code": null,
"e": 26788,
"s": 26688,
"text": "ChromeDriver: ChromeDriver is a separate executable that Selenium WebDriver uses to control Chrome."
},
{
"code": null,
"e": 26803,
"s": 26788,
"text": "Google Chrome "
},
{
"code": null,
"e": 26850,
"s": 26803,
"text": "Step 1: Importing all the necessary libraries."
},
{
"code": null,
"e": 26858,
"s": 26850,
"text": "Python3"
},
{
"code": "from selenium import webdriverimport osimport timefrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditionsfrom selenium.webdriver.common.keys import Keysfrom webdriver_manager.chrome import ChromeDriverManager",
"e": 27168,
"s": 26858,
"text": null
},
{
"code": null,
"e": 27276,
"s": 27168,
"text": "Step 2: Using chrome with this code will always work (no need to worry about updating chromedriver version)"
},
{
"code": null,
"e": 27284,
"s": 27276,
"text": "Python3"
},
{
"code": "driver = webdriver.Chrome(ChromeDriverManager().install())",
"e": 27343,
"s": 27284,
"text": null
},
{
"code": null,
"e": 27598,
"s": 27343,
"text": "Step 3: Before declaring a Class we will make a list of users( any no. of users in this code I am using three users.) in that list you have to send the username of the person you want to send a message to and the message we want to send to all the users."
},
{
"code": null,
"e": 27606,
"s": 27598,
"text": "Python3"
},
{
"code": "# you can take any valid usernameaudience = [ 'sundarpichai','virat.kholi','rudymancuso']message = \"testing of a bot\"",
"e": 27724,
"s": 27606,
"text": null
},
{
"code": null,
"e": 28056,
"s": 27724,
"text": "Step 4: Here I am creating a class function all the code will be written inside this class so, In the end, we just have to just call this class. Let’s create an __init__ function that can be called when an object is created from the class,__init__ will provide the access that is required to initialize the attributes of the class."
},
{
"code": null,
"e": 28064,
"s": 28056,
"text": "Python3"
},
{
"code": "class bot: def __init__(self, username, password, audience, message): # initializing the username self.username = username # initializing the password self.password = password # passing the list of user or initializing self.user = user # passing the message of user or initializing self.message = message # initializing the base url. self.base_url = 'https://www.instagram.com/' # here it calls the driver to open chrome web browser. self.bot = driver # initializing the login function we will create self.login()",
"e": 28749,
"s": 28064,
"text": null
},
{
"code": null,
"e": 28819,
"s": 28749,
"text": "Step 5: Creating a Login function where all the steps will be written"
},
{
"code": null,
"e": 28827,
"s": 28819,
"text": "Python3"
},
{
"code": "def login(self): self.bot.get(self.base_url) # ENTERING THE USERNAME FOR LOGIN INTO INSTAGRAM enter_username = WebDriverWait(self.bot, 20).until( expected_conditions.presence_of_element_located((By.NAME, 'username'))) enter_username.send_keys(self.username) # ENTERING THE PASSWORD FOR LOGIN INTO INSTAGRAM enter_password = WebDriverWait(self.bot, 20).until( expected_conditions.presence_of_element_located((By.NAME, 'password'))) enter_password.send_keys(self.password) # RETURNING THE PASSWORD and login into the account enter_password.send_keys(Keys.RETURN) time.sleep(5)",
"e": 29464,
"s": 28827,
"text": null
},
{
"code": null,
"e": 29569,
"s": 29464,
"text": "Note: for finding the XPath right-click on the element then you see the inspect option on a web browser."
},
{
"code": null,
"e": 29585,
"s": 29569,
"text": "Selecting xpath"
},
{
"code": null,
"e": 29935,
"s": 29585,
"text": "Step 6: HANDLING POP-UP BOXES – When you log in to Instagram you will come across two pop-up boxes as shown in the images. The first one will be asking about do you want to save info or not it will click on not now. The second one will be asking you to turn off the notifications or not so we will again click on not now as shown in the given code."
},
{
"code": null,
"e": 29943,
"s": 29935,
"text": "Python3"
},
{
"code": "# first pop-up boxself.bot.find_element_by_xpath( '//*[@id=\"react-root\"]/section/main/div/div/div/div/button').click()time.sleep(3) # 2nd pop-up boxself.bot.find_element_by_xpath( '/html/body/div[4]/div/div/div/div[3]/button[2]').click() time.sleep(4)",
"e": 30203,
"s": 29943,
"text": null
},
{
"code": null,
"e": 30218,
"s": 30203,
"text": "1st pop-up box"
},
{
"code": null,
"e": 30234,
"s": 30218,
"text": "2nd pop-up box"
},
{
"code": null,
"e": 30294,
"s": 30234,
"text": "Step 7: Clicking on the message option on the right corner "
},
{
"code": null,
"e": 30324,
"s": 30294,
"text": "Message button(Direct button)"
},
{
"code": null,
"e": 30377,
"s": 30324,
"text": "Note: This will click on the message(direct) option."
},
{
"code": null,
"e": 30385,
"s": 30377,
"text": "Python3"
},
{
"code": "# this will click on message(direct) option.self.bot.find_element_by_xpath( '//a[@class=\"xWeGp\"]/*[name()=\"svg\"][@aria-label=\"Direct\"]').click() time.sleep(3)",
"e": 30548,
"s": 30385,
"text": null
},
{
"code": null,
"e": 30616,
"s": 30548,
"text": "Step 8: Clicking on the pencil option here we type the user’s name."
},
{
"code": null,
"e": 30624,
"s": 30616,
"text": "Python3"
},
{
"code": "# This will click on the pencil icon as shown in the figure.self.bot.find_element_by_xpath( '//*[@id=\"react-root\"]/section/div/div[2]/div/div/div[2]/div/button').click()time.sleep(2)",
"e": 30810,
"s": 30624,
"text": null
},
{
"code": null,
"e": 30976,
"s": 30810,
"text": "Step 9: Here is the main part of the code where we take a username from the list search for it and message that person. This process is in the loop to take username."
},
{
"code": null,
"e": 30984,
"s": 30976,
"text": "Python3"
},
{
"code": "for i in user: # enter the username self.bot.find_element_by_xpath( '/html/body/div[4]/div/div/div[2]/div[1]/div/div[2]/input').send_keys(i) time.sleep(2) # click on the username self.bot.find_element_by_xpath( '/html/body/div[4]/div/div/div[2]/div[2]/div').click() time.sleep(2) # next button self.bot.find_element_by_xpath( '/html/body/div[4]/div/div/div[1]/div/div[2]/div/button').click() time.sleep(2) # click on message area send = self.bot.find_element_by_xpath( '/html/body/div[1]/section/div/div[2]/div/div/div[2]/div[2]/div/div[2]/div/div/div[2]/textarea') # types message send.send_keys(self.message) time.sleep(1) # send message send.send_keys(Keys.RETURN) time.sleep(2) # clicks on pencil icon self.bot.find_element_by_xpath( '/html/body/div[1]/section/div/div[2]/div/div/div[1]/div[1]/div/div[3]/button').click() time.sleep(2) # here will take the next username from the user's list.",
"e": 31993,
"s": 30984,
"text": null
},
{
"code": null,
"e": 32184,
"s": 31993,
"text": "Step 10: We have finally completed the code. It’s time to create a function where we will pass the username and the password of the account in which we want to login and call our class here."
},
{
"code": null,
"e": 32192,
"s": 32184,
"text": "Python3"
},
{
"code": "def init(): # you can even enter your personal account. bot('username', 'password', user, message_) input(\"DONE\")",
"e": 32319,
"s": 32192,
"text": null
},
{
"code": null,
"e": 32352,
"s": 32319,
"text": "Step 11: Let’s call our function"
},
{
"code": null,
"e": 32360,
"s": 32352,
"text": "Python3"
},
{
"code": "# calling this function will message everyone's# that is on your user's list...:)init()",
"e": 32448,
"s": 32360,
"text": null
},
{
"code": null,
"e": 32480,
"s": 32448,
"text": "Let’s put all the code together"
},
{
"code": null,
"e": 32488,
"s": 32480,
"text": "Python3"
},
{
"code": "# importing modulefrom selenium import webdriverimport osimport timefrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditionsfrom selenium.webdriver.common.keys import Keysfrom webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(ChromeDriverManager().install()) # enter receiver user nameuser = ['User_name', 'User_name ']message_ = (\"final test\") class bot: def __init__(self, username, password, user, message): self.username = username self.password = password self.user = user self.message = message self.base_url = 'https://www.instagram.com/' self.bot = driver self.login() def login(self): self.bot.get(self.base_url) enter_username = WebDriverWait(self.bot, 20).until( expected_conditions.presence_of_element_located((By.NAME, 'username'))) enter_username.send_keys(self.username) enter_password = WebDriverWait(self.bot, 20).until( expected_conditions.presence_of_element_located((By.NAME, 'password'))) enter_password.send_keys(self.password) enter_password.send_keys(Keys.RETURN) time.sleep(5) # first pop-up self.bot.find_element_by_xpath( '//*[@id=\"react-root\"]/section/main/div/div/div/div/button').click() time.sleep(3) # 2nd pop-up self.bot.find_element_by_xpath( '/html/body/div[4]/div/div/div/div[3]/button[2]').click() time.sleep(4) # direct button self.bot.find_element_by_xpath( '//a[@class=\"xWeGp\"]/*[name()=\"svg\"][@aria-label=\"Direct\"]').click() time.sleep(3) # clicks on pencil icon self.bot.find_element_by_xpath( '//*[@id=\"react-root\"]/section/div/div[2]/div/div/div[2]/div/button').click() time.sleep(2) for i in user: # enter the username self.bot.find_element_by_xpath( '/html/body/div[4]/div/div/div[2]/div[1]/div/div[2]/input').send_keys(i) time.sleep(2) # click on the username self.bot.find_element_by_xpath( '/html/body/div[4]/div/div/div[2]/div[2]/div').click() time.sleep(2) # next button self.bot.find_element_by_xpath( '/html/body/div[4]/div/div/div[1]/div/div[2]/div/button').click() time.sleep(2) # click on message area send = self.bot.find_element_by_xpath( '/html/body/div[1]/section/div/div[2]/div/div/div[2]/div[2]/div/div[2]/div/div/div[2]/textarea') # types message send.send_keys(self.message) time.sleep(1) # send message send.send_keys(Keys.RETURN) time.sleep(2) # clicks on direct option or pencl icon self.bot.find_element_by_xpath( '/html/body/div[1]/section/div/div[2]/div/div/div[1]/div[1]/div/div[3]/button').click() time.sleep(2) def init(): bot('username', 'password', user, message_) # when our program ends it will show \"done\". input(\"DONE\") # calling the functioninit()",
"e": 35748,
"s": 32488,
"text": null
},
{
"code": null,
"e": 35763,
"s": 35748,
"text": "python-utility"
},
{
"code": null,
"e": 35787,
"s": 35763,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 35795,
"s": 35787,
"text": "Project"
},
{
"code": null,
"e": 35814,
"s": 35795,
"text": "Technical Scripter"
},
{
"code": null,
"e": 35912,
"s": 35814,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35961,
"s": 35912,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 35991,
"s": 35961,
"text": "Simple Chat Room using Python"
},
{
"code": null,
"e": 36034,
"s": 35991,
"text": "Java Swing | Simple User Registration Form"
},
{
"code": null,
"e": 36072,
"s": 36034,
"text": "OpenCV C++ Program for Face Detection"
},
{
"code": null,
"e": 36112,
"s": 36072,
"text": "Twitter Sentiment Analysis using Python"
},
{
"code": null,
"e": 36150,
"s": 36112,
"text": "Banking Transaction System using Java"
},
{
"code": null,
"e": 36201,
"s": 36150,
"text": "Face Detection using Python and OpenCV with webcam"
},
{
"code": null,
"e": 36240,
"s": 36201,
"text": "Program for Employee Management System"
},
{
"code": null,
"e": 36256,
"s": 36240,
"text": "Snake Game in C"
}
] |
numpy.ones() in Python - GeeksforGeeks
|
21 Feb, 2022
The numpy.ones() function returns a new array of given shape and type, with ones.
Syntax: numpy.ones(shape, dtype = None, order = 'C')
Parameters :
shape : integer or sequence of integers
order : C_contiguous or F_contiguous
C-contiguous order in memory(last index varies the fastest)
C order means that operating row-rise on the array will be slightly quicker
FORTRAN-contiguous order in memory (first index varies the fastest).
F order means that column-wise operations will be faster.
dtype : [optional, float(byDefault)] Data type of returned array.
Returns :
ndarray of ones having given shape, order and datatype.
Python
# Python Program illustrating# numpy.ones method import numpy as geek b = geek.ones(2, dtype = int)print("Matrix b : \n", b) a = geek.ones([2, 2], dtype = int)print("\nMatrix a : \n", a) c = geek.ones([3, 3])print("\nMatrix c : \n", c)
Output :
Matrix b :
[1 1]
Matrix a :
[[1 1]
[1 1]]
Matrix c :
[[ 1. 1. 1.]
[ 1. 1. 1.]
[ 1. 1. 1.]]
Reference : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.ones.html Note : Ones, unlike zeros and empty, does not set the array values to zero or random values respectively.Also, these codes won’t run on online-ID. Please run them on your systems to explore the working.This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
avtarkumar719
Python numpy-arrayCreation
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
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
|
[
{
"code": null,
"e": 25335,
"s": 25307,
"text": "\n21 Feb, 2022"
},
{
"code": null,
"e": 25418,
"s": 25335,
"text": "The numpy.ones() function returns a new array of given shape and type, with ones. "
},
{
"code": null,
"e": 25472,
"s": 25418,
"text": "Syntax: numpy.ones(shape, dtype = None, order = 'C') "
},
{
"code": null,
"e": 25486,
"s": 25472,
"text": "Parameters : "
},
{
"code": null,
"e": 25932,
"s": 25486,
"text": "shape : integer or sequence of integers\norder : C_contiguous or F_contiguous\n C-contiguous order in memory(last index varies the fastest)\n C order means that operating row-rise on the array will be slightly quicker\n FORTRAN-contiguous order in memory (first index varies the fastest).\n F order means that column-wise operations will be faster. \ndtype : [optional, float(byDefault)] Data type of returned array. "
},
{
"code": null,
"e": 25944,
"s": 25932,
"text": "Returns : "
},
{
"code": null,
"e": 26000,
"s": 25944,
"text": "ndarray of ones having given shape, order and datatype."
},
{
"code": null,
"e": 26009,
"s": 26002,
"text": "Python"
},
{
"code": "# Python Program illustrating# numpy.ones method import numpy as geek b = geek.ones(2, dtype = int)print(\"Matrix b : \\n\", b) a = geek.ones([2, 2], dtype = int)print(\"\\nMatrix a : \\n\", a) c = geek.ones([3, 3])print(\"\\nMatrix c : \\n\", c)",
"e": 26245,
"s": 26009,
"text": null
},
{
"code": null,
"e": 26256,
"s": 26245,
"text": "Output : "
},
{
"code": null,
"e": 26364,
"s": 26256,
"text": "Matrix b : \n [1 1]\n\nMatrix a : \n [[1 1]\n [1 1]]\n\nMatrix c : \n [[ 1. 1. 1.]\n [ 1. 1. 1.]\n [ 1. 1. 1.]]"
},
{
"code": null,
"e": 27076,
"s": 26364,
"text": "Reference : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.ones.html Note : Ones, unlike zeros and empty, does not set the array values to zero or random values respectively.Also, these codes won’t run on online-ID. Please run them on your systems to explore the working.This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 27090,
"s": 27076,
"text": "avtarkumar719"
},
{
"code": null,
"e": 27117,
"s": 27090,
"text": "Python numpy-arrayCreation"
},
{
"code": null,
"e": 27130,
"s": 27117,
"text": "Python-numpy"
},
{
"code": null,
"e": 27137,
"s": 27130,
"text": "Python"
},
{
"code": null,
"e": 27235,
"s": 27137,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27253,
"s": 27235,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27288,
"s": 27253,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27320,
"s": 27288,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27342,
"s": 27320,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27384,
"s": 27342,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27414,
"s": 27384,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27440,
"s": 27414,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27484,
"s": 27440,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27513,
"s": 27484,
"text": "*args and **kwargs in Python"
}
] |
Basic SQL Injection and Mitigation with Example - GeeksforGeeks
|
08 Apr, 2019
SQL injection is a code injection technique, used to attack data driven applications, in which malicious SQL statements are inserted into an entry field for execution (e.g. to dump the database contents to the attacker).
SQL Injection can be used in a range of ways to cause serious problems.
By levering SQL Injection, an attacker could bypass authentication, access, modify and delete data within a database.
For a moment, place yourself in the role of an attacker. Your goal is simple. You want to get any unexpected SQL statement executed by the database. You’re only looking to get something to work because that will reveal the fact that the application has a potential vulnerability. For example, consider the simple authentication form shown in Figure 1.
Figure 1
Code for Figure 1
<form action="/login.php" method="POST"><p>Username: <input type="text" name="username" /></p><p>Password: <input type="text" name="password" /></p><p><input type="submit" value="Log In" /></p></form>
You can already make a very educated guess about the type of SQL statement that this application might use to verify the access credentials. It will most likely be a SELECT statement. You can also make a guess about the naming convention used in the database table because it probably matches the simple names used in the HTML form. Because this form is for authentication, there is probably WHERE clause that uses
$_POST['username'] and $_POST['password'].
From all of this, you might predict the following:
<?php $sql = "SELECT count(*) FROM users WHERE username = '{$_POST['username']}'AND password = '...'"; ?>
Assuming this guess is correct, what can you do to manipulate this query? Imagine sending the following username:
akash' /*
SELECT count(*)FROM users WHERE username = 'akash' /*'AND password = '...'";
In this example, /* is used to begin a multi-line comment,
effectively terminating the query at that point. This has
been tested successfully with MySQL. A standard comment
in SQL begins with --, and it's trivial to try both.
This query suggests a successful authentication attempt as long as the akash account exists, regardless of the password. This particular attack is frequently used to steal accounts. Of course, any username can be used (admin is a popular target). Thus, by sending a malformed username, you can manage to log in without having a valid account.
Mitigation using Prepared Statements (Parameterized Queries)
There are a lot of ways to defend SQL injection. One of the primary defense techniques is “Prepared Statements (Parameterized Queries)”. This technique force the developer to define all the SQL code and then pass in each parameter to the query later. This style allows the database to differentiate between code and data, regardless of what user input is supplied.Prepared statements ensure that an attacker is not able to change the intent of a query, even if SQL commands are inserted by an attacker. For example, if an attacker enters the userID of ABC or ‘1’=’1, the parameterized query would not be vulnerable and would instead look for a username which literally matched the entire string ABC or ‘1’=’1.Working:
Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled “?”).Example:SELECT count(*)FROM users WHERE username = ? AND password = ?;Parse: The database parses, compiles, and performs query optimization on the SQL statement template, and stores the result without executing it.Execute: At a later time, the application binds the values to the parameters, and the database executes the statement. The application may execute the statement as many times as it wants with different values.
Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled “?”).Example:SELECT count(*)FROM users WHERE username = ? AND password = ?;
SELECT count(*)FROM users WHERE username = ? AND password = ?;
Parse: The database parses, compiles, and performs query optimization on the SQL statement template, and stores the result without executing it.
Execute: At a later time, the application binds the values to the parameters, and the database executes the statement. The application may execute the statement as many times as it wants with different values.
Implementation:
<?php $stmt = $dbConnection->prepare('SELECT count(*)FROM users WHERE username = ? AND password = ?'); $stmt->bind_param('ss', $username,$password); $stmt->execute(); $result = $stmt->get_result(); echo $result;?>
This is just a simple example of bypassing user login page whereas SQL Injection can provide an attacker with unauthorized access to sensitive data including, customer data, personally identifiable information (PII), trade secrets, intellectual property, and other sensitive information. There is also an SQL Injection Automation tool sqlmap that is used to perform all type of SQL injection.So we have to apply Secure Coding so that system will be protected from being compromised.
References:
Wikipedia
OWASP
Related Article :Mitigation of SQL Injection Attack using Prepared Statements (Parameterized Queries)
This article is contributed by Akash Sharan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ayushgangwar
secure-coding
sql-injection
Advanced Computer Subject
DBMS
SQL
Technical Scripter
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
System Design Tutorial
Copying Files to and from Docker Containers
ML | Underfitting and Overfitting
Clustering in Machine Learning
ML | Label Encoding of datasets in Python
SQL | Join (Inner, Left, Right and Full Joins)
ACID Properties in DBMS
SQL | WITH clause
Normal Forms in DBMS
SQL query to find second highest salary?
|
[
{
"code": null,
"e": 24258,
"s": 24230,
"text": "\n08 Apr, 2019"
},
{
"code": null,
"e": 24479,
"s": 24258,
"text": "SQL injection is a code injection technique, used to attack data driven applications, in which malicious SQL statements are inserted into an entry field for execution (e.g. to dump the database contents to the attacker)."
},
{
"code": null,
"e": 24551,
"s": 24479,
"text": "SQL Injection can be used in a range of ways to cause serious problems."
},
{
"code": null,
"e": 24669,
"s": 24551,
"text": "By levering SQL Injection, an attacker could bypass authentication, access, modify and delete data within a database."
},
{
"code": null,
"e": 25021,
"s": 24669,
"text": "For a moment, place yourself in the role of an attacker. Your goal is simple. You want to get any unexpected SQL statement executed by the database. You’re only looking to get something to work because that will reveal the fact that the application has a potential vulnerability. For example, consider the simple authentication form shown in Figure 1."
},
{
"code": null,
"e": 25074,
"s": 25021,
"text": " \n Figure 1"
},
{
"code": null,
"e": 25092,
"s": 25074,
"text": "Code for Figure 1"
},
{
"code": "<form action=\"/login.php\" method=\"POST\"><p>Username: <input type=\"text\" name=\"username\" /></p><p>Password: <input type=\"text\" name=\"password\" /></p><p><input type=\"submit\" value=\"Log In\" /></p></form>",
"e": 25293,
"s": 25092,
"text": null
},
{
"code": null,
"e": 25708,
"s": 25293,
"text": "You can already make a very educated guess about the type of SQL statement that this application might use to verify the access credentials. It will most likely be a SELECT statement. You can also make a guess about the naming convention used in the database table because it probably matches the simple names used in the HTML form. Because this form is for authentication, there is probably WHERE clause that uses"
},
{
"code": null,
"e": 25751,
"s": 25708,
"text": "$_POST['username'] and $_POST['password']."
},
{
"code": null,
"e": 25802,
"s": 25751,
"text": "From all of this, you might predict the following:"
},
{
"code": "<?php $sql = \"SELECT count(*) FROM users WHERE username = '{$_POST['username']}'AND password = '...'\"; ?>",
"e": 25936,
"s": 25802,
"text": null
},
{
"code": null,
"e": 26050,
"s": 25936,
"text": "Assuming this guess is correct, what can you do to manipulate this query? Imagine sending the following username:"
},
{
"code": null,
"e": 26060,
"s": 26050,
"text": "akash' /*"
},
{
"code": "SELECT count(*)FROM users WHERE username = 'akash' /*'AND password = '...'\";",
"e": 26137,
"s": 26060,
"text": null
},
{
"code": null,
"e": 26364,
"s": 26137,
"text": "In this example, /* is used to begin a multi-line comment,\neffectively terminating the query at that point. This has\nbeen tested successfully with MySQL. A standard comment \nin SQL begins with --, and it's trivial to try both."
},
{
"code": null,
"e": 26707,
"s": 26364,
"text": "This query suggests a successful authentication attempt as long as the akash account exists, regardless of the password. This particular attack is frequently used to steal accounts. Of course, any username can be used (admin is a popular target). Thus, by sending a malformed username, you can manage to log in without having a valid account."
},
{
"code": null,
"e": 26768,
"s": 26707,
"text": "Mitigation using Prepared Statements (Parameterized Queries)"
},
{
"code": null,
"e": 27486,
"s": 26768,
"text": "There are a lot of ways to defend SQL injection. One of the primary defense techniques is “Prepared Statements (Parameterized Queries)”. This technique force the developer to define all the SQL code and then pass in each parameter to the query later. This style allows the database to differentiate between code and data, regardless of what user input is supplied.Prepared statements ensure that an attacker is not able to change the intent of a query, even if SQL commands are inserted by an attacker. For example, if an attacker enters the userID of ABC or ‘1’=’1, the parameterized query would not be vulnerable and would instead look for a username which literally matched the entire string ABC or ‘1’=’1.Working:"
},
{
"code": null,
"e": 28051,
"s": 27486,
"text": "Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled “?”).Example:SELECT count(*)FROM users WHERE username = ? AND password = ?;Parse: The database parses, compiles, and performs query optimization on the SQL statement template, and stores the result without executing it.Execute: At a later time, the application binds the values to the parameters, and the database executes the statement. The application may execute the statement as many times as it wants with different values."
},
{
"code": null,
"e": 28263,
"s": 28051,
"text": "Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled “?”).Example:SELECT count(*)FROM users WHERE username = ? AND password = ?;"
},
{
"code": null,
"e": 28326,
"s": 28263,
"text": "SELECT count(*)FROM users WHERE username = ? AND password = ?;"
},
{
"code": null,
"e": 28471,
"s": 28326,
"text": "Parse: The database parses, compiles, and performs query optimization on the SQL statement template, and stores the result without executing it."
},
{
"code": null,
"e": 28681,
"s": 28471,
"text": "Execute: At a later time, the application binds the values to the parameters, and the database executes the statement. The application may execute the statement as many times as it wants with different values."
},
{
"code": null,
"e": 28697,
"s": 28681,
"text": "Implementation:"
},
{
"code": "<?php $stmt = $dbConnection->prepare('SELECT count(*)FROM users WHERE username = ? AND password = ?'); $stmt->bind_param('ss', $username,$password); $stmt->execute(); $result = $stmt->get_result(); echo $result;?>",
"e": 28915,
"s": 28697,
"text": null
},
{
"code": null,
"e": 29398,
"s": 28915,
"text": "This is just a simple example of bypassing user login page whereas SQL Injection can provide an attacker with unauthorized access to sensitive data including, customer data, personally identifiable information (PII), trade secrets, intellectual property, and other sensitive information. There is also an SQL Injection Automation tool sqlmap that is used to perform all type of SQL injection.So we have to apply Secure Coding so that system will be protected from being compromised."
},
{
"code": null,
"e": 29410,
"s": 29398,
"text": "References:"
},
{
"code": null,
"e": 29420,
"s": 29410,
"text": "Wikipedia"
},
{
"code": null,
"e": 29426,
"s": 29420,
"text": "OWASP"
},
{
"code": null,
"e": 29528,
"s": 29426,
"text": "Related Article :Mitigation of SQL Injection Attack using Prepared Statements (Parameterized Queries)"
},
{
"code": null,
"e": 29828,
"s": 29528,
"text": "This article is contributed by Akash Sharan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 29953,
"s": 29828,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29966,
"s": 29953,
"text": "ayushgangwar"
},
{
"code": null,
"e": 29980,
"s": 29966,
"text": "secure-coding"
},
{
"code": null,
"e": 29994,
"s": 29980,
"text": "sql-injection"
},
{
"code": null,
"e": 30020,
"s": 29994,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 30025,
"s": 30020,
"text": "DBMS"
},
{
"code": null,
"e": 30029,
"s": 30025,
"text": "SQL"
},
{
"code": null,
"e": 30048,
"s": 30029,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30053,
"s": 30048,
"text": "DBMS"
},
{
"code": null,
"e": 30057,
"s": 30053,
"text": "SQL"
},
{
"code": null,
"e": 30155,
"s": 30057,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30164,
"s": 30155,
"text": "Comments"
},
{
"code": null,
"e": 30177,
"s": 30164,
"text": "Old Comments"
},
{
"code": null,
"e": 30200,
"s": 30177,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 30244,
"s": 30200,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 30278,
"s": 30244,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 30309,
"s": 30278,
"text": "Clustering in Machine Learning"
},
{
"code": null,
"e": 30351,
"s": 30309,
"text": "ML | Label Encoding of datasets in Python"
},
{
"code": null,
"e": 30398,
"s": 30351,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 30422,
"s": 30398,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 30440,
"s": 30422,
"text": "SQL | WITH clause"
},
{
"code": null,
"e": 30461,
"s": 30440,
"text": "Normal Forms in DBMS"
}
] |
How to decode a string after encoding in JavaScript?
|
To encode a string we need encodeURIComponent() or encodeURI() and to decode a string we need decodeURIComponent() or decodeURI(). Initially, we have used escape() to encode a string but since it is deprecated we are now using encodeURI().
encodeURIComponent(string);
decodeURIComponent(string);
In the following example, initially, a string is taken and encoded using encodeURI() and later decoded using decodeURI(). Later on both the encoded and decoded results were displayed in the output.
Live Demo
<html>
<body>
<p id = "encoding"></p>
<script>
var str = "Tutorix is the best e-learning platform";
var enc = encodeURI(str);
var dec = decodeURI(enc);
var res = "After encoding: " + enc + "
</br>" + "After Decoding: " + dec;
document.getElementById("encoding").innerHTML = res;
</script>
</body>
</html>
After encoding: Tutorix%20is%20the%20best%20e-learning%20platform
After Decoding: Tutorix is the best e-learning platform
|
[
{
"code": null,
"e": 1302,
"s": 1062,
"text": "To encode a string we need encodeURIComponent() or encodeURI() and to decode a string we need decodeURIComponent() or decodeURI(). Initially, we have used escape() to encode a string but since it is deprecated we are now using encodeURI()."
},
{
"code": null,
"e": 1330,
"s": 1302,
"text": "encodeURIComponent(string);"
},
{
"code": null,
"e": 1358,
"s": 1330,
"text": "decodeURIComponent(string);"
},
{
"code": null,
"e": 1556,
"s": 1358,
"text": "In the following example, initially, a string is taken and encoded using encodeURI() and later decoded using decodeURI(). Later on both the encoded and decoded results were displayed in the output."
},
{
"code": null,
"e": 1566,
"s": 1556,
"text": "Live Demo"
},
{
"code": null,
"e": 1889,
"s": 1566,
"text": "<html>\n<body>\n<p id = \"encoding\"></p>\n<script>\n var str = \"Tutorix is the best e-learning platform\";\n var enc = encodeURI(str);\n var dec = decodeURI(enc);\n var res = \"After encoding: \" + enc + \"\n </br>\" + \"After Decoding: \" + dec;\n document.getElementById(\"encoding\").innerHTML = res;\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2011,
"s": 1889,
"text": "After encoding: Tutorix%20is%20the%20best%20e-learning%20platform\nAfter Decoding: Tutorix is the best e-learning platform"
}
] |
Bootstrap 4 .card-img-bottom class
|
Use the card-img-bottom class in Bootstrap 4 to place an image at the bottom inside a Bootstrap 4 card.
Set the card body, and within that, the card title and card text −
<div class="card-body">
<h4 class="card-title">Quantitative Aptitude</h4>
<p class="card-text">For Entrance Exams</p>
<a href="#" class="btn btn-primary">Sample Questions</a>
</div>
Now set image with class “card-img-bottom”−
<img class="card-img-bottom" src="Image-Source" alt="alt text" style="width:100%">
Let us see an example to learn how to implement Bootstrap 4 .card-img-bottom 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">
<h3>Quantitative Aptitude Questions Answers</h3>
<div class="card" style="width:400px">
<div class="card-body">
<h4 class="card-title">Quantitative Aptitude</h4>
<p class="card-text">For Entrance Exams</p>
<a href="#" class="btn btn-primary">Sample Questions</a>
</div>
<img class="card-img-bottom" src="https://www.tutorialspoint.com/videotutorials/images/numerical_ability_home.jpg" alt="QA" style="width:100%">
</div>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1166,
"s": 1062,
"text": "Use the card-img-bottom class in Bootstrap 4 to place an image at the bottom inside a Bootstrap 4 card."
},
{
"code": null,
"e": 1233,
"s": 1166,
"text": "Set the card body, and within that, the card title and card text −"
},
{
"code": null,
"e": 1421,
"s": 1233,
"text": "<div class=\"card-body\">\n <h4 class=\"card-title\">Quantitative Aptitude</h4>\n <p class=\"card-text\">For Entrance Exams</p>\n <a href=\"#\" class=\"btn btn-primary\">Sample Questions</a>\n</div>"
},
{
"code": null,
"e": 1465,
"s": 1421,
"text": "Now set image with class “card-img-bottom”−"
},
{
"code": null,
"e": 1548,
"s": 1465,
"text": "<img class=\"card-img-bottom\" src=\"Image-Source\" alt=\"alt text\" style=\"width:100%\">"
},
{
"code": null,
"e": 1633,
"s": 1548,
"text": "Let us see an example to learn how to implement Bootstrap 4 .card-img-bottom class −"
},
{
"code": null,
"e": 1643,
"s": 1633,
"text": "Live Demo"
},
{
"code": null,
"e": 2660,
"s": 1643,
"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<body>\n <div class=\"container\">\n <h3>Quantitative Aptitude Questions Answers</h3>\n <div class=\"card\" style=\"width:400px\">\n <div class=\"card-body\">\n <h4 class=\"card-title\">Quantitative Aptitude</h4>\n <p class=\"card-text\">For Entrance Exams</p>\n <a href=\"#\" class=\"btn btn-primary\">Sample Questions</a>\n </div>\n <img class=\"card-img-bottom\" src=\"https://www.tutorialspoint.com/videotutorials/images/numerical_ability_home.jpg\" alt=\"QA\" style=\"width:100%\">\n </div>\n </div>\n </body>\n</html>"
}
] |
How to properly highlight selected items on Android RecyclerView using Kotlin?
|
This example demonstrates how to properly highlight selected items on Android RecyclerView 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="4dp"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="8dp" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val recyclerView: RecyclerView = findViewById(R.id.recyclerView)
recyclerView.addItemDecoration(SimpleItemDecoration(this))
val layoutManager = LinearLayoutManager(this@MainActivity)
recyclerView.layoutManager = layoutManager
val posts = returnListItems()
val adapter = RecyclerViewAdapter(this@MainActivity, posts)
recyclerView.adapter = adapter
}
private fun returnListItems(): List<ItemObject>? {
val items: MutableList<ItemObject> = ArrayList()
items.add(ItemObject("Ballon'd'or", "2007", "Ricardo KaKa"))
items.add(ItemObject("Ballon'd'or", "2008", "Cristiano Ronaldo"))
items.add(ItemObject("Ballon'd'or", "2009 - 2012, 2015", "Lionel Messi"))
items.add(ItemObject("Ballon'd'or", "2013, 2014, 2016, 2017", "Cristiano Ronaldo"))
items.add(ItemObject("Ballon'd'or", "2018", "Luca Modric"))
items.add(ItemObject("Ballon'd'or", "2019", "Lionel Messi"))
return items
}
}
Step 4 − Create kotlin class files as mentioned below and add the respective codes
ItemObject.kt −
internal class ItemObject(val awardTitle: String, val awardYear: String, val player: String) {
}
RecyclerViewAdapter.kt −
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.NonNull
import androidx.recyclerview.widget.RecyclerView
class RecyclerViewAdapter internal constructor(
context: MainActivity,
private val itemList: List<ItemObject>?
) : RecyclerView.Adapter<RecyclerViewHolders>() {
@NonNull
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolders {
val layoutView = LayoutInflater.from(parent.context).inflate(R.layout.list_layout, null)
return RecyclerViewHolders(layoutView)
}
override fun onBindViewHolder(holder: RecyclerViewHolders, position: Int) {
holder.awardTitle.text = "Award Title: " + itemList!![position].awardTitle
holder.awardYear.text = "Award Year: " + itemList[position].awardYear
holder.player.text = "Player Name: " + itemList[position].player
}
override fun getItemCount(): Int {
return this.itemList!!.size
}
}
RecyclerViewHolders.kt −
import android.util.SparseBooleanArray
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
class RecyclerViewHolders(itemView: View) : ViewHolder(itemView),
View.OnClickListener {
var awardTitle: TextView
var awardYear: TextView
var player: TextView
private val selectedItems = SparseBooleanArray()
override fun onClick(view: View) {
if (selectedItems[adapterPosition, false]) {
selectedItems.delete(adapterPosition)
view.isSelected = false
}
else {
selectedItems.put(adapterPosition, true)
view.isSelected = true
}
}
init {
itemView.setOnClickListener(this)
awardTitle = itemView.findViewById(R.id.awardTitle)
awardYear = itemView.findViewById(R.id.awardYear)
player = itemView.findViewById(R.id.playerName)
}
}
SimpleItemDecoration.kt −
import android.content.Context
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import androidx.annotation.NonNull
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
internal class SimpleItemDecoration(context: Context) : RecyclerView.ItemDecoration() {
private val drawable: Drawable = ContextCompat.getDrawable(context, R.drawable.line_divider)!!
override fun onDrawOver(
@NonNull canvas: Canvas,
parent: RecyclerView,
@NonNull state: RecyclerView.State
)
{
val left = parent.paddingLeft
val right = parent.width - parent.paddingRight
val childCount = parent.childCount
for (i in 0 until childCount) {
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
val top = child.bottom + params.bottomMargin
val bottom = top + drawable.intrinsicHeight
drawable.setBounds(left, top, right, bottom)
drawable.draw(canvas)
}
}
}
Step 5 − Create drawable resource files as mentioned below and add the respective codes
background_selecter.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/holo_green_light" android:state_pressed="false" android:state_selected="true" />
<item android:drawable="@android:color/holo_purple" android:state_selected="false" />
</selector>
line_divider.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size
android:width="2dp"
android:height="2dp" />
<solid android:color="@color/colorPrimaryDark" />
</shape>
Step 6 − Create a layout resource file (list_layout.xml) and add the following code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background_selector"
android:padding="16dp">
<TextView
android:id="@+id/awardTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="New Text"
android:textColor="@android:color/background_dark"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="@+id/awardYear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/awardTitle"
android:layout_alignStart="@+id/awardTitle"
android:layout_marginTop="20dp"
android:text="New Text"
android:textColor="@android:color/background_dark" />
<TextView
android:layout_marginBottom="10dp"
android:id="@+id/playerName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:text="New Text"
android:textColor="@android:color/background_dark" />
</RelativeLayout>
Step 7 − Add the following code to androidManifest.xmlv
<?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": 1167,
"s": 1062,
"text": "This example demonstrates how to properly highlight selected items on Android RecyclerView using Kotlin."
},
{
"code": null,
"e": 1296,
"s": 1167,
"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": 1361,
"s": 1296,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1886,
"s": 1361,
"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=\"4dp\"\n tools:context=\".MainActivity\">\n <androidx.recyclerview.widget.RecyclerView\n android:id=\"@+id/recyclerView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:paddingBottom=\"8dp\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 1941,
"s": 1886,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3301,
"s": 1941,
"text": "import android.os.Bundle\nimport androidx.appcompat.app.AppCompatActivity\nimport androidx.recyclerview.widget.LinearLayoutManager\nimport androidx.recyclerview.widget.RecyclerView\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n val recyclerView: RecyclerView = findViewById(R.id.recyclerView)\n recyclerView.addItemDecoration(SimpleItemDecoration(this))\n val layoutManager = LinearLayoutManager(this@MainActivity)\n recyclerView.layoutManager = layoutManager\n val posts = returnListItems()\n val adapter = RecyclerViewAdapter(this@MainActivity, posts)\n recyclerView.adapter = adapter\n }\n private fun returnListItems(): List<ItemObject>? {\n val items: MutableList<ItemObject> = ArrayList()\n items.add(ItemObject(\"Ballon'd'or\", \"2007\", \"Ricardo KaKa\"))\n items.add(ItemObject(\"Ballon'd'or\", \"2008\", \"Cristiano Ronaldo\"))\n items.add(ItemObject(\"Ballon'd'or\", \"2009 - 2012, 2015\", \"Lionel Messi\"))\n items.add(ItemObject(\"Ballon'd'or\", \"2013, 2014, 2016, 2017\", \"Cristiano Ronaldo\"))\n items.add(ItemObject(\"Ballon'd'or\", \"2018\", \"Luca Modric\"))\n items.add(ItemObject(\"Ballon'd'or\", \"2019\", \"Lionel Messi\"))\n return items\n }\n}"
},
{
"code": null,
"e": 3384,
"s": 3301,
"text": "Step 4 − Create kotlin class files as mentioned below and add the respective codes"
},
{
"code": null,
"e": 3400,
"s": 3384,
"text": "ItemObject.kt −"
},
{
"code": null,
"e": 3497,
"s": 3400,
"text": "internal class ItemObject(val awardTitle: String, val awardYear: String, val player: String) {\n}"
},
{
"code": null,
"e": 3522,
"s": 3497,
"text": "RecyclerViewAdapter.kt −"
},
{
"code": null,
"e": 4478,
"s": 3522,
"text": "import android.view.LayoutInflater\nimport android.view.ViewGroup\nimport androidx.annotation.NonNull\nimport androidx.recyclerview.widget.RecyclerView\nclass RecyclerViewAdapter internal constructor(\n context: MainActivity,\n private val itemList: List<ItemObject>?\n) : RecyclerView.Adapter<RecyclerViewHolders>() {\n @NonNull\n override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolders {\n val layoutView = LayoutInflater.from(parent.context).inflate(R.layout.list_layout, null)\n return RecyclerViewHolders(layoutView)\n }\n override fun onBindViewHolder(holder: RecyclerViewHolders, position: Int) {\n holder.awardTitle.text = \"Award Title: \" + itemList!![position].awardTitle\n holder.awardYear.text = \"Award Year: \" + itemList[position].awardYear\n holder.player.text = \"Player Name: \" + itemList[position].player\n }\n override fun getItemCount(): Int {\n return this.itemList!!.size\n }\n}"
},
{
"code": null,
"e": 4503,
"s": 4478,
"text": "RecyclerViewHolders.kt −"
},
{
"code": null,
"e": 5388,
"s": 4503,
"text": "import android.util.SparseBooleanArray\nimport android.view.View\nimport android.widget.TextView\nimport androidx.recyclerview.widget.RecyclerView.ViewHolder\nclass RecyclerViewHolders(itemView: View) : ViewHolder(itemView),\nView.OnClickListener {\n var awardTitle: TextView\n var awardYear: TextView\n var player: TextView\n private val selectedItems = SparseBooleanArray()\n override fun onClick(view: View) {\n if (selectedItems[adapterPosition, false]) {\n selectedItems.delete(adapterPosition)\n view.isSelected = false\n }\n else {\n selectedItems.put(adapterPosition, true)\n view.isSelected = true\n }\n }\n init {\n itemView.setOnClickListener(this)\n awardTitle = itemView.findViewById(R.id.awardTitle)\n awardYear = itemView.findViewById(R.id.awardYear)\n player = itemView.findViewById(R.id.playerName)\n }\n}"
},
{
"code": null,
"e": 5414,
"s": 5388,
"text": "SimpleItemDecoration.kt −"
},
{
"code": null,
"e": 6456,
"s": 5414,
"text": "import android.content.Context\nimport android.graphics.Canvas\nimport android.graphics.drawable.Drawable\nimport androidx.annotation.NonNull\nimport androidx.core.content.ContextCompat\nimport androidx.recyclerview.widget.RecyclerView\ninternal class SimpleItemDecoration(context: Context) : RecyclerView.ItemDecoration() {\n private val drawable: Drawable = ContextCompat.getDrawable(context, R.drawable.line_divider)!!\n override fun onDrawOver(\n @NonNull canvas: Canvas,\n parent: RecyclerView,\n @NonNull state: RecyclerView.State\n )\n {\n val left = parent.paddingLeft\n val right = parent.width - parent.paddingRight\n val childCount = parent.childCount\n for (i in 0 until childCount) {\n val child = parent.getChildAt(i)\n val params = child.layoutParams as RecyclerView.LayoutParams\n val top = child.bottom + params.bottomMargin\n val bottom = top + drawable.intrinsicHeight\n drawable.setBounds(left, top, right, bottom)\n drawable.draw(canvas)\n }\n }\n}"
},
{
"code": null,
"e": 6545,
"s": 6456,
"text": "Step 5 − Create drawable resource files as mentioned below and add the respective codes "
},
{
"code": null,
"e": 6569,
"s": 6545,
"text": "background_selecter.xml"
},
{
"code": null,
"e": 6902,
"s": 6569,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<selector xmlns:android=\"http://schemas.android.com/apk/res/android\">\n <item android:drawable=\"@android:color/holo_green_light\" android:state_pressed=\"false\" android:state_selected=\"true\" />\n <item android:drawable=\"@android:color/holo_purple\" android:state_selected=\"false\" />\n</selector>"
},
{
"code": null,
"e": 6919,
"s": 6902,
"text": "line_divider.xml"
},
{
"code": null,
"e": 7181,
"s": 6919,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<shape xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:shape=\"rectangle\">\n <size\n android:width=\"2dp\"\n android:height=\"2dp\" />\n <solid android:color=\"@color/colorPrimaryDark\" />\n</shape>"
},
{
"code": null,
"e": 7265,
"s": 7181,
"text": "Step 6 − Create a layout resource file (list_layout.xml) and add the following code"
},
{
"code": null,
"e": 8572,
"s": 7265,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:id=\"@+id/container\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:background=\"@drawable/background_selector\"\n android:padding=\"16dp\">\n <TextView\n android:id=\"@+id/awardTitle\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"10dp\"\n android:text=\"New Text\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"18sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:id=\"@+id/awardYear\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/awardTitle\"\n android:layout_alignStart=\"@+id/awardTitle\"\n android:layout_marginTop=\"20dp\"\n android:text=\"New Text\"\n android:textColor=\"@android:color/background_dark\" />\n <TextView\n android:layout_marginBottom=\"10dp\"\n android:id=\"@+id/playerName\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentEnd=\"true\"\n android:text=\"New Text\"\n android:textColor=\"@android:color/background_dark\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 8628,
"s": 8572,
"text": "Step 7 − Add the following code to androidManifest.xmlv"
},
{
"code": null,
"e": 9302,
"s": 8628,
"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": 9651,
"s": 9302,
"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"
}
] |
Progress Bars in Python (and pandas!) | by Peter Nistrup | Towards Data Science
|
Time and estimate the progress of your functions in Python (and pandas!)
In this article I’ll try to break my own record for the shortest, most concise article ever, so without further ado, let’s go!
tqdm is a package for Python that enables you to instantly create progress bars and estimate TTC (Time To Completion) for your functions and loops!
Simply install tqdm using pip in your favorite terminal and you’re ready to go:
pip install tqdm
Using tqdm is really quite easy, simply import tqdm:
>>> from tqdm import tqdm, tqdm_notebook
And any time you see a loop somewhere in your code you can simply wrap it in either tdqm()or tqdm_notebook()if you’re working in a Jupyter Notebook environment. You can give your progress-bars a description as well, using the desc= argument:
Once you’ve imported tqdm, you can initiate the method: tqdm.pandas() or if you’re running your code in a Jupyter Notebook environment use:
>>> from tqdm._tqdm_notebook import tqdm_notebook>>> tqdm_notebook.pandas()
Then you can simply replace all your .apply() functions with .progress_apply() it’s really that simple!
Thanks for reading! I’ve found that people seem to enjoy this style of fast and to-the-point articles, similar to my Exploring your data with just 1 line of Python article, so hopefully you enjoyed this as well!
If you want to see and learn more, be sure to follow me on Medium🔍 and Twitter 🐦
|
[
{
"code": null,
"e": 120,
"s": 47,
"text": "Time and estimate the progress of your functions in Python (and pandas!)"
},
{
"code": null,
"e": 247,
"s": 120,
"text": "In this article I’ll try to break my own record for the shortest, most concise article ever, so without further ado, let’s go!"
},
{
"code": null,
"e": 395,
"s": 247,
"text": "tqdm is a package for Python that enables you to instantly create progress bars and estimate TTC (Time To Completion) for your functions and loops!"
},
{
"code": null,
"e": 475,
"s": 395,
"text": "Simply install tqdm using pip in your favorite terminal and you’re ready to go:"
},
{
"code": null,
"e": 492,
"s": 475,
"text": "pip install tqdm"
},
{
"code": null,
"e": 545,
"s": 492,
"text": "Using tqdm is really quite easy, simply import tqdm:"
},
{
"code": null,
"e": 586,
"s": 545,
"text": ">>> from tqdm import tqdm, tqdm_notebook"
},
{
"code": null,
"e": 828,
"s": 586,
"text": "And any time you see a loop somewhere in your code you can simply wrap it in either tdqm()or tqdm_notebook()if you’re working in a Jupyter Notebook environment. You can give your progress-bars a description as well, using the desc= argument:"
},
{
"code": null,
"e": 968,
"s": 828,
"text": "Once you’ve imported tqdm, you can initiate the method: tqdm.pandas() or if you’re running your code in a Jupyter Notebook environment use:"
},
{
"code": null,
"e": 1044,
"s": 968,
"text": ">>> from tqdm._tqdm_notebook import tqdm_notebook>>> tqdm_notebook.pandas()"
},
{
"code": null,
"e": 1148,
"s": 1044,
"text": "Then you can simply replace all your .apply() functions with .progress_apply() it’s really that simple!"
},
{
"code": null,
"e": 1360,
"s": 1148,
"text": "Thanks for reading! I’ve found that people seem to enjoy this style of fast and to-the-point articles, similar to my Exploring your data with just 1 line of Python article, so hopefully you enjoyed this as well!"
}
] |
Matplotlib.pyplot.axhspan() in Python - GeeksforGeeks
|
27 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The axhspan() function in pyplot module of matplotlib library is used to add a horizontal span (rectangle) across the axis.
Syntax: matplotlib.pyplot.axhspan(ymin, ymax, xmin=0, xmax=1, **kwargs)
Parameters: This method accept the following parameters that are described below:
ymin: This parameter is the lower limit of the horizontal span in data units.
ymax: This parameter is the upper limit of the horizontal span in data units.
xmin: This parameter is the lower limit of the vertical span in data units.
xmax: This parameter is the upper limit of the vertical span in data units.
Returns: This returns the Polygon.
Below examples illustrate the matplotlib.pyplot.axhspan() function in matplotlib.pyplot:
Example 1:
import matplotlib.pyplot as plt # xmin = 0 and xmax = 1 is the# default valueplt.axhspan(0.25, 0.75, facecolor ='r', alpha = 0.7)
Output:
Example 2:
#Implementation of matplotlib functionimport numpy as np import matplotlib.pyplot as plt t = np.arange(-2, 3, .01) s = np.sin(np.pi * t) plt.plot(t, s, color ='black') plt.axhline(y = 1, color ='black') plt.axvline(x = 1, color ='black') plt.axvline(x = 0.5, ymin = 0.75, linewidth = 8, color ='green') plt.axhline(y =.5, xmin = 0.25, xmax = 0.75, color ='black') plt.axhspan(0.25, 0.75, facecolor ='0.5', alpha = 0.5) plt.axvspan(2.25, 2.55, facecolor ='green', alpha = 0.5) plt.title('matplotlib.pyplot.axhspan() Example\n', fontsize=14, fontweight='bold') plt.show()
Output:
Matplotlib Pyplot-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Convert integer to string in Python
|
[
{
"code": null,
"e": 25753,
"s": 25725,
"text": "\n27 Apr, 2020"
},
{
"code": null,
"e": 25948,
"s": 25753,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface."
},
{
"code": null,
"e": 26072,
"s": 25948,
"text": "The axhspan() function in pyplot module of matplotlib library is used to add a horizontal span (rectangle) across the axis."
},
{
"code": null,
"e": 26144,
"s": 26072,
"text": "Syntax: matplotlib.pyplot.axhspan(ymin, ymax, xmin=0, xmax=1, **kwargs)"
},
{
"code": null,
"e": 26226,
"s": 26144,
"text": "Parameters: This method accept the following parameters that are described below:"
},
{
"code": null,
"e": 26304,
"s": 26226,
"text": "ymin: This parameter is the lower limit of the horizontal span in data units."
},
{
"code": null,
"e": 26382,
"s": 26304,
"text": "ymax: This parameter is the upper limit of the horizontal span in data units."
},
{
"code": null,
"e": 26458,
"s": 26382,
"text": "xmin: This parameter is the lower limit of the vertical span in data units."
},
{
"code": null,
"e": 26534,
"s": 26458,
"text": "xmax: This parameter is the upper limit of the vertical span in data units."
},
{
"code": null,
"e": 26569,
"s": 26534,
"text": "Returns: This returns the Polygon."
},
{
"code": null,
"e": 26658,
"s": 26569,
"text": "Below examples illustrate the matplotlib.pyplot.axhspan() function in matplotlib.pyplot:"
},
{
"code": null,
"e": 26669,
"s": 26658,
"text": "Example 1:"
},
{
"code": "import matplotlib.pyplot as plt # xmin = 0 and xmax = 1 is the# default valueplt.axhspan(0.25, 0.75, facecolor ='r', alpha = 0.7)",
"e": 26802,
"s": 26669,
"text": null
},
{
"code": null,
"e": 26810,
"s": 26802,
"text": "Output:"
},
{
"code": null,
"e": 26821,
"s": 26810,
"text": "Example 2:"
},
{
"code": "#Implementation of matplotlib functionimport numpy as np import matplotlib.pyplot as plt t = np.arange(-2, 3, .01) s = np.sin(np.pi * t) plt.plot(t, s, color ='black') plt.axhline(y = 1, color ='black') plt.axvline(x = 1, color ='black') plt.axvline(x = 0.5, ymin = 0.75, linewidth = 8, color ='green') plt.axhline(y =.5, xmin = 0.25, xmax = 0.75, color ='black') plt.axhspan(0.25, 0.75, facecolor ='0.5', alpha = 0.5) plt.axvspan(2.25, 2.55, facecolor ='green', alpha = 0.5) plt.title('matplotlib.pyplot.axhspan() Example\\n', fontsize=14, fontweight='bold') plt.show()",
"e": 27441,
"s": 26821,
"text": null
},
{
"code": null,
"e": 27449,
"s": 27441,
"text": "Output:"
},
{
"code": null,
"e": 27473,
"s": 27449,
"text": "Matplotlib Pyplot-class"
},
{
"code": null,
"e": 27491,
"s": 27473,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 27498,
"s": 27491,
"text": "Python"
},
{
"code": null,
"e": 27596,
"s": 27498,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27614,
"s": 27596,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27646,
"s": 27614,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27688,
"s": 27646,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27714,
"s": 27688,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27758,
"s": 27714,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27787,
"s": 27758,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27824,
"s": 27787,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27866,
"s": 27824,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27908,
"s": 27866,
"text": "How To Convert Python Dictionary To JSON?"
}
] |
C++ Boolean Matrix
|
Boolean matrix is a matrix that has only two elements 0 and 1. For this boolean Matrix question, we have a boolean matrix arr[m][n] of size mXn. And the condition to solve is, if m[i][j] = 1 then m[i] = 1 and m[j] = 1 which means all elements of the ith row and jth column will become 1.
Let’s take an example,
Input: arr[2][2] = 1 0
0 0
Output: arr[2][2] = 1 1
1 0
Explanation− arr[0][0] = 1 which means arr[0][0]=arr[0][1]=1 & arr[0][0]=arr[1][0]=1.
Here, we will take two flag variables and check if the rows and columns need to be changed to one of not. If yes flag = 1 otherwise 0. And then based on this flag value we will change the values of the elements of the rows and columns. We will do the same procedure for all the elements of the array.
Live Demo
#include <bits/stdc++.h>
using namespace std;
const int R = 3;
#define C 4
void matrixflip(int mat[R][C]) {
int row_flag = 0;
int col_flag = 0;
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
if (i == 0 && mat[i][j] == 1)
row_flag = 1;
if (j == 0 && mat[i][j] == 1)
col_flag = 1;
if (mat[i][j] == 1) {
mat[0][j] = 1;
mat[i][0] = 1;
}
}
}
for (int i = 1; i < R; i++) {
for (int j = 1; j < C; j++) {
if (mat[0][j] == 1 || mat[i][0] == 1) {
mat[i][j] = 1;
}
}
}
if (row_flag) {
for (int i = 0; i < C; i++) {
mat[0][i] = 1;
}
}
if (col_flag) {
for (int i = 0; i < R; i++) {
mat[i][0] = 1;
}
}
}
int main() {
int mat[R][C] = { { 1, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 1, 0 } };
cout << "Input Matrix :\n";
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
cout << mat[i][j]<<" ";
}
cout <<endl;
}
matrixflip(mat);
cout << "Matrix after bit flip :\n";
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
cout << mat[i][j]<<" ";
}
cout <<endl;
}
return 0;
}
Input Martix:
1 0 0 0
0 0 0 0
0 0 1 0
Matirx after bit flip :
1 1 1 1
1 0 1 0
1 1 1 1
|
[
{
"code": null,
"e": 1350,
"s": 1062,
"text": "Boolean matrix is a matrix that has only two elements 0 and 1. For this boolean Matrix question, we have a boolean matrix arr[m][n] of size mXn. And the condition to solve is, if m[i][j] = 1 then m[i] = 1 and m[j] = 1 which means all elements of the ith row and jth column will become 1."
},
{
"code": null,
"e": 1373,
"s": 1350,
"text": "Let’s take an example,"
},
{
"code": null,
"e": 1467,
"s": 1373,
"text": "Input: arr[2][2] = 1 0\n 0 0\nOutput: arr[2][2] = 1 1\n 1 0"
},
{
"code": null,
"e": 1553,
"s": 1467,
"text": "Explanation− arr[0][0] = 1 which means arr[0][0]=arr[0][1]=1 & arr[0][0]=arr[1][0]=1."
},
{
"code": null,
"e": 1854,
"s": 1553,
"text": "Here, we will take two flag variables and check if the rows and columns need to be changed to one of not. If yes flag = 1 otherwise 0. And then based on this flag value we will change the values of the elements of the rows and columns. We will do the same procedure for all the elements of the array."
},
{
"code": null,
"e": 1865,
"s": 1854,
"text": " Live Demo"
},
{
"code": null,
"e": 3136,
"s": 1865,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nconst int R = 3;\n#define C 4\nvoid matrixflip(int mat[R][C]) {\n int row_flag = 0;\n int col_flag = 0;\n for (int i = 0; i < R; i++) {\n for (int j = 0; j < C; j++) {\n if (i == 0 && mat[i][j] == 1)\n row_flag = 1;\n if (j == 0 && mat[i][j] == 1)\n col_flag = 1;\n if (mat[i][j] == 1) {\n mat[0][j] = 1;\n mat[i][0] = 1;\n }\n }\n }\n for (int i = 1; i < R; i++) {\n for (int j = 1; j < C; j++) {\n if (mat[0][j] == 1 || mat[i][0] == 1) {\n mat[i][j] = 1;\n }\n }\n }\n if (row_flag) {\n for (int i = 0; i < C; i++) {\n mat[0][i] = 1;\n }\n }\n if (col_flag) {\n for (int i = 0; i < R; i++) {\n mat[i][0] = 1;\n }\n }\n}\nint main() {\n int mat[R][C] = { { 1, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 1, 0 } };\n cout << \"Input Matrix :\\n\";\n for (int i = 0; i < R; i++) {\n for (int j = 0; j < C; j++) {\n cout << mat[i][j]<<\" \";\n }\n cout <<endl;\n }\n matrixflip(mat);\n cout << \"Matrix after bit flip :\\n\";\n for (int i = 0; i < R; i++) {\n for (int j = 0; j < C; j++) {\n cout << mat[i][j]<<\" \";\n }\n cout <<endl;\n }\n return 0;\n}"
},
{
"code": null,
"e": 3222,
"s": 3136,
"text": "Input Martix:\n1 0 0 0\n0 0 0 0\n0 0 1 0\nMatirx after bit flip :\n1 1 1 1\n1 0 1 0\n1 1 1 1"
}
] |
Tail recursion to calculate sum of array elements. - GeeksforGeeks
|
14 May, 2021
Given an array A[], we need to find the sum of its elements using Tail Recursion Method. We generally want to achieve tail recursion (a recursive function where recursive call is the last thing that function does) so that compilers can optimize the code. Basically, if recursive call is the last statement, the compiler does not need to save the state of parent call. Examples:
Input : A[] = {1, 8, 9}
Output : 18
Input : A[] = {2, 55, 1, 7}
Output : 65
For Linear Recursion Method, refer: https://www.geeksforgeeks.org/sum-array-elements-using-recursion/Logic: Here the key to tail recursion is whatever operation is applied with the function call, maintain it as a separate function parameter. So, keep the sum of the last elements K elements as a function parameter and return sum when K=0.
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; // Tail recursive functionint arrSum(int* array, int size, int sum = 0){ // Base Case if (size == 0) return sum; // Function Call Observe sum+array[size-1] // to maintain sum of elements return arrSum(array, size - 1, sum + array[size - 1]);} int main(){ int array[] = { 2, 55, 1, 7 }; int size = sizeof(array) / sizeof(array[0]); cout << arrSum(array, size); return 0;}
// Java implementation of the given approach.class GFG{ // Tail recursive functionstatic int arrSum(int []array, int size, int sum){ // Base Case if (size == 0) return sum; // Function Call Observe sum+array[size-1] // to maintain sum of elements return arrSum(array, size - 1, sum + array[size - 1]);} // Driver codepublic static void main(String[] args){ int array[] = { 2, 55, 1, 7 }; int size = array.length; System.out.print(arrSum(array, size, 0));}} // This code is contributed by Rajput-Ji
# Python3 implementation of the given approach. # Tail recursive functiondef arrSum(array, size, Sum = 0): # Base Case if size == 0: return Sum # Function Call Observe sum+array[size-1] # to maintain sum of elements return arrSum(array, size - 1, Sum + array[size - 1]) # Driver Codeif __name__ == "__main__": array = [2, 55, 1, 7] size = len(array) print(arrSum(array, size)) # This code is contributed by Rituraj Jain
// C# implementation of the given approach.using System; class GFG{ // Tail recursive functionstatic int arrSum(int []array, int size, int sum){ // Base Case if (size == 0) return sum; // Function Call Observe sum+array[size-1] // to maintain sum of elements return arrSum(array, size - 1, sum + array[size - 1]);} // Driver codepublic static void Main(String[] args){ int []array = { 2, 55, 1, 7 }; int size = array.Length; Console.WriteLine(arrSum(array, size, 0));}} // This code is contributed by 29AjayKumar
<script> // Tail recursive functionfunction arrSum(array, size, sum = 0){ // Base Case if (size == 0) return sum; // Function Call Observe sum+array[size-1] // to maintain sum of elements return arrSum(array, size - 1, sum + array[size - 1]);} var array = [2, 55, 1, 7];var size = array.length;document.write( arrSum(array, size)); </script>
65
Time Complexity: O(n)
rituraj_jain
Rajput-Ji
29AjayKumar
itsok
tail-recursion
Recursion
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Practice Questions for Recursion | Set 1
Recursively Reversing a linked list (A simple implementation)
Sum of natural numbers using recursion
Count N-length strings consisting only of vowels sorted lexicographically
Count number of nodes in a complete Binary Tree
Generating subarrays using recursion
Recursive Insertion Sort
Practice Questions for Recursion | Set 2
Program to reverse a string (Iterative and Recursive)
How will you print numbers from 1 to 100 without using loop?
|
[
{
"code": null,
"e": 26357,
"s": 26329,
"text": "\n14 May, 2021"
},
{
"code": null,
"e": 26737,
"s": 26357,
"text": "Given an array A[], we need to find the sum of its elements using Tail Recursion Method. We generally want to achieve tail recursion (a recursive function where recursive call is the last thing that function does) so that compilers can optimize the code. Basically, if recursive call is the last statement, the compiler does not need to save the state of parent call. Examples: "
},
{
"code": null,
"e": 26814,
"s": 26737,
"text": "Input : A[] = {1, 8, 9}\nOutput : 18\n\nInput : A[] = {2, 55, 1, 7}\nOutput : 65"
},
{
"code": null,
"e": 27155,
"s": 26814,
"text": "For Linear Recursion Method, refer: https://www.geeksforgeeks.org/sum-array-elements-using-recursion/Logic: Here the key to tail recursion is whatever operation is applied with the function call, maintain it as a separate function parameter. So, keep the sum of the last elements K elements as a function parameter and return sum when K=0. "
},
{
"code": null,
"e": 27159,
"s": 27155,
"text": "C++"
},
{
"code": null,
"e": 27164,
"s": 27159,
"text": "Java"
},
{
"code": null,
"e": 27172,
"s": 27164,
"text": "Python3"
},
{
"code": null,
"e": 27175,
"s": 27172,
"text": "C#"
},
{
"code": null,
"e": 27186,
"s": 27175,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // Tail recursive functionint arrSum(int* array, int size, int sum = 0){ // Base Case if (size == 0) return sum; // Function Call Observe sum+array[size-1] // to maintain sum of elements return arrSum(array, size - 1, sum + array[size - 1]);} int main(){ int array[] = { 2, 55, 1, 7 }; int size = sizeof(array) / sizeof(array[0]); cout << arrSum(array, size); return 0;}",
"e": 27637,
"s": 27186,
"text": null
},
{
"code": "// Java implementation of the given approach.class GFG{ // Tail recursive functionstatic int arrSum(int []array, int size, int sum){ // Base Case if (size == 0) return sum; // Function Call Observe sum+array[size-1] // to maintain sum of elements return arrSum(array, size - 1, sum + array[size - 1]);} // Driver codepublic static void main(String[] args){ int array[] = { 2, 55, 1, 7 }; int size = array.length; System.out.print(arrSum(array, size, 0));}} // This code is contributed by Rajput-Ji",
"e": 28167,
"s": 27637,
"text": null
},
{
"code": "# Python3 implementation of the given approach. # Tail recursive functiondef arrSum(array, size, Sum = 0): # Base Case if size == 0: return Sum # Function Call Observe sum+array[size-1] # to maintain sum of elements return arrSum(array, size - 1, Sum + array[size - 1]) # Driver Codeif __name__ == \"__main__\": array = [2, 55, 1, 7] size = len(array) print(arrSum(array, size)) # This code is contributed by Rituraj Jain",
"e": 28632,
"s": 28167,
"text": null
},
{
"code": " // C# implementation of the given approach.using System; class GFG{ // Tail recursive functionstatic int arrSum(int []array, int size, int sum){ // Base Case if (size == 0) return sum; // Function Call Observe sum+array[size-1] // to maintain sum of elements return arrSum(array, size - 1, sum + array[size - 1]);} // Driver codepublic static void Main(String[] args){ int []array = { 2, 55, 1, 7 }; int size = array.Length; Console.WriteLine(arrSum(array, size, 0));}} // This code is contributed by 29AjayKumar",
"e": 29182,
"s": 28632,
"text": null
},
{
"code": "<script> // Tail recursive functionfunction arrSum(array, size, sum = 0){ // Base Case if (size == 0) return sum; // Function Call Observe sum+array[size-1] // to maintain sum of elements return arrSum(array, size - 1, sum + array[size - 1]);} var array = [2, 55, 1, 7];var size = array.length;document.write( arrSum(array, size)); </script> ",
"e": 29550,
"s": 29182,
"text": null
},
{
"code": null,
"e": 29553,
"s": 29550,
"text": "65"
},
{
"code": null,
"e": 29578,
"s": 29555,
"text": "Time Complexity: O(n) "
},
{
"code": null,
"e": 29591,
"s": 29578,
"text": "rituraj_jain"
},
{
"code": null,
"e": 29601,
"s": 29591,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 29613,
"s": 29601,
"text": "29AjayKumar"
},
{
"code": null,
"e": 29619,
"s": 29613,
"text": "itsok"
},
{
"code": null,
"e": 29634,
"s": 29619,
"text": "tail-recursion"
},
{
"code": null,
"e": 29644,
"s": 29634,
"text": "Recursion"
},
{
"code": null,
"e": 29654,
"s": 29644,
"text": "Recursion"
},
{
"code": null,
"e": 29752,
"s": 29654,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29793,
"s": 29752,
"text": "Practice Questions for Recursion | Set 1"
},
{
"code": null,
"e": 29855,
"s": 29793,
"text": "Recursively Reversing a linked list (A simple implementation)"
},
{
"code": null,
"e": 29894,
"s": 29855,
"text": "Sum of natural numbers using recursion"
},
{
"code": null,
"e": 29968,
"s": 29894,
"text": "Count N-length strings consisting only of vowels sorted lexicographically"
},
{
"code": null,
"e": 30016,
"s": 29968,
"text": "Count number of nodes in a complete Binary Tree"
},
{
"code": null,
"e": 30053,
"s": 30016,
"text": "Generating subarrays using recursion"
},
{
"code": null,
"e": 30078,
"s": 30053,
"text": "Recursive Insertion Sort"
},
{
"code": null,
"e": 30119,
"s": 30078,
"text": "Practice Questions for Recursion | Set 2"
},
{
"code": null,
"e": 30173,
"s": 30119,
"text": "Program to reverse a string (Iterative and Recursive)"
}
] |
Find if a number is divisible by every number in a list - GeeksforGeeks
|
27 Jan, 2022
Given a list and a number task is to find the number which is divided by every element of the list. Examples :
Input : List = [1, 2, 3, 4, 5]
Number = 3
Output : No
Input : List = [4, 8, 12, 16, 20]
Number = 4
Output : Yes
Algorithm:
1. Run a loop till length of the list
2. Divide every element with the given number
3. If number is not divided by any element,
return 0.
4. Return 1.
C++
Java
Python3
C#
PHP
Javascript
// C++ program which check is a number// divided with every element in list or not#include <bits/stdc++.h>using namespace std; // Function which check is a number// divided with every element in list or notbool findNoIsDivisibleOrNot(int a[], int n, int l){ for (int i = 0; i < l; i++) { if (a[i] % n != 0) return false; } return true;} // driver programint main(){ int a[] = {14, 12, 4, 18}; int n = 2; int l = (sizeof(a) / sizeof(a[0])); if (findNoIsDivisibleOrNot(a, n, l)) cout << "Yes"; else cout << "No"; return 0;} // This code is contributed by Sam007
// Java program which check is a number// divided with every element in list// or not class GFG { // Function which check is a number // divided with every element in list or not static boolean findNoIsDivisibleOrNot(int a[], int n) { for (int i = 0; i < a.length; i++) { if (a[i] % n != 0) return false; } return true; } // driver program public static void main(String[] args) { int a[] = {14, 12, 4, 18}; int n = 2; if (findNoIsDivisibleOrNot(a, n)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by Pramod Kumar
# Python program which check is a number# divided with every element in list# or notdef findNoIsDivisibleOrNot(n, l =[]): # Checking if a number is divided # by every element or not for i in range(0, len(l)): if l[i]% n != 0: return 0 return 1 # Driver codel = [14, 12, 4, 18]n = 2if findNoIsDivisibleOrNot(n, l) == 1: print ("Yes")else: print ("No")
// C# program which check is a number// divided with every element in list or nousing System; class GFG { // Function which check is a number // divided with every element in list or not static bool findNoIsDivisibleOrNot(int[] a, int n) { for (int i = 0; i < a.Length; i++) { if (a[i] % n != 0) return false; } return true; } // driver program public static void Main() { int[] a = {14, 12, 4, 18}; int n = 2; if (findNoIsDivisibleOrNot(a, n)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by Sam007
<?php// PHP program which// check is a number// divided with every// element in list or not // Function which check// is a number divided// with every element// in list or notfunction findNoIsDivisibleOrNot($a, $n, $l){ for ($i = 0; $i < $l; $i++) { if ($a[$i] % $n != 0) return false; } return true;} // Driver Code $a = array(14, 12, 4, 18); $n = 2; $l = sizeof($a); if (findNoIsDivisibleOrNot($a, $n, $l)) echo "Yes"; else echo "No"; // This code is contributed by ajit?>
<script> // JavaScript program which check is a number// divided with every element in list or not // Function which check is a number// divided with every element in list or notfunction findNoIsDivisibleOrNot(a, n, l){ for (let i = 0; i < l; i++) { if (a[i] % n != 0) return false; } return true;} // driver program let a = [14, 12, 4, 18]; let n = 2; let l = a.length; if (findNoIsDivisibleOrNot(a, n, l)) document.write("Yes"); else document.write("No"); </script>
Output:
Yes
This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Sam007
jit_t
souravmahato348
amartyaghoshgfg
Mathematical
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
Sieve of Eratosthenes
Operators in C / C++
The Knight's tour problem | Backtracking-1
Program for factorial of a number
Find minimum number of coins that make a given value
|
[
{
"code": null,
"e": 26603,
"s": 26575,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 26716,
"s": 26603,
"text": "Given a list and a number task is to find the number which is divided by every element of the list. Examples : "
},
{
"code": null,
"e": 26849,
"s": 26716,
"text": "Input : List = [1, 2, 3, 4, 5]\n Number = 3\nOutput : No\n\nInput : List = [4, 8, 12, 16, 20]\n Number = 4\nOutput : Yes"
},
{
"code": null,
"e": 26862,
"s": 26849,
"text": "Algorithm: "
},
{
"code": null,
"e": 27017,
"s": 26862,
"text": "1. Run a loop till length of the list\n2. Divide every element with the given number\n3. If number is not divided by any element, \n return 0.\n4. Return 1."
},
{
"code": null,
"e": 27023,
"s": 27019,
"text": "C++"
},
{
"code": null,
"e": 27028,
"s": 27023,
"text": "Java"
},
{
"code": null,
"e": 27036,
"s": 27028,
"text": "Python3"
},
{
"code": null,
"e": 27039,
"s": 27036,
"text": "C#"
},
{
"code": null,
"e": 27043,
"s": 27039,
"text": "PHP"
},
{
"code": null,
"e": 27054,
"s": 27043,
"text": "Javascript"
},
{
"code": "// C++ program which check is a number// divided with every element in list or not#include <bits/stdc++.h>using namespace std; // Function which check is a number// divided with every element in list or notbool findNoIsDivisibleOrNot(int a[], int n, int l){ for (int i = 0; i < l; i++) { if (a[i] % n != 0) return false; } return true;} // driver programint main(){ int a[] = {14, 12, 4, 18}; int n = 2; int l = (sizeof(a) / sizeof(a[0])); if (findNoIsDivisibleOrNot(a, n, l)) cout << \"Yes\"; else cout << \"No\"; return 0;} // This code is contributed by Sam007",
"e": 27674,
"s": 27054,
"text": null
},
{
"code": "// Java program which check is a number// divided with every element in list// or not class GFG { // Function which check is a number // divided with every element in list or not static boolean findNoIsDivisibleOrNot(int a[], int n) { for (int i = 0; i < a.length; i++) { if (a[i] % n != 0) return false; } return true; } // driver program public static void main(String[] args) { int a[] = {14, 12, 4, 18}; int n = 2; if (findNoIsDivisibleOrNot(a, n)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by Pramod Kumar",
"e": 28358,
"s": 27674,
"text": null
},
{
"code": "# Python program which check is a number# divided with every element in list# or notdef findNoIsDivisibleOrNot(n, l =[]): # Checking if a number is divided # by every element or not for i in range(0, len(l)): if l[i]% n != 0: return 0 return 1 # Driver codel = [14, 12, 4, 18]n = 2if findNoIsDivisibleOrNot(n, l) == 1: print (\"Yes\")else: print (\"No\")",
"e": 28746,
"s": 28358,
"text": null
},
{
"code": "// C# program which check is a number// divided with every element in list or nousing System; class GFG { // Function which check is a number // divided with every element in list or not static bool findNoIsDivisibleOrNot(int[] a, int n) { for (int i = 0; i < a.Length; i++) { if (a[i] % n != 0) return false; } return true; } // driver program public static void Main() { int[] a = {14, 12, 4, 18}; int n = 2; if (findNoIsDivisibleOrNot(a, n)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by Sam007",
"e": 29414,
"s": 28746,
"text": null
},
{
"code": "<?php// PHP program which// check is a number// divided with every// element in list or not // Function which check// is a number divided// with every element// in list or notfunction findNoIsDivisibleOrNot($a, $n, $l){ for ($i = 0; $i < $l; $i++) { if ($a[$i] % $n != 0) return false; } return true;} // Driver Code $a = array(14, 12, 4, 18); $n = 2; $l = sizeof($a); if (findNoIsDivisibleOrNot($a, $n, $l)) echo \"Yes\"; else echo \"No\"; // This code is contributed by ajit?>",
"e": 29952,
"s": 29414,
"text": null
},
{
"code": "<script> // JavaScript program which check is a number// divided with every element in list or not // Function which check is a number// divided with every element in list or notfunction findNoIsDivisibleOrNot(a, n, l){ for (let i = 0; i < l; i++) { if (a[i] % n != 0) return false; } return true;} // driver program let a = [14, 12, 4, 18]; let n = 2; let l = a.length; if (findNoIsDivisibleOrNot(a, n, l)) document.write(\"Yes\"); else document.write(\"No\"); </script>",
"e": 30476,
"s": 29952,
"text": null
},
{
"code": null,
"e": 30485,
"s": 30476,
"text": "Output: "
},
{
"code": null,
"e": 30489,
"s": 30485,
"text": "Yes"
},
{
"code": null,
"e": 30910,
"s": 30489,
"text": "This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 30917,
"s": 30910,
"text": "Sam007"
},
{
"code": null,
"e": 30923,
"s": 30917,
"text": "jit_t"
},
{
"code": null,
"e": 30939,
"s": 30923,
"text": "souravmahato348"
},
{
"code": null,
"e": 30955,
"s": 30939,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 30968,
"s": 30955,
"text": "Mathematical"
},
{
"code": null,
"e": 30981,
"s": 30968,
"text": "Mathematical"
},
{
"code": null,
"e": 31079,
"s": 30981,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31103,
"s": 31079,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 31146,
"s": 31103,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 31160,
"s": 31146,
"text": "Prime Numbers"
},
{
"code": null,
"e": 31202,
"s": 31160,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 31275,
"s": 31202,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 31297,
"s": 31275,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 31318,
"s": 31297,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 31361,
"s": 31318,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 31395,
"s": 31361,
"text": "Program for factorial of a number"
}
] |
Determine The Face Tilt Using OpenCV - Python - GeeksforGeeks
|
01 Oct, 2021
In this article, we are going to see how to determine the face tilt using OpenCV in Python.
To achieve this we will be using a popular computer vision library opencv-python. In this program with the help of the OpenCV library, we will detect faces in a live stream from a webcam or a video file and subsequently also determine the angle by how much the face is tilted.
Install OpenCV for python.
We will be using two pre-trained XML classifiers to detect faces and eyes respectively. These classifiers can be downloaded from opencv library or just click the links below.
Classifier for face detection: haarcascade_frontalface_default.xml
Classifier for eye detection: haarcascade_eye.xml
First, we detect the face in the webcam feed/video using the above-mentioned haarcascade classifier for the face and make a green color bounding box around it.
Next, we detect the eyes using a similar haarcascade classifier trained on eyes and make a red color bounding box around each eye.
In addition to making a box around each eye, we also identify and store the center of each box. Here, we are assuming that the center of the bounding box is the same as the center of the eye.
For computing the angle of tilt we will assume that the line joining the centers of two eyes is perpendicular to the face.
We have the coordinates of two centers in terms of (x,y) coordinates. The x-axis is the horizontal axis and y-axis is the vertical axis.
When two points are given & , the angle which the line joining the two points makes with the x-axis can be obtained from geometry using the following expression:
In our case, the angle made by the line joining the centers of two eyes with the horizontal is computed. The positive angle indicates the right tilt and the negative angle indicates the left tilt.
Provided a margin of error of 10 degrees (i.e, if the face tilts more than 10 degrees on either side the program will classify as right or left tilt).
Python
import cv2 as cvimport numpy as np # 0 for webcam feed ; add "path to file"# for detection in video filecapture = cv.VideoCapture(0)face_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml')eye_cascade = cv.CascadeClassifier("haarcascade_eye.xml") while True: ret, frame = capture.read() gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.1, 5) x, y, w, h = 0, 0, 0, 0 for (x, y, w, h) in faces: cv.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) cv.circle(frame, (x + int(w * 0.5), y + int(h * 0.5)), 4, (0, 255, 0), -1) eyes = eye_cascade.detectMultiScale(gray[y:(y + h), x:(x + w)], 1.1, 4) index = 0 eye_1 = [None, None, None, None] eye_2 = [None, None, None, None] for (ex, ey, ew, eh) in eyes: if index == 0: eye_1 = [ex, ey, ew, eh] elif index == 1: eye_2 = [ex, ey, ew, eh] cv.rectangle(frame[y:(y + h), x:(x + w)], (ex, ey), (ex + ew, ey + eh), (0, 0, 255), 2) index = index + 1 if (eye_1[0] is not None) and (eye_2[0] is not None): if eye_1[0] < eye_2[0]: left_eye = eye_1 right_eye = eye_2 else: left_eye = eye_2 right_eye = eye_1 left_eye_center = ( int(left_eye[0] + (left_eye[2] / 2)), int(left_eye[1] + (left_eye[3] / 2))) right_eye_center = ( int(right_eye[0] + (right_eye[2] / 2)), int(right_eye[1] + (right_eye[3] / 2))) left_eye_x = left_eye_center[0] left_eye_y = left_eye_center[1] right_eye_x = right_eye_center[0] right_eye_y = right_eye_center[1] delta_x = right_eye_x - left_eye_x delta_y = right_eye_y - left_eye_y # Slope of line formula angle = np.arctan(delta_y / delta_x) # Converting radians to degrees angle = (angle * 180) / np.pi # Provided a margin of error of 10 degrees # (i.e, if the face tilts more than 10 degrees # on either side the program will classify as right or left tilt) if angle > 10: cv.putText(frame, 'RIGHT TILT :' + str(int(angle))+' degrees', (20, 30), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2, cv.LINE_4) elif angle < -10: cv.putText(frame, 'LEFT TILT :' + str(int(angle))+' degrees', (20, 30), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2, cv.LINE_4) else: cv.putText(frame, 'STRAIGHT :', (20, 30), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2, cv.LINE_4) cv.imshow('Frame', frame) if cv.waitKey(1) & 0xFF == 27: breakcapture.release()cv.destroyAllWindows()
Output:
anikaseth98
Blogathon-2021
Python-OpenCV
Python-projects
Blogathon
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
How to Create a Table With Multiple Foreign Keys in SQL?
How to Install Tkinter in Windows?
SQL Query to Convert Datetime to Date
SQL Query to Create Table With a Primary Key
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": 24838,
"s": 24810,
"text": "\n01 Oct, 2021"
},
{
"code": null,
"e": 24930,
"s": 24838,
"text": "In this article, we are going to see how to determine the face tilt using OpenCV in Python."
},
{
"code": null,
"e": 25207,
"s": 24930,
"text": "To achieve this we will be using a popular computer vision library opencv-python. In this program with the help of the OpenCV library, we will detect faces in a live stream from a webcam or a video file and subsequently also determine the angle by how much the face is tilted."
},
{
"code": null,
"e": 25234,
"s": 25207,
"text": "Install OpenCV for python."
},
{
"code": null,
"e": 25410,
"s": 25234,
"text": "We will be using two pre-trained XML classifiers to detect faces and eyes respectively. These classifiers can be downloaded from opencv library or just click the links below."
},
{
"code": null,
"e": 25477,
"s": 25410,
"text": "Classifier for face detection: haarcascade_frontalface_default.xml"
},
{
"code": null,
"e": 25527,
"s": 25477,
"text": "Classifier for eye detection: haarcascade_eye.xml"
},
{
"code": null,
"e": 25687,
"s": 25527,
"text": "First, we detect the face in the webcam feed/video using the above-mentioned haarcascade classifier for the face and make a green color bounding box around it."
},
{
"code": null,
"e": 25818,
"s": 25687,
"text": "Next, we detect the eyes using a similar haarcascade classifier trained on eyes and make a red color bounding box around each eye."
},
{
"code": null,
"e": 26010,
"s": 25818,
"text": "In addition to making a box around each eye, we also identify and store the center of each box. Here, we are assuming that the center of the bounding box is the same as the center of the eye."
},
{
"code": null,
"e": 26133,
"s": 26010,
"text": "For computing the angle of tilt we will assume that the line joining the centers of two eyes is perpendicular to the face."
},
{
"code": null,
"e": 26270,
"s": 26133,
"text": "We have the coordinates of two centers in terms of (x,y) coordinates. The x-axis is the horizontal axis and y-axis is the vertical axis."
},
{
"code": null,
"e": 26434,
"s": 26270,
"text": "When two points are given & , the angle which the line joining the two points makes with the x-axis can be obtained from geometry using the following expression:"
},
{
"code": null,
"e": 26631,
"s": 26434,
"text": "In our case, the angle made by the line joining the centers of two eyes with the horizontal is computed. The positive angle indicates the right tilt and the negative angle indicates the left tilt."
},
{
"code": null,
"e": 26782,
"s": 26631,
"text": "Provided a margin of error of 10 degrees (i.e, if the face tilts more than 10 degrees on either side the program will classify as right or left tilt)."
},
{
"code": null,
"e": 26789,
"s": 26782,
"text": "Python"
},
{
"code": "import cv2 as cvimport numpy as np # 0 for webcam feed ; add \"path to file\"# for detection in video filecapture = cv.VideoCapture(0)face_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml')eye_cascade = cv.CascadeClassifier(\"haarcascade_eye.xml\") while True: ret, frame = capture.read() gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.1, 5) x, y, w, h = 0, 0, 0, 0 for (x, y, w, h) in faces: cv.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) cv.circle(frame, (x + int(w * 0.5), y + int(h * 0.5)), 4, (0, 255, 0), -1) eyes = eye_cascade.detectMultiScale(gray[y:(y + h), x:(x + w)], 1.1, 4) index = 0 eye_1 = [None, None, None, None] eye_2 = [None, None, None, None] for (ex, ey, ew, eh) in eyes: if index == 0: eye_1 = [ex, ey, ew, eh] elif index == 1: eye_2 = [ex, ey, ew, eh] cv.rectangle(frame[y:(y + h), x:(x + w)], (ex, ey), (ex + ew, ey + eh), (0, 0, 255), 2) index = index + 1 if (eye_1[0] is not None) and (eye_2[0] is not None): if eye_1[0] < eye_2[0]: left_eye = eye_1 right_eye = eye_2 else: left_eye = eye_2 right_eye = eye_1 left_eye_center = ( int(left_eye[0] + (left_eye[2] / 2)), int(left_eye[1] + (left_eye[3] / 2))) right_eye_center = ( int(right_eye[0] + (right_eye[2] / 2)), int(right_eye[1] + (right_eye[3] / 2))) left_eye_x = left_eye_center[0] left_eye_y = left_eye_center[1] right_eye_x = right_eye_center[0] right_eye_y = right_eye_center[1] delta_x = right_eye_x - left_eye_x delta_y = right_eye_y - left_eye_y # Slope of line formula angle = np.arctan(delta_y / delta_x) # Converting radians to degrees angle = (angle * 180) / np.pi # Provided a margin of error of 10 degrees # (i.e, if the face tilts more than 10 degrees # on either side the program will classify as right or left tilt) if angle > 10: cv.putText(frame, 'RIGHT TILT :' + str(int(angle))+' degrees', (20, 30), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2, cv.LINE_4) elif angle < -10: cv.putText(frame, 'LEFT TILT :' + str(int(angle))+' degrees', (20, 30), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2, cv.LINE_4) else: cv.putText(frame, 'STRAIGHT :', (20, 30), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2, cv.LINE_4) cv.imshow('Frame', frame) if cv.waitKey(1) & 0xFF == 27: breakcapture.release()cv.destroyAllWindows()",
"e": 29648,
"s": 26789,
"text": null
},
{
"code": null,
"e": 29656,
"s": 29648,
"text": "Output:"
},
{
"code": null,
"e": 29668,
"s": 29656,
"text": "anikaseth98"
},
{
"code": null,
"e": 29683,
"s": 29668,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 29697,
"s": 29683,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 29713,
"s": 29697,
"text": "Python-projects"
},
{
"code": null,
"e": 29723,
"s": 29713,
"text": "Blogathon"
},
{
"code": null,
"e": 29730,
"s": 29723,
"text": "Python"
},
{
"code": null,
"e": 29828,
"s": 29730,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29869,
"s": 29828,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 29926,
"s": 29869,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 29961,
"s": 29926,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 29999,
"s": 29961,
"text": "SQL Query to Convert Datetime to Date"
},
{
"code": null,
"e": 30044,
"s": 29999,
"text": "SQL Query to Create Table With a Primary Key"
},
{
"code": null,
"e": 30072,
"s": 30044,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 30122,
"s": 30072,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 30144,
"s": 30122,
"text": "Python map() function"
}
] |
CSS Combinators
|
A combinator is something that explains the relationship between the selectors.
A CSS selector can contain more than one simple selector. Between the simple
selectors, we can include a combinator.
There are four different combinators in CSS:
descendant selector (space)
child selector (>)
adjacent sibling selector (+)
general sibling selector (~)
The descendant selector matches all elements that are descendants of a specified
element.
The following example selects all <p> elements inside <div> elements:
The child selector selects all elements that are the children of a
specified element.
The following example selects all <p> elements that are
children of a <div>
element:
The adjacent sibling selector is used to select an element that is directly
after another specific element.
Sibling elements must have the same parent element, and "adjacent" means
"immediately following".
The following example selects the first <p> element that are placed immediately after <div> elements:
The general sibling selector selects all elements that are next siblings of a specified element.
The following example selects all <p> elements that are next siblings of <div> elements:
Change the color of all <p> elements, that are descendants of <div> elements, to "red".
<style>
{
color: red;
}
</style>
<body>
<div>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
</div>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
</body>
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 80,
"s": 0,
"text": "A combinator is something that explains the relationship between the selectors."
},
{
"code": null,
"e": 198,
"s": 80,
"text": "A CSS selector can contain more than one simple selector. Between the simple \nselectors, we can include a combinator."
},
{
"code": null,
"e": 243,
"s": 198,
"text": "There are four different combinators in CSS:"
},
{
"code": null,
"e": 271,
"s": 243,
"text": "descendant selector (space)"
},
{
"code": null,
"e": 290,
"s": 271,
"text": "child selector (>)"
},
{
"code": null,
"e": 320,
"s": 290,
"text": "adjacent sibling selector (+)"
},
{
"code": null,
"e": 349,
"s": 320,
"text": "general sibling selector (~)"
},
{
"code": null,
"e": 440,
"s": 349,
"text": "The descendant selector matches all elements that are descendants of a specified \nelement."
},
{
"code": null,
"e": 511,
"s": 440,
"text": "The following example selects all <p> elements inside <div> elements: "
},
{
"code": null,
"e": 598,
"s": 511,
"text": "The child selector selects all elements that are the children of a \nspecified element."
},
{
"code": null,
"e": 686,
"s": 598,
"text": "The following example selects all <p> elements that are \nchildren of a <div> \nelement:"
},
{
"code": null,
"e": 795,
"s": 686,
"text": "The adjacent sibling selector is used to select an element that is directly \nafter another specific element."
},
{
"code": null,
"e": 894,
"s": 795,
"text": "Sibling elements must have the same parent element, and \"adjacent\" means \n\"immediately following\"."
},
{
"code": null,
"e": 996,
"s": 894,
"text": "The following example selects the first <p> element that are placed immediately after <div> elements:"
},
{
"code": null,
"e": 1093,
"s": 996,
"text": "The general sibling selector selects all elements that are next siblings of a specified element."
},
{
"code": null,
"e": 1183,
"s": 1093,
"text": "The following example selects all <p> elements that are next siblings of <div> elements: "
},
{
"code": null,
"e": 1271,
"s": 1183,
"text": "Change the color of all <p> elements, that are descendants of <div> elements, to \"red\"."
},
{
"code": null,
"e": 1455,
"s": 1271,
"text": "<style>\n {\n color: red;\n}\n</style>\n\n<body>\n\n<div>\n <p>This is a paragraph.</p>\n <p>This is a paragraph.</p>\n</div>\n<p>This is a paragraph.</p>\n<p>This is a paragraph.</p>\n\n</body>\n"
},
{
"code": null,
"e": 1474,
"s": 1455,
"text": "Start the Exercise"
},
{
"code": null,
"e": 1507,
"s": 1474,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1549,
"s": 1507,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1656,
"s": 1549,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1675,
"s": 1656,
"text": "[email protected]"
}
] |
Factors affecting Cache Memory Performance - GeeksforGeeks
|
11 Jan, 2021
Computers are made of three primary blocs. A CPU, a memory, and an I/O system. The performance of a computer system is very much dependent on the speed with which the CPU can fetch instructions from the memory and write to the same memory. Computers are using cache memory to bridge the gap between the processor’s ability to execute instructions and the time it takes to fetch operations from main memory.
Time taken by a program to execute with a cache depends on
The number of instructions needed to perform the task.
The average number of CPU cycles needed to perform the desired task.
The CPU’s cycle time.
While Engineering any product or feature the generic structure of the device remains the same what changes the specific part of the device which needs to be optimized because of client requirements. How does an engineer go about improving the design? Simple we start by making a mathematical model connecting the inputs to the outputs.
Execution Time = Instruction Count x Cycles per Instruction x Cycle Time
=Instruction Count x (CPU Cycles per Instr. + Memory Cycles per Instr.) x Cycle Time
=Instruction Count x [CPU Cycles per Instr. +(References per Instr. x Cycles per References)] x Cycle Time
These four boxes represent four major pain points that can be addressed to have a significant performance change either positive or negative on the machine. The first element of the equation the number of instructions needed to perform a function is dependent on the instruction set architecture and is the same across all implementations. It is also dependent on the compiler’s design to produce efficient code. Optimizing compilers to execute functions with fewer executed instructions is desired.
CPU cycles per instructions are also dependent on compiler optimizations as the compiler can be made to choose instructions that are less CPU intensive and have a shorter path length. Pipelining instructions efficiently also improve this parameter which makes instructions maximize hardware resource optimization.
The average number of memory references per instruction and the average number of cycles per memory reference combine to form the average number of cycles per instruction. The former is a function of architecture and instruction selection algorithms of the compiler. This is constant across implementations of the architecture.
Instruction Set Architecture :
Reduced Instruction Set Computer (RISC) –Reduced Instruction Set Computer (RISC) is one of the most popular instruction set. This is used by ARM processors and those are one of the most widely used chips for products.
Complex Instruction Set Computer (CISC) –Complex Instruction Set Computer (CISC) is an instruction set architecture for the very specialized operation which has been researched and studied upon so thoroughly that even the processor microarchitecture is built for that specific purpose only.
Minimal instruction set computers (MISC) –Minimal instruction set computers (MISC) the 8085 may be considered in this category compared to modern processors.
Explicitly parallel instruction computing (EPIC) –Explicitly parallel instruction computing (EPIC) is an instruction set that is widely used in supercomputers.
One instruction set computer (OISC) –One instruction set computer (OISC) uses assembly only.
Zero instruction set computer (ZISC) –This is a neural network on a computer.
Compiler Technology :
Single Pass Compiler –This source code is directly converted into machine code.
Two-Pass Compiler –Source code is converted onto an intermediate representation which is converted into machine code.
Multipass Compiler –In this source code is converted into intermediate code from the front end then it is converted into intermediate code after the middle-end then passed to the back end which is converted into machine code.
CPU Implementation :
The micro-architecture is dependent upon the design philosophy and methodology of the Engineers involved in the process. Take a simple example of making a circuit to take input from a common jack passing it through an amplifier then storing the data in a buffer.
Two approaches can be taken to solve the problem which is either putting a buffer in the beginning and putting two amplifiers and bypassing the current through either which would make sense if two different types of signals are supposed to be amplified or if there is a slight difference in the saturation region of the amplifiers. Or we could make a common current path and introduce a temporal dependence upon the buffer in which data is stored thereby eliminating the need for buffers altogether.
Minute differences like these in the VLSI microarchitecture of the processor create massive timing differences in the same Instruction Set Implementations by two different companies.
Cache and Memory Hierarchy :
This is again dependent upon the use case for which the system was built. Using a general-purpose computer also called a Personal Computer which can perform a wide variety of mathematical calculations and produce wide results but reasonably accurate for non-real-time systems in a hard real-time system will be very unwise.
A very big difference will be the time taken to access data in the cache.
A simple experiment may be run on your computer whereby you may find the cache size of your particular model of processor and try to access elements of an array around that array a massive speed down will be observed while trying to access an array greater than the cache size.
Computer Organization and Architecture
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Cache Coherence and Memory Consistency
Example of Interfacing Seven Segments LED Display with 8085
Difference between Hardware and Peripherals
North Bridge and its functions
Basic Cache Optimization Techniques
Layers of OSI Model
ACID Properties in DBMS
Normal Forms in DBMS
Types of Operating Systems
Page Replacement Algorithms in Operating Systems
|
[
{
"code": null,
"e": 24786,
"s": 24758,
"text": "\n11 Jan, 2021"
},
{
"code": null,
"e": 25193,
"s": 24786,
"text": "Computers are made of three primary blocs. A CPU, a memory, and an I/O system. The performance of a computer system is very much dependent on the speed with which the CPU can fetch instructions from the memory and write to the same memory. Computers are using cache memory to bridge the gap between the processor’s ability to execute instructions and the time it takes to fetch operations from main memory."
},
{
"code": null,
"e": 25252,
"s": 25193,
"text": "Time taken by a program to execute with a cache depends on"
},
{
"code": null,
"e": 25307,
"s": 25252,
"text": "The number of instructions needed to perform the task."
},
{
"code": null,
"e": 25376,
"s": 25307,
"text": "The average number of CPU cycles needed to perform the desired task."
},
{
"code": null,
"e": 25398,
"s": 25376,
"text": "The CPU’s cycle time."
},
{
"code": null,
"e": 25734,
"s": 25398,
"text": "While Engineering any product or feature the generic structure of the device remains the same what changes the specific part of the device which needs to be optimized because of client requirements. How does an engineer go about improving the design? Simple we start by making a mathematical model connecting the inputs to the outputs."
},
{
"code": null,
"e": 25999,
"s": 25734,
"text": "Execution Time = Instruction Count x Cycles per Instruction x Cycle Time\n=Instruction Count x (CPU Cycles per Instr. + Memory Cycles per Instr.) x Cycle Time\n=Instruction Count x [CPU Cycles per Instr. +(References per Instr. x Cycles per References)] x Cycle Time"
},
{
"code": null,
"e": 26499,
"s": 25999,
"text": "These four boxes represent four major pain points that can be addressed to have a significant performance change either positive or negative on the machine. The first element of the equation the number of instructions needed to perform a function is dependent on the instruction set architecture and is the same across all implementations. It is also dependent on the compiler’s design to produce efficient code. Optimizing compilers to execute functions with fewer executed instructions is desired."
},
{
"code": null,
"e": 26813,
"s": 26499,
"text": "CPU cycles per instructions are also dependent on compiler optimizations as the compiler can be made to choose instructions that are less CPU intensive and have a shorter path length. Pipelining instructions efficiently also improve this parameter which makes instructions maximize hardware resource optimization."
},
{
"code": null,
"e": 27143,
"s": 26813,
"text": "The average number of memory references per instruction and the average number of cycles per memory reference combine to form the average number of cycles per instruction. The former is a function of architecture and instruction selection algorithms of the compiler. This is constant across implementations of the architecture. "
},
{
"code": null,
"e": 27174,
"s": 27143,
"text": "Instruction Set Architecture :"
},
{
"code": null,
"e": 27393,
"s": 27174,
"text": "Reduced Instruction Set Computer (RISC) –Reduced Instruction Set Computer (RISC) is one of the most popular instruction set. This is used by ARM processors and those are one of the most widely used chips for products. "
},
{
"code": null,
"e": 27685,
"s": 27393,
"text": "Complex Instruction Set Computer (CISC) –Complex Instruction Set Computer (CISC) is an instruction set architecture for the very specialized operation which has been researched and studied upon so thoroughly that even the processor microarchitecture is built for that specific purpose only. "
},
{
"code": null,
"e": 27844,
"s": 27685,
"text": "Minimal instruction set computers (MISC) –Minimal instruction set computers (MISC) the 8085 may be considered in this category compared to modern processors. "
},
{
"code": null,
"e": 28006,
"s": 27844,
"text": "Explicitly parallel instruction computing (EPIC) –Explicitly parallel instruction computing (EPIC) is an instruction set that is widely used in supercomputers. "
},
{
"code": null,
"e": 28100,
"s": 28006,
"text": "One instruction set computer (OISC) –One instruction set computer (OISC) uses assembly only. "
},
{
"code": null,
"e": 28178,
"s": 28100,
"text": "Zero instruction set computer (ZISC) –This is a neural network on a computer."
},
{
"code": null,
"e": 28200,
"s": 28178,
"text": "Compiler Technology :"
},
{
"code": null,
"e": 28281,
"s": 28200,
"text": "Single Pass Compiler –This source code is directly converted into machine code. "
},
{
"code": null,
"e": 28400,
"s": 28281,
"text": "Two-Pass Compiler –Source code is converted onto an intermediate representation which is converted into machine code. "
},
{
"code": null,
"e": 28626,
"s": 28400,
"text": "Multipass Compiler –In this source code is converted into intermediate code from the front end then it is converted into intermediate code after the middle-end then passed to the back end which is converted into machine code."
},
{
"code": null,
"e": 28647,
"s": 28626,
"text": "CPU Implementation :"
},
{
"code": null,
"e": 28911,
"s": 28647,
"text": "The micro-architecture is dependent upon the design philosophy and methodology of the Engineers involved in the process. Take a simple example of making a circuit to take input from a common jack passing it through an amplifier then storing the data in a buffer. "
},
{
"code": null,
"e": 29411,
"s": 28911,
"text": "Two approaches can be taken to solve the problem which is either putting a buffer in the beginning and putting two amplifiers and bypassing the current through either which would make sense if two different types of signals are supposed to be amplified or if there is a slight difference in the saturation region of the amplifiers. Or we could make a common current path and introduce a temporal dependence upon the buffer in which data is stored thereby eliminating the need for buffers altogether."
},
{
"code": null,
"e": 29594,
"s": 29411,
"text": "Minute differences like these in the VLSI microarchitecture of the processor create massive timing differences in the same Instruction Set Implementations by two different companies."
},
{
"code": null,
"e": 29623,
"s": 29594,
"text": "Cache and Memory Hierarchy :"
},
{
"code": null,
"e": 29947,
"s": 29623,
"text": "This is again dependent upon the use case for which the system was built. Using a general-purpose computer also called a Personal Computer which can perform a wide variety of mathematical calculations and produce wide results but reasonably accurate for non-real-time systems in a hard real-time system will be very unwise."
},
{
"code": null,
"e": 30021,
"s": 29947,
"text": "A very big difference will be the time taken to access data in the cache."
},
{
"code": null,
"e": 30299,
"s": 30021,
"text": "A simple experiment may be run on your computer whereby you may find the cache size of your particular model of processor and try to access elements of an array around that array a massive speed down will be observed while trying to access an array greater than the cache size."
},
{
"code": null,
"e": 30338,
"s": 30299,
"text": "Computer Organization and Architecture"
},
{
"code": null,
"e": 30346,
"s": 30338,
"text": "GATE CS"
},
{
"code": null,
"e": 30444,
"s": 30346,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30453,
"s": 30444,
"text": "Comments"
},
{
"code": null,
"e": 30466,
"s": 30453,
"text": "Old Comments"
},
{
"code": null,
"e": 30524,
"s": 30466,
"text": "Difference between Cache Coherence and Memory Consistency"
},
{
"code": null,
"e": 30584,
"s": 30524,
"text": "Example of Interfacing Seven Segments LED Display with 8085"
},
{
"code": null,
"e": 30628,
"s": 30584,
"text": "Difference between Hardware and Peripherals"
},
{
"code": null,
"e": 30659,
"s": 30628,
"text": "North Bridge and its functions"
},
{
"code": null,
"e": 30695,
"s": 30659,
"text": "Basic Cache Optimization Techniques"
},
{
"code": null,
"e": 30715,
"s": 30695,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 30739,
"s": 30715,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 30760,
"s": 30739,
"text": "Normal Forms in DBMS"
},
{
"code": null,
"e": 30787,
"s": 30760,
"text": "Types of Operating Systems"
}
] |
Java Program For Rearranging An Array In Maximum Minimum Form - Set 2 (O(1) extra space) - GeeksforGeeks
|
06 Jan, 2022
Given a sorted array of positive integers, rearrange the array alternately i.e first element should be the maximum value, second minimum value, third-second max, fourth-second min and so on. Examples:
Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: arr[] = {7, 1, 6, 2, 5, 3, 4}Input: arr[] = {1, 2, 3, 4, 5, 6} Output: arr[] = {6, 1, 5, 2, 4, 3}
We have discussed a solution in below post: Rearrange an array in maximum minimum form | Set 1 : The solution discussed here requires extra space, how to solve this problem with O(1) extra space.
In this post a solution that requires O(n) time and O(1) extra space is discussed. The idea is to use multiplication and modular trick to store two elements at an index.
even index : remaining maximum element.
odd index : remaining minimum element.
max_index : Index of remaining maximum element
(Moves from right to left)
min_index : Index of remaining minimum element
(Moves from left to right)
Initialize: max_index = 'n-1'
min_index = 0
// can be any element which is more
// than the maximum value in array
max_element = arr[max_index] + 1
For i = 0 to n-1
If 'i' is even
arr[i] += arr[max_index] % max_element * max_element
max_index--
// if 'i' is odd
ELSE
arr[i] += arr[min_index] % max_element * max_element
min_index++
How does expression “arr[i] += arr[max_index] % max_element * max_element” work ? The purpose of this expression is to store two elements at index arr[i]. arr[max_index] is stored as multiplier and “arr[i]” is stored as remainder. For example in {1 2 3 4 5 6 7 8 9}, max_element is 10 and we store 91 at index 0. With 91, we can get original element as 91%10 and new element as 91/10.Below implementation of above idea:
Java
// Java program to rearrange an// array in minimum maximum formpublic class Main { // Prints max at first position, min // at second position second max at // third position, second min at // fourth position and so on. public static void rearrange(int arr[], int n) { // Initialize index of first minimum // and first maximum element int max_idx = n - 1, min_idx = 0; // Store maximum element of array int max_elem = arr[n - 1] + 1; // Traverse array elements for (int i = 0; i < n; i++) { // At even index : we have to put // maximum element if (i % 2 == 0) { arr[i] += ((arr[max_idx] % max_elem) * max_elem); max_idx--; } // At odd index : we have to put // minimum element else { arr[i] += ((arr[min_idx] % max_elem) * max_elem); min_idx++; } } // Array elements back to it's // original form for (int i = 0; i < n; i++) arr[i] = arr[i] / max_elem; } // Driver code public static void main(String args[]) { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int n = arr.length; System.out.println( "Original Array"); for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); rearrange(arr, n); System.out.print( "Modified Array"); for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); }}// This code is contributed by Swetank Modi
Output :
Original Array
1 2 3 4 5 6 7 8 9
Modified Array
9 1 8 2 7 3 6 4 5
Thanks Saurabh Srivastava and Gaurav Ahirwar for suggesting this approach. Another Approach: A simpler approach will be to observe indexing positioning of maximum elements and minimum elements. The even index stores maximum elements and the odd index stores the minimum elements. With every increasing index, the maximum element decreases by one and the minimum element increases by one. A simple traversal can be done and arr[] can be filled in again.Note: This approach is only valid when elements of given sorted array are consecutive i.e., vary by one unit.Below is the implementation of the above approach:
Java
// Java program to rearrange an// array in minimum maximum formpublic class Main { // Prints max at first position, min // at second position second max at // third position, second min at // fourth position and so on. public static void rearrange(int arr[], int n) { // Initialize index of first minimum // and first maximum element int max_ele = arr[n - 1]; int min_ele = arr[0]; // Traverse array elements for (int i = 0; i < n; i++) { // At even index : we have to put // maximum element if (i % 2 == 0) { arr[i] = max_ele; max_ele -= 1; } // At odd index : we have to put // minimum element else { arr[i] = min_ele; min_ele += 1; } } } // Driver code public static void main(String args[]) { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int n = arr.length; System.out.println("Original Array"); for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); rearrange(arr, n); System.out.print( "Modified Array"); for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); }}
Output :
Original Array
1 2 3 4 5 6 7 8 9
Modified Array
9 1 8 2 7 3 6 4 5
Please refer complete article on Rearrange an array in maximum minimum form | Set 2 (O(1) extra space) for more details!
array-rearrange
Modular Arithmetic
Zoho
Arrays
Java Programs
Sorting
Zoho
Arrays
Sorting
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Reversal algorithm for array rotation
Window Sliding Technique
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Initializing a List in Java
Convert a String to Character Array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
|
[
{
"code": null,
"e": 26151,
"s": 26123,
"text": "\n06 Jan, 2022"
},
{
"code": null,
"e": 26352,
"s": 26151,
"text": "Given a sorted array of positive integers, rearrange the array alternately i.e first element should be the maximum value, second minimum value, third-second max, fourth-second min and so on. Examples:"
},
{
"code": null,
"e": 26495,
"s": 26352,
"text": "Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: arr[] = {7, 1, 6, 2, 5, 3, 4}Input: arr[] = {1, 2, 3, 4, 5, 6} Output: arr[] = {6, 1, 5, 2, 4, 3}"
},
{
"code": null,
"e": 26691,
"s": 26495,
"text": "We have discussed a solution in below post: Rearrange an array in maximum minimum form | Set 1 : The solution discussed here requires extra space, how to solve this problem with O(1) extra space."
},
{
"code": null,
"e": 26861,
"s": 26691,
"text": "In this post a solution that requires O(n) time and O(1) extra space is discussed. The idea is to use multiplication and modular trick to store two elements at an index."
},
{
"code": null,
"e": 27563,
"s": 26861,
"text": "even index : remaining maximum element.\nodd index : remaining minimum element.\n \nmax_index : Index of remaining maximum element\n (Moves from right to left)\nmin_index : Index of remaining minimum element\n (Moves from left to right)\n\nInitialize: max_index = 'n-1'\n min_index = 0 \n\n // can be any element which is more \n // than the maximum value in array\n max_element = arr[max_index] + 1 \n\nFor i = 0 to n-1 \n If 'i' is even\n arr[i] += arr[max_index] % max_element * max_element \n max_index-- \n\n // if 'i' is odd \n ELSE \n arr[i] += arr[min_index] % max_element * max_element\n min_index++"
},
{
"code": null,
"e": 27983,
"s": 27563,
"text": "How does expression “arr[i] += arr[max_index] % max_element * max_element” work ? The purpose of this expression is to store two elements at index arr[i]. arr[max_index] is stored as multiplier and “arr[i]” is stored as remainder. For example in {1 2 3 4 5 6 7 8 9}, max_element is 10 and we store 91 at index 0. With 91, we can get original element as 91%10 and new element as 91/10.Below implementation of above idea:"
},
{
"code": null,
"e": 27988,
"s": 27983,
"text": "Java"
},
{
"code": "// Java program to rearrange an// array in minimum maximum formpublic class Main { // Prints max at first position, min // at second position second max at // third position, second min at // fourth position and so on. public static void rearrange(int arr[], int n) { // Initialize index of first minimum // and first maximum element int max_idx = n - 1, min_idx = 0; // Store maximum element of array int max_elem = arr[n - 1] + 1; // Traverse array elements for (int i = 0; i < n; i++) { // At even index : we have to put // maximum element if (i % 2 == 0) { arr[i] += ((arr[max_idx] % max_elem) * max_elem); max_idx--; } // At odd index : we have to put // minimum element else { arr[i] += ((arr[min_idx] % max_elem) * max_elem); min_idx++; } } // Array elements back to it's // original form for (int i = 0; i < n; i++) arr[i] = arr[i] / max_elem; } // Driver code public static void main(String args[]) { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int n = arr.length; System.out.println( \"Original Array\"); for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); rearrange(arr, n); System.out.print( \"Modified Array\"); for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); }}// This code is contributed by Swetank Modi",
"e": 29740,
"s": 27988,
"text": null
},
{
"code": null,
"e": 29750,
"s": 29740,
"text": "Output : "
},
{
"code": null,
"e": 29818,
"s": 29750,
"text": "Original Array\n1 2 3 4 5 6 7 8 9 \nModified Array\n9 1 8 2 7 3 6 4 5 "
},
{
"code": null,
"e": 30430,
"s": 29818,
"text": "Thanks Saurabh Srivastava and Gaurav Ahirwar for suggesting this approach. Another Approach: A simpler approach will be to observe indexing positioning of maximum elements and minimum elements. The even index stores maximum elements and the odd index stores the minimum elements. With every increasing index, the maximum element decreases by one and the minimum element increases by one. A simple traversal can be done and arr[] can be filled in again.Note: This approach is only valid when elements of given sorted array are consecutive i.e., vary by one unit.Below is the implementation of the above approach:"
},
{
"code": null,
"e": 30435,
"s": 30430,
"text": "Java"
},
{
"code": "// Java program to rearrange an// array in minimum maximum formpublic class Main { // Prints max at first position, min // at second position second max at // third position, second min at // fourth position and so on. public static void rearrange(int arr[], int n) { // Initialize index of first minimum // and first maximum element int max_ele = arr[n - 1]; int min_ele = arr[0]; // Traverse array elements for (int i = 0; i < n; i++) { // At even index : we have to put // maximum element if (i % 2 == 0) { arr[i] = max_ele; max_ele -= 1; } // At odd index : we have to put // minimum element else { arr[i] = min_ele; min_ele += 1; } } } // Driver code public static void main(String args[]) { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int n = arr.length; System.out.println(\"Original Array\"); for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); rearrange(arr, n); System.out.print( \"Modified Array\"); for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); }}",
"e": 31822,
"s": 30435,
"text": null
},
{
"code": null,
"e": 31832,
"s": 31822,
"text": "Output : "
},
{
"code": null,
"e": 31900,
"s": 31832,
"text": "Original Array\n1 2 3 4 5 6 7 8 9 \nModified Array\n9 1 8 2 7 3 6 4 5 "
},
{
"code": null,
"e": 32021,
"s": 31900,
"text": "Please refer complete article on Rearrange an array in maximum minimum form | Set 2 (O(1) extra space) for more details!"
},
{
"code": null,
"e": 32037,
"s": 32021,
"text": "array-rearrange"
},
{
"code": null,
"e": 32056,
"s": 32037,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 32061,
"s": 32056,
"text": "Zoho"
},
{
"code": null,
"e": 32068,
"s": 32061,
"text": "Arrays"
},
{
"code": null,
"e": 32082,
"s": 32068,
"text": "Java Programs"
},
{
"code": null,
"e": 32090,
"s": 32082,
"text": "Sorting"
},
{
"code": null,
"e": 32095,
"s": 32090,
"text": "Zoho"
},
{
"code": null,
"e": 32102,
"s": 32095,
"text": "Arrays"
},
{
"code": null,
"e": 32110,
"s": 32102,
"text": "Sorting"
},
{
"code": null,
"e": 32129,
"s": 32110,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 32227,
"s": 32129,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32258,
"s": 32227,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 32296,
"s": 32258,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 32321,
"s": 32296,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 32342,
"s": 32321,
"text": "Next Greater Element"
},
{
"code": null,
"e": 32400,
"s": 32342,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 32428,
"s": 32400,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 32472,
"s": 32428,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 32498,
"s": 32472,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 32532,
"s": 32498,
"text": "Convert Double to Integer in Java"
}
] |
GATE | GATE-CS-2009 | Question 42 - GeeksforGeeks
|
28 Jun, 2021
Which of the following statements are TRUE?
I. There exist parsing algorithms for some programming languages
whose complexities are less than O(n3).
II. A programming language which allows recursion can be implemented
with static storage allocation.
III. No L-attributed definition can be evaluated in The framework
of bottom-up parsing.
IV. Code improving transformations can be performed at both source
language and intermediate code level.
(A) I and II(B) I and IV(C) III and IV(D) I, III and IVAnswer: (B)Explanation: II is false, in recursion, compiler cannot determine the space needed for recursive calls.
III is false. See http://www.cs.sunysb.edu/~cse304/Fall09/Lectures/attributes-handout.pdfQuiz of this Question
GATE-CS-2009
GATE-GATE-CS-2009
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
|
[
{
"code": null,
"e": 25695,
"s": 25667,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25739,
"s": 25695,
"text": "Which of the following statements are TRUE?"
},
{
"code": null,
"e": 26162,
"s": 25739,
"text": "I. There exist parsing algorithms for some programming languages \n whose complexities are less than O(n3).\nII. A programming language which allows recursion can be implemented \n with static storage allocation.\nIII. No L-attributed definition can be evaluated in The framework \n of bottom-up parsing.\nIV. Code improving transformations can be performed at both source \n language and intermediate code level."
},
{
"code": null,
"e": 26332,
"s": 26162,
"text": "(A) I and II(B) I and IV(C) III and IV(D) I, III and IVAnswer: (B)Explanation: II is false, in recursion, compiler cannot determine the space needed for recursive calls."
},
{
"code": null,
"e": 26444,
"s": 26332,
"text": "III is false. See http://www.cs.sunysb.edu/~cse304/Fall09/Lectures/attributes-handout.pdfQuiz of this Question"
},
{
"code": null,
"e": 26457,
"s": 26444,
"text": "GATE-CS-2009"
},
{
"code": null,
"e": 26475,
"s": 26457,
"text": "GATE-GATE-CS-2009"
},
{
"code": null,
"e": 26480,
"s": 26475,
"text": "GATE"
},
{
"code": null,
"e": 26578,
"s": 26480,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26612,
"s": 26578,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 26646,
"s": 26612,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 26680,
"s": 26646,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 26713,
"s": 26680,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 26749,
"s": 26713,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 26783,
"s": 26749,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 26819,
"s": 26783,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 26853,
"s": 26819,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 26887,
"s": 26853,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
Number of edges in a perfect binary tree with N levels
|
10 Mar, 2022
Given a positive integer N, the task is to find the count of edges of a perfect binary tree with N levels.Examples:
Input: N = 2
Output: 2
1
/ \
2 3
Input: N = 3
Output: 6
1
/ \
2 3
/ \ / \
4 5 6 7
Approach: It can be observed that for the values of N = 1, 2, 3, ..., a series will be formed as 0, 2, 6, 14, 30, 62, ... whose Nth term is 2N – 2.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count// of edges in an n-level// perfect binary treeint cntEdges(int n){ int edges = pow(2, n) - 2; return edges;} // Driver codeint main(){ int n = 4; cout << cntEdges(n); return 0;}
// Java implementation of the approachclass GFG{ // Function to return the count// of edges in an n-level// perfect binary treestatic int cntEdges(int n){ int edges = (int)Math.pow(2, n) - 2; return edges;} // Driver codepublic static void main(String[] args){ int n = 4; System.out.println(cntEdges(n));}} // This code is contributed by Code_Mech
# Python3 implementation of the approach # Function to return the count# of edges in an n-level# perfect binary treedef cntEdges(n) : edges = 2 ** n - 2; return edges; # Driver codeif __name__ == "__main__" : n = 4; print(cntEdges(n)); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System;class GFG{ // Function to return the count// of edges in an n-level// perfect binary treestatic int cntEdges(int n){ int edges = (int)Math.Pow(2, n) - 2; return edges;} // Driver codepublic static void Main(String[] args){ int n = 4; Console.Write(cntEdges(n));}} // This code is contributed by Mohit Kumar
<script> // Javascript implementation of the approach // Function to return the count// of edges in an n-level// perfect binary treefunction cntEdges(n){ var edges = Math.pow(2, n) - 2; return edges;} // Driver codevar n = 4;document.write(cntEdges(n)); </script>
14
Time Complexity: O(log n)
Auxiliary Space: O(1)
ankthon
Code_Mech
mohit kumar 29
shubham_singh
noob2000
subhammahato348
Binary Tree
Mathematical
Tree
Mathematical
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Mar, 2022"
},
{
"code": null,
"e": 146,
"s": 28,
"text": "Given a positive integer N, the task is to find the count of edges of a perfect binary tree with N levels.Examples: "
},
{
"code": null,
"e": 263,
"s": 146,
"text": "Input: N = 2\nOutput: 2\n 1\n / \\\n2 3\n\nInput: N = 3\nOutput: 6\n 1\n / \\\n 2 3\n / \\ / \\\n4 5 6 7"
},
{
"code": null,
"e": 465,
"s": 265,
"text": "Approach: It can be observed that for the values of N = 1, 2, 3, ..., a series will be formed as 0, 2, 6, 14, 30, 62, ... whose Nth term is 2N – 2.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 469,
"s": 465,
"text": "C++"
},
{
"code": null,
"e": 474,
"s": 469,
"text": "Java"
},
{
"code": null,
"e": 482,
"s": 474,
"text": "Python3"
},
{
"code": null,
"e": 485,
"s": 482,
"text": "C#"
},
{
"code": null,
"e": 496,
"s": 485,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count// of edges in an n-level// perfect binary treeint cntEdges(int n){ int edges = pow(2, n) - 2; return edges;} // Driver codeint main(){ int n = 4; cout << cntEdges(n); return 0;}",
"e": 805,
"s": 496,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function to return the count// of edges in an n-level// perfect binary treestatic int cntEdges(int n){ int edges = (int)Math.pow(2, n) - 2; return edges;} // Driver codepublic static void main(String[] args){ int n = 4; System.out.println(cntEdges(n));}} // This code is contributed by Code_Mech",
"e": 1170,
"s": 805,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the count# of edges in an n-level# perfect binary treedef cntEdges(n) : edges = 2 ** n - 2; return edges; # Driver codeif __name__ == \"__main__\" : n = 4; print(cntEdges(n)); # This code is contributed by AnkitRai01",
"e": 1467,
"s": 1170,
"text": null
},
{
"code": "// C# implementation of the approachusing System;class GFG{ // Function to return the count// of edges in an n-level// perfect binary treestatic int cntEdges(int n){ int edges = (int)Math.Pow(2, n) - 2; return edges;} // Driver codepublic static void Main(String[] args){ int n = 4; Console.Write(cntEdges(n));}} // This code is contributed by Mohit Kumar",
"e": 1840,
"s": 1467,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the count// of edges in an n-level// perfect binary treefunction cntEdges(n){ var edges = Math.pow(2, n) - 2; return edges;} // Driver codevar n = 4;document.write(cntEdges(n)); </script>",
"e": 2111,
"s": 1840,
"text": null
},
{
"code": null,
"e": 2114,
"s": 2111,
"text": "14"
},
{
"code": null,
"e": 2142,
"s": 2116,
"text": "Time Complexity: O(log n)"
},
{
"code": null,
"e": 2164,
"s": 2142,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 2172,
"s": 2164,
"text": "ankthon"
},
{
"code": null,
"e": 2182,
"s": 2172,
"text": "Code_Mech"
},
{
"code": null,
"e": 2197,
"s": 2182,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 2211,
"s": 2197,
"text": "shubham_singh"
},
{
"code": null,
"e": 2220,
"s": 2211,
"text": "noob2000"
},
{
"code": null,
"e": 2236,
"s": 2220,
"text": "subhammahato348"
},
{
"code": null,
"e": 2248,
"s": 2236,
"text": "Binary Tree"
},
{
"code": null,
"e": 2261,
"s": 2248,
"text": "Mathematical"
},
{
"code": null,
"e": 2266,
"s": 2261,
"text": "Tree"
},
{
"code": null,
"e": 2279,
"s": 2266,
"text": "Mathematical"
},
{
"code": null,
"e": 2284,
"s": 2279,
"text": "Tree"
}
] |
Underscore (_) in Python
|
16 Nov, 2021
Following are different places where _ is used in Python:
Single Underscore:In InterpreterAfter a nameBefore a nameDouble Underscore:__leading_double_underscore__before_after__
Single Underscore:In InterpreterAfter a nameBefore a name
In Interpreter
After a name
Before a name
Double Underscore:__leading_double_underscore__before_after__
__leading_double_underscore__before_after__
__leading_double_underscore
__before_after__
Single Underscore
In Interpreter:_ returns the value of last executed expression value in Python Prompt/Interpreter
>>> a = 10>>> b = 10>>> _Traceback (most recent call last):File "<stdin>", line 1, in <module>NameError: name '_' is not defined>>> a+b20>>> _20>>> _ * 240>>> _40>>> _ / 220
For ignoring values:Multiple time we do not want return values at that time to assign those values to Underscore. It used as throwaway variable.
# Ignore a value of specific location/indexfor _ in range(10) print ("Test") # Ignore a value when unpackinga,b,_,_ = my_method(var1)
After a namePython has their by default keywords which we can not use as the variable name. To avoid such conflict between python keyword and variable we use underscore after name
Example:
>>> class MyClass():... def __init__(self):... print ("OWK") >>> def my_defination(var1 = 1, class_ = MyClass):... print (var1)... print (class_) >>> my_defination()1__main__.MyClass>>>
Before a nameLeading Underscore before variable/function/method name indicates to programmer that It is for internal use only, that can be modified whenever class want.
Here name prefix by underscore is treated as non-public. If specify from Import * all the name starts with _ will not import. Python does not specify truly private so this ones can be call directly from other modules if it is specified in __all__, We also call it weak Private
class Prefix:... def __init__(self):... self.public = 10... self._private = 12>>> test = Prefix()>>> test.public10>>> test._private12
Python class_file.py
def public_api(): print ("public api") def _private_api(): print ("private api")
Calling file from Prompt
>>> from class_file import *>>> public_api()public api >>> _private_api()Traceback (most recent call last):File "<stdin>", line 1, in <module>NameError: name '_private_api' is not defined >>> import class_file>>> class_file.public_api()public api>>> class_file._private_api()private api
Double Underscore(__)
__leading_double_underscoreLeading double underscore tell python interpreter to rewrite name in order to avoid conflict in subclass.Interpreter changes variable name with class extension and that feature known as the Mangling.testFile.py
class Myclass(): def __init__(self): self.__variable = 10
Calling from Interpreter
>>> import testFile>>> obj = testFile.Myclass()>>> obj.__variableTraceback (most recent call last):File "", line 1, inAttributeError: Myclass instance has no attribute '__variable'nce has no attribute 'Myclass'>>> obj._Myclass__variable10
In Mangling python interpreter modify variable name with ___. So Multiple time It use as the Private member because another class can not access that variable directly. Main purpose for __ is to use variable/method in class only If you want to use it outside of the class you can make public api
class Myclass(): def __init__(self): self.__variable = 10 def func(self) print (self.__variable)
Calling from Interpreter
>>> import testFile>>> obj = testFile.Myclass()>>> obj.func()10
__BEFORE_AFTER__Name with start with __ and ends with same considers special methods in Python. Python provides these methods to use it as the operator overloading depending on the user.
Python provides this convention to differentiate between the user-defined function with the module’s function
class Myclass(): def __add__(self,a,b): print (a*b)
Calling from Interpreter
>>> import testFile>>> obj = testFile.Myclass()>>> obj.__add__(1,2)2>>> obj.__add__(5,2)10
This article is contributed by Nirmi Shah. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vishalsingh80
caseyfueller
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Introduction To PYTHON
Python OOPs Concepts
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Nov, 2021"
},
{
"code": null,
"e": 112,
"s": 54,
"text": "Following are different places where _ is used in Python:"
},
{
"code": null,
"e": 231,
"s": 112,
"text": "Single Underscore:In InterpreterAfter a nameBefore a nameDouble Underscore:__leading_double_underscore__before_after__"
},
{
"code": null,
"e": 289,
"s": 231,
"text": "Single Underscore:In InterpreterAfter a nameBefore a name"
},
{
"code": null,
"e": 304,
"s": 289,
"text": "In Interpreter"
},
{
"code": null,
"e": 317,
"s": 304,
"text": "After a name"
},
{
"code": null,
"e": 331,
"s": 317,
"text": "Before a name"
},
{
"code": null,
"e": 393,
"s": 331,
"text": "Double Underscore:__leading_double_underscore__before_after__"
},
{
"code": null,
"e": 437,
"s": 393,
"text": "__leading_double_underscore__before_after__"
},
{
"code": null,
"e": 465,
"s": 437,
"text": "__leading_double_underscore"
},
{
"code": null,
"e": 482,
"s": 465,
"text": "__before_after__"
},
{
"code": null,
"e": 500,
"s": 482,
"text": "Single Underscore"
},
{
"code": null,
"e": 598,
"s": 500,
"text": "In Interpreter:_ returns the value of last executed expression value in Python Prompt/Interpreter"
},
{
"code": ">>> a = 10>>> b = 10>>> _Traceback (most recent call last):File \"<stdin>\", line 1, in <module>NameError: name '_' is not defined>>> a+b20>>> _20>>> _ * 240>>> _40>>> _ / 220",
"e": 772,
"s": 598,
"text": null
},
{
"code": null,
"e": 917,
"s": 772,
"text": "For ignoring values:Multiple time we do not want return values at that time to assign those values to Underscore. It used as throwaway variable."
},
{
"code": "# Ignore a value of specific location/indexfor _ in range(10) print (\"Test\") # Ignore a value when unpackinga,b,_,_ = my_method(var1)",
"e": 1055,
"s": 917,
"text": null
},
{
"code": null,
"e": 1235,
"s": 1055,
"text": "After a namePython has their by default keywords which we can not use as the variable name. To avoid such conflict between python keyword and variable we use underscore after name"
},
{
"code": null,
"e": 1244,
"s": 1235,
"text": "Example:"
},
{
"code": ">>> class MyClass():... def __init__(self):... print (\"OWK\") >>> def my_defination(var1 = 1, class_ = MyClass):... print (var1)... print (class_) >>> my_defination()1__main__.MyClass>>>",
"e": 1456,
"s": 1244,
"text": null
},
{
"code": null,
"e": 1625,
"s": 1456,
"text": "Before a nameLeading Underscore before variable/function/method name indicates to programmer that It is for internal use only, that can be modified whenever class want."
},
{
"code": null,
"e": 1902,
"s": 1625,
"text": "Here name prefix by underscore is treated as non-public. If specify from Import * all the name starts with _ will not import. Python does not specify truly private so this ones can be call directly from other modules if it is specified in __all__, We also call it weak Private"
},
{
"code": "class Prefix:... def __init__(self):... self.public = 10... self._private = 12>>> test = Prefix()>>> test.public10>>> test._private12",
"e": 2064,
"s": 1902,
"text": null
},
{
"code": null,
"e": 2085,
"s": 2064,
"text": "Python class_file.py"
},
{
"code": "def public_api(): print (\"public api\") def _private_api(): print (\"private api\")",
"e": 2173,
"s": 2085,
"text": null
},
{
"code": null,
"e": 2198,
"s": 2173,
"text": "Calling file from Prompt"
},
{
"code": ">>> from class_file import *>>> public_api()public api >>> _private_api()Traceback (most recent call last):File \"<stdin>\", line 1, in <module>NameError: name '_private_api' is not defined >>> import class_file>>> class_file.public_api()public api>>> class_file._private_api()private api",
"e": 2487,
"s": 2198,
"text": null
},
{
"code": null,
"e": 2509,
"s": 2487,
"text": "Double Underscore(__)"
},
{
"code": null,
"e": 2747,
"s": 2509,
"text": "__leading_double_underscoreLeading double underscore tell python interpreter to rewrite name in order to avoid conflict in subclass.Interpreter changes variable name with class extension and that feature known as the Mangling.testFile.py"
},
{
"code": "class Myclass(): def __init__(self): self.__variable = 10",
"e": 2815,
"s": 2747,
"text": null
},
{
"code": null,
"e": 2840,
"s": 2815,
"text": "Calling from Interpreter"
},
{
"code": ">>> import testFile>>> obj = testFile.Myclass()>>> obj.__variableTraceback (most recent call last):File \"\", line 1, inAttributeError: Myclass instance has no attribute '__variable'nce has no attribute 'Myclass'>>> obj._Myclass__variable10",
"e": 3079,
"s": 2840,
"text": null
},
{
"code": null,
"e": 3375,
"s": 3079,
"text": "In Mangling python interpreter modify variable name with ___. So Multiple time It use as the Private member because another class can not access that variable directly. Main purpose for __ is to use variable/method in class only If you want to use it outside of the class you can make public api"
},
{
"code": "class Myclass(): def __init__(self): self.__variable = 10 def func(self) print (self.__variable)",
"e": 3492,
"s": 3375,
"text": null
},
{
"code": null,
"e": 3517,
"s": 3492,
"text": "Calling from Interpreter"
},
{
"code": ">>> import testFile>>> obj = testFile.Myclass()>>> obj.func()10",
"e": 3581,
"s": 3517,
"text": null
},
{
"code": null,
"e": 3768,
"s": 3581,
"text": "__BEFORE_AFTER__Name with start with __ and ends with same considers special methods in Python. Python provides these methods to use it as the operator overloading depending on the user."
},
{
"code": null,
"e": 3878,
"s": 3768,
"text": "Python provides this convention to differentiate between the user-defined function with the module’s function"
},
{
"code": "class Myclass(): def __add__(self,a,b): print (a*b)",
"e": 3940,
"s": 3878,
"text": null
},
{
"code": null,
"e": 3965,
"s": 3940,
"text": "Calling from Interpreter"
},
{
"code": ">>> import testFile>>> obj = testFile.Myclass()>>> obj.__add__(1,2)2>>> obj.__add__(5,2)10",
"e": 4056,
"s": 3965,
"text": null
},
{
"code": null,
"e": 4350,
"s": 4056,
"text": "This article is contributed by Nirmi Shah. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 4475,
"s": 4350,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4489,
"s": 4475,
"text": "vishalsingh80"
},
{
"code": null,
"e": 4502,
"s": 4489,
"text": "caseyfueller"
},
{
"code": null,
"e": 4509,
"s": 4502,
"text": "Python"
},
{
"code": null,
"e": 4607,
"s": 4509,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4649,
"s": 4607,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4671,
"s": 4649,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4706,
"s": 4671,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 4732,
"s": 4706,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4764,
"s": 4732,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4793,
"s": 4764,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4823,
"s": 4793,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 4850,
"s": 4823,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4873,
"s": 4850,
"text": "Introduction To PYTHON"
}
] |
PostgreSQL - LIKE Clause
|
The PostgreSQL LIKE operator is used to match text values against a pattern using wildcards. If the search expression can be matched to the pattern expression, the LIKE operator will return true, which is 1.
There are two wildcards used in conjunction with the LIKE operator −
The percent sign (%)
The underscore (_)
The percent sign represents zero, one, or multiple numbers or characters. The underscore represents a single number or character. These symbols can be used in combinations.
If either of these two signs is not used in conjunction with the LIKE clause, then the LIKE acts like the equals operator.
The basic syntax of % and _ is as follows −
SELECT FROM table_name
WHERE column LIKE 'XXXX%'
or
SELECT FROM table_name
WHERE column LIKE '%XXXX%'
or
SELECT FROM table_name
WHERE column LIKE 'XXXX_'
or
SELECT FROM table_name
WHERE column LIKE '_XXXX'
or
SELECT FROM table_name
WHERE column LIKE '_XXXX_'
You can combine N number of conditions using AND or OR operators. Here XXXX could be any numeric or string value.
Here are number of examples showing WHERE part having different LIKE clause with '%' and '_' operators −
WHERE SALARY::text LIKE '200%'
Finds any values that start with 200
WHERE SALARY::text LIKE '%200%'
Finds any values that have 200 in any position
WHERE SALARY::text LIKE '_00%'
Finds any values that have 00 in the second and third positions
WHERE SALARY::text LIKE '2_%_%'
Finds any values that start with 2 and are at least 3 characters in length
WHERE SALARY::text LIKE '%2'
Finds any values that end with 2
WHERE SALARY::text LIKE '_2%3'
Finds any values that have 2 in the second position and end with a 3
WHERE SALARY::text LIKE '2___3'
Finds any values in a five-digit number that start with 2 and end with 3
Let us take a real example, consider the table COMPANY, having records as follows −
# select * from COMPANY;
id | name | age | address | salary
----+-------+-----+-----------+--------
1 | Paul | 32 | California| 20000
2 | Allen | 25 | Texas | 15000
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
6 | Kim | 22 | South-Hall| 45000
7 | James | 24 | Houston | 10000
(7 rows)
The following is an example, which would display all the records from COMPANY table where AGE starts with 2 −
testdb=# SELECT * FROM COMPANY WHERE AGE::text LIKE '2%';
This would produce the following result −
id | name | age | address | salary
----+-------+-----+-------------+--------
2 | Allen | 25 | Texas | 15000
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
6 | Kim | 22 | South-Hall | 45000
7 | James | 24 | Houston | 10000
8 | Paul | 24 | Houston | 20000
(7 rows)
The following is an example, which would display all the records from COMPANY table where ADDRESS will have a hyphen (-) inside the text −
testdb=# SELECT * FROM COMPANY WHERE ADDRESS LIKE '%-%';
This would produce the following result −
id | name | age | address | salary
----+------+-----+-------------------------------------------+--------
4 | Mark | 25 | Rich-Mond | 65000
6 | Kim | 22 | South-Hall | 45000
|
[
{
"code": null,
"e": 3167,
"s": 2959,
"text": "The PostgreSQL LIKE operator is used to match text values against a pattern using wildcards. If the search expression can be matched to the pattern expression, the LIKE operator will return true, which is 1."
},
{
"code": null,
"e": 3236,
"s": 3167,
"text": "There are two wildcards used in conjunction with the LIKE operator −"
},
{
"code": null,
"e": 3257,
"s": 3236,
"text": "The percent sign (%)"
},
{
"code": null,
"e": 3276,
"s": 3257,
"text": "The underscore (_)"
},
{
"code": null,
"e": 3449,
"s": 3276,
"text": "The percent sign represents zero, one, or multiple numbers or characters. The underscore represents a single number or character. These symbols can be used in combinations."
},
{
"code": null,
"e": 3572,
"s": 3449,
"text": "If either of these two signs is not used in conjunction with the LIKE clause, then the LIKE acts like the equals operator."
},
{
"code": null,
"e": 3616,
"s": 3572,
"text": "The basic syntax of % and _ is as follows −"
},
{
"code": null,
"e": 3884,
"s": 3616,
"text": "SELECT FROM table_name\nWHERE column LIKE 'XXXX%'\n\nor\n\nSELECT FROM table_name\nWHERE column LIKE '%XXXX%'\n\nor\n\nSELECT FROM table_name\nWHERE column LIKE 'XXXX_'\n\nor\n\nSELECT FROM table_name\nWHERE column LIKE '_XXXX'\n\nor\n\nSELECT FROM table_name\nWHERE column LIKE '_XXXX_'\n"
},
{
"code": null,
"e": 3998,
"s": 3884,
"text": "You can combine N number of conditions using AND or OR operators. Here XXXX could be any numeric or string value."
},
{
"code": null,
"e": 4103,
"s": 3998,
"text": "Here are number of examples showing WHERE part having different LIKE clause with '%' and '_' operators −"
},
{
"code": null,
"e": 4134,
"s": 4103,
"text": "WHERE SALARY::text LIKE '200%'"
},
{
"code": null,
"e": 4171,
"s": 4134,
"text": "Finds any values that start with 200"
},
{
"code": null,
"e": 4203,
"s": 4171,
"text": "WHERE SALARY::text LIKE '%200%'"
},
{
"code": null,
"e": 4250,
"s": 4203,
"text": "Finds any values that have 200 in any position"
},
{
"code": null,
"e": 4281,
"s": 4250,
"text": "WHERE SALARY::text LIKE '_00%'"
},
{
"code": null,
"e": 4345,
"s": 4281,
"text": "Finds any values that have 00 in the second and third positions"
},
{
"code": null,
"e": 4377,
"s": 4345,
"text": "WHERE SALARY::text LIKE '2_%_%'"
},
{
"code": null,
"e": 4452,
"s": 4377,
"text": "Finds any values that start with 2 and are at least 3 characters in length"
},
{
"code": null,
"e": 4481,
"s": 4452,
"text": "WHERE SALARY::text LIKE '%2'"
},
{
"code": null,
"e": 4514,
"s": 4481,
"text": "Finds any values that end with 2"
},
{
"code": null,
"e": 4545,
"s": 4514,
"text": "WHERE SALARY::text LIKE '_2%3'"
},
{
"code": null,
"e": 4614,
"s": 4545,
"text": "Finds any values that have 2 in the second position and end with a 3"
},
{
"code": null,
"e": 4646,
"s": 4614,
"text": "WHERE SALARY::text LIKE '2___3'"
},
{
"code": null,
"e": 4719,
"s": 4646,
"text": "Finds any values in a five-digit number that start with 2 and end with 3"
},
{
"code": null,
"e": 4803,
"s": 4719,
"text": "Let us take a real example, consider the table COMPANY, having records as follows −"
},
{
"code": null,
"e": 5189,
"s": 4803,
"text": "# select * from COMPANY;\n id | name | age | address | salary\n----+-------+-----+-----------+--------\n 1 | Paul | 32 | California| 20000\n 2 | Allen | 25 | Texas | 15000\n 3 | Teddy | 23 | Norway | 20000\n 4 | Mark | 25 | Rich-Mond | 65000\n 5 | David | 27 | Texas | 85000\n 6 | Kim | 22 | South-Hall| 45000\n 7 | James | 24 | Houston | 10000\n(7 rows)"
},
{
"code": null,
"e": 5299,
"s": 5189,
"text": "The following is an example, which would display all the records from COMPANY table where AGE starts with 2 −"
},
{
"code": null,
"e": 5357,
"s": 5299,
"text": "testdb=# SELECT * FROM COMPANY WHERE AGE::text LIKE '2%';"
},
{
"code": null,
"e": 5399,
"s": 5357,
"text": "This would produce the following result −"
},
{
"code": null,
"e": 5779,
"s": 5399,
"text": " id | name | age | address | salary\n----+-------+-----+-------------+--------\n 2 | Allen | 25 | Texas | 15000\n 3 | Teddy | 23 | Norway | 20000\n 4 | Mark | 25 | Rich-Mond | 65000\n 5 | David | 27 | Texas | 85000\n 6 | Kim | 22 | South-Hall | 45000\n 7 | James | 24 | Houston | 10000\n 8 | Paul | 24 | Houston | 20000\n(7 rows)\n"
},
{
"code": null,
"e": 5918,
"s": 5779,
"text": "The following is an example, which would display all the records from COMPANY table where ADDRESS will have a hyphen (-) inside the text −"
},
{
"code": null,
"e": 5976,
"s": 5918,
"text": "testdb=# SELECT * FROM COMPANY WHERE ADDRESS LIKE '%-%';"
},
{
"code": null,
"e": 6018,
"s": 5976,
"text": "This would produce the following result −"
}
] |
ReactJS UI Ant Design InputNumber Component
|
21 May, 2021
Ant Design Library has this component pre-built, and it is very easy to integrate as well. InputNumber Component allows the user to enter a number within a certain range with the help of a keyboard or mouse. We can use the following approach in ReactJS to use the Ant Design InputNumber Component.
InputNumber Methods:
blur(): This method is used to remove the focus from the element.
focus(): This method is used to get the focus on the element.
InputNumber Props:
autoFocus: It is used to get the focus when the component is mounted.
bordered: It is used to specify whether it has border style or not.
decimalSeparator: It is used to indicate the decimal separator.
defaultValue: It is used to specify the initial value.
disabled: It is used to disable the input.
formatter: It is used to specify the format of the value presented.
keyboard: It is used to enable keyboard behavior.
max: It is used to denote the maximum value.
min: It is used to denote the minimum value.
parser: It is used to specify the extracted value from formatter.
precision: It is used to denote the precision of input value.
readOnly: It is used to make the input read-only.
size: It is used to indicate the height of the input box.
step: It is used to denote the number to which the current value is decreased or increased.
stringMode: It is used to set value as string to support decimals of high precision.
value: It is used to denote the current value.
onChange: It is the callback function which is triggered when the value is changed.
onPressEnter: It is the callback function which is triggered when the user press the enter key.
onStep: It is the callback function which is triggered when the user clicks up or down buttons.
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 required module using the following command:npm install antd
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install antd
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, { useState } from 'react'import "antd/dist/antd.css";import { InputNumber } from 'antd'; export default function App() { // Our state to hold current value of input const [currentValue, setCurrentValue] = useState(0) return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design InputNumber Component</h4> <InputNumber min={0} defaultValue={0} onChange={(value) => { setCurrentValue(value) }} /> <br /> Current Entered Value : {currentValue} </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://ant.design/components/input-number/
ReactJS-Ant Design
JavaScript
ReactJS
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
How to append HTML code to a div using JavaScript ?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
Axios in React: A Guide for Beginners
ReactJS Functional Components
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 326,
"s": 28,
"text": "Ant Design Library has this component pre-built, and it is very easy to integrate as well. InputNumber Component allows the user to enter a number within a certain range with the help of a keyboard or mouse. We can use the following approach in ReactJS to use the Ant Design InputNumber Component."
},
{
"code": null,
"e": 347,
"s": 326,
"text": "InputNumber Methods:"
},
{
"code": null,
"e": 413,
"s": 347,
"text": "blur(): This method is used to remove the focus from the element."
},
{
"code": null,
"e": 475,
"s": 413,
"text": "focus(): This method is used to get the focus on the element."
},
{
"code": null,
"e": 494,
"s": 475,
"text": "InputNumber Props:"
},
{
"code": null,
"e": 564,
"s": 494,
"text": "autoFocus: It is used to get the focus when the component is mounted."
},
{
"code": null,
"e": 632,
"s": 564,
"text": "bordered: It is used to specify whether it has border style or not."
},
{
"code": null,
"e": 696,
"s": 632,
"text": "decimalSeparator: It is used to indicate the decimal separator."
},
{
"code": null,
"e": 751,
"s": 696,
"text": "defaultValue: It is used to specify the initial value."
},
{
"code": null,
"e": 794,
"s": 751,
"text": "disabled: It is used to disable the input."
},
{
"code": null,
"e": 862,
"s": 794,
"text": "formatter: It is used to specify the format of the value presented."
},
{
"code": null,
"e": 912,
"s": 862,
"text": "keyboard: It is used to enable keyboard behavior."
},
{
"code": null,
"e": 957,
"s": 912,
"text": "max: It is used to denote the maximum value."
},
{
"code": null,
"e": 1002,
"s": 957,
"text": "min: It is used to denote the minimum value."
},
{
"code": null,
"e": 1068,
"s": 1002,
"text": "parser: It is used to specify the extracted value from formatter."
},
{
"code": null,
"e": 1130,
"s": 1068,
"text": "precision: It is used to denote the precision of input value."
},
{
"code": null,
"e": 1180,
"s": 1130,
"text": "readOnly: It is used to make the input read-only."
},
{
"code": null,
"e": 1238,
"s": 1180,
"text": "size: It is used to indicate the height of the input box."
},
{
"code": null,
"e": 1330,
"s": 1238,
"text": "step: It is used to denote the number to which the current value is decreased or increased."
},
{
"code": null,
"e": 1415,
"s": 1330,
"text": "stringMode: It is used to set value as string to support decimals of high precision."
},
{
"code": null,
"e": 1462,
"s": 1415,
"text": "value: It is used to denote the current value."
},
{
"code": null,
"e": 1546,
"s": 1462,
"text": "onChange: It is the callback function which is triggered when the value is changed."
},
{
"code": null,
"e": 1642,
"s": 1546,
"text": "onPressEnter: It is the callback function which is triggered when the user press the enter key."
},
{
"code": null,
"e": 1738,
"s": 1642,
"text": "onStep: It is the callback function which is triggered when the user clicks up or down buttons."
},
{
"code": null,
"e": 1788,
"s": 1738,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 1883,
"s": 1788,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 1947,
"s": 1883,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 1979,
"s": 1947,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 2092,
"s": 1979,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 2192,
"s": 2092,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 2206,
"s": 2192,
"text": "cd foldername"
},
{
"code": null,
"e": 2327,
"s": 2206,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd"
},
{
"code": null,
"e": 2432,
"s": 2327,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 2449,
"s": 2432,
"text": "npm install antd"
},
{
"code": null,
"e": 2501,
"s": 2449,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 2519,
"s": 2501,
"text": "Project Structure"
},
{
"code": null,
"e": 2649,
"s": 2519,
"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": 2656,
"s": 2649,
"text": "App.js"
},
{
"code": "import React, { useState } from 'react'import \"antd/dist/antd.css\";import { InputNumber } from 'antd'; export default function App() { // Our state to hold current value of input const [currentValue, setCurrentValue] = useState(0) return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design InputNumber Component</h4> <InputNumber min={0} defaultValue={0} onChange={(value) => { setCurrentValue(value) }} /> <br /> Current Entered Value : {currentValue} </div> );}",
"e": 3206,
"s": 2656,
"text": null
},
{
"code": null,
"e": 3319,
"s": 3206,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 3329,
"s": 3319,
"text": "npm start"
},
{
"code": null,
"e": 3428,
"s": 3329,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 3483,
"s": 3428,
"text": "Reference: https://ant.design/components/input-number/"
},
{
"code": null,
"e": 3502,
"s": 3483,
"text": "ReactJS-Ant Design"
},
{
"code": null,
"e": 3513,
"s": 3502,
"text": "JavaScript"
},
{
"code": null,
"e": 3521,
"s": 3513,
"text": "ReactJS"
},
{
"code": null,
"e": 3538,
"s": 3521,
"text": "Web Technologies"
},
{
"code": null,
"e": 3636,
"s": 3538,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3697,
"s": 3636,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3769,
"s": 3697,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3809,
"s": 3769,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3862,
"s": 3809,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 3914,
"s": 3862,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 3957,
"s": 3914,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 4002,
"s": 3957,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 4040,
"s": 4002,
"text": "Axios in React: A Guide for Beginners"
}
] |
Program to express a positive integer number in words in C++
|
Suppose we are given a positive integer number. We have to spell the number in words; like if a number "56" is given as input the output will be "Fifty-Six". The range of conversion is up to a billion.
So, if the input is like input = 5678, then the output will be Five Thousand Six Hundred Seventy-Eight.
To solve this, we will follow these steps −
Define an array ‘numbers’ that contain pairs such as − {{"Billion", 1000000000},{"Million", 1000000},{"Thousand", 1000},{"Hundred", 100},{"Ninety", 90},{"Eighty", 80},{"Seventy", 70},{"Sixty", 60},{"Fifty", 50},{"Forty", 40},{"Thirty", 30},{"Twenty", 20},{"Nineteen", 19},{"Eighteen", 18},{"Seventeen", 17},{"Sixteen", 16},{"Fifteen", 15},{"Fourteen", 14},{"Thirteen", 13},{"Twelve", 12},{"Eleven", 11},{"Ten", 10},{"Nine", 9},{"Eight", 8},{"Seven", 7},{"Six", 6},{"Five", 5},{"Four", 4},{"Three", 3},{"Two", 2},{"One", 1}}
{"Million", 1000000},
{"Thousand", 1000},
{"Hundred", 100},
{"Ninety", 90},
{"Eighty", 80},
{"Seventy", 70},
{"Sixty", 60},
{"Fifty", 50},
{"Forty", 40},
{"Thirty", 30},
{"Twenty", 20},
{"Nineteen", 19},
{"Eighteen", 18},
{"Seventeen", 17},
{"Sixteen", 16},
{"Fifteen", 15},
{"Fourteen", 14},
{"Thirteen", 13},
{"Twelve", 12},
{"Eleven", 11},
{"Ten", 10},
{"Nine", 9},
{"Eight", 8},
{"Seven", 7},
{"Six", 6},
{"Five", 5},
{"Four", 4},
{"Three", 3},
{"Two", 2},
{"One", 1}}
Define a function solve(). This takes input.if input is same as 0, then −return "Zero"for each num in array numbers, doif second value of num <= input, then −if second value of num >= 100, then −result := solve(input / second value of num)if input > (input / second value of num) * second value of m, then −result := result + " " + solve(input - (input / second value of num))otherwise,result := first value of num + ((if input > second value of num , then: " " + solve(input - second value of num), otherwise: " "))Come out from the loopreturn result
if input is same as 0, then −return "Zero"
return "Zero"
for each num in array numbers, doif second value of num <= input, then −if second value of num >= 100, then −result := solve(input / second value of num)if input > (input / second value of num) * second value of m, then −result := result + " " + solve(input - (input / second value of num))otherwise,result := first value of num + ((if input > second value of num , then: " " + solve(input - second value of num), otherwise: " "))Come out from the loop
if second value of num <= input, then −if second value of num >= 100, then −result := solve(input / second value of num)if input > (input / second value of num) * second value of m, then −result := result + " " + solve(input - (input / second value of num))otherwise,result := first value of num + ((if input > second value of num , then: " " + solve(input - second value of num), otherwise: " "))Come out from the loop
if second value of num >= 100, then −result := solve(input / second value of num)if input > (input / second value of num) * second value of m, then −result := result + " " + solve(input - (input / second value of num))
result := solve(input / second value of num)
if input > (input / second value of num) * second value of m, then −result := result + " " + solve(input - (input / second value of num))
result := result + " " + solve(input - (input / second value of num))
otherwise,result := first value of num + ((if input > second value of num , then: " " + solve(input - second value of num), otherwise: " "))
result := first value of num + ((if input > second value of num , then: " " + solve(input - second value of num), otherwise: " "))
Come out from the loop
return result
solve(input)
Let us see the following implementation to get better understanding −
#include<bits/stdc++.h>
using namespace std;
vector<pair<string, int>> numbers{{"Billion", 1000000000},
{"Million", 1000000},
{"Thousand", 1000},
{"Hundred", 100},
{"Ninety", 90},
{"Eighty", 80},
{"Seventy", 70},
{"Sixty", 60},
{"Fifty", 50},
{"Forty", 40},
{"Thirty", 30},
{"Twenty", 20},
{"Nineteen", 19},
{"Eighteen", 18},
{"Seventeen", 17},
{"Sixteen", 16},
{"Fifteen", 15},
{"Fourteen", 14},
{"Thirteen", 13},
{"Twelve", 12},
{"Eleven", 11},
{"Ten", 10},
{"Nine", 9},
{"Eight", 8},
{"Seven", 7},
{"Six", 6},
{"Five", 5},
{"Four", 4},
{"Three", 3},
{"Two", 2},
{"One", 1}};
string solve(int input) {
if (input == 0) return "Zero";
string result;
for (auto& num : numbers) {
if (num.second <= input) {
if (num.second >= 100) {
result = solve(input / num.second) + " " + num.first;
if (input > (input / num.second) * num.second)
result += " " + solve(input - (input / num.second) * num.second);
} else {
result = num.first + (input > num.second ? " " + solve(input - num.second) : "");
}
break;
}
}
return result;
}
int main() {
cout<< solve(5678) <<endl;
return 0;
}
5678
Five Thousand Six Hundred Seventy Eight
|
[
{
"code": null,
"e": 1389,
"s": 1187,
"text": "Suppose we are given a positive integer number. We have to spell the number in words; like if a number \"56\" is given as input the output will be \"Fifty-Six\". The range of conversion is up to a billion."
},
{
"code": null,
"e": 1493,
"s": 1389,
"text": "So, if the input is like input = 5678, then the output will be Five Thousand Six Hundred Seventy-Eight."
},
{
"code": null,
"e": 1537,
"s": 1493,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 2061,
"s": 1537,
"text": "Define an array ‘numbers’ that contain pairs such as − {{\"Billion\", 1000000000},{\"Million\", 1000000},{\"Thousand\", 1000},{\"Hundred\", 100},{\"Ninety\", 90},{\"Eighty\", 80},{\"Seventy\", 70},{\"Sixty\", 60},{\"Fifty\", 50},{\"Forty\", 40},{\"Thirty\", 30},{\"Twenty\", 20},{\"Nineteen\", 19},{\"Eighteen\", 18},{\"Seventeen\", 17},{\"Sixteen\", 16},{\"Fifteen\", 15},{\"Fourteen\", 14},{\"Thirteen\", 13},{\"Twelve\", 12},{\"Eleven\", 11},{\"Ten\", 10},{\"Nine\", 9},{\"Eight\", 8},{\"Seven\", 7},{\"Six\", 6},{\"Five\", 5},{\"Four\", 4},{\"Three\", 3},{\"Two\", 2},{\"One\", 1}}"
},
{
"code": null,
"e": 2083,
"s": 2061,
"text": "{\"Million\", 1000000},"
},
{
"code": null,
"e": 2103,
"s": 2083,
"text": "{\"Thousand\", 1000},"
},
{
"code": null,
"e": 2121,
"s": 2103,
"text": "{\"Hundred\", 100},"
},
{
"code": null,
"e": 2137,
"s": 2121,
"text": "{\"Ninety\", 90},"
},
{
"code": null,
"e": 2153,
"s": 2137,
"text": "{\"Eighty\", 80},"
},
{
"code": null,
"e": 2170,
"s": 2153,
"text": "{\"Seventy\", 70},"
},
{
"code": null,
"e": 2185,
"s": 2170,
"text": "{\"Sixty\", 60},"
},
{
"code": null,
"e": 2200,
"s": 2185,
"text": "{\"Fifty\", 50},"
},
{
"code": null,
"e": 2215,
"s": 2200,
"text": "{\"Forty\", 40},"
},
{
"code": null,
"e": 2231,
"s": 2215,
"text": "{\"Thirty\", 30},"
},
{
"code": null,
"e": 2247,
"s": 2231,
"text": "{\"Twenty\", 20},"
},
{
"code": null,
"e": 2265,
"s": 2247,
"text": "{\"Nineteen\", 19},"
},
{
"code": null,
"e": 2283,
"s": 2265,
"text": "{\"Eighteen\", 18},"
},
{
"code": null,
"e": 2302,
"s": 2283,
"text": "{\"Seventeen\", 17},"
},
{
"code": null,
"e": 2319,
"s": 2302,
"text": "{\"Sixteen\", 16},"
},
{
"code": null,
"e": 2336,
"s": 2319,
"text": "{\"Fifteen\", 15},"
},
{
"code": null,
"e": 2354,
"s": 2336,
"text": "{\"Fourteen\", 14},"
},
{
"code": null,
"e": 2372,
"s": 2354,
"text": "{\"Thirteen\", 13},"
},
{
"code": null,
"e": 2388,
"s": 2372,
"text": "{\"Twelve\", 12},"
},
{
"code": null,
"e": 2404,
"s": 2388,
"text": "{\"Eleven\", 11},"
},
{
"code": null,
"e": 2417,
"s": 2404,
"text": "{\"Ten\", 10},"
},
{
"code": null,
"e": 2430,
"s": 2417,
"text": "{\"Nine\", 9},"
},
{
"code": null,
"e": 2444,
"s": 2430,
"text": "{\"Eight\", 8},"
},
{
"code": null,
"e": 2458,
"s": 2444,
"text": "{\"Seven\", 7},"
},
{
"code": null,
"e": 2470,
"s": 2458,
"text": "{\"Six\", 6},"
},
{
"code": null,
"e": 2483,
"s": 2470,
"text": "{\"Five\", 5},"
},
{
"code": null,
"e": 2496,
"s": 2483,
"text": "{\"Four\", 4},"
},
{
"code": null,
"e": 2510,
"s": 2496,
"text": "{\"Three\", 3},"
},
{
"code": null,
"e": 2522,
"s": 2510,
"text": "{\"Two\", 2},"
},
{
"code": null,
"e": 2534,
"s": 2522,
"text": "{\"One\", 1}}"
},
{
"code": null,
"e": 3086,
"s": 2534,
"text": "Define a function solve(). This takes input.if input is same as 0, then −return \"Zero\"for each num in array numbers, doif second value of num <= input, then −if second value of num >= 100, then −result := solve(input / second value of num)if input > (input / second value of num) * second value of m, then −result := result + \" \" + solve(input - (input / second value of num))otherwise,result := first value of num + ((if input > second value of num , then: \" \" + solve(input - second value of num), otherwise: \" \"))Come out from the loopreturn result"
},
{
"code": null,
"e": 3129,
"s": 3086,
"text": "if input is same as 0, then −return \"Zero\""
},
{
"code": null,
"e": 3143,
"s": 3129,
"text": "return \"Zero\""
},
{
"code": null,
"e": 3596,
"s": 3143,
"text": "for each num in array numbers, doif second value of num <= input, then −if second value of num >= 100, then −result := solve(input / second value of num)if input > (input / second value of num) * second value of m, then −result := result + \" \" + solve(input - (input / second value of num))otherwise,result := first value of num + ((if input > second value of num , then: \" \" + solve(input - second value of num), otherwise: \" \"))Come out from the loop"
},
{
"code": null,
"e": 4016,
"s": 3596,
"text": "if second value of num <= input, then −if second value of num >= 100, then −result := solve(input / second value of num)if input > (input / second value of num) * second value of m, then −result := result + \" \" + solve(input - (input / second value of num))otherwise,result := first value of num + ((if input > second value of num , then: \" \" + solve(input - second value of num), otherwise: \" \"))Come out from the loop"
},
{
"code": null,
"e": 4235,
"s": 4016,
"text": "if second value of num >= 100, then −result := solve(input / second value of num)if input > (input / second value of num) * second value of m, then −result := result + \" \" + solve(input - (input / second value of num))"
},
{
"code": null,
"e": 4280,
"s": 4235,
"text": "result := solve(input / second value of num)"
},
{
"code": null,
"e": 4418,
"s": 4280,
"text": "if input > (input / second value of num) * second value of m, then −result := result + \" \" + solve(input - (input / second value of num))"
},
{
"code": null,
"e": 4488,
"s": 4418,
"text": "result := result + \" \" + solve(input - (input / second value of num))"
},
{
"code": null,
"e": 4629,
"s": 4488,
"text": "otherwise,result := first value of num + ((if input > second value of num , then: \" \" + solve(input - second value of num), otherwise: \" \"))"
},
{
"code": null,
"e": 4760,
"s": 4629,
"text": "result := first value of num + ((if input > second value of num , then: \" \" + solve(input - second value of num), otherwise: \" \"))"
},
{
"code": null,
"e": 4783,
"s": 4760,
"text": "Come out from the loop"
},
{
"code": null,
"e": 4797,
"s": 4783,
"text": "return result"
},
{
"code": null,
"e": 4810,
"s": 4797,
"text": "solve(input)"
},
{
"code": null,
"e": 4880,
"s": 4810,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 6163,
"s": 4880,
"text": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nvector<pair<string, int>> numbers{{\"Billion\", 1000000000},\n {\"Million\", 1000000},\n {\"Thousand\", 1000},\n {\"Hundred\", 100},\n {\"Ninety\", 90},\n {\"Eighty\", 80},\n {\"Seventy\", 70},\n {\"Sixty\", 60},\n {\"Fifty\", 50},\n {\"Forty\", 40},\n {\"Thirty\", 30},\n {\"Twenty\", 20},\n {\"Nineteen\", 19},\n {\"Eighteen\", 18},\n {\"Seventeen\", 17},\n {\"Sixteen\", 16},\n {\"Fifteen\", 15},\n {\"Fourteen\", 14},\n {\"Thirteen\", 13},\n {\"Twelve\", 12},\n {\"Eleven\", 11},\n {\"Ten\", 10},\n {\"Nine\", 9},\n {\"Eight\", 8},\n {\"Seven\", 7},\n {\"Six\", 6},\n {\"Five\", 5},\n {\"Four\", 4},\n {\"Three\", 3},\n {\"Two\", 2},\n {\"One\", 1}};\nstring solve(int input) {\n if (input == 0) return \"Zero\";\n string result;\n for (auto& num : numbers) {\n if (num.second <= input) {\n if (num.second >= 100) {\n result = solve(input / num.second) + \" \" + num.first;\n if (input > (input / num.second) * num.second)\n result += \" \" + solve(input - (input / num.second) * num.second);\n } else {\n result = num.first + (input > num.second ? \" \" + solve(input - num.second) : \"\");\n }\n break;\n }\n }\n return result;\n}\n\nint main() {\n cout<< solve(5678) <<endl;\n return 0;\n}"
},
{
"code": null,
"e": 6168,
"s": 6163,
"text": "5678"
},
{
"code": null,
"e": 6208,
"s": 6168,
"text": "Five Thousand Six Hundred Seventy Eight"
}
] |
PHP | Unset() vs Unlink() Function
|
26 May, 2021
Both the function are used to do some undo operations but used in different situations cause both acts differently. The unlink() function is used when you want to delete the files completely. The unset() Function is used when you want to make that file empty.Unlink() function: The unlink() function is an inbuilt function in PHP which is used to delete a file. The filename of the file which has to be deleted is sent as a parameter and the function returns True on success and False on failure. The unlink() function in PHP accepts two-parameter.Syntax:
unlink( filename, context )
Parameters: This function accepts two parameters as mentioned above and described below:
filename: It is a mandatory parameter which specifies the filename of the file which has to be deleted.
context: It is an optional parameter which specifies the context of the file handle which can be used to modify the nature of the stream.
Return Value: It returns True on success and False on failure.Suppose there is a file named ‘gfg.txt’Example:
php
<?php // PHP program to delete a file named gfg.txt// using unlink() function $file_pointer = fopen('gfg.txt'); // Writing on a file named gfg.txtfwrite($file_pointer, 'A computer science portal for geeks!');fclose($file_pointer); // Using unlink() function to delete a fileunlink('gfg.txt'); ?>
Output:
1
Note: If we don’t have permissions to the file “gfg.txt”, the unlink() function generates an E_WARNING level error on failure.Unset() function: The Unset() function is an inbuilt function in PHP which is used to remove the content from the file by emptying it. It means that the function clears the content of a file rather deleting it. The unset() function not only clears the file content but also is used to unset a variable, thereby making it empty.Syntax:
unset( $variable )
Parameter: This function accepts single parameter variable which is required. It is the variable which is needed to be unset.Return Value: This function does not return any value.Example:
php
<?php $var = "hello"; // Change would be reflected outside the function function unset_value() { unset($GLOBALS['var']);} unset_value();echo $var;?>
Output:
No output
Difference between unlink() and unset() function:
Akanksha_Rai
Divik Shrivastava
PHP-function
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to get parameters from a URL string in PHP?
Download file from URL using PHP
Split a comma delimited string into an array in PHP
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to get parameters from a URL string in PHP?
Split a comma delimited string into an array in PHP
How to pass JavaScript variables to PHP ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 May, 2021"
},
{
"code": null,
"e": 586,
"s": 28,
"text": "Both the function are used to do some undo operations but used in different situations cause both acts differently. The unlink() function is used when you want to delete the files completely. The unset() Function is used when you want to make that file empty.Unlink() function: The unlink() function is an inbuilt function in PHP which is used to delete a file. The filename of the file which has to be deleted is sent as a parameter and the function returns True on success and False on failure. The unlink() function in PHP accepts two-parameter.Syntax: "
},
{
"code": null,
"e": 614,
"s": 586,
"text": "unlink( filename, context )"
},
{
"code": null,
"e": 705,
"s": 614,
"text": "Parameters: This function accepts two parameters as mentioned above and described below: "
},
{
"code": null,
"e": 809,
"s": 705,
"text": "filename: It is a mandatory parameter which specifies the filename of the file which has to be deleted."
},
{
"code": null,
"e": 947,
"s": 809,
"text": "context: It is an optional parameter which specifies the context of the file handle which can be used to modify the nature of the stream."
},
{
"code": null,
"e": 1059,
"s": 947,
"text": "Return Value: It returns True on success and False on failure.Suppose there is a file named ‘gfg.txt’Example: "
},
{
"code": null,
"e": 1063,
"s": 1059,
"text": "php"
},
{
"code": "<?php // PHP program to delete a file named gfg.txt// using unlink() function $file_pointer = fopen('gfg.txt'); // Writing on a file named gfg.txtfwrite($file_pointer, 'A computer science portal for geeks!');fclose($file_pointer); // Using unlink() function to delete a fileunlink('gfg.txt'); ?>",
"e": 1359,
"s": 1063,
"text": null
},
{
"code": null,
"e": 1369,
"s": 1359,
"text": "Output: "
},
{
"code": null,
"e": 1371,
"s": 1369,
"text": "1"
},
{
"code": null,
"e": 1834,
"s": 1371,
"text": "Note: If we don’t have permissions to the file “gfg.txt”, the unlink() function generates an E_WARNING level error on failure.Unset() function: The Unset() function is an inbuilt function in PHP which is used to remove the content from the file by emptying it. It means that the function clears the content of a file rather deleting it. The unset() function not only clears the file content but also is used to unset a variable, thereby making it empty.Syntax: "
},
{
"code": null,
"e": 1853,
"s": 1834,
"text": "unset( $variable )"
},
{
"code": null,
"e": 2043,
"s": 1853,
"text": "Parameter: This function accepts single parameter variable which is required. It is the variable which is needed to be unset.Return Value: This function does not return any value.Example: "
},
{
"code": null,
"e": 2047,
"s": 2043,
"text": "php"
},
{
"code": "<?php $var = \"hello\"; // Change would be reflected outside the function function unset_value() { unset($GLOBALS['var']);} unset_value();echo $var;?>",
"e": 2220,
"s": 2047,
"text": null
},
{
"code": null,
"e": 2230,
"s": 2220,
"text": "Output: "
},
{
"code": null,
"e": 2240,
"s": 2230,
"text": "No output"
},
{
"code": null,
"e": 2292,
"s": 2240,
"text": "Difference between unlink() and unset() function: "
},
{
"code": null,
"e": 2307,
"s": 2294,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 2325,
"s": 2307,
"text": "Divik Shrivastava"
},
{
"code": null,
"e": 2338,
"s": 2325,
"text": "PHP-function"
},
{
"code": null,
"e": 2342,
"s": 2338,
"text": "PHP"
},
{
"code": null,
"e": 2355,
"s": 2342,
"text": "PHP Programs"
},
{
"code": null,
"e": 2372,
"s": 2355,
"text": "Web Technologies"
},
{
"code": null,
"e": 2399,
"s": 2372,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2403,
"s": 2399,
"text": "PHP"
},
{
"code": null,
"e": 2501,
"s": 2403,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2541,
"s": 2501,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2586,
"s": 2541,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 2634,
"s": 2586,
"text": "How to get parameters from a URL string in PHP?"
},
{
"code": null,
"e": 2667,
"s": 2634,
"text": "Download file from URL using PHP"
},
{
"code": null,
"e": 2719,
"s": 2667,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 2759,
"s": 2719,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2811,
"s": 2759,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 2859,
"s": 2811,
"text": "How to get parameters from a URL string in PHP?"
},
{
"code": null,
"e": 2911,
"s": 2859,
"text": "Split a comma delimited string into an array in PHP"
}
] |
Line Chart using Plotly in Python
|
12 Feb, 2021
Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
Line plot in Plotly is much accessible and illustrious annexation to plotly which manage a variety of types of data and assemble easy-to-style statistic. With px.line each data position is represented as a vertex transformed(which location is given by the x and y columns) of a polyline mark in 2D space. Line chart Displays a series of numerical data as points which are connected by lines. It visualizes to show two data trends. The main productive feature is it can display thousands of data points without scrolling. It can be created using the line() method of plotly.express class.
Syntax: plotly.express.line(data_frame=None, x=None, y=None, line_group=None, color=None, line_dash=None, hover_name=None, hover_data=None, custom_data=None, text=None, facet_row=None, facet_col=None, facet_col_wrap=0, error_x=None, error_x_minus=None, error_y=None, error_y_minus=None, animation_frame=None, animation_group=None, category_orders={}, labels={}, orientation=None, color_discrete_sequence=None, color_discrete_map={}, line_dash_sequence=None, line_dash_map={}, log_x=False, log_y=False, range_x=None, range_y=None, line_shape=None, render_mode=’auto’, title=None, template=None, width=None, height=None)
Parameters:
Example 1: In this example, we will see a simple line plot with two different datasets.
Python3
import plotly.express as px x = [1,2,3,4,5]y = [1,3,4,5,6]fig = px.line( x = x , y = y, title = 'A simple line graph')fig.show()
Output:
Example 2: In this example we will plot using go.Scatter. plotly.express has two functions scatter and line, go.Scatter can be used both for plotting points (makers) or lines, depending on the value of mode.
Python3
import numpy as npimport plotly.graph_objects as go x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]y = [1, 3, 4, 5, 6]fig = go.Figure(data=go.Scatter(x = x, y = y))fig.show()
Output:
Example 3: Using the Iris dataset we will plot the line chart.
Python3
import plotly.express as px # Loading the iris datasetdf = px.data.iris() fig = px.line(df, x="sepal_width", y="sepal_length")fig.show()
Output:
Column encoding color is also known as, color mapping which is a type of method which represents text or numeric data in colors inline form.
Example 1: In This example, we will use color attributes to plot the line with a different color.
Python3
import plotly.express as px df = px.data.iris().head(20) fig = px.line(df, x = "sepal_width", y = "sepal_length" , color = "sepal_length")fig.show()
Output:
Example 2: In this example, we will use different color aspect.
Python3
import plotly.express as px # Loading the iris datasetdf = px.data.iris() fig = px.line(df, x = "sepal_width", y = "sepal_length", color = "species")fig.show()
Output:
kumar_satyam
Python-Plotly
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
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Feb, 2021"
},
{
"code": null,
"e": 331,
"s": 28,
"text": "Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. "
},
{
"code": null,
"e": 919,
"s": 331,
"text": "Line plot in Plotly is much accessible and illustrious annexation to plotly which manage a variety of types of data and assemble easy-to-style statistic. With px.line each data position is represented as a vertex transformed(which location is given by the x and y columns) of a polyline mark in 2D space. Line chart Displays a series of numerical data as points which are connected by lines. It visualizes to show two data trends. The main productive feature is it can display thousands of data points without scrolling. It can be created using the line() method of plotly.express class."
},
{
"code": null,
"e": 1538,
"s": 919,
"text": "Syntax: plotly.express.line(data_frame=None, x=None, y=None, line_group=None, color=None, line_dash=None, hover_name=None, hover_data=None, custom_data=None, text=None, facet_row=None, facet_col=None, facet_col_wrap=0, error_x=None, error_x_minus=None, error_y=None, error_y_minus=None, animation_frame=None, animation_group=None, category_orders={}, labels={}, orientation=None, color_discrete_sequence=None, color_discrete_map={}, line_dash_sequence=None, line_dash_map={}, log_x=False, log_y=False, range_x=None, range_y=None, line_shape=None, render_mode=’auto’, title=None, template=None, width=None, height=None)"
},
{
"code": null,
"e": 1550,
"s": 1538,
"text": "Parameters:"
},
{
"code": null,
"e": 1638,
"s": 1550,
"text": "Example 1: In this example, we will see a simple line plot with two different datasets."
},
{
"code": null,
"e": 1646,
"s": 1638,
"text": "Python3"
},
{
"code": "import plotly.express as px x = [1,2,3,4,5]y = [1,3,4,5,6]fig = px.line( x = x , y = y, title = 'A simple line graph')fig.show()",
"e": 1801,
"s": 1646,
"text": null
},
{
"code": null,
"e": 1809,
"s": 1801,
"text": "Output:"
},
{
"code": null,
"e": 2017,
"s": 1809,
"text": "Example 2: In this example we will plot using go.Scatter. plotly.express has two functions scatter and line, go.Scatter can be used both for plotting points (makers) or lines, depending on the value of mode."
},
{
"code": null,
"e": 2025,
"s": 2017,
"text": "Python3"
},
{
"code": "import numpy as npimport plotly.graph_objects as go x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]y = [1, 3, 4, 5, 6]fig = go.Figure(data=go.Scatter(x = x, y = y))fig.show()",
"e": 2187,
"s": 2025,
"text": null
},
{
"code": null,
"e": 2195,
"s": 2187,
"text": "Output:"
},
{
"code": null,
"e": 2258,
"s": 2195,
"text": "Example 3: Using the Iris dataset we will plot the line chart."
},
{
"code": null,
"e": 2266,
"s": 2258,
"text": "Python3"
},
{
"code": "import plotly.express as px # Loading the iris datasetdf = px.data.iris() fig = px.line(df, x=\"sepal_width\", y=\"sepal_length\")fig.show()",
"e": 2403,
"s": 2266,
"text": null
},
{
"code": null,
"e": 2411,
"s": 2403,
"text": "Output:"
},
{
"code": null,
"e": 2553,
"s": 2411,
"text": "Column encoding color is also known as, color mapping which is a type of method which represents text or numeric data in colors inline form. "
},
{
"code": null,
"e": 2652,
"s": 2553,
"text": "Example 1: In This example, we will use color attributes to plot the line with a different color. "
},
{
"code": null,
"e": 2660,
"s": 2652,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.iris().head(20) fig = px.line(df, x = \"sepal_width\", y = \"sepal_length\" , color = \"sepal_length\")fig.show()",
"e": 2835,
"s": 2660,
"text": null
},
{
"code": null,
"e": 2843,
"s": 2835,
"text": "Output:"
},
{
"code": null,
"e": 2909,
"s": 2845,
"text": "Example 2: In this example, we will use different color aspect."
},
{
"code": null,
"e": 2917,
"s": 2909,
"text": "Python3"
},
{
"code": "import plotly.express as px # Loading the iris datasetdf = px.data.iris() fig = px.line(df, x = \"sepal_width\", y = \"sepal_length\", color = \"species\")fig.show()",
"e": 3090,
"s": 2917,
"text": null
},
{
"code": null,
"e": 3098,
"s": 3090,
"text": "Output:"
},
{
"code": null,
"e": 3113,
"s": 3100,
"text": "kumar_satyam"
},
{
"code": null,
"e": 3127,
"s": 3113,
"text": "Python-Plotly"
},
{
"code": null,
"e": 3134,
"s": 3127,
"text": "Python"
},
{
"code": null,
"e": 3232,
"s": 3134,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3260,
"s": 3232,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3310,
"s": 3260,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3332,
"s": 3310,
"text": "Python map() function"
},
{
"code": null,
"e": 3350,
"s": 3332,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3394,
"s": 3350,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 3436,
"s": 3394,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3459,
"s": 3436,
"text": "Taking input in Python"
},
{
"code": null,
"e": 3481,
"s": 3459,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3516,
"s": 3481,
"text": "Read a file line by line in Python"
}
] |
How to hide an element when printing a web page using CSS?
|
22 Mar, 2021
The media query is used to hide an element when printing web pages. Use @media print query and set the visibility hidden to that element that needs to hide at printing.
Example 1: In this example, hide the element h1 at printing time. To hide the element h1 use media query and set visibility:hidden.
html
<!DOCTYPE html><html> <head> <title>Hide element at print</title> <style> body { text-align:center; } h1 { color:green; } @media print { .noprint { visibility: hidden; } } </style> </head> <body> <h1 class = "noprint">GeeksforGeeks</h1> <p>GeeksforGeeks: It is a computer science portal for geeks</p> </body></html>
Output: Before printing the page:
After printing the page:
Example 2: In this example, use a media query to hide image elements when printing the web pages.
html
<!DOCTYPE html><html> <head> <title>Hide element at printing</title> <style> body { text-align:center; } h1 { color:green; } @media print { img { visibility: hidden; } } </style> </head> <body> <h1>GeeksforGeeks</h1> <p>A computer science portal for geeks</p> <img src="gfg.png" alt="image"> <style> .noprint { visibility: hidden; } </style> </body></html>
Output: Before printing the page:
After printing the page:
AshokJaiswal
Picked
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Mar, 2021"
},
{
"code": null,
"e": 198,
"s": 28,
"text": "The media query is used to hide an element when printing web pages. Use @media print query and set the visibility hidden to that element that needs to hide at printing. "
},
{
"code": null,
"e": 331,
"s": 198,
"text": "Example 1: In this example, hide the element h1 at printing time. To hide the element h1 use media query and set visibility:hidden. "
},
{
"code": null,
"e": 336,
"s": 331,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Hide element at print</title> <style> body { text-align:center; } h1 { color:green; } @media print { .noprint { visibility: hidden; } } </style> </head> <body> <h1 class = \"noprint\">GeeksforGeeks</h1> <p>GeeksforGeeks: It is a computer science portal for geeks</p> </body></html> ",
"e": 886,
"s": 336,
"text": null
},
{
"code": null,
"e": 922,
"s": 886,
"text": "Output: Before printing the page: "
},
{
"code": null,
"e": 949,
"s": 922,
"text": "After printing the page: "
},
{
"code": null,
"e": 1048,
"s": 949,
"text": "Example 2: In this example, use a media query to hide image elements when printing the web pages. "
},
{
"code": null,
"e": 1053,
"s": 1048,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Hide element at printing</title> <style> body { text-align:center; } h1 { color:green; } @media print { img { visibility: hidden; } } </style> </head> <body> <h1>GeeksforGeeks</h1> <p>A computer science portal for geeks</p> <img src=\"gfg.png\" alt=\"image\"> <style> .noprint { visibility: hidden; } </style> </body></html> ",
"e": 1681,
"s": 1053,
"text": null
},
{
"code": null,
"e": 1717,
"s": 1681,
"text": "Output: Before printing the page: "
},
{
"code": null,
"e": 1744,
"s": 1717,
"text": "After printing the page: "
},
{
"code": null,
"e": 1759,
"s": 1746,
"text": "AshokJaiswal"
},
{
"code": null,
"e": 1766,
"s": 1759,
"text": "Picked"
},
{
"code": null,
"e": 1770,
"s": 1766,
"text": "CSS"
},
{
"code": null,
"e": 1775,
"s": 1770,
"text": "HTML"
},
{
"code": null,
"e": 1792,
"s": 1775,
"text": "Web Technologies"
},
{
"code": null,
"e": 1819,
"s": 1792,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1824,
"s": 1819,
"text": "HTML"
}
] |
Submatrix Sum Queries
|
16 Jun, 2022
Given a matrix of size M x N, there are large number of queries to find submatrix sums. Inputs to queries are left top and right bottom indexes of submatrix whose sum is to find out. How to preprocess the matrix so that submatrix sum queries can be performed in O(1) time.Example :
tli : Row number of top left of query submatrix
tlj : Column number of top left of query submatrix
rbi : Row number of bottom right of query submatrix
rbj : Column number of bottom right of query submatrix
Input: mat[M][N] = {{1, 2, 3, 4, 6},
{5, 3, 8, 1, 2},
{4, 6, 7, 5, 5},
{2, 4, 8, 9, 4} };
Query1: tli = 0, tlj = 0, rbi = 1, rbj = 1
Query2: tli = 2, tlj = 2, rbi = 3, rbj = 4
Query3: tli = 1, tlj = 2, rbi = 3, rbj = 3;
Output:
Query1: 11 // Sum between (0, 0) and (1, 1)
Query2: 38 // Sum between (2, 2) and (3, 4)
Query3: 38 // Sum between (1, 2) and (3, 3)
We strongly recommend you to minimize your browser and try this yourself first.The idea is to first create an auxiliary matrix aux[M][N] such that aux[i][j] stores sum of elements in submatrix from (0,0) to (i,j). Once aux[][] is constructed, we can compute sum of submatrix between (tli, tlj) and (rbi, rbj) in O(1) time. We need to consider aux[rbi][rbj] and subtract all unnecessary elements. Below is complete expression to compute submatrix sum in O(1) time.
Sum between (tli, tlj) and (rbi, rbj) is,
aux[rbi][rbj] - aux[tli-1][rbj] -
aux[rbi][tlj-1] + aux[tli-1][tlj-1]
The submatrix aux[tli-1][tlj-1] is added because
elements of it are subtracted twice.
Illustration:
mat[M][N] = {{1, 2, 3, 4, 6},
{5, 3, 8, 1, 2},
{4, 6, 7, 5, 5},
{2, 4, 8, 9, 4} };
We first preprocess the matrix and build
following aux[M][N]
aux[M][N] = {1, 3, 6, 10, 16}
{6, 11, 22, 27, 35},
{10, 21, 39, 49, 62},
{12, 27, 53, 72, 89} }
Query : tli = 2, tlj = 2, rbi = 3, rbj = 4
Sum between (2, 2) and (3, 4) = 89 - 35 - 27 + 11
= 38
How to build aux[M][N]? 1. Copy first row of mat[][] to aux[][] 2. Do column wise sum of the matrix and store it. 3. Do the row wise sum of updated matrix aux[][] in step 2.Below is the program based on above idea.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to compute submatrix query sum in O(1)// time#include<iostream>using namespace std;#define M 4#define N 5 // Function to preprocess input mat[M][N]. This function// mainly fills aux[M][N] such that aux[i][j] stores sum// of elements from (0,0) to (i,j)int preProcess(int mat[M][N], int aux[M][N]){ // Copy first row of mat[][] to aux[][] for (int i=0; i<N; i++) aux[0][i] = mat[0][i]; // Do column wise sum for (int i=1; i<M; i++) for (int j=0; j<N; j++) aux[i][j] = mat[i][j] + aux[i-1][j]; // Do row wise sum for (int i=0; i<M; i++) for (int j=1; j<N; j++) aux[i][j] += aux[i][j-1];} // A O(1) time function to compute sum of submatrix// between (tli, tlj) and (rbi, rbj) using aux[][]// which is built by the preprocess functionint sumQuery(int aux[M][N], int tli, int tlj, int rbi, int rbj){ // result is now sum of elements between (0, 0) and // (rbi, rbj) int res = aux[rbi][rbj]; // Remove elements between (0, 0) and (tli-1, rbj) if (tli > 0) res = res - aux[tli-1][rbj]; // Remove elements between (0, 0) and (rbi, tlj-1) if (tlj > 0) res = res - aux[rbi][tlj-1]; // Add aux[tli-1][tlj-1] as elements between (0, 0) // and (tli-1, tlj-1) are subtracted twice if (tli > 0 && tlj > 0) res = res + aux[tli-1][tlj-1]; return res;} // Driver programint main(){ int mat[M][N] = {{1, 2, 3, 4, 6}, {5, 3, 8, 1, 2}, {4, 6, 7, 5, 5}, {2, 4, 8, 9, 4} }; int aux[M][N]; preProcess(mat, aux); int tli = 2, tlj = 2, rbi = 3, rbj = 4; cout << "\nQuery1: " << sumQuery(aux, tli, tlj, rbi, rbj); tli = 0, tlj = 0, rbi = 1, rbj = 1; cout << "\nQuery2: " << sumQuery(aux, tli, tlj, rbi, rbj); tli = 1, tlj = 2, rbi = 3, rbj = 3; cout << "\nQuery3: " << sumQuery(aux, tli, tlj, rbi, rbj); return 0;}
// Java program to compute submatrix query// sum in O(1) timeclass GFG { static final int M = 4; static final int N = 5; // Function to preprocess input mat[M][N]. // This function mainly fills aux[M][N] // such that aux[i][j] stores sum of // elements from (0,0) to (i,j) static int preProcess(int mat[][], int aux[][]) { // Copy first row of mat[][] to aux[][] for (int i = 0; i < N; i++) aux[0][i] = mat[0][i]; // Do column wise sum for (int i = 1; i < M; i++) for (int j = 0; j < N; j++) aux[i][j] = mat[i][j] + aux[i-1][j]; // Do row wise sum for (int i = 0; i < M; i++) for (int j = 1; j < N; j++) aux[i][j] += aux[i][j-1]; return 0; } // A O(1) time function to compute sum // of submatrix between (tli, tlj) and // (rbi, rbj) using aux[][] which is // built by the preprocess function static int sumQuery(int aux[][], int tli, int tlj, int rbi, int rbj) { // result is now sum of elements // between (0, 0) and (rbi, rbj) int res = aux[rbi][rbj]; // Remove elements between (0, 0) // and (tli-1, rbj) if (tli > 0) res = res - aux[tli-1][rbj]; // Remove elements between (0, 0) // and (rbi, tlj-1) if (tlj > 0) res = res - aux[rbi][tlj-1]; // Add aux[tli-1][tlj-1] as elements // between (0, 0) and (tli-1, tlj-1) // are subtracted twice if (tli > 0 && tlj > 0) res = res + aux[tli-1][tlj-1]; return res; } // Driver code public static void main (String[] args) { int mat[][] = {{1, 2, 3, 4, 6}, {5, 3, 8, 1, 2}, {4, 6, 7, 5, 5}, {2, 4, 8, 9, 4}}; int aux[][] = new int[M][N]; preProcess(mat, aux); int tli = 2, tlj = 2, rbi = 3, rbj = 4; System.out.print("\nQuery1: " + sumQuery(aux, tli, tlj, rbi, rbj)); tli = 0; tlj = 0; rbi = 1; rbj = 1; System.out.print("\nQuery2: " + sumQuery(aux, tli, tlj, rbi, rbj)); tli = 1; tlj = 2; rbi = 3; rbj = 3; System.out.print("\nQuery3: " + sumQuery(aux, tli, tlj, rbi, rbj)); }} // This code is contributed by Anant Agarwal.
# Python 3 program to compute submatrix# query sum in O(1) time M = 4N = 5 # Function to preprocess input mat[M][N].# This function mainly fills aux[M][N]# such that aux[i][j] stores sum# of elements from (0,0) to (i,j)def preProcess(mat, aux): # Copy first row of mat[][] to aux[][] for i in range(0, N, 1): aux[0][i] = mat[0][i] # Do column wise sum for i in range(1, M, 1): for j in range(0, N, 1): aux[i][j] = mat[i][j] + aux[i - 1][j] # Do row wise sum for i in range(0, M, 1): for j in range(1, N, 1): aux[i][j] += aux[i][j - 1] # A O(1) time function to compute sum of submatrix# between (tli, tlj) and (rbi, rbj) using aux[][]# which is built by the preprocess functiondef sumQuery(aux, tli, tlj, rbi, rbj): # result is now sum of elements # between (0, 0) and (rbi, rbj) res = aux[rbi][rbj] # Remove elements between (0, 0) # and (tli-1, rbj) if (tli > 0): res = res - aux[tli - 1][rbj] # Remove elements between (0, 0) # and (rbi, tlj-1) if (tlj > 0): res = res - aux[rbi][tlj - 1] # Add aux[tli-1][tlj-1] as elements # between (0, 0) and (tli-1, tlj-1) # are subtracted twice if (tli > 0 and tlj > 0): res = res + aux[tli - 1][tlj - 1] return res # Driver Codeif __name__ == '__main__': mat = [[1, 2, 3, 4, 6], [5, 3, 8, 1, 2], [4, 6, 7, 5, 5], [2, 4, 8, 9, 4]]aux = [[0 for i in range(N)] for j in range(M)] preProcess(mat, aux) tli = 2tlj = 2rbi = 3rbj = 4print("Query1:", sumQuery(aux, tli, tlj, rbi, rbj)) tli = 0tlj = 0rbi = 1rbj = 1print("Query2:", sumQuery(aux, tli, tlj, rbi, rbj)) tli = 1tlj = 2rbi = 3rbj = 3print("Query3:", sumQuery(aux, tli, tlj, rbi, rbj)) # This code is contributed by# Shashank_Sharma
// C# program to compute submatrix// query sum in O(1) timeusing System; class GFG{ static int M = 4; static int N = 5; // Function to preprocess input mat[M][N]. // This function mainly fills aux[M][N] // such that aux[i][j] stores sum of // elements from (0,0) to (i,j) static int preProcess(int [,]mat, int [,]aux) { // Copy first row of mat[][] to aux[][] for (int i = 0; i < N; i++) aux[0,i] = mat[0,i]; // Do column wise sum for (int i = 1; i < M; i++) for (int j = 0; j < N; j++) aux[i,j] = mat[i,j] + aux[i-1,j]; // Do row wise sum for (int i = 0; i < M; i++) for (int j = 1; j < N; j++) aux[i,j] += aux[i,j-1]; return 0; } // A O(1) time function to compute sum // of submatrix between (tli, tlj) and // (rbi, rbj) using aux[][] which is // built by the preprocess function static int sumQuery(int [,]aux, int tli, int tlj, int rbi, int rbj) { // result is now sum of elements // between (0, 0) and (rbi, rbj) int res = aux[rbi,rbj]; // Remove elements between (0, 0) // and (tli-1, rbj) if (tli > 0) res = res - aux[tli-1,rbj]; // Remove elements between (0, 0) // and (rbi, tlj-1) if (tlj > 0) res = res - aux[rbi,tlj-1]; // Add aux[tli-1][tlj-1] as elements // between (0, 0) and (tli-1, tlj-1) // are subtracted twice if (tli > 0 && tlj > 0) res = res + aux[tli-1,tlj-1]; return res; } // Driver code public static void Main () { int [,]mat = {{1, 2, 3, 4, 6}, {5, 3, 8, 1, 2}, {4, 6, 7, 5, 5}, {2, 4, 8, 9, 4}}; int [,]aux = new int[M,N]; preProcess(mat, aux); int tli = 2, tlj = 2, rbi = 3, rbj = 4; Console.Write("\nQuery1: " + sumQuery(aux, tli, tlj, rbi, rbj)); tli = 0; tlj = 0; rbi = 1; rbj = 1; Console.Write("\nQuery2: " + sumQuery(aux, tli, tlj, rbi, rbj)); tli = 1; tlj = 2; rbi = 3; rbj = 3; Console.Write("\nQuery3: " + sumQuery(aux, tli, tlj, rbi, rbj)); }} // This code is contributed by Sam007.
<?php// PHP program to compute submatrix// query sum in O(1) time // Function to preprocess input mat[M][N].// This function mainly fills aux[M][N]// such that aux[i][j] stores sum// of elements from (0,0) to (i,j)function preProcess(&$mat, &$aux){ $M = 4; $N = 5; // Copy first row of mat[][] to aux[][] for ($i = 0; $i < $N; $i++) $aux[0][$i] = $mat[0][$i]; // Do column wise sum for ($i = 1; $i < $M; $i++) for ($j = 0; $j < $N; $j++) $aux[$i][$j] = $mat[$i][$j] + $aux[$i - 1][$j]; // Do row wise sum for ($i = 0; $i < $M; $i++) for ($j = 1; $j < $N; $j++) $aux[$i][$j] += $aux[$i][$j - 1];} // A O(1) time function to compute sum of// submatrix between (tli, tlj) and// (rbi, rbj) using aux[][] which is built// by the preprocess functionfunction sumQuery(&$aux, $tli, $tlj, $rbi,$rbj){ // result is now sum of elements // between (0, 0) and (rbi, rbj) $res = $aux[$rbi][$rbj]; // Remove elements between (0, 0) // and (tli-1, rbj) if ($tli > 0) $res = $res - $aux[$tli - 1][$rbj]; // Remove elements between (0, 0) // and (rbi, tlj-1) if ($tlj > 0) $res = $res - $aux[$rbi][$tlj - 1]; // Add aux[tli-1][tlj-1] as elements between (0, 0) // and (tli-1, tlj-1) are subtracted twice if ($tli > 0 && $tlj > 0) $res = $res + $aux[$tli - 1][$tlj - 1]; return $res;} // Driver Code$mat = array(array(1, 2, 3, 4, 6), array(5, 3, 8, 1, 2), array(4, 6, 7, 5, 5), array(2, 4, 8, 9, 4)); preProcess($mat, $aux); $tli = 2;$tlj = 2;$rbi = 3;$rbj = 4;echo ("Query1: ");echo(sumQuery($aux, $tli, $tlj, $rbi, $rbj)); $tli = 0;$tlj = 0;$rbi = 1;$rbj = 1;echo ("\nQuery2: ");echo(sumQuery($aux, $tli, $tlj, $rbi, $rbj)); $tli = 1;$tlj = 2;$rbi = 3;$rbj = 3;echo ("\nQuery3: ");echo(sumQuery($aux, $tli, $tlj, $rbi, $rbj)); // This code is contributed by Shivi_Aggarwal?>
<script>// Javascript program to compute submatrix query// sum in O(1) time var M = 4; var N = 5; // Function to preprocess input mat[M][N]. // This function mainly fills aux[M][N] // such that aux[i][j] stores sum of // elements from (0,0) to (i,j) function preProcess(mat, aux) { // Copy first row of mat[][] to aux[][] for (var i = 0; i < N; i++) aux[0,i] = mat[0,i]; // Do column wise sum for (var i = 1; i < M; i++) for (var j = 0; j < N; j++) aux[i][j] = mat[i][j] + aux[i-1][j]; // Do row wise sum for (var i = 0; i < M; i++) for (var j = 1; j < N; j++) aux[i][j] += aux[i][j-1]; return 0; } // A O(1) time function to compute sum // of submatrix between (tli, tlj) and // (rbi, rbj) using aux[][] which is // built by the preprocess function function sumQuery( aux, tli, tlj, rbi, rbj) { // result is now sum of elements // between (0, 0) and (rbi, rbj) var res = aux[rbi][rbj]; // Remove elements between (0, 0) // and (tli-1, rbj) if (tli > 0) res = res - aux[tli-1][rbj]; // Remove elements between (0, 0) // and (rbi, tlj-1) if (tlj > 0) res = res - aux[rbi][tlj-1]; // Add aux[tli-1][tlj-1] as elements // between (0, 0) and (tli-1, tlj-1) // are subtracted twice if (tli > 0 && tlj > 0) res = res + aux[tli-1][tlj-1]; return res; } // Driver code var mat= [[1, 2, 3, 4, 6], [5, 3, 8, 1, 2], [4, 6, 7, 5, 5], [2, 4, 8, 9, 4]]; var aux = new Array(M,N); preProcess(mat, aux); var tli = 2, tlj = 2, rbi = 3, rbj = 4; document.write("\nQuery1: " + sumQuery(aux, tli, tlj, rbi, rbj)+"<br>"); tli = 0; tlj = 0; rbi = 1; rbj = 1; document.write("\nQuery2: " + sumQuery(aux, tli, tlj, rbi, rbj)+"<br>"); tli = 1; tlj = 2; rbi = 3; rbj = 3; document.write("\nQuery3: " + sumQuery(aux, tli, tlj, rbi, rbj)); }} // This code is contributed by shivanisinghss2110</script>
Output:
Query1: 38
Query2: 11
Query3: 38
Time complexity: O(M x N).Auxiliary Space: O(M x N)
This article is contributed by Aarti_Rathi and Shivam Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Submatrix Sum Queries | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersSubmatrix Sum Queries | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 12:15•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=-d8KbQVx-mM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Source: https://www.geeksforgeeks.org/amazon-interview-experience-set-241-1-5-years-experience/
Sam007
Shashank_Sharma
Shivi_Aggarwal
varshagumber28
shivanisinghss2110
surinderdawra388
codewithshinchan
Amazon
Arrays
Matrix
Amazon
Arrays
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 338,
"s": 54,
"text": "Given a matrix of size M x N, there are large number of queries to find submatrix sums. Inputs to queries are left top and right bottom indexes of submatrix whose sum is to find out. How to preprocess the matrix so that submatrix sum queries can be performed in O(1) time.Example : "
},
{
"code": null,
"e": 973,
"s": 338,
"text": "tli : Row number of top left of query submatrix\ntlj : Column number of top left of query submatrix\nrbi : Row number of bottom right of query submatrix\nrbj : Column number of bottom right of query submatrix\n\nInput: mat[M][N] = {{1, 2, 3, 4, 6},\n {5, 3, 8, 1, 2},\n {4, 6, 7, 5, 5},\n {2, 4, 8, 9, 4} };\nQuery1: tli = 0, tlj = 0, rbi = 1, rbj = 1\nQuery2: tli = 2, tlj = 2, rbi = 3, rbj = 4\nQuery3: tli = 1, tlj = 2, rbi = 3, rbj = 3;\n\nOutput:\nQuery1: 11 // Sum between (0, 0) and (1, 1)\nQuery2: 38 // Sum between (2, 2) and (3, 4)\nQuery3: 38 // Sum between (1, 2) and (3, 3)"
},
{
"code": null,
"e": 1438,
"s": 973,
"text": "We strongly recommend you to minimize your browser and try this yourself first.The idea is to first create an auxiliary matrix aux[M][N] such that aux[i][j] stores sum of elements in submatrix from (0,0) to (i,j). Once aux[][] is constructed, we can compute sum of submatrix between (tli, tlj) and (rbi, rbj) in O(1) time. We need to consider aux[rbi][rbj] and subtract all unnecessary elements. Below is complete expression to compute submatrix sum in O(1) time. "
},
{
"code": null,
"e": 1646,
"s": 1438,
"text": "Sum between (tli, tlj) and (rbi, rbj) is,\n aux[rbi][rbj] - aux[tli-1][rbj] - \n aux[rbi][tlj-1] + aux[tli-1][tlj-1]\n\nThe submatrix aux[tli-1][tlj-1] is added because \nelements of it are subtracted twice."
},
{
"code": null,
"e": 1662,
"s": 1646,
"text": "Illustration: "
},
{
"code": null,
"e": 2139,
"s": 1662,
"text": "mat[M][N] = {{1, 2, 3, 4, 6},\n {5, 3, 8, 1, 2},\n {4, 6, 7, 5, 5},\n {2, 4, 8, 9, 4} };\n\nWe first preprocess the matrix and build\nfollowing aux[M][N]\naux[M][N] = {1, 3, 6, 10, 16}\n {6, 11, 22, 27, 35},\n {10, 21, 39, 49, 62}, \n {12, 27, 53, 72, 89} }\n\nQuery : tli = 2, tlj = 2, rbi = 3, rbj = 4 \n \nSum between (2, 2) and (3, 4) = 89 - 35 - 27 + 11\n = 38\n "
},
{
"code": null,
"e": 2355,
"s": 2139,
"text": "How to build aux[M][N]? 1. Copy first row of mat[][] to aux[][] 2. Do column wise sum of the matrix and store it. 3. Do the row wise sum of updated matrix aux[][] in step 2.Below is the program based on above idea. "
},
{
"code": null,
"e": 2359,
"s": 2355,
"text": "C++"
},
{
"code": null,
"e": 2364,
"s": 2359,
"text": "Java"
},
{
"code": null,
"e": 2372,
"s": 2364,
"text": "Python3"
},
{
"code": null,
"e": 2375,
"s": 2372,
"text": "C#"
},
{
"code": null,
"e": 2379,
"s": 2375,
"text": "PHP"
},
{
"code": null,
"e": 2390,
"s": 2379,
"text": "Javascript"
},
{
"code": "// C++ program to compute submatrix query sum in O(1)// time#include<iostream>using namespace std;#define M 4#define N 5 // Function to preprocess input mat[M][N]. This function// mainly fills aux[M][N] such that aux[i][j] stores sum// of elements from (0,0) to (i,j)int preProcess(int mat[M][N], int aux[M][N]){ // Copy first row of mat[][] to aux[][] for (int i=0; i<N; i++) aux[0][i] = mat[0][i]; // Do column wise sum for (int i=1; i<M; i++) for (int j=0; j<N; j++) aux[i][j] = mat[i][j] + aux[i-1][j]; // Do row wise sum for (int i=0; i<M; i++) for (int j=1; j<N; j++) aux[i][j] += aux[i][j-1];} // A O(1) time function to compute sum of submatrix// between (tli, tlj) and (rbi, rbj) using aux[][]// which is built by the preprocess functionint sumQuery(int aux[M][N], int tli, int tlj, int rbi, int rbj){ // result is now sum of elements between (0, 0) and // (rbi, rbj) int res = aux[rbi][rbj]; // Remove elements between (0, 0) and (tli-1, rbj) if (tli > 0) res = res - aux[tli-1][rbj]; // Remove elements between (0, 0) and (rbi, tlj-1) if (tlj > 0) res = res - aux[rbi][tlj-1]; // Add aux[tli-1][tlj-1] as elements between (0, 0) // and (tli-1, tlj-1) are subtracted twice if (tli > 0 && tlj > 0) res = res + aux[tli-1][tlj-1]; return res;} // Driver programint main(){ int mat[M][N] = {{1, 2, 3, 4, 6}, {5, 3, 8, 1, 2}, {4, 6, 7, 5, 5}, {2, 4, 8, 9, 4} }; int aux[M][N]; preProcess(mat, aux); int tli = 2, tlj = 2, rbi = 3, rbj = 4; cout << \"\\nQuery1: \" << sumQuery(aux, tli, tlj, rbi, rbj); tli = 0, tlj = 0, rbi = 1, rbj = 1; cout << \"\\nQuery2: \" << sumQuery(aux, tli, tlj, rbi, rbj); tli = 1, tlj = 2, rbi = 3, rbj = 3; cout << \"\\nQuery3: \" << sumQuery(aux, tli, tlj, rbi, rbj); return 0;}",
"e": 4322,
"s": 2390,
"text": null
},
{
"code": "// Java program to compute submatrix query// sum in O(1) timeclass GFG { static final int M = 4; static final int N = 5; // Function to preprocess input mat[M][N]. // This function mainly fills aux[M][N] // such that aux[i][j] stores sum of // elements from (0,0) to (i,j) static int preProcess(int mat[][], int aux[][]) { // Copy first row of mat[][] to aux[][] for (int i = 0; i < N; i++) aux[0][i] = mat[0][i]; // Do column wise sum for (int i = 1; i < M; i++) for (int j = 0; j < N; j++) aux[i][j] = mat[i][j] + aux[i-1][j]; // Do row wise sum for (int i = 0; i < M; i++) for (int j = 1; j < N; j++) aux[i][j] += aux[i][j-1]; return 0; } // A O(1) time function to compute sum // of submatrix between (tli, tlj) and // (rbi, rbj) using aux[][] which is // built by the preprocess function static int sumQuery(int aux[][], int tli, int tlj, int rbi, int rbj) { // result is now sum of elements // between (0, 0) and (rbi, rbj) int res = aux[rbi][rbj]; // Remove elements between (0, 0) // and (tli-1, rbj) if (tli > 0) res = res - aux[tli-1][rbj]; // Remove elements between (0, 0) // and (rbi, tlj-1) if (tlj > 0) res = res - aux[rbi][tlj-1]; // Add aux[tli-1][tlj-1] as elements // between (0, 0) and (tli-1, tlj-1) // are subtracted twice if (tli > 0 && tlj > 0) res = res + aux[tli-1][tlj-1]; return res; } // Driver code public static void main (String[] args) { int mat[][] = {{1, 2, 3, 4, 6}, {5, 3, 8, 1, 2}, {4, 6, 7, 5, 5}, {2, 4, 8, 9, 4}}; int aux[][] = new int[M][N]; preProcess(mat, aux); int tli = 2, tlj = 2, rbi = 3, rbj = 4; System.out.print(\"\\nQuery1: \" + sumQuery(aux, tli, tlj, rbi, rbj)); tli = 0; tlj = 0; rbi = 1; rbj = 1; System.out.print(\"\\nQuery2: \" + sumQuery(aux, tli, tlj, rbi, rbj)); tli = 1; tlj = 2; rbi = 3; rbj = 3; System.out.print(\"\\nQuery3: \" + sumQuery(aux, tli, tlj, rbi, rbj)); }} // This code is contributed by Anant Agarwal.",
"e": 6861,
"s": 4322,
"text": null
},
{
"code": "# Python 3 program to compute submatrix# query sum in O(1) time M = 4N = 5 # Function to preprocess input mat[M][N].# This function mainly fills aux[M][N]# such that aux[i][j] stores sum# of elements from (0,0) to (i,j)def preProcess(mat, aux): # Copy first row of mat[][] to aux[][] for i in range(0, N, 1): aux[0][i] = mat[0][i] # Do column wise sum for i in range(1, M, 1): for j in range(0, N, 1): aux[i][j] = mat[i][j] + aux[i - 1][j] # Do row wise sum for i in range(0, M, 1): for j in range(1, N, 1): aux[i][j] += aux[i][j - 1] # A O(1) time function to compute sum of submatrix# between (tli, tlj) and (rbi, rbj) using aux[][]# which is built by the preprocess functiondef sumQuery(aux, tli, tlj, rbi, rbj): # result is now sum of elements # between (0, 0) and (rbi, rbj) res = aux[rbi][rbj] # Remove elements between (0, 0) # and (tli-1, rbj) if (tli > 0): res = res - aux[tli - 1][rbj] # Remove elements between (0, 0) # and (rbi, tlj-1) if (tlj > 0): res = res - aux[rbi][tlj - 1] # Add aux[tli-1][tlj-1] as elements # between (0, 0) and (tli-1, tlj-1) # are subtracted twice if (tli > 0 and tlj > 0): res = res + aux[tli - 1][tlj - 1] return res # Driver Codeif __name__ == '__main__': mat = [[1, 2, 3, 4, 6], [5, 3, 8, 1, 2], [4, 6, 7, 5, 5], [2, 4, 8, 9, 4]]aux = [[0 for i in range(N)] for j in range(M)] preProcess(mat, aux) tli = 2tlj = 2rbi = 3rbj = 4print(\"Query1:\", sumQuery(aux, tli, tlj, rbi, rbj)) tli = 0tlj = 0rbi = 1rbj = 1print(\"Query2:\", sumQuery(aux, tli, tlj, rbi, rbj)) tli = 1tlj = 2rbi = 3rbj = 3print(\"Query3:\", sumQuery(aux, tli, tlj, rbi, rbj)) # This code is contributed by# Shashank_Sharma",
"e": 8671,
"s": 6861,
"text": null
},
{
"code": "// C# program to compute submatrix// query sum in O(1) timeusing System; class GFG{ static int M = 4; static int N = 5; // Function to preprocess input mat[M][N]. // This function mainly fills aux[M][N] // such that aux[i][j] stores sum of // elements from (0,0) to (i,j) static int preProcess(int [,]mat, int [,]aux) { // Copy first row of mat[][] to aux[][] for (int i = 0; i < N; i++) aux[0,i] = mat[0,i]; // Do column wise sum for (int i = 1; i < M; i++) for (int j = 0; j < N; j++) aux[i,j] = mat[i,j] + aux[i-1,j]; // Do row wise sum for (int i = 0; i < M; i++) for (int j = 1; j < N; j++) aux[i,j] += aux[i,j-1]; return 0; } // A O(1) time function to compute sum // of submatrix between (tli, tlj) and // (rbi, rbj) using aux[][] which is // built by the preprocess function static int sumQuery(int [,]aux, int tli, int tlj, int rbi, int rbj) { // result is now sum of elements // between (0, 0) and (rbi, rbj) int res = aux[rbi,rbj]; // Remove elements between (0, 0) // and (tli-1, rbj) if (tli > 0) res = res - aux[tli-1,rbj]; // Remove elements between (0, 0) // and (rbi, tlj-1) if (tlj > 0) res = res - aux[rbi,tlj-1]; // Add aux[tli-1][tlj-1] as elements // between (0, 0) and (tli-1, tlj-1) // are subtracted twice if (tli > 0 && tlj > 0) res = res + aux[tli-1,tlj-1]; return res; } // Driver code public static void Main () { int [,]mat = {{1, 2, 3, 4, 6}, {5, 3, 8, 1, 2}, {4, 6, 7, 5, 5}, {2, 4, 8, 9, 4}}; int [,]aux = new int[M,N]; preProcess(mat, aux); int tli = 2, tlj = 2, rbi = 3, rbj = 4; Console.Write(\"\\nQuery1: \" + sumQuery(aux, tli, tlj, rbi, rbj)); tli = 0; tlj = 0; rbi = 1; rbj = 1; Console.Write(\"\\nQuery2: \" + sumQuery(aux, tli, tlj, rbi, rbj)); tli = 1; tlj = 2; rbi = 3; rbj = 3; Console.Write(\"\\nQuery3: \" + sumQuery(aux, tli, tlj, rbi, rbj)); }} // This code is contributed by Sam007.",
"e": 11168,
"s": 8671,
"text": null
},
{
"code": "<?php// PHP program to compute submatrix// query sum in O(1) time // Function to preprocess input mat[M][N].// This function mainly fills aux[M][N]// such that aux[i][j] stores sum// of elements from (0,0) to (i,j)function preProcess(&$mat, &$aux){ $M = 4; $N = 5; // Copy first row of mat[][] to aux[][] for ($i = 0; $i < $N; $i++) $aux[0][$i] = $mat[0][$i]; // Do column wise sum for ($i = 1; $i < $M; $i++) for ($j = 0; $j < $N; $j++) $aux[$i][$j] = $mat[$i][$j] + $aux[$i - 1][$j]; // Do row wise sum for ($i = 0; $i < $M; $i++) for ($j = 1; $j < $N; $j++) $aux[$i][$j] += $aux[$i][$j - 1];} // A O(1) time function to compute sum of// submatrix between (tli, tlj) and// (rbi, rbj) using aux[][] which is built// by the preprocess functionfunction sumQuery(&$aux, $tli, $tlj, $rbi,$rbj){ // result is now sum of elements // between (0, 0) and (rbi, rbj) $res = $aux[$rbi][$rbj]; // Remove elements between (0, 0) // and (tli-1, rbj) if ($tli > 0) $res = $res - $aux[$tli - 1][$rbj]; // Remove elements between (0, 0) // and (rbi, tlj-1) if ($tlj > 0) $res = $res - $aux[$rbi][$tlj - 1]; // Add aux[tli-1][tlj-1] as elements between (0, 0) // and (tli-1, tlj-1) are subtracted twice if ($tli > 0 && $tlj > 0) $res = $res + $aux[$tli - 1][$tlj - 1]; return $res;} // Driver Code$mat = array(array(1, 2, 3, 4, 6), array(5, 3, 8, 1, 2), array(4, 6, 7, 5, 5), array(2, 4, 8, 9, 4)); preProcess($mat, $aux); $tli = 2;$tlj = 2;$rbi = 3;$rbj = 4;echo (\"Query1: \");echo(sumQuery($aux, $tli, $tlj, $rbi, $rbj)); $tli = 0;$tlj = 0;$rbi = 1;$rbj = 1;echo (\"\\nQuery2: \");echo(sumQuery($aux, $tli, $tlj, $rbi, $rbj)); $tli = 1;$tlj = 2;$rbi = 3;$rbj = 3;echo (\"\\nQuery3: \");echo(sumQuery($aux, $tli, $tlj, $rbi, $rbj)); // This code is contributed by Shivi_Aggarwal?>",
"e": 13123,
"s": 11168,
"text": null
},
{
"code": "<script>// Javascript program to compute submatrix query// sum in O(1) time var M = 4; var N = 5; // Function to preprocess input mat[M][N]. // This function mainly fills aux[M][N] // such that aux[i][j] stores sum of // elements from (0,0) to (i,j) function preProcess(mat, aux) { // Copy first row of mat[][] to aux[][] for (var i = 0; i < N; i++) aux[0,i] = mat[0,i]; // Do column wise sum for (var i = 1; i < M; i++) for (var j = 0; j < N; j++) aux[i][j] = mat[i][j] + aux[i-1][j]; // Do row wise sum for (var i = 0; i < M; i++) for (var j = 1; j < N; j++) aux[i][j] += aux[i][j-1]; return 0; } // A O(1) time function to compute sum // of submatrix between (tli, tlj) and // (rbi, rbj) using aux[][] which is // built by the preprocess function function sumQuery( aux, tli, tlj, rbi, rbj) { // result is now sum of elements // between (0, 0) and (rbi, rbj) var res = aux[rbi][rbj]; // Remove elements between (0, 0) // and (tli-1, rbj) if (tli > 0) res = res - aux[tli-1][rbj]; // Remove elements between (0, 0) // and (rbi, tlj-1) if (tlj > 0) res = res - aux[rbi][tlj-1]; // Add aux[tli-1][tlj-1] as elements // between (0, 0) and (tli-1, tlj-1) // are subtracted twice if (tli > 0 && tlj > 0) res = res + aux[tli-1][tlj-1]; return res; } // Driver code var mat= [[1, 2, 3, 4, 6], [5, 3, 8, 1, 2], [4, 6, 7, 5, 5], [2, 4, 8, 9, 4]]; var aux = new Array(M,N); preProcess(mat, aux); var tli = 2, tlj = 2, rbi = 3, rbj = 4; document.write(\"\\nQuery1: \" + sumQuery(aux, tli, tlj, rbi, rbj)+\"<br>\"); tli = 0; tlj = 0; rbi = 1; rbj = 1; document.write(\"\\nQuery2: \" + sumQuery(aux, tli, tlj, rbi, rbj)+\"<br>\"); tli = 1; tlj = 2; rbi = 3; rbj = 3; document.write(\"\\nQuery3: \" + sumQuery(aux, tli, tlj, rbi, rbj)); }} // This code is contributed by shivanisinghss2110</script>",
"e": 15546,
"s": 13123,
"text": null
},
{
"code": null,
"e": 15556,
"s": 15546,
"text": "Output: "
},
{
"code": null,
"e": 15589,
"s": 15556,
"text": "Query1: 38\nQuery2: 11\nQuery3: 38"
},
{
"code": null,
"e": 15642,
"s": 15589,
"text": "Time complexity: O(M x N).Auxiliary Space: O(M x N) "
},
{
"code": null,
"e": 15951,
"s": 15642,
"text": "This article is contributed by Aarti_Rathi and Shivam Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 16812,
"s": 15951,
"text": "Submatrix Sum Queries | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersSubmatrix Sum Queries | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 12:15•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=-d8KbQVx-mM\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 16909,
"s": 16812,
"text": "Source: https://www.geeksforgeeks.org/amazon-interview-experience-set-241-1-5-years-experience/ "
},
{
"code": null,
"e": 16916,
"s": 16909,
"text": "Sam007"
},
{
"code": null,
"e": 16932,
"s": 16916,
"text": "Shashank_Sharma"
},
{
"code": null,
"e": 16947,
"s": 16932,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 16962,
"s": 16947,
"text": "varshagumber28"
},
{
"code": null,
"e": 16981,
"s": 16962,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 16998,
"s": 16981,
"text": "surinderdawra388"
},
{
"code": null,
"e": 17015,
"s": 16998,
"text": "codewithshinchan"
},
{
"code": null,
"e": 17022,
"s": 17015,
"text": "Amazon"
},
{
"code": null,
"e": 17029,
"s": 17022,
"text": "Arrays"
},
{
"code": null,
"e": 17036,
"s": 17029,
"text": "Matrix"
},
{
"code": null,
"e": 17043,
"s": 17036,
"text": "Amazon"
},
{
"code": null,
"e": 17050,
"s": 17043,
"text": "Arrays"
},
{
"code": null,
"e": 17057,
"s": 17050,
"text": "Matrix"
}
] |
ReactJS Props Complete Reference
|
07 Jun, 2022
React allows us to pass information to a Component (from a parent component to a child component) using something called props (short for properties). Props is basically an object which is available for all the React components. Props are read only and cannot be modified by the component to which it belongs.
Passing and Accessing props: We can pass props to any component as we declare attributes for any HTML tag. Have a look at the below code snippet:
<Welcome fullName = "Harsh Agarwal" />
In the above code snippet, we are passing a prop named fullName to the component named Welcome. This prop has the value “Harsh Agarwal”. Let us now see how can we access this prop (property).
For a React component, props object will store the prop as key : value pairs and it will look as shown below. fullName is the key and “John Wick” is the value.
props = { fullName: "Harsh Agarwal" }
In case of functional components, we can access a prop value as shown below.
props.propName;
Example:
Javascript
import React from "react";import ReactDOM from "react-dom"; /* Below given code will create a functional component called Welcome. This component takes one prop called fullName and displays a welcome message to the user. */ function Welcome(props) { return ( <div> <h1>Hello {props.fullName}</h1> <h2>Welcome to GeeksforGeeks</h2> </div> );} /* Below given code will render the HTML returned by the Welcome component inside the HTML element for which the id is "root" */ ReactDOM.render( <Welcome fullName="Harsh Agarwal" />, document.getElementById("root"));
Output:
The Complete list of Props are listed below:
ReactJS | Methods as Props
ReactJS | PropTypes
ReactJS | Props – Set 1
ReactJS | Props – Set 2
Unidirectional Data Flow
ReactJS | State in React
ReactJS | State vs props
ReactJS | Implementing State & Lifecycle
Rohit_Dwivedi
react-js
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jun, 2022"
},
{
"code": null,
"e": 339,
"s": 28,
"text": "React allows us to pass information to a Component (from a parent component to a child component) using something called props (short for properties). Props is basically an object which is available for all the React components. Props are read only and cannot be modified by the component to which it belongs. "
},
{
"code": null,
"e": 485,
"s": 339,
"text": "Passing and Accessing props: We can pass props to any component as we declare attributes for any HTML tag. Have a look at the below code snippet:"
},
{
"code": null,
"e": 524,
"s": 485,
"text": "<Welcome fullName = \"Harsh Agarwal\" />"
},
{
"code": null,
"e": 716,
"s": 524,
"text": "In the above code snippet, we are passing a prop named fullName to the component named Welcome. This prop has the value “Harsh Agarwal”. Let us now see how can we access this prop (property)."
},
{
"code": null,
"e": 876,
"s": 716,
"text": "For a React component, props object will store the prop as key : value pairs and it will look as shown below. fullName is the key and “John Wick” is the value."
},
{
"code": null,
"e": 914,
"s": 876,
"text": "props = { fullName: \"Harsh Agarwal\" }"
},
{
"code": null,
"e": 991,
"s": 914,
"text": "In case of functional components, we can access a prop value as shown below."
},
{
"code": null,
"e": 1007,
"s": 991,
"text": "props.propName;"
},
{
"code": null,
"e": 1016,
"s": 1007,
"text": "Example:"
},
{
"code": null,
"e": 1027,
"s": 1016,
"text": "Javascript"
},
{
"code": "import React from \"react\";import ReactDOM from \"react-dom\"; /* Below given code will create a functional component called Welcome. This component takes one prop called fullName and displays a welcome message to the user. */ function Welcome(props) { return ( <div> <h1>Hello {props.fullName}</h1> <h2>Welcome to GeeksforGeeks</h2> </div> );} /* Below given code will render the HTML returned by the Welcome component inside the HTML element for which the id is \"root\" */ ReactDOM.render( <Welcome fullName=\"Harsh Agarwal\" />, document.getElementById(\"root\"));",
"e": 1615,
"s": 1027,
"text": null
},
{
"code": null,
"e": 1623,
"s": 1615,
"text": "Output:"
},
{
"code": null,
"e": 1670,
"s": 1625,
"text": "The Complete list of Props are listed below:"
},
{
"code": null,
"e": 1697,
"s": 1670,
"text": "ReactJS | Methods as Props"
},
{
"code": null,
"e": 1717,
"s": 1697,
"text": "ReactJS | PropTypes"
},
{
"code": null,
"e": 1741,
"s": 1717,
"text": "ReactJS | Props – Set 1"
},
{
"code": null,
"e": 1765,
"s": 1741,
"text": "ReactJS | Props – Set 2"
},
{
"code": null,
"e": 1790,
"s": 1765,
"text": "Unidirectional Data Flow"
},
{
"code": null,
"e": 1815,
"s": 1790,
"text": "ReactJS | State in React"
},
{
"code": null,
"e": 1840,
"s": 1815,
"text": "ReactJS | State vs props"
},
{
"code": null,
"e": 1881,
"s": 1840,
"text": "ReactJS | Implementing State & Lifecycle"
},
{
"code": null,
"e": 1895,
"s": 1881,
"text": "Rohit_Dwivedi"
},
{
"code": null,
"e": 1904,
"s": 1895,
"text": "react-js"
},
{
"code": null,
"e": 1915,
"s": 1904,
"text": "JavaScript"
},
{
"code": null,
"e": 1923,
"s": 1915,
"text": "ReactJS"
},
{
"code": null,
"e": 1940,
"s": 1923,
"text": "Web Technologies"
}
] |
What is AGP(Accelerated Graphics Port)?
|
22 May, 2020
An Accelerated Graphics Port (AGP) is a point to point channel that is used for high-speed video output. This port is used to connect graphic cards to a computer’s motherboard. It increases the speed at which machines can render graphics while using the system’s resources more efficiently. The primary purpose of an AGP is to convey 3-D images much more smoothly than is possible on a regular PC.
The AGP was developed by Intel in the year 1996 and was launched in Socket 7 Intel P5 Pentium and Slot 1 P6 Pentium II processors. Gradually everyone started using it. Chipsets like VIA Apollo VP3, SiS 5591/5592, and the ALI Aladdin V were the first Socket 7 chipsets to support AGP.Early AGP boards used graphics processors built around Peripheral Component Interconnect (PCI) and were simply bridged to AGP. It can be said that the AGP is built from the PCI that PCI is the base. Bridging didn’t help the cards benefit much from the new bus except for the increased 66 MHz bus clock and the doubled bandwidth over PCI. Intel’s i740 was explicitly designed to exploit the new features of AGP. In fact, it was designed to texture only from AGP memory.
The various versions of AGP are discussed here
It has high quality and very fast performance.
It has a direct path to the PC’s main memory.
It connects to the CPU and operates at the speed of the processor bus.
It sends video information more quickly to the card for processing.
It uses the main memory to hold 3D images.
It provides the graphics card with two methods of directly accessing texture maps in system memory: pipelining and sideband addressing.
The port is identified by its brown colour.
It enabled to develop new classes of applications on the PC such as 3D CAD/CAM, data visualization and 3D user interfaces.
Direct Memory Execution of textures-The texture maps are directly accessed from the system memory instead of pre-loading the texture data into the Graphic card’s own memory and then accessing it. It eliminates the extra work by allowing the texture to remain in system memory where it can be directly executed on by the graphics chip.
Creation of 3D images- The CPU must perform intensive 3D calculations. The graphics controller processes the texture data and bitmaps. In many cases, the controller has to read elements from 7 or 8 different textures and combine them into a single pixel on the screen. When this calculation is performed, the pixel must be stored in the memory buffer. The memory occupied by these textures are so large, they cannot be stored on the video card’s buffer. With APG they are stored in the main system memory.
AGP was introduced as a replacement for the slower Peripheral Component Interconnect (PCI) interfaces. AGP provides a direct line of communication to the CPU and RAM, which in turn allows for quicker rendering of graphics.
Picked
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n22 May, 2020"
},
{
"code": null,
"e": 451,
"s": 53,
"text": "An Accelerated Graphics Port (AGP) is a point to point channel that is used for high-speed video output. This port is used to connect graphic cards to a computer’s motherboard. It increases the speed at which machines can render graphics while using the system’s resources more efficiently. The primary purpose of an AGP is to convey 3-D images much more smoothly than is possible on a regular PC."
},
{
"code": null,
"e": 1203,
"s": 451,
"text": "The AGP was developed by Intel in the year 1996 and was launched in Socket 7 Intel P5 Pentium and Slot 1 P6 Pentium II processors. Gradually everyone started using it. Chipsets like VIA Apollo VP3, SiS 5591/5592, and the ALI Aladdin V were the first Socket 7 chipsets to support AGP.Early AGP boards used graphics processors built around Peripheral Component Interconnect (PCI) and were simply bridged to AGP. It can be said that the AGP is built from the PCI that PCI is the base. Bridging didn’t help the cards benefit much from the new bus except for the increased 66 MHz bus clock and the doubled bandwidth over PCI. Intel’s i740 was explicitly designed to exploit the new features of AGP. In fact, it was designed to texture only from AGP memory."
},
{
"code": null,
"e": 1250,
"s": 1203,
"text": "The various versions of AGP are discussed here"
},
{
"code": null,
"e": 1297,
"s": 1250,
"text": "It has high quality and very fast performance."
},
{
"code": null,
"e": 1343,
"s": 1297,
"text": "It has a direct path to the PC’s main memory."
},
{
"code": null,
"e": 1414,
"s": 1343,
"text": "It connects to the CPU and operates at the speed of the processor bus."
},
{
"code": null,
"e": 1482,
"s": 1414,
"text": "It sends video information more quickly to the card for processing."
},
{
"code": null,
"e": 1525,
"s": 1482,
"text": "It uses the main memory to hold 3D images."
},
{
"code": null,
"e": 1661,
"s": 1525,
"text": "It provides the graphics card with two methods of directly accessing texture maps in system memory: pipelining and sideband addressing."
},
{
"code": null,
"e": 1705,
"s": 1661,
"text": "The port is identified by its brown colour."
},
{
"code": null,
"e": 1828,
"s": 1705,
"text": "It enabled to develop new classes of applications on the PC such as 3D CAD/CAM, data visualization and 3D user interfaces."
},
{
"code": null,
"e": 2163,
"s": 1828,
"text": "Direct Memory Execution of textures-The texture maps are directly accessed from the system memory instead of pre-loading the texture data into the Graphic card’s own memory and then accessing it. It eliminates the extra work by allowing the texture to remain in system memory where it can be directly executed on by the graphics chip."
},
{
"code": null,
"e": 2669,
"s": 2163,
"text": "Creation of 3D images- The CPU must perform intensive 3D calculations. The graphics controller processes the texture data and bitmaps. In many cases, the controller has to read elements from 7 or 8 different textures and combine them into a single pixel on the screen. When this calculation is performed, the pixel must be stored in the memory buffer. The memory occupied by these textures are so large, they cannot be stored on the video card’s buffer. With APG they are stored in the main system memory."
},
{
"code": null,
"e": 2892,
"s": 2669,
"text": "AGP was introduced as a replacement for the slower Peripheral Component Interconnect (PCI) interfaces. AGP provides a direct line of communication to the CPU and RAM, which in turn allows for quicker rendering of graphics."
},
{
"code": null,
"e": 2899,
"s": 2892,
"text": "Picked"
},
{
"code": null,
"e": 2925,
"s": 2899,
"text": "Advanced Computer Subject"
}
] |
Matplotlib.patches.Wedge class in Python
|
07 Oct, 2021
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.Wedge class is used to add wedge-shaped patches in the plot. The wedge is centered at xy = (x, y) with a radius r and it sweeps theta1 to theta2 (in degrees). The partial wedge is drawn from inner radius r – width to outer radius r if width is given.
Syntax: class matplotlib.patches.Wedge(center, r, theta1, theta2, width=None, **kwargs)Parameters:
center: The center point of the the wedge. r: Radius of the wedge. theta1: First angle of sweep. theta2: Second angle of sweep. width: Width of the sweep
center: The center point of the the wedge.
r: Radius of the wedge.
theta1: First angle of sweep.
theta2: Second angle of sweep.
width: Width of the sweep
The kwargs attributes are given in the table below:
Example 1:
Python3
import numpy as npfrom matplotlib.patches import Circle, Wedge, Polygonfrom matplotlib.collections import PatchCollectionimport matplotlib.pyplot as plt # Fixing random state for reproducibilitynp.random.seed(19680801) fig, ax = plt.subplots() resolution = 50 # the number of verticesN = 3x = np.random.rand(N)y = np.random.rand(N)radii = 0.1 * np.random.rand(N)patches = [] for x1, y1, r in zip(x, y, radii): circle = Circle((x1, y1), r) patches.append(circle) x = np.random.rand(N)y = np.random.rand(N)radii = 0.1 * np.random.rand(N)theta1 = 360.0 * np.random.rand(N)theta2 = 360.0 * np.random.rand(N) for x1, y1, r, t1, t2 in zip(x, y, radii, theta1, theta2): wedge = Wedge((x1, y1), r, t1, t2) patches.append(wedge) # Some limiting conditions on Wedgepatches += [ Wedge((.3, .7), .1, 0, 360), # Full circle Wedge((.7, .8), .2, 0, 360, width = 0.05), # Full ring Wedge((.8, .3), .2, 0, 45), # Full sector Wedge((.8, .3), .2, 45, 90, width = 0.10), # Ring sector] for i in range(N): polygon = Polygon(np.random.rand(N, 2), True) patches.append(polygon) colors = 100 * np.random.rand(len(patches))p = PatchCollection(patches, alpha = 0.4)p.set_array(np.array(colors))ax.add_collection(p)fig.colorbar(p, ax = ax) plt.show()
Output:
Example 2:
Python3
import numpy as npimport matplotlib.pyplot as plt fig, ax = plt.subplots(figsize =(6, 3), subplot_kw = dict(aspect ="equal")) recipe = ["375 g flour", "75 g sugar", "250 g butter", "300 g berries"] data = [float(x.split()[0]) for x in recipe]ingredients = [x.split()[-1] for x in recipe] def func(pct, allvals): absolute = int(pct / 100.*np.sum(allvals)) return "{:.1f}%\n({:d} g)".format(pct, absolute) wedges, texts, autotexts = ax.pie(data, autopct = lambda pct: func(pct, data), textprops = dict(color ="w")) ax.legend(wedges, ingredients, title ="Ingredients", loc ="center left", bbox_to_anchor =(1, 0, 0.5, 1)) plt.setp(autotexts, size = 8, weight ="bold") ax.set_title("Recipe for a pie") plt.show()
Output:
adnanirshad158
anikaseth98
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.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 242,
"s": 28,
"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": 517,
"s": 242,
"text": "The matplotlib.patches.Wedge class is used to add wedge-shaped patches in the plot. The wedge is centered at xy = (x, y) with a radius r and it sweeps theta1 to theta2 (in degrees). The partial wedge is drawn from inner radius r – width to outer radius r if width is given. "
},
{
"code": null,
"e": 618,
"s": 517,
"text": "Syntax: class matplotlib.patches.Wedge(center, r, theta1, theta2, width=None, **kwargs)Parameters: "
},
{
"code": null,
"e": 773,
"s": 618,
"text": "center: The center point of the the wedge. r: Radius of the wedge. theta1: First angle of sweep. theta2: Second angle of sweep. width: Width of the sweep "
},
{
"code": null,
"e": 817,
"s": 773,
"text": "center: The center point of the the wedge. "
},
{
"code": null,
"e": 842,
"s": 817,
"text": "r: Radius of the wedge. "
},
{
"code": null,
"e": 873,
"s": 842,
"text": "theta1: First angle of sweep. "
},
{
"code": null,
"e": 905,
"s": 873,
"text": "theta2: Second angle of sweep. "
},
{
"code": null,
"e": 932,
"s": 905,
"text": "width: Width of the sweep "
},
{
"code": null,
"e": 986,
"s": 932,
"text": "The kwargs attributes are given in the table below: "
},
{
"code": null,
"e": 999,
"s": 986,
"text": "Example 1: "
},
{
"code": null,
"e": 1007,
"s": 999,
"text": "Python3"
},
{
"code": "import numpy as npfrom matplotlib.patches import Circle, Wedge, Polygonfrom matplotlib.collections import PatchCollectionimport matplotlib.pyplot as plt # Fixing random state for reproducibilitynp.random.seed(19680801) fig, ax = plt.subplots() resolution = 50 # the number of verticesN = 3x = np.random.rand(N)y = np.random.rand(N)radii = 0.1 * np.random.rand(N)patches = [] for x1, y1, r in zip(x, y, radii): circle = Circle((x1, y1), r) patches.append(circle) x = np.random.rand(N)y = np.random.rand(N)radii = 0.1 * np.random.rand(N)theta1 = 360.0 * np.random.rand(N)theta2 = 360.0 * np.random.rand(N) for x1, y1, r, t1, t2 in zip(x, y, radii, theta1, theta2): wedge = Wedge((x1, y1), r, t1, t2) patches.append(wedge) # Some limiting conditions on Wedgepatches += [ Wedge((.3, .7), .1, 0, 360), # Full circle Wedge((.7, .8), .2, 0, 360, width = 0.05), # Full ring Wedge((.8, .3), .2, 0, 45), # Full sector Wedge((.8, .3), .2, 45, 90, width = 0.10), # Ring sector] for i in range(N): polygon = Polygon(np.random.rand(N, 2), True) patches.append(polygon) colors = 100 * np.random.rand(len(patches))p = PatchCollection(patches, alpha = 0.4)p.set_array(np.array(colors))ax.add_collection(p)fig.colorbar(p, ax = ax) plt.show()",
"e": 2318,
"s": 1007,
"text": null
},
{
"code": null,
"e": 2328,
"s": 2318,
"text": "Output: "
},
{
"code": null,
"e": 2341,
"s": 2328,
"text": "Example 2: "
},
{
"code": null,
"e": 2349,
"s": 2341,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt fig, ax = plt.subplots(figsize =(6, 3), subplot_kw = dict(aspect =\"equal\")) recipe = [\"375 g flour\", \"75 g sugar\", \"250 g butter\", \"300 g berries\"] data = [float(x.split()[0]) for x in recipe]ingredients = [x.split()[-1] for x in recipe] def func(pct, allvals): absolute = int(pct / 100.*np.sum(allvals)) return \"{:.1f}%\\n({:d} g)\".format(pct, absolute) wedges, texts, autotexts = ax.pie(data, autopct = lambda pct: func(pct, data), textprops = dict(color =\"w\")) ax.legend(wedges, ingredients, title =\"Ingredients\", loc =\"center left\", bbox_to_anchor =(1, 0, 0.5, 1)) plt.setp(autotexts, size = 8, weight =\"bold\") ax.set_title(\"Recipe for a pie\") plt.show()",
"e": 3213,
"s": 2349,
"text": null
},
{
"code": null,
"e": 3223,
"s": 3213,
"text": "Output: "
},
{
"code": null,
"e": 3240,
"s": 3225,
"text": "adnanirshad158"
},
{
"code": null,
"e": 3252,
"s": 3240,
"text": "anikaseth98"
},
{
"code": null,
"e": 3277,
"s": 3252,
"text": "Matplotlib patches-class"
},
{
"code": null,
"e": 3295,
"s": 3277,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 3302,
"s": 3295,
"text": "Python"
},
{
"code": null,
"e": 3318,
"s": 3302,
"text": "Write From Home"
}
] |
Implement rand12() using rand6() in one line
|
20 Aug, 2016
Given a function rand6() that returns random numbers from 1 to 6 with equal probability, implement one-liner function rand12() using rand6() that returns random numbers from 1 to 12 with equal probability. Solution should minimize the number of calls to rand6() method. Use of any other library function and floating point arithmetic are not allowed.
The idea is to use expression rand6() + (rand6() % 2) * 6. It returns random numbers from 1 to 12 with equal probability. The expression is equivalent to –
// if rand6() is even
if (rand6() % 2)
return 6 + rand6();
else // if rand6() is odd
return rand6();
We can also use any one of below expressions that works in a similar way –
rand6() + !(rand6() % 2) * 6 or
rand6() + (rand6() & 1) * 6 or
rand6() + !(rand6() & 1) * 6
Below is C++ implementation of above idea –
// C++ Program to print random numbers from 1 to 12// with equal probability using a function that returns// random numbers from 1 to 6 with equal probability#include <iostream>using namespace std; // Function that returns random numbers from 1 to 6// with equal probabilityint rand6(){ // rand() will generate random numbers between 0 and // RAND_MAX with equal probability // rand() % 6 returns number from 0 to 5 equal probability // (rand() % 6) + 1 returns number from 1 to 6 with // equal probability return (rand() % 6) + 1;} // The function uses rand6() to return random numbers// from 1 to 12 with equal probabilityint rand12(){ return rand6() + (rand6() % 2) * 6;} // Driver code to test above functionsint main(){ // Initialize random number generator srand(time(NULL)); int N = 12; int freq[N + 1] = { 0 }; // call rand12() multiple times and store its results for (int i = 0; i < N * 100000; i++) freq[rand12()]++; // print frequency of numbers 1-12 for (int i = 1; i <= N; i++) cout << freq[i] << " "; return 0;}
Output:
100237 100202 99678 99867 100253 99929 100287 100449 99827 99298 100019 99954
Another Solution –
int rand12()
{
return (rand6() * 2) - (rand6() & 1);
}
rand6() * 2 will return even numbers 2, 4, 6, 8, 10 and 12 with equal probability and rand6() & 1 will return 0 or 1 based on rand6() is even or odd respectively. So, the expression (rand6() * 2) – (rand6() & 1) will return random numbers from 1 to 12 with equal probability.
Please note above solutions will produce different results every time we run them.
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Randomized
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)
Shuffle a given array using Fisher–Yates shuffle Algorithm
Shuffle or Randomize a list in Java
Generating Random String Using PHP
Estimating the value of Pi using Monte Carlo
Operations on Sparse Matrices
Reservoir Sampling
Expected Number of Trials until Success
Shuffle a deck of cards
Randomized Binary Search Algorithm
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 Aug, 2016"
},
{
"code": null,
"e": 405,
"s": 54,
"text": "Given a function rand6() that returns random numbers from 1 to 6 with equal probability, implement one-liner function rand12() using rand6() that returns random numbers from 1 to 12 with equal probability. Solution should minimize the number of calls to rand6() method. Use of any other library function and floating point arithmetic are not allowed."
},
{
"code": null,
"e": 561,
"s": 405,
"text": "The idea is to use expression rand6() + (rand6() % 2) * 6. It returns random numbers from 1 to 12 with equal probability. The expression is equivalent to –"
},
{
"code": null,
"e": 671,
"s": 561,
"text": "// if rand6() is even\nif (rand6() % 2)\n return 6 + rand6();\nelse // if rand6() is odd\n return rand6();\n"
},
{
"code": null,
"e": 746,
"s": 671,
"text": "We can also use any one of below expressions that works in a similar way –"
},
{
"code": null,
"e": 778,
"s": 746,
"text": "rand6() + !(rand6() % 2) * 6 or"
},
{
"code": null,
"e": 809,
"s": 778,
"text": "rand6() + (rand6() & 1) * 6 or"
},
{
"code": null,
"e": 838,
"s": 809,
"text": "rand6() + !(rand6() & 1) * 6"
},
{
"code": null,
"e": 882,
"s": 838,
"text": "Below is C++ implementation of above idea –"
},
{
"code": "// C++ Program to print random numbers from 1 to 12// with equal probability using a function that returns// random numbers from 1 to 6 with equal probability#include <iostream>using namespace std; // Function that returns random numbers from 1 to 6// with equal probabilityint rand6(){ // rand() will generate random numbers between 0 and // RAND_MAX with equal probability // rand() % 6 returns number from 0 to 5 equal probability // (rand() % 6) + 1 returns number from 1 to 6 with // equal probability return (rand() % 6) + 1;} // The function uses rand6() to return random numbers// from 1 to 12 with equal probabilityint rand12(){ return rand6() + (rand6() % 2) * 6;} // Driver code to test above functionsint main(){ // Initialize random number generator srand(time(NULL)); int N = 12; int freq[N + 1] = { 0 }; // call rand12() multiple times and store its results for (int i = 0; i < N * 100000; i++) freq[rand12()]++; // print frequency of numbers 1-12 for (int i = 1; i <= N; i++) cout << freq[i] << \" \"; return 0;}",
"e": 1982,
"s": 882,
"text": null
},
{
"code": null,
"e": 1990,
"s": 1982,
"text": "Output:"
},
{
"code": null,
"e": 2070,
"s": 1990,
"text": "100237 100202 99678 99867 100253 99929 100287 100449 99827 99298 100019 99954 \n"
},
{
"code": null,
"e": 2089,
"s": 2070,
"text": "Another Solution –"
},
{
"code": null,
"e": 2149,
"s": 2089,
"text": "int rand12()\n{\n return (rand6() * 2) - (rand6() & 1);\n}\n"
},
{
"code": null,
"e": 2425,
"s": 2149,
"text": "rand6() * 2 will return even numbers 2, 4, 6, 8, 10 and 12 with equal probability and rand6() & 1 will return 0 or 1 based on rand6() is even or odd respectively. So, the expression (rand6() * 2) – (rand6() & 1) will return random numbers from 1 to 12 with equal probability."
},
{
"code": null,
"e": 2508,
"s": 2425,
"text": "Please note above solutions will produce different results every time we run them."
},
{
"code": null,
"e": 2807,
"s": 2508,
"text": "This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 2932,
"s": 2807,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 2943,
"s": 2932,
"text": "Randomized"
},
{
"code": null,
"e": 3041,
"s": 2943,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3120,
"s": 3041,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)"
},
{
"code": null,
"e": 3179,
"s": 3120,
"text": "Shuffle a given array using Fisher–Yates shuffle Algorithm"
},
{
"code": null,
"e": 3215,
"s": 3179,
"text": "Shuffle or Randomize a list in Java"
},
{
"code": null,
"e": 3250,
"s": 3215,
"text": "Generating Random String Using PHP"
},
{
"code": null,
"e": 3295,
"s": 3250,
"text": "Estimating the value of Pi using Monte Carlo"
},
{
"code": null,
"e": 3325,
"s": 3295,
"text": "Operations on Sparse Matrices"
},
{
"code": null,
"e": 3344,
"s": 3325,
"text": "Reservoir Sampling"
},
{
"code": null,
"e": 3384,
"s": 3344,
"text": "Expected Number of Trials until Success"
},
{
"code": null,
"e": 3408,
"s": 3384,
"text": "Shuffle a deck of cards"
}
] |
Lodash _.throttle() Method
|
23 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.throttle() method in lodash is used to create a throttled function that can only call the func parameter maximally once per every wait milliseconds. The throttled function here has a cancel method which is used to cancel func calls that are delayed and it also has a flush method which is used to immediately call that delayed func. Moreover, it provides some options which are used to imply whether the func stated should be called on the leading and/or the trailing edge of the wait timeout.
Syntax:
_.throttle(func, wait, options)
Parameters: The method accept three parameters as mentioned above and described below:
func: It is the function to be throttled.
wait: It is the number of milliseconds for which the calls are to be throttled.
options: It is the options object.options.leading: It defines the calling on the leading edge of the timeout.options.trailing: It defines the calling on the trailing edge of the timeout.
options.leading: It defines the calling on the leading edge of the timeout.
options.trailing: It defines the calling on the trailing edge of the timeout.
Return Value: This method returns the new throttled function.
Note:
Here, func is called with the last arguments that are given to the throttled function. However, consequent calls to the throttled function return the result of the last func call.
Here, if the leading and the trailing options are true, then func is called on the trailing edge of the timeout if and only if the throttled function is called more than once throughout the wait timeout.
Here, if the wait time is 0 and the leading option is false, then the func call is delayed until to the next tick.
Example 1:
Javascript
// Requiring lodash libraryconst _ = require('lodash'); // Calling throttle() method with its parametervar throt_fun = _.throttle(function () { console.log('Function throttled after 1000ms!'); }, 1000); throt_fun();
Output: Here, after the function is throttled after 1000ms as the waiting time here is 1000ms.
Function throttled after 1000ms!
Example 2:
Javascript
// Requiring lodash libraryconst _ = require('lodash'); // Calling throttle() method with its parametervar throt_fun = _.throttle(function() { console.log('Function throttled after 1000ms!'); }, 1000); // Defining loopvar loop = function() { setTimeout(loop, 5) throt_fun();}; // Calling loop to startloop();
Output: So, here the loop doesn’t stop until you stop it manually.
Function throttled after 1000ms!
Function throttled after 1000ms!
Function throttled after 1000ms!
Function throttled after 1000ms!
Function throttled after 1000ms!
Function throttled after 1000ms!
.
.
.
.
// So on until you stop it manually.
Example 3: Here, the function is called on the trailing edge of the timeout.
Javascript
// Requiring lodash libraryconst _ = require('lodash'); // Calling throttle() method with its parametervar throt_fun = _.throttle(function () { console.log('Function is called on the' + ' trailing edge of the timeout ' + 'and throttled after 2000ms!'); }, 2000, { 'trailing': true }); throt_fun();
Output:
Function is called on the trailing edge of the
timeout and throttled after 2000ms!
Reference: https://lodash.com/docs/4.17.15#throttle
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Sep, 2020"
},
{
"code": null,
"e": 168,
"s": 28,
"text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc."
},
{
"code": null,
"e": 668,
"s": 168,
"text": "The _.throttle() method in lodash is used to create a throttled function that can only call the func parameter maximally once per every wait milliseconds. The throttled function here has a cancel method which is used to cancel func calls that are delayed and it also has a flush method which is used to immediately call that delayed func. Moreover, it provides some options which are used to imply whether the func stated should be called on the leading and/or the trailing edge of the wait timeout."
},
{
"code": null,
"e": 676,
"s": 668,
"text": "Syntax:"
},
{
"code": null,
"e": 708,
"s": 676,
"text": "_.throttle(func, wait, options)"
},
{
"code": null,
"e": 795,
"s": 708,
"text": "Parameters: The method accept three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 837,
"s": 795,
"text": "func: It is the function to be throttled."
},
{
"code": null,
"e": 917,
"s": 837,
"text": "wait: It is the number of milliseconds for which the calls are to be throttled."
},
{
"code": null,
"e": 1104,
"s": 917,
"text": "options: It is the options object.options.leading: It defines the calling on the leading edge of the timeout.options.trailing: It defines the calling on the trailing edge of the timeout."
},
{
"code": null,
"e": 1180,
"s": 1104,
"text": "options.leading: It defines the calling on the leading edge of the timeout."
},
{
"code": null,
"e": 1258,
"s": 1180,
"text": "options.trailing: It defines the calling on the trailing edge of the timeout."
},
{
"code": null,
"e": 1320,
"s": 1258,
"text": "Return Value: This method returns the new throttled function."
},
{
"code": null,
"e": 1326,
"s": 1320,
"text": "Note:"
},
{
"code": null,
"e": 1506,
"s": 1326,
"text": "Here, func is called with the last arguments that are given to the throttled function. However, consequent calls to the throttled function return the result of the last func call."
},
{
"code": null,
"e": 1710,
"s": 1506,
"text": "Here, if the leading and the trailing options are true, then func is called on the trailing edge of the timeout if and only if the throttled function is called more than once throughout the wait timeout."
},
{
"code": null,
"e": 1825,
"s": 1710,
"text": "Here, if the wait time is 0 and the leading option is false, then the func call is delayed until to the next tick."
},
{
"code": null,
"e": 1836,
"s": 1825,
"text": "Example 1:"
},
{
"code": null,
"e": 1847,
"s": 1836,
"text": "Javascript"
},
{
"code": "// Requiring lodash libraryconst _ = require('lodash'); // Calling throttle() method with its parametervar throt_fun = _.throttle(function () { console.log('Function throttled after 1000ms!'); }, 1000); throt_fun();",
"e": 2075,
"s": 1847,
"text": null
},
{
"code": null,
"e": 2170,
"s": 2075,
"text": "Output: Here, after the function is throttled after 1000ms as the waiting time here is 1000ms."
},
{
"code": null,
"e": 2203,
"s": 2170,
"text": "Function throttled after 1000ms!"
},
{
"code": null,
"e": 2214,
"s": 2203,
"text": "Example 2:"
},
{
"code": null,
"e": 2225,
"s": 2214,
"text": "Javascript"
},
{
"code": "// Requiring lodash libraryconst _ = require('lodash'); // Calling throttle() method with its parametervar throt_fun = _.throttle(function() { console.log('Function throttled after 1000ms!'); }, 1000); // Defining loopvar loop = function() { setTimeout(loop, 5) throt_fun();}; // Calling loop to startloop();",
"e": 2553,
"s": 2225,
"text": null
},
{
"code": null,
"e": 2620,
"s": 2553,
"text": "Output: So, here the loop doesn’t stop until you stop it manually."
},
{
"code": null,
"e": 2864,
"s": 2620,
"text": "Function throttled after 1000ms!\nFunction throttled after 1000ms!\nFunction throttled after 1000ms!\nFunction throttled after 1000ms!\nFunction throttled after 1000ms!\nFunction throttled after 1000ms!\n.\n.\n.\n.\n// So on until you stop it manually.\n"
},
{
"code": null,
"e": 2941,
"s": 2864,
"text": "Example 3: Here, the function is called on the trailing edge of the timeout."
},
{
"code": null,
"e": 2952,
"s": 2941,
"text": "Javascript"
},
{
"code": "// Requiring lodash libraryconst _ = require('lodash'); // Calling throttle() method with its parametervar throt_fun = _.throttle(function () { console.log('Function is called on the' + ' trailing edge of the timeout ' + 'and throttled after 2000ms!'); }, 2000, { 'trailing': true }); throt_fun();",
"e": 3272,
"s": 2952,
"text": null
},
{
"code": null,
"e": 3280,
"s": 3272,
"text": "Output:"
},
{
"code": null,
"e": 3364,
"s": 3280,
"text": "Function is called on the trailing edge of the \ntimeout and throttled after 2000ms!"
},
{
"code": null,
"e": 3416,
"s": 3364,
"text": "Reference: https://lodash.com/docs/4.17.15#throttle"
},
{
"code": null,
"e": 3434,
"s": 3416,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 3445,
"s": 3434,
"text": "JavaScript"
},
{
"code": null,
"e": 3462,
"s": 3445,
"text": "Web Technologies"
},
{
"code": null,
"e": 3560,
"s": 3462,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3621,
"s": 3560,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3693,
"s": 3621,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3733,
"s": 3693,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3774,
"s": 3733,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3820,
"s": 3774,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 3853,
"s": 3820,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3915,
"s": 3853,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3976,
"s": 3915,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4026,
"s": 3976,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
All the Core Functions of Python Pandas You Need to Know | Towards Data Science
|
As one of the most popular libraries in the Python programming language, Pandas is a “must-learn” library for Data I/O, cleansing, transforming and aggregation.
It is quite common to see such kinds of questions in Stack Overflow regarding Pandas:
How to transform my data frame like ...
How to count distinct values of a column ...
How to convert column types from ... to ...
How to merge two data frames ...
and so on
In my opinion, all the newbies of Pandas should know at least the basic Pandas functions and practice them before starting to actually use them. There are not too many, but can help you to solve most of the regular problems.
What are these functions? OK. In this article, I’ve organised all of these functions into different categories with separated tables. If you believe that you may already know some ( If you have ever used Pandas you must know at least some of them), the tables below are TD; DL for you to check your knowledge before you read through.
Notations in the tables:
pd: Pandas
df: Data Frame Object
s: Series Object (a column of Data Frame)
Next, let me demonstrate these functions. I will give sample usage of them, but of course, I can’t enumerate all the scenarios that these functions that might be used. So, it is highly recommended to practice them by yourself.
Reading and Writing from CSV, Excel and JSON documents are used very similarly. Note that you can either read from a local path or an URL.
# Read from local pathdf1 = pd.read_csv('./data.csv')df2 = pd.read_excel('./data.xlsx', sheet_name='Sheet1')df3 = pd.read_json('http://example.com/data.json', orient='records')
In read_excel, we can specify which spreadsheet to load by giving the sheet_name, if multiple sheets are existing.
For read_json, it is important to use the orient parameter correctly. The most commonly used are records when the JSON document is an array, and index if you want to use the root keys as indices.
The to_csv, to_excel and to_json are the corresponding writing functions. The important difference is that we need to call these functions from a Data Frame object rather than the Pandas object.
df1.to_csv('./data.csv')df2.to_excel('./data.xlsx')df3.to_json('./data.json')
Reading and Writing directly from/to the database is a bit more tricky. Pandas support multiple libraries such as pymssql for SQL Server and pymysql for MySQL. However, the one I like the most is sqlalchemy which supports the most popular databases even including cloud databases such as Snowflake DB.
from sqlalchemy import create_enginedb_engine = create_engine( 'snowflake://{user}:{password}@{account}/'.format( user='...', password='...', account='...',))df = pd.read_sql("SHOW TABLES", db_engine)df.head()
Very often, we want to get a general picture of the dataset we have, or just want to check whether the data has been loaded into Pandas data frame correctly or not. We’ll need to know several functions to do such.
df = pd.DataFrame({ 'id': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'name': ['Alice', 'Bob', 'Chris', 'David', 'Ella', 'Frank', 'Grace', 'Hellen', 'Iva', 'Jack']})df.head()
For demonstrating purpose, I firstly created a data frame with two columns — “id” and “name”.
The df.head() function shows the top 5 rows by default.
However, you can always specify how many rows to show such as df.head(10) to show 10 rows.
df.tail()
Similar to df.head() this function will show the tail n rows.
This will be helpful when your dataset is sorted, and you want to check the results.
df.sort_values(by='name', ascending=False, inplace=True)df.head()
We can sort by either ascending or descending. Note that inplace needs to be set to True if you want to assign the sorted data frame back to your variable. Otherwise, your data frame df will not be changed.
Please note that this is not a function, but a property of the data frame.
df.columns
Getting the property value will return the following results.
Also, you can assign a list to this property to rename all the columns of the data frame. For example:
df.columns = ['no', 'firstname']
This is also a property of the data frame that returns all the data types for the columns. It is very useful when you want to check the data types, especially dealing with datetime columns.
df.dtypes
This is probably the property that I use the most. Very frequently we may want to check the number of rows and columns of our data frame.
df.shape
Please note that this property is a tuple, where the first element is row count and the second one is column count.
df.describe()
When we are dealing with some measures, we may want to have a picture of the data distribution. df.describe() gives this rough statistics.
When this function is called for a data frame with multiple columns, the non-numeric ones will be ignored.
Note that the stats for id columns doesn’t make any sense, but it demonstrates the function.
This function applies to a Pandas series rather than a data frame. It counts the occurrence of each value in the series.
Let’s create another data frame with some duplicated names. Then, count the name frequencies in this data frame. Please note that we use df.name or df['name'] to get the name column of the data frame as a series on which the value_counts() function can be applied.
df = pd.DataFrame({'id': [1, 2, 3, 4, 5], 'name': ['Alice', 'Bob', 'Chris', 'Chris', 'Alice']})df.name.value_counts()
It is quite common that the raw dataset we got is not perfect. So, we need to clean the dataset before use. Here are the related Pandas functions.
When we want to filter “NULL” values in the data frame, this function will help. Let’s create another data frame with some NULL values in the name column. Note that we use None in Python for null objects.
df = pd.DataFrame({'id': [1, 2, 3, 4, 5], 'name': ['Alice', 'Bob', None, 'Chris', None]})
Then, suppose we want to filter all the NULL values out.
df[~df.name.isna()]
df.name helps to get the “name” column of the data frame as a series, and then isna() returns a series of boolean values representing whether the name is null. After that, the ~ sign at the beginning reversed the boolean value, since we want to reserve the rows that NOT having NULL values. Finally, the data frame df will be filtered by this boolean series, where the row with the “False” boolean value will be discarded.
df = pd.DataFrame({'id': [1, 2, 3, None, 5], 'name': ['Alice', 'Bob', None, 'Chris', None]})df.dropna()
What if we have multiple columns that have null values and we want to filter out all the rows having at least one null value? Well, we could still use the above method but you’ll need to repeat many times for every column.
df = pd.DataFrame({'id': [1, 2, 3, 4, 5], 'name': ['Alice', 'Bob', None, 'Chris', None]})df.fillna('Unknown')
Sometimes we may don’t want to simply discard the row with null values. Instead, we want to fill the null values with something else.
In this example, the name column with null values are replaced with the “Unknown” string, and we still have these rows.
df = pd.DataFrame({'id': [1, 2, 3, 4, 3], 'name': ['Alice', 'Bob', 'Chris', 'David', 'Chris']})df.drop_duplicates()
Sometimes the raw dataset may have some duplicated rows which we don’t actually want them.
In this example, we have two “Chris” with id = 3. So, the function dropped the second.
df = pd.DataFrame({'id': [1, 2, 3, 4, 3], 'name': ['Alice', 'Bob', 'Chris', 'David', 'Ella'], 'comments': ['', '', 'author', '', '']})df.drop(columns=['comments'])
In this example, the data frame has 3 columns.
Suppose that we don’t need the “comments” column, we could use df.drop() function to drop it.
This function can also be used to drop rows.
df = pd.DataFrame({'id': [1, 2, 3, 4, 5], 'name': ['Alice', 'Bob', 'Chris', 'David', 'Ella']})df.rename(columns={'id': 'no', 'name': 'firstname'})
In this example, the data frame is still created with the column names “id” and “name”. However, the df.rename() function helped to rename the column headers.
Please note that it takes a dictionary as the parameter, where the keys are the old headers and the values are the new headers.
df = pd.DataFrame({'name': ['Alice', 'Bob', 'Chris', 'David', 'Ella']})df.reset_index()
In this example, the data frame has only the “name” column. So, what if we want to create another column as an identity?
If you think a column from the row number is fine, simply use the df.reset_index() function.
There is another typical usage of this function. Imagine that we have just cleansed the dataset that some duplicated rows were discarded. However, the index will not be continuous anymore. If you want to have a continuous index again, this function helps too.
After the data cleansing, we may need to transform the data.
Commonly, we have our raw dataset with all the dates or times in string format. For the later on analytics purposes such as sorting, we may want to convert these strings into the datetime objects.
df = pd.DataFrame({'datetime': ['01/04/2020', '02/04/2020', '03/04/2020']})pd.to_datetime(df.datetime, format='%d/%m/%Y')
Please note that this function returns a series, so we can assign it back to the column of the data frame.
This function helps us to convert the data type of a column easily. In the example, the data frame was created with its “id” field with all string types. Then, the s.astype() function helped to convert them into integers.
df = pd.DataFrame({'id': ['1', '2', '3', '4', '5']})df.id.astype(int)
This is probably the function that I used the most. Although Pandas allows us to easily perform some transformation to a whole column of a data frame, for example, df.col + 1 will add 1 to all the values of this column. However, sometimes we may need to do something unique which are not supported by Pandas built-in functions. In this case, the apply() function helps.
When we use the apply() function, it is very common to use a lambda function along with it. In the example below, we manually used apply() function achieved df.number + 1.
df = pd.DataFrame({'number': [1, 2, 3, 4, 5]})df.number.apply(lambda n: n+1)
In some special cases, the lambda function may not be enough. For example, we have a whole bunch of logic to apply to a column, which can only be put in a customised function. So, the apply() function can also be used along with customised functions.
The example below uses a customised function that does the same thing.
def add1(n): return n+1df.number.apply(add1)
What if we need to use multiple columns in an apply() function? In fact, the apply() function can be used on a data frame object as well.
df = pd.DataFrame({'num1': [1, 2, 3, 4, 5], 'num2': [5, 4, 3, 2, 1]})df.apply(lambda row: row['num1'] + row['num2'], axis=1)
In the above example, the data frame is created with two numeric columns. Then, we use the lambda function to get each row with all the cells. After that, we can still use ['col_name'] to access the values. So, row[‘num1’] + row[‘num2’] will return the sum of the values from both of the columns.
Very importantly, the parameter axis=1 must be specified here, because the apply() function on a data frame object will be applied on row indices by default.
Similarly, we can also use a customised function.
def sum_cols(row): return row['num1'] + row['num2']df.apply(sum_cols, axis=1)
I used to use this function when dealing with JSON documents. Because of the style of JSON, sometimes we have one key with an array value. In this case, we can easily flatten the array.
df = pd.DataFrame([{ 'name': 'Chris', 'languages': ['Python', 'Java']},{ 'name': 'Jade', 'languages': ['Java', 'Javascript']}])
In this example, the languages that are directly loaded from a JSON document are still arrays. Then, let’s use df.explode() function to flatten it out.
df.explode('languages')
Data Aggregation plays an important role in Data Analytics. Pandas provide many ways to perform data aggregation. Here I organised some functions that you must know as basics.
df1 = pd.DataFrame({'id': [1, 2, 3], 'name': ['Alice', 'Bob', 'Chris']})df2 = pd.DataFrame({'id': [4, 5], 'name': ['David', 'Ella']})pd.concat([df1, df2])
In this example, two data frames are created.
Then, we can use the pd.concat() function to concatenate them together as one.
Please note that we can also use this function to concatenate vertically. Feel not comfortable about the index? Do you still remember the df.reset_index() function? :)
This is another one that I used a lot in practice. If you have experience in SQL queries, this is just like joining two tables.
df1 = pd.DataFrame({'id': [1, 2, 3], 'name': ['Olivier', 'Jade', 'Chris']})df2 = pd.DataFrame({'id': [1, 2, 3], 'language': ['Objective-C', 'Java', 'Python']})pd.merge(df1, df2, on='id', how='inner')
As shown in the code block above, there are two data frames created with the “name” column and the “language” column respectively. Then, we can use this function to “join” them together. Please note that we need to specify which column that is used to join on with on='id' and specify how the two data frames are joined how='inner'.
These two functions would be better demonstrated together, as the function df.groupby() cannot produce meaningful results by itself. It has to be used together with other functions that apply to the groups, which I believe df.groupby().agg() is the most common one.
df = pd.DataFrame({'id': [1, 2, 3, 4, 5], 'name': ['Alice', 'Bob', 'Chris', 'David', 'Ella'], 'language': ['Python', 'Java', 'Python', 'COBOL', 'Java'], 'age': [21, 32, 31, 68, 29]})df.groupby('language').agg({'name': 'count', 'age': 'mean'})
In this example, we created a data frame with “name”, “language” and “age”.
Then, the data frame is grouped by the languages, and we count the number of names and averaging the ages among these persons. Well, the column headers don’t make sense now, but we can use the df.rename() function to fix them.
For the above example, we can also implement it using the pd.pivot_table() function. That is, we need to specify the group keys and the measure values as follows (using the same data frame in the previous example):
pd.pivot_table(df, values=['name', 'age'], index=['language'], aggfunc={'name': 'count', 'age': ['min', 'max', 'mean']})
Therefore, it is obvious that the pd.pivot_table() function is more convenient when we have multiple levels of group keys and measure values.
Indeed, the Pandas library of Python has a lot more functions that makes it such a flexible and powerful data analytics tool in Python. In this article, I just organised the basic ones that I believe are the most useful. If one can nail all of them, definitely can start to use Pandas to perform some simple data analytics. Of course, there is still a lot to learn to become a master.
medium.com
If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)
|
[
{
"code": null,
"e": 333,
"s": 172,
"text": "As one of the most popular libraries in the Python programming language, Pandas is a “must-learn” library for Data I/O, cleansing, transforming and aggregation."
},
{
"code": null,
"e": 419,
"s": 333,
"text": "It is quite common to see such kinds of questions in Stack Overflow regarding Pandas:"
},
{
"code": null,
"e": 459,
"s": 419,
"text": "How to transform my data frame like ..."
},
{
"code": null,
"e": 504,
"s": 459,
"text": "How to count distinct values of a column ..."
},
{
"code": null,
"e": 548,
"s": 504,
"text": "How to convert column types from ... to ..."
},
{
"code": null,
"e": 581,
"s": 548,
"text": "How to merge two data frames ..."
},
{
"code": null,
"e": 591,
"s": 581,
"text": "and so on"
},
{
"code": null,
"e": 816,
"s": 591,
"text": "In my opinion, all the newbies of Pandas should know at least the basic Pandas functions and practice them before starting to actually use them. There are not too many, but can help you to solve most of the regular problems."
},
{
"code": null,
"e": 1150,
"s": 816,
"text": "What are these functions? OK. In this article, I’ve organised all of these functions into different categories with separated tables. If you believe that you may already know some ( If you have ever used Pandas you must know at least some of them), the tables below are TD; DL for you to check your knowledge before you read through."
},
{
"code": null,
"e": 1175,
"s": 1150,
"text": "Notations in the tables:"
},
{
"code": null,
"e": 1186,
"s": 1175,
"text": "pd: Pandas"
},
{
"code": null,
"e": 1208,
"s": 1186,
"text": "df: Data Frame Object"
},
{
"code": null,
"e": 1250,
"s": 1208,
"text": "s: Series Object (a column of Data Frame)"
},
{
"code": null,
"e": 1477,
"s": 1250,
"text": "Next, let me demonstrate these functions. I will give sample usage of them, but of course, I can’t enumerate all the scenarios that these functions that might be used. So, it is highly recommended to practice them by yourself."
},
{
"code": null,
"e": 1616,
"s": 1477,
"text": "Reading and Writing from CSV, Excel and JSON documents are used very similarly. Note that you can either read from a local path or an URL."
},
{
"code": null,
"e": 1793,
"s": 1616,
"text": "# Read from local pathdf1 = pd.read_csv('./data.csv')df2 = pd.read_excel('./data.xlsx', sheet_name='Sheet1')df3 = pd.read_json('http://example.com/data.json', orient='records')"
},
{
"code": null,
"e": 1908,
"s": 1793,
"text": "In read_excel, we can specify which spreadsheet to load by giving the sheet_name, if multiple sheets are existing."
},
{
"code": null,
"e": 2104,
"s": 1908,
"text": "For read_json, it is important to use the orient parameter correctly. The most commonly used are records when the JSON document is an array, and index if you want to use the root keys as indices."
},
{
"code": null,
"e": 2299,
"s": 2104,
"text": "The to_csv, to_excel and to_json are the corresponding writing functions. The important difference is that we need to call these functions from a Data Frame object rather than the Pandas object."
},
{
"code": null,
"e": 2377,
"s": 2299,
"text": "df1.to_csv('./data.csv')df2.to_excel('./data.xlsx')df3.to_json('./data.json')"
},
{
"code": null,
"e": 2679,
"s": 2377,
"text": "Reading and Writing directly from/to the database is a bit more tricky. Pandas support multiple libraries such as pymssql for SQL Server and pymysql for MySQL. However, the one I like the most is sqlalchemy which supports the most popular databases even including cloud databases such as Snowflake DB."
},
{
"code": null,
"e": 2901,
"s": 2679,
"text": "from sqlalchemy import create_enginedb_engine = create_engine( 'snowflake://{user}:{password}@{account}/'.format( user='...', password='...', account='...',))df = pd.read_sql(\"SHOW TABLES\", db_engine)df.head()"
},
{
"code": null,
"e": 3115,
"s": 2901,
"text": "Very often, we want to get a general picture of the dataset we have, or just want to check whether the data has been loaded into Pandas data frame correctly or not. We’ll need to know several functions to do such."
},
{
"code": null,
"e": 3285,
"s": 3115,
"text": "df = pd.DataFrame({ 'id': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'name': ['Alice', 'Bob', 'Chris', 'David', 'Ella', 'Frank', 'Grace', 'Hellen', 'Iva', 'Jack']})df.head()"
},
{
"code": null,
"e": 3379,
"s": 3285,
"text": "For demonstrating purpose, I firstly created a data frame with two columns — “id” and “name”."
},
{
"code": null,
"e": 3435,
"s": 3379,
"text": "The df.head() function shows the top 5 rows by default."
},
{
"code": null,
"e": 3526,
"s": 3435,
"text": "However, you can always specify how many rows to show such as df.head(10) to show 10 rows."
},
{
"code": null,
"e": 3536,
"s": 3526,
"text": "df.tail()"
},
{
"code": null,
"e": 3598,
"s": 3536,
"text": "Similar to df.head() this function will show the tail n rows."
},
{
"code": null,
"e": 3683,
"s": 3598,
"text": "This will be helpful when your dataset is sorted, and you want to check the results."
},
{
"code": null,
"e": 3749,
"s": 3683,
"text": "df.sort_values(by='name', ascending=False, inplace=True)df.head()"
},
{
"code": null,
"e": 3956,
"s": 3749,
"text": "We can sort by either ascending or descending. Note that inplace needs to be set to True if you want to assign the sorted data frame back to your variable. Otherwise, your data frame df will not be changed."
},
{
"code": null,
"e": 4031,
"s": 3956,
"text": "Please note that this is not a function, but a property of the data frame."
},
{
"code": null,
"e": 4042,
"s": 4031,
"text": "df.columns"
},
{
"code": null,
"e": 4104,
"s": 4042,
"text": "Getting the property value will return the following results."
},
{
"code": null,
"e": 4207,
"s": 4104,
"text": "Also, you can assign a list to this property to rename all the columns of the data frame. For example:"
},
{
"code": null,
"e": 4240,
"s": 4207,
"text": "df.columns = ['no', 'firstname']"
},
{
"code": null,
"e": 4430,
"s": 4240,
"text": "This is also a property of the data frame that returns all the data types for the columns. It is very useful when you want to check the data types, especially dealing with datetime columns."
},
{
"code": null,
"e": 4440,
"s": 4430,
"text": "df.dtypes"
},
{
"code": null,
"e": 4578,
"s": 4440,
"text": "This is probably the property that I use the most. Very frequently we may want to check the number of rows and columns of our data frame."
},
{
"code": null,
"e": 4587,
"s": 4578,
"text": "df.shape"
},
{
"code": null,
"e": 4703,
"s": 4587,
"text": "Please note that this property is a tuple, where the first element is row count and the second one is column count."
},
{
"code": null,
"e": 4717,
"s": 4703,
"text": "df.describe()"
},
{
"code": null,
"e": 4856,
"s": 4717,
"text": "When we are dealing with some measures, we may want to have a picture of the data distribution. df.describe() gives this rough statistics."
},
{
"code": null,
"e": 4963,
"s": 4856,
"text": "When this function is called for a data frame with multiple columns, the non-numeric ones will be ignored."
},
{
"code": null,
"e": 5056,
"s": 4963,
"text": "Note that the stats for id columns doesn’t make any sense, but it demonstrates the function."
},
{
"code": null,
"e": 5177,
"s": 5056,
"text": "This function applies to a Pandas series rather than a data frame. It counts the occurrence of each value in the series."
},
{
"code": null,
"e": 5442,
"s": 5177,
"text": "Let’s create another data frame with some duplicated names. Then, count the name frequencies in this data frame. Please note that we use df.name or df['name'] to get the name column of the data frame as a series on which the value_counts() function can be applied."
},
{
"code": null,
"e": 5578,
"s": 5442,
"text": "df = pd.DataFrame({'id': [1, 2, 3, 4, 5], 'name': ['Alice', 'Bob', 'Chris', 'Chris', 'Alice']})df.name.value_counts()"
},
{
"code": null,
"e": 5725,
"s": 5578,
"text": "It is quite common that the raw dataset we got is not perfect. So, we need to clean the dataset before use. Here are the related Pandas functions."
},
{
"code": null,
"e": 5930,
"s": 5725,
"text": "When we want to filter “NULL” values in the data frame, this function will help. Let’s create another data frame with some NULL values in the name column. Note that we use None in Python for null objects."
},
{
"code": null,
"e": 6038,
"s": 5930,
"text": "df = pd.DataFrame({'id': [1, 2, 3, 4, 5], 'name': ['Alice', 'Bob', None, 'Chris', None]})"
},
{
"code": null,
"e": 6095,
"s": 6038,
"text": "Then, suppose we want to filter all the NULL values out."
},
{
"code": null,
"e": 6115,
"s": 6095,
"text": "df[~df.name.isna()]"
},
{
"code": null,
"e": 6538,
"s": 6115,
"text": "df.name helps to get the “name” column of the data frame as a series, and then isna() returns a series of boolean values representing whether the name is null. After that, the ~ sign at the beginning reversed the boolean value, since we want to reserve the rows that NOT having NULL values. Finally, the data frame df will be filtered by this boolean series, where the row with the “False” boolean value will be discarded."
},
{
"code": null,
"e": 6642,
"s": 6538,
"text": "df = pd.DataFrame({'id': [1, 2, 3, None, 5], 'name': ['Alice', 'Bob', None, 'Chris', None]})df.dropna()"
},
{
"code": null,
"e": 6865,
"s": 6642,
"text": "What if we have multiple columns that have null values and we want to filter out all the rows having at least one null value? Well, we could still use the above method but you’ll need to repeat many times for every column."
},
{
"code": null,
"e": 6993,
"s": 6865,
"text": "df = pd.DataFrame({'id': [1, 2, 3, 4, 5], 'name': ['Alice', 'Bob', None, 'Chris', None]})df.fillna('Unknown')"
},
{
"code": null,
"e": 7127,
"s": 6993,
"text": "Sometimes we may don’t want to simply discard the row with null values. Instead, we want to fill the null values with something else."
},
{
"code": null,
"e": 7247,
"s": 7127,
"text": "In this example, the name column with null values are replaced with the “Unknown” string, and we still have these rows."
},
{
"code": null,
"e": 7381,
"s": 7247,
"text": "df = pd.DataFrame({'id': [1, 2, 3, 4, 3], 'name': ['Alice', 'Bob', 'Chris', 'David', 'Chris']})df.drop_duplicates()"
},
{
"code": null,
"e": 7472,
"s": 7381,
"text": "Sometimes the raw dataset may have some duplicated rows which we don’t actually want them."
},
{
"code": null,
"e": 7559,
"s": 7472,
"text": "In this example, we have two “Chris” with id = 3. So, the function dropped the second."
},
{
"code": null,
"e": 7759,
"s": 7559,
"text": "df = pd.DataFrame({'id': [1, 2, 3, 4, 3], 'name': ['Alice', 'Bob', 'Chris', 'David', 'Ella'], 'comments': ['', '', 'author', '', '']})df.drop(columns=['comments'])"
},
{
"code": null,
"e": 7806,
"s": 7759,
"text": "In this example, the data frame has 3 columns."
},
{
"code": null,
"e": 7900,
"s": 7806,
"text": "Suppose that we don’t need the “comments” column, we could use df.drop() function to drop it."
},
{
"code": null,
"e": 7945,
"s": 7900,
"text": "This function can also be used to drop rows."
},
{
"code": null,
"e": 8110,
"s": 7945,
"text": "df = pd.DataFrame({'id': [1, 2, 3, 4, 5], 'name': ['Alice', 'Bob', 'Chris', 'David', 'Ella']})df.rename(columns={'id': 'no', 'name': 'firstname'})"
},
{
"code": null,
"e": 8269,
"s": 8110,
"text": "In this example, the data frame is still created with the column names “id” and “name”. However, the df.rename() function helped to rename the column headers."
},
{
"code": null,
"e": 8397,
"s": 8269,
"text": "Please note that it takes a dictionary as the parameter, where the keys are the old headers and the values are the new headers."
},
{
"code": null,
"e": 8485,
"s": 8397,
"text": "df = pd.DataFrame({'name': ['Alice', 'Bob', 'Chris', 'David', 'Ella']})df.reset_index()"
},
{
"code": null,
"e": 8606,
"s": 8485,
"text": "In this example, the data frame has only the “name” column. So, what if we want to create another column as an identity?"
},
{
"code": null,
"e": 8699,
"s": 8606,
"text": "If you think a column from the row number is fine, simply use the df.reset_index() function."
},
{
"code": null,
"e": 8959,
"s": 8699,
"text": "There is another typical usage of this function. Imagine that we have just cleansed the dataset that some duplicated rows were discarded. However, the index will not be continuous anymore. If you want to have a continuous index again, this function helps too."
},
{
"code": null,
"e": 9020,
"s": 8959,
"text": "After the data cleansing, we may need to transform the data."
},
{
"code": null,
"e": 9217,
"s": 9020,
"text": "Commonly, we have our raw dataset with all the dates or times in string format. For the later on analytics purposes such as sorting, we may want to convert these strings into the datetime objects."
},
{
"code": null,
"e": 9339,
"s": 9217,
"text": "df = pd.DataFrame({'datetime': ['01/04/2020', '02/04/2020', '03/04/2020']})pd.to_datetime(df.datetime, format='%d/%m/%Y')"
},
{
"code": null,
"e": 9446,
"s": 9339,
"text": "Please note that this function returns a series, so we can assign it back to the column of the data frame."
},
{
"code": null,
"e": 9668,
"s": 9446,
"text": "This function helps us to convert the data type of a column easily. In the example, the data frame was created with its “id” field with all string types. Then, the s.astype() function helped to convert them into integers."
},
{
"code": null,
"e": 9738,
"s": 9668,
"text": "df = pd.DataFrame({'id': ['1', '2', '3', '4', '5']})df.id.astype(int)"
},
{
"code": null,
"e": 10108,
"s": 9738,
"text": "This is probably the function that I used the most. Although Pandas allows us to easily perform some transformation to a whole column of a data frame, for example, df.col + 1 will add 1 to all the values of this column. However, sometimes we may need to do something unique which are not supported by Pandas built-in functions. In this case, the apply() function helps."
},
{
"code": null,
"e": 10280,
"s": 10108,
"text": "When we use the apply() function, it is very common to use a lambda function along with it. In the example below, we manually used apply() function achieved df.number + 1."
},
{
"code": null,
"e": 10357,
"s": 10280,
"text": "df = pd.DataFrame({'number': [1, 2, 3, 4, 5]})df.number.apply(lambda n: n+1)"
},
{
"code": null,
"e": 10608,
"s": 10357,
"text": "In some special cases, the lambda function may not be enough. For example, we have a whole bunch of logic to apply to a column, which can only be put in a customised function. So, the apply() function can also be used along with customised functions."
},
{
"code": null,
"e": 10679,
"s": 10608,
"text": "The example below uses a customised function that does the same thing."
},
{
"code": null,
"e": 10727,
"s": 10679,
"text": "def add1(n): return n+1df.number.apply(add1)"
},
{
"code": null,
"e": 10865,
"s": 10727,
"text": "What if we need to use multiple columns in an apply() function? In fact, the apply() function can be used on a data frame object as well."
},
{
"code": null,
"e": 11008,
"s": 10865,
"text": "df = pd.DataFrame({'num1': [1, 2, 3, 4, 5], 'num2': [5, 4, 3, 2, 1]})df.apply(lambda row: row['num1'] + row['num2'], axis=1)"
},
{
"code": null,
"e": 11305,
"s": 11008,
"text": "In the above example, the data frame is created with two numeric columns. Then, we use the lambda function to get each row with all the cells. After that, we can still use ['col_name'] to access the values. So, row[‘num1’] + row[‘num2’] will return the sum of the values from both of the columns."
},
{
"code": null,
"e": 11463,
"s": 11305,
"text": "Very importantly, the parameter axis=1 must be specified here, because the apply() function on a data frame object will be applied on row indices by default."
},
{
"code": null,
"e": 11513,
"s": 11463,
"text": "Similarly, we can also use a customised function."
},
{
"code": null,
"e": 11594,
"s": 11513,
"text": "def sum_cols(row): return row['num1'] + row['num2']df.apply(sum_cols, axis=1)"
},
{
"code": null,
"e": 11780,
"s": 11594,
"text": "I used to use this function when dealing with JSON documents. Because of the style of JSON, sometimes we have one key with an array value. In this case, we can easily flatten the array."
},
{
"code": null,
"e": 11921,
"s": 11780,
"text": "df = pd.DataFrame([{ 'name': 'Chris', 'languages': ['Python', 'Java']},{ 'name': 'Jade', 'languages': ['Java', 'Javascript']}])"
},
{
"code": null,
"e": 12073,
"s": 11921,
"text": "In this example, the languages that are directly loaded from a JSON document are still arrays. Then, let’s use df.explode() function to flatten it out."
},
{
"code": null,
"e": 12097,
"s": 12073,
"text": "df.explode('languages')"
},
{
"code": null,
"e": 12273,
"s": 12097,
"text": "Data Aggregation plays an important role in Data Analytics. Pandas provide many ways to perform data aggregation. Here I organised some functions that you must know as basics."
},
{
"code": null,
"e": 12465,
"s": 12273,
"text": "df1 = pd.DataFrame({'id': [1, 2, 3], 'name': ['Alice', 'Bob', 'Chris']})df2 = pd.DataFrame({'id': [4, 5], 'name': ['David', 'Ella']})pd.concat([df1, df2])"
},
{
"code": null,
"e": 12511,
"s": 12465,
"text": "In this example, two data frames are created."
},
{
"code": null,
"e": 12590,
"s": 12511,
"text": "Then, we can use the pd.concat() function to concatenate them together as one."
},
{
"code": null,
"e": 12758,
"s": 12590,
"text": "Please note that we can also use this function to concatenate vertically. Feel not comfortable about the index? Do you still remember the df.reset_index() function? :)"
},
{
"code": null,
"e": 12886,
"s": 12758,
"text": "This is another one that I used a lot in practice. If you have experience in SQL queries, this is just like joining two tables."
},
{
"code": null,
"e": 13123,
"s": 12886,
"text": "df1 = pd.DataFrame({'id': [1, 2, 3], 'name': ['Olivier', 'Jade', 'Chris']})df2 = pd.DataFrame({'id': [1, 2, 3], 'language': ['Objective-C', 'Java', 'Python']})pd.merge(df1, df2, on='id', how='inner')"
},
{
"code": null,
"e": 13456,
"s": 13123,
"text": "As shown in the code block above, there are two data frames created with the “name” column and the “language” column respectively. Then, we can use this function to “join” them together. Please note that we need to specify which column that is used to join on with on='id' and specify how the two data frames are joined how='inner'."
},
{
"code": null,
"e": 13722,
"s": 13456,
"text": "These two functions would be better demonstrated together, as the function df.groupby() cannot produce meaningful results by itself. It has to be used together with other functions that apply to the groups, which I believe df.groupby().agg() is the most common one."
},
{
"code": null,
"e": 14019,
"s": 13722,
"text": "df = pd.DataFrame({'id': [1, 2, 3, 4, 5], 'name': ['Alice', 'Bob', 'Chris', 'David', 'Ella'], 'language': ['Python', 'Java', 'Python', 'COBOL', 'Java'], 'age': [21, 32, 31, 68, 29]})df.groupby('language').agg({'name': 'count', 'age': 'mean'})"
},
{
"code": null,
"e": 14095,
"s": 14019,
"text": "In this example, we created a data frame with “name”, “language” and “age”."
},
{
"code": null,
"e": 14322,
"s": 14095,
"text": "Then, the data frame is grouped by the languages, and we count the number of names and averaging the ages among these persons. Well, the column headers don’t make sense now, but we can use the df.rename() function to fix them."
},
{
"code": null,
"e": 14537,
"s": 14322,
"text": "For the above example, we can also implement it using the pd.pivot_table() function. That is, we need to specify the group keys and the measure values as follows (using the same data frame in the previous example):"
},
{
"code": null,
"e": 14703,
"s": 14537,
"text": "pd.pivot_table(df, values=['name', 'age'], index=['language'], aggfunc={'name': 'count', 'age': ['min', 'max', 'mean']})"
},
{
"code": null,
"e": 14845,
"s": 14703,
"text": "Therefore, it is obvious that the pd.pivot_table() function is more convenient when we have multiple levels of group keys and measure values."
},
{
"code": null,
"e": 15230,
"s": 14845,
"text": "Indeed, the Pandas library of Python has a lot more functions that makes it such a flexible and powerful data analytics tool in Python. In this article, I just organised the basic ones that I believe are the most useful. If one can nail all of them, definitely can start to use Pandas to perform some simple data analytics. Of course, there is still a lot to learn to become a master."
},
{
"code": null,
"e": 15241,
"s": 15230,
"text": "medium.com"
}
] |
Bootstrap 4 .btn-outline-success Button class
|
Use the btn-outline-success class in Bootstrap to set green outline to a button.
Green button outline states success and you can set a button like this −
<button type="button" class="btn btn-outline-success">
Result
</button>
Above I have set the class on <button> element just like we set a class on any other element in HTML or Bootstrap.
Here is an example to learn how to work with the btn-outline-success class in Bootstrap −
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>
<h2>Result</h2>
<p>The following are the subjects:</p>
<ul class = "list-group">
<li class = "list-group-item">Maths</li>
<li class = "list-group-item">Digital Electronics</li>
</ul>
<p>For result, click below:</p>
<button type="button" class="btn btn-outline-success">Result</button>
</body>
</html>
|
[
{
"code": null,
"e": 1143,
"s": 1062,
"text": "Use the btn-outline-success class in Bootstrap to set green outline to a button."
},
{
"code": null,
"e": 1216,
"s": 1143,
"text": "Green button outline states success and you can set a button like this −"
},
{
"code": null,
"e": 1290,
"s": 1216,
"text": "<button type=\"button\" class=\"btn btn-outline-success\">\n Result\n</button>"
},
{
"code": null,
"e": 1405,
"s": 1290,
"text": "Above I have set the class on <button> element just like we set a class on any other element in HTML or Bootstrap."
},
{
"code": null,
"e": 1495,
"s": 1405,
"text": "Here is an example to learn how to work with the btn-outline-success class in Bootstrap −"
},
{
"code": null,
"e": 1505,
"s": 1495,
"text": "Live Demo"
},
{
"code": null,
"e": 2317,
"s": 1505,
"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<body>\n <h2>Result</h2>\n <p>The following are the subjects:</p>\n <ul class = \"list-group\">\n <li class = \"list-group-item\">Maths</li>\n <li class = \"list-group-item\">Digital Electronics</li>\n </ul>\n <p>For result, click below:</p>\n <button type=\"button\" class=\"btn btn-outline-success\">Result</button>\n\n</body>\n</html>"
}
] |
How out-gridview selection works in PowerShell?
|
With the PowerShell Out-Gridview output, you have an option to select one or multiple selections.
For example, if we run the below command, it will show us the output in the grid format.
PS C:\> Get-Process | Out-GridView
In this output, you don’t get any option to select the rows because its output mode is none. To add the single selection from the output, use the Output mode to single, and for the multiple selections use the output mode to multiple. Once you add the OutpuMode property you can see the OK and Cancel button at the bottom right of the grid.
Single output mode −
PS C:\> Get-Process | Out-GridView -OutputMode Single
We will select cmd and press ok.
NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName
------ ----- ----- ------ ----- -- -----------
5 2.36 17.58 0.22 26096 1 cmd
Multiple selections,
PS C:\> Get-Process | Out-GridView -OutputMode Multiple
NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName
------ ----- ----- ------ ----- -- -----------
5 2.36 17.42 0.22 26096 1 cmd
41 20.99 7.89 29.95 24040 1 AcroRd32
|
[
{
"code": null,
"e": 1160,
"s": 1062,
"text": "With the PowerShell Out-Gridview output, you have an option to select one or multiple selections."
},
{
"code": null,
"e": 1249,
"s": 1160,
"text": "For example, if we run the below command, it will show us the output in the grid format."
},
{
"code": null,
"e": 1284,
"s": 1249,
"text": "PS C:\\> Get-Process | Out-GridView"
},
{
"code": null,
"e": 1624,
"s": 1284,
"text": "In this output, you don’t get any option to select the rows because its output mode is none. To add the single selection from the output, use the Output mode to single, and for the multiple selections use the output mode to multiple. Once you add the OutpuMode property you can see the OK and Cancel button at the bottom right of the grid."
},
{
"code": null,
"e": 1645,
"s": 1624,
"text": "Single output mode −"
},
{
"code": null,
"e": 1699,
"s": 1645,
"text": "PS C:\\> Get-Process | Out-GridView -OutputMode Single"
},
{
"code": null,
"e": 1732,
"s": 1699,
"text": "We will select cmd and press ok."
},
{
"code": null,
"e": 1865,
"s": 1732,
"text": "NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName\n------ ----- ----- ------ ----- -- -----------\n5 2.36 17.58 0.22 26096 1 cmd"
},
{
"code": null,
"e": 1886,
"s": 1865,
"text": "Multiple selections,"
},
{
"code": null,
"e": 2114,
"s": 1886,
"text": "PS C:\\> Get-Process | Out-GridView -OutputMode Multiple\nNPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName\n------ ----- ----- ------ ----- -- -----------\n5 2.36 17.42 0.22 26096 1 cmd\n41 20.99 7.89 29.95 24040 1 AcroRd32"
}
] |
Java Program to find transpose of a matrix - GeeksforGeeks
|
07 Nov, 2018
Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose of A[][] is obtained by changing A[i][j] to A[j][i].
For Square Matrix :
The below program finds transpose of A[][] and stores the result in B[][], we can change N for different dimension.
// Java Program to find // transpose of a matrix class GFG{ static final int N = 4; // This function stores transpose // of A[][] in B[][] static void transpose(int A[][], int B[][]) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) B[i][j] = A[j][i]; } // Driver code public static void main (String[] args) { int A[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[][] = new int[N][N], i, j; transpose(A, B); System.out.print("Result matrix is \n"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) System.out.print(B[i][j] + " "); System.out.print("\n"); } }} // This code is contributed by Anant Agarwal.
Result matrix is
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
For Rectangular Matrix :
The below program finds transpose of A[][] and stores the result in B[][].
// Java Program to find // transpose of a matrix class GFG{ static final int M = 3; static final int N = 4; // This function stores transpose // of A[][] in B[][] static void transpose(int A[][], int B[][]) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < M; j++) B[i][j] = A[j][i]; } // Driver code public static void main (String[] args) { int A[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}}; int B[][] = new int[N][M], i, j; transpose(A, B); System.out.print("Result matrix is \n"); for (i = 0; i < N; i++) { for (j = 0; j < M; j++) System.out.print(B[i][j] + " "); System.out.print("\n"); } }} // This code is contributed by Anant Agarwal.
Result matrix is
1 2 3
1 2 3
1 2 3
1 2 3
In-Place for Square Matrix:
// Java Program to find // transpose of a matrix class GFG{ static final int N = 4; // Finds transpose of A[][] in-place static void transpose(int A[][]) { for (int i = 0; i < N; i++) for (int j = i+1; j < N; j++) { int temp = A[i][j]; A[i][j] = A[j][i]; A[j][i] = temp; } } // Driver code public static void main (String[] args) { int A[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; transpose(A); System.out.print("Modified matrix is \n"); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print(A[i][j] + " "); System.out.print("\n"); } }}
Modified matrix is
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
Please refer complete article on Program to find transpose of a matrix for more details!
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Iterate HashMap in Java?
How to Get Elements By Index from HashSet in Java?
Implementing Generic Graph in Java
Parameter Passing Techniques in Java with Examples
Iterate Over the Characters of a String in Java
Java Program to Reverse a List
How to Override compareTo Method in Java?
Java Program to Search for a File in a Directory
Reading and writing in the array using threads
Java Program to Multiply two Matrices of any size
|
[
{
"code": null,
"e": 24513,
"s": 24485,
"text": "\n07 Nov, 2018"
},
{
"code": null,
"e": 24675,
"s": 24513,
"text": "Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose of A[][] is obtained by changing A[i][j] to A[j][i]."
},
{
"code": null,
"e": 24695,
"s": 24675,
"text": "For Square Matrix :"
},
{
"code": null,
"e": 24811,
"s": 24695,
"text": "The below program finds transpose of A[][] and stores the result in B[][], we can change N for different dimension."
},
{
"code": "// Java Program to find // transpose of a matrix class GFG{ static final int N = 4; // This function stores transpose // of A[][] in B[][] static void transpose(int A[][], int B[][]) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) B[i][j] = A[j][i]; } // Driver code public static void main (String[] args) { int A[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[][] = new int[N][N], i, j; transpose(A, B); System.out.print(\"Result matrix is \\n\"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) System.out.print(B[i][j] + \" \"); System.out.print(\"\\n\"); } }} // This code is contributed by Anant Agarwal.",
"e": 25699,
"s": 24811,
"text": null
},
{
"code": null,
"e": 25753,
"s": 25699,
"text": "Result matrix is \n1 2 3 4 \n1 2 3 4 \n1 2 3 4 \n1 2 3 4\n"
},
{
"code": null,
"e": 25778,
"s": 25753,
"text": "For Rectangular Matrix :"
},
{
"code": null,
"e": 25853,
"s": 25778,
"text": "The below program finds transpose of A[][] and stores the result in B[][]."
},
{
"code": "// Java Program to find // transpose of a matrix class GFG{ static final int M = 3; static final int N = 4; // This function stores transpose // of A[][] in B[][] static void transpose(int A[][], int B[][]) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < M; j++) B[i][j] = A[j][i]; } // Driver code public static void main (String[] args) { int A[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}}; int B[][] = new int[N][M], i, j; transpose(A, B); System.out.print(\"Result matrix is \\n\"); for (i = 0; i < N; i++) { for (j = 0; j < M; j++) System.out.print(B[i][j] + \" \"); System.out.print(\"\\n\"); } }} // This code is contributed by Anant Agarwal.",
"e": 26733,
"s": 25853,
"text": null
},
{
"code": null,
"e": 26779,
"s": 26733,
"text": "Result matrix is \n1 2 3 \n1 2 3 \n1 2 3 \n1 2 3\n"
},
{
"code": null,
"e": 26807,
"s": 26779,
"text": "In-Place for Square Matrix:"
},
{
"code": "// Java Program to find // transpose of a matrix class GFG{ static final int N = 4; // Finds transpose of A[][] in-place static void transpose(int A[][]) { for (int i = 0; i < N; i++) for (int j = i+1; j < N; j++) { int temp = A[i][j]; A[i][j] = A[j][i]; A[j][i] = temp; } } // Driver code public static void main (String[] args) { int A[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; transpose(A); System.out.print(\"Modified matrix is \\n\"); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print(A[i][j] + \" \"); System.out.print(\"\\n\"); } }}",
"e": 27668,
"s": 26807,
"text": null
},
{
"code": null,
"e": 27724,
"s": 27668,
"text": "Modified matrix is \n1 2 3 4 \n1 2 3 4 \n1 2 3 4 \n1 2 3 4\n"
},
{
"code": null,
"e": 27813,
"s": 27724,
"text": "Please refer complete article on Program to find transpose of a matrix for more details!"
},
{
"code": null,
"e": 27827,
"s": 27813,
"text": "Java Programs"
},
{
"code": null,
"e": 27925,
"s": 27827,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27934,
"s": 27925,
"text": "Comments"
},
{
"code": null,
"e": 27947,
"s": 27934,
"text": "Old Comments"
},
{
"code": null,
"e": 27979,
"s": 27947,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 28030,
"s": 27979,
"text": "How to Get Elements By Index from HashSet in Java?"
},
{
"code": null,
"e": 28065,
"s": 28030,
"text": "Implementing Generic Graph in Java"
},
{
"code": null,
"e": 28116,
"s": 28065,
"text": "Parameter Passing Techniques in Java with Examples"
},
{
"code": null,
"e": 28164,
"s": 28116,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 28195,
"s": 28164,
"text": "Java Program to Reverse a List"
},
{
"code": null,
"e": 28237,
"s": 28195,
"text": "How to Override compareTo Method in Java?"
},
{
"code": null,
"e": 28286,
"s": 28237,
"text": "Java Program to Search for a File in a Directory"
},
{
"code": null,
"e": 28333,
"s": 28286,
"text": "Reading and writing in the array using threads"
}
] |
Create a stopwatch using python
|
A stopwatch is used to measure the time interval between two events usually in seconds to minutes. It has various usage like in sports or measuring the flow of heat, current etc in an industrial setup. Python can be used to creat a stopwatch by using its tkinter library.
This library will have the GUI features to create a stopwatch showing the Start, Stop and Reset option. The key component of the program is using the lable.after() module of tkinter.
label.after(parent, ms, function = None)
where
parent: The object of the widget which is using this function.
ms: Time in miliseconds.
function: Call back function
In the below program we use this method as out key component of the program and design a widget showing the GUI features in the stopwatch.
import tkinter as tink
count = -1
run = False
def var_name(mark):
def value():
if run:
global count
# Just beore starting
if count == -1:
show = "Starting"
else:
show = str(count)
mark['text'] = show
#Increment the count after
#every 1 second
mark.after(1000, value)
count += 1
value()
# While Running
def Start(mark):
global run
run = True
var_name(mark)
start['state'] = 'disabled'
stop['state'] = 'normal'
reset['state'] = 'normal'
# While stopped
def Stop():
global run
start['state'] = 'normal'
stop['state'] = 'disabled'
reset['state'] = 'normal'
run = False
# For Reset
def Reset(label):
global count
count = -1
if run == False:
reset['state'] = 'disabled'
mark['text'] = 'Welcome'
else:
mark['text'] = 'Start'
base = tink.Tk()
base.title("PYTHON STOPWATCH")
base.minsize(width=300, height=200)
mark = tink.Label(base, text="Welcome", fg="blue", font="Times 25 bold",bg="white")
mark.pack()
start = tink.Button(base, text='Start',width=25, command=lambda: Start(mark))
stop = tink.Button(base, text='Stop', width=25, state='disabled', command=Stop)
reset = tink.Button(base, text='Reset',width=25, state='disabled', command=lambda: Reset(mark))
start.pack()
stop.pack()
reset.pack()
base.mainloop()
The below images show the three different scenarios when the stopwatch is run.
|
[
{
"code": null,
"e": 1334,
"s": 1062,
"text": "A stopwatch is used to measure the time interval between two events usually in seconds to minutes. It has various usage like in sports or measuring the flow of heat, current etc in an industrial setup. Python can be used to creat a stopwatch by using its tkinter library."
},
{
"code": null,
"e": 1520,
"s": 1334,
"text": "This library will have the GUI features to create a stopwatch showing the Start, Stop and Reset option. The key component of the program is using the lable.after() module of tkinter."
},
{
"code": null,
"e": 1684,
"s": 1520,
"text": "label.after(parent, ms, function = None)\nwhere\nparent: The object of the widget which is using this function.\nms: Time in miliseconds.\nfunction: Call back function"
},
{
"code": null,
"e": 1823,
"s": 1684,
"text": "In the below program we use this method as out key component of the program and design a widget showing the GUI features in the stopwatch."
},
{
"code": null,
"e": 3210,
"s": 1823,
"text": "import tkinter as tink\ncount = -1\nrun = False\ndef var_name(mark):\n def value():\n if run:\n global count\n # Just beore starting\n if count == -1:\n show = \"Starting\"\n else:\n show = str(count)\n mark['text'] = show\n #Increment the count after\n #every 1 second\n mark.after(1000, value)\n count += 1\n value()\n# While Running\ndef Start(mark):\n global run\n run = True\n var_name(mark)\n start['state'] = 'disabled'\n stop['state'] = 'normal'\n reset['state'] = 'normal'\n# While stopped\ndef Stop():\n global run\n start['state'] = 'normal'\n stop['state'] = 'disabled'\n reset['state'] = 'normal'\n run = False\n# For Reset\ndef Reset(label):\n global count\n count = -1\n if run == False:\n reset['state'] = 'disabled'\n mark['text'] = 'Welcome'\n else:\n mark['text'] = 'Start'\n\nbase = tink.Tk()\nbase.title(\"PYTHON STOPWATCH\")\nbase.minsize(width=300, height=200)\nmark = tink.Label(base, text=\"Welcome\", fg=\"blue\", font=\"Times 25 bold\",bg=\"white\")\nmark.pack()\nstart = tink.Button(base, text='Start',width=25, command=lambda: Start(mark))\nstop = tink.Button(base, text='Stop', width=25, state='disabled', command=Stop)\nreset = tink.Button(base, text='Reset',width=25, state='disabled', command=lambda: Reset(mark))\nstart.pack()\nstop.pack()\nreset.pack()\nbase.mainloop()"
},
{
"code": null,
"e": 3289,
"s": 3210,
"text": "The below images show the three different scenarios when the stopwatch is run."
}
] |
Perl continue Statement
|
A continue BLOCK, is always executed just before the conditional is about to be evaluated again. A continue statement can be used with while and foreach loops. A continue statement can also be used alone along with a BLOCK of code in which case it will be assumed as a flow control statement rather than a function.
The syntax for a continue statement with while loop is as follows −
while(condition) {
statement(s);
} continue {
statement(s);
}
The syntax for a continue statement with foreach loop is as follows −
foreach $a (@listA) {
statement(s);
} continue {
statement(s);
}
The syntax for a continue statement with a BLOCK of code is as follows −
continue {
statement(s);
}
The following program simulates a for loop using a while loop −
#/usr/local/bin/perl
$a = 0;
while($a < 3) {
print "Value of a = $a\n";
} continue {
$a = $a + 1;
}
This would produce the following result −
Value of a = 0
Value of a = 1
Value of a = 2
The following program shows the usage of continue statement with foreach loop −
#/usr/local/bin/perl
@list = (1, 2, 3, 4, 5);
foreach $a (@list) {
print "Value of a = $a\n";
} continue {
last if $a == 4;
}
This would produce the following result −
Value of a = 1
Value of a = 2
Value of a = 3
Value of a = 4
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2536,
"s": 2220,
"text": "A continue BLOCK, is always executed just before the conditional is about to be evaluated again. A continue statement can be used with while and foreach loops. A continue statement can also be used alone along with a BLOCK of code in which case it will be assumed as a flow control statement rather than a function."
},
{
"code": null,
"e": 2604,
"s": 2536,
"text": "The syntax for a continue statement with while loop is as follows −"
},
{
"code": null,
"e": 2673,
"s": 2604,
"text": "while(condition) {\n statement(s);\n} continue {\n statement(s);\n}\n"
},
{
"code": null,
"e": 2743,
"s": 2673,
"text": "The syntax for a continue statement with foreach loop is as follows −"
},
{
"code": null,
"e": 2815,
"s": 2743,
"text": "foreach $a (@listA) {\n statement(s);\n} continue {\n statement(s);\n}\n"
},
{
"code": null,
"e": 2888,
"s": 2815,
"text": "The syntax for a continue statement with a BLOCK of code is as follows −"
},
{
"code": null,
"e": 2919,
"s": 2888,
"text": "continue {\n statement(s);\n}\n"
},
{
"code": null,
"e": 2983,
"s": 2919,
"text": "The following program simulates a for loop using a while loop −"
},
{
"code": null,
"e": 3093,
"s": 2983,
"text": "#/usr/local/bin/perl\n \n$a = 0;\nwhile($a < 3) {\n print \"Value of a = $a\\n\";\n} continue {\n $a = $a + 1;\n}"
},
{
"code": null,
"e": 3135,
"s": 3093,
"text": "This would produce the following result −"
},
{
"code": null,
"e": 3181,
"s": 3135,
"text": "Value of a = 0\nValue of a = 1\nValue of a = 2\n"
},
{
"code": null,
"e": 3261,
"s": 3181,
"text": "The following program shows the usage of continue statement with foreach loop −"
},
{
"code": null,
"e": 3397,
"s": 3261,
"text": "#/usr/local/bin/perl\n \n@list = (1, 2, 3, 4, 5);\nforeach $a (@list) {\n print \"Value of a = $a\\n\";\n} continue {\n last if $a == 4;\n}"
},
{
"code": null,
"e": 3439,
"s": 3397,
"text": "This would produce the following result −"
},
{
"code": null,
"e": 3500,
"s": 3439,
"text": "Value of a = 1\nValue of a = 2\nValue of a = 3\nValue of a = 4\n"
},
{
"code": null,
"e": 3535,
"s": 3500,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3549,
"s": 3535,
"text": " Devi Killada"
},
{
"code": null,
"e": 3584,
"s": 3549,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3604,
"s": 3584,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 3637,
"s": 3604,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3653,
"s": 3637,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3686,
"s": 3653,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3703,
"s": 3686,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 3736,
"s": 3703,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3759,
"s": 3736,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3794,
"s": 3759,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3817,
"s": 3794,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3824,
"s": 3817,
"text": " Print"
},
{
"code": null,
"e": 3835,
"s": 3824,
"text": " Add Notes"
}
] |
Price Elasticity of Demand, Statistical Modeling with Python | by Susan Li | Towards Data Science
|
Price elasticity of demand (PED) is a measure used in economics to show the responsiveness, or elasticity, of the quantity demanded of a good or service to a change in its price when nothing but the price changes. More precisely, it gives the percentage change in quantity demanded in response to a one percent change in price.
In economics, elasticity is a measure of how sensitive demand or supply is to price.In marketing, it is how sensitive consumers are to a change in price of a product.
It gives answers to questions such as:
“If I lower the price of a product, how much more will sell?”
“If I raise the price of one product, how will that affect sales of the other products?”
“If the market price of a product goes down, how much will that affect the amount that firms will be willing to supply to the market?”
We will build a linear regression model to estimate PED, and we will use Python’s Statsmodels to estimate our models as well as conduct statistical tests, and data exploration. Let’s get started!
We will work with the beef price and demand data that can be downloaded from here.
%matplotlib inlinefrom __future__ import print_functionfrom statsmodels.compat import lzipimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport statsmodels.api as smfrom statsmodels.formula.api import olsbeef = pd.read_csv('beef.csv')beef.head(10)
beef_model = ols("Quantity ~ Price", data=beef).fit()print(beef_model.summary())
Observations:
The small P values indicate that we can reject the null hypothesis that Price has no effect on Quantity.Hight R-squared indicates that our model explains a lot of the response variability.In regression analysis, we’d like our regression model to have significant variables and to produce a high R-squared value.We will show graphs to help interpret regression analysis results more intuitively.
The small P values indicate that we can reject the null hypothesis that Price has no effect on Quantity.
Hight R-squared indicates that our model explains a lot of the response variability.
In regression analysis, we’d like our regression model to have significant variables and to produce a high R-squared value.
We will show graphs to help interpret regression analysis results more intuitively.
fig = plt.figure(figsize=(12,8))fig = sm.graphics.plot_partregress_grid(beef_model, fig=fig)
The trend indicates that the predictor variables (Price) provides information about the response (Quantity), and data points do not fall further from the regression line, and the predictions are very precise given a prediction interval that extends from about 29 to 31.
The CCPR plot provides a way to judge the effect of one regressor on the response variable by taking into account the effects of the other independent variables.
fig = plt.figure(figsize=(12, 8))fig = sm.graphics.plot_ccpr_grid(beef_model, fig=fig)
As you can see the relationship between the variation in Quantity explained by Price is definite linear. There are not many observations that are exerting considerable influence on the relationships.
We use plot_regress_exog function to quickly check model assumptions with respect to a single regressor, Price in this case.
fig = plt.figure(figsize=(12,8))fig = sm.graphics.plot_regress_exog(beef_model, 'Price', fig=fig)
Finally we apply Recursive Least Square (RLS) filter to investigate parameter instability.
Before RLS estimation, we will manipulate the data and create a date time index.
beef['Year'] = pd.to_datetime(beef['Year'], format="%Y")from pandas.tseries.offsets import *beef['Date'] = beef.apply(lambda x:(x['Year'] + BQuarterBegin(x['Quarter'])), axis=1)beef.drop(['Year', 'Quarter'], axis=1, inplace=True)beef.set_index('Date', inplace=True)beef.head(10)
endog = beef['Quantity']exog = sm.add_constant(beef['Price'])mod = sm.RecursiveLS(endog, exog)res = mod.fit()print(res.summary())
The RLS model computes the regression parameters recursively, so there are as many estimates as there are data points, the summary table only presents the regression parameters estimated on the entire sample; these estimates are equivalent to OLS estimates.
We can generate the recursively estimated coefficients plot on a given variable.
res.plot_recursive_coefficient(range(mod.k_exog), alpha=None, figsize=(10,6));
For convenience, we visually check for parameter stability using the plot_cusum function.
fig = res.plot_cusum(figsize=(10,6));
In the plot above, the CUSUM statistic does not move outside of the 5% significance bands, so we fail to reject the null hypothesis of stable parameters at the 5% level.
Source code can be found on Github. Have a wonderful long weekend!
|
[
{
"code": null,
"e": 500,
"s": 172,
"text": "Price elasticity of demand (PED) is a measure used in economics to show the responsiveness, or elasticity, of the quantity demanded of a good or service to a change in its price when nothing but the price changes. More precisely, it gives the percentage change in quantity demanded in response to a one percent change in price."
},
{
"code": null,
"e": 667,
"s": 500,
"text": "In economics, elasticity is a measure of how sensitive demand or supply is to price.In marketing, it is how sensitive consumers are to a change in price of a product."
},
{
"code": null,
"e": 706,
"s": 667,
"text": "It gives answers to questions such as:"
},
{
"code": null,
"e": 768,
"s": 706,
"text": "“If I lower the price of a product, how much more will sell?”"
},
{
"code": null,
"e": 857,
"s": 768,
"text": "“If I raise the price of one product, how will that affect sales of the other products?”"
},
{
"code": null,
"e": 992,
"s": 857,
"text": "“If the market price of a product goes down, how much will that affect the amount that firms will be willing to supply to the market?”"
},
{
"code": null,
"e": 1188,
"s": 992,
"text": "We will build a linear regression model to estimate PED, and we will use Python’s Statsmodels to estimate our models as well as conduct statistical tests, and data exploration. Let’s get started!"
},
{
"code": null,
"e": 1271,
"s": 1188,
"text": "We will work with the beef price and demand data that can be downloaded from here."
},
{
"code": null,
"e": 1540,
"s": 1271,
"text": "%matplotlib inlinefrom __future__ import print_functionfrom statsmodels.compat import lzipimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport statsmodels.api as smfrom statsmodels.formula.api import olsbeef = pd.read_csv('beef.csv')beef.head(10)"
},
{
"code": null,
"e": 1621,
"s": 1540,
"text": "beef_model = ols(\"Quantity ~ Price\", data=beef).fit()print(beef_model.summary())"
},
{
"code": null,
"e": 1635,
"s": 1621,
"text": "Observations:"
},
{
"code": null,
"e": 2030,
"s": 1635,
"text": "The small P values indicate that we can reject the null hypothesis that Price has no effect on Quantity.Hight R-squared indicates that our model explains a lot of the response variability.In regression analysis, we’d like our regression model to have significant variables and to produce a high R-squared value.We will show graphs to help interpret regression analysis results more intuitively."
},
{
"code": null,
"e": 2135,
"s": 2030,
"text": "The small P values indicate that we can reject the null hypothesis that Price has no effect on Quantity."
},
{
"code": null,
"e": 2220,
"s": 2135,
"text": "Hight R-squared indicates that our model explains a lot of the response variability."
},
{
"code": null,
"e": 2344,
"s": 2220,
"text": "In regression analysis, we’d like our regression model to have significant variables and to produce a high R-squared value."
},
{
"code": null,
"e": 2428,
"s": 2344,
"text": "We will show graphs to help interpret regression analysis results more intuitively."
},
{
"code": null,
"e": 2521,
"s": 2428,
"text": "fig = plt.figure(figsize=(12,8))fig = sm.graphics.plot_partregress_grid(beef_model, fig=fig)"
},
{
"code": null,
"e": 2791,
"s": 2521,
"text": "The trend indicates that the predictor variables (Price) provides information about the response (Quantity), and data points do not fall further from the regression line, and the predictions are very precise given a prediction interval that extends from about 29 to 31."
},
{
"code": null,
"e": 2953,
"s": 2791,
"text": "The CCPR plot provides a way to judge the effect of one regressor on the response variable by taking into account the effects of the other independent variables."
},
{
"code": null,
"e": 3040,
"s": 2953,
"text": "fig = plt.figure(figsize=(12, 8))fig = sm.graphics.plot_ccpr_grid(beef_model, fig=fig)"
},
{
"code": null,
"e": 3240,
"s": 3040,
"text": "As you can see the relationship between the variation in Quantity explained by Price is definite linear. There are not many observations that are exerting considerable influence on the relationships."
},
{
"code": null,
"e": 3365,
"s": 3240,
"text": "We use plot_regress_exog function to quickly check model assumptions with respect to a single regressor, Price in this case."
},
{
"code": null,
"e": 3463,
"s": 3365,
"text": "fig = plt.figure(figsize=(12,8))fig = sm.graphics.plot_regress_exog(beef_model, 'Price', fig=fig)"
},
{
"code": null,
"e": 3554,
"s": 3463,
"text": "Finally we apply Recursive Least Square (RLS) filter to investigate parameter instability."
},
{
"code": null,
"e": 3635,
"s": 3554,
"text": "Before RLS estimation, we will manipulate the data and create a date time index."
},
{
"code": null,
"e": 3914,
"s": 3635,
"text": "beef['Year'] = pd.to_datetime(beef['Year'], format=\"%Y\")from pandas.tseries.offsets import *beef['Date'] = beef.apply(lambda x:(x['Year'] + BQuarterBegin(x['Quarter'])), axis=1)beef.drop(['Year', 'Quarter'], axis=1, inplace=True)beef.set_index('Date', inplace=True)beef.head(10)"
},
{
"code": null,
"e": 4044,
"s": 3914,
"text": "endog = beef['Quantity']exog = sm.add_constant(beef['Price'])mod = sm.RecursiveLS(endog, exog)res = mod.fit()print(res.summary())"
},
{
"code": null,
"e": 4302,
"s": 4044,
"text": "The RLS model computes the regression parameters recursively, so there are as many estimates as there are data points, the summary table only presents the regression parameters estimated on the entire sample; these estimates are equivalent to OLS estimates."
},
{
"code": null,
"e": 4383,
"s": 4302,
"text": "We can generate the recursively estimated coefficients plot on a given variable."
},
{
"code": null,
"e": 4462,
"s": 4383,
"text": "res.plot_recursive_coefficient(range(mod.k_exog), alpha=None, figsize=(10,6));"
},
{
"code": null,
"e": 4552,
"s": 4462,
"text": "For convenience, we visually check for parameter stability using the plot_cusum function."
},
{
"code": null,
"e": 4590,
"s": 4552,
"text": "fig = res.plot_cusum(figsize=(10,6));"
},
{
"code": null,
"e": 4760,
"s": 4590,
"text": "In the plot above, the CUSUM statistic does not move outside of the 5% significance bands, so we fail to reject the null hypothesis of stable parameters at the 5% level."
}
] |
AngularJS | Scope - GeeksforGeeks
|
23 Feb, 2022
Scope in AngularJS is the binding part of HTML view and JavaScript controller. When you add properties into the scope object in the JavaScript controller, only then the HTML view gets access to those properties. There are two types of Scope in AngularJS.
$Scope
$rootScope
Scope: There is few specific features in Scope those are listed below
The HTML view
The data which is available for the current view known as Model
The JavaScript function that makes/changes/removes/controls the data known as Controller.
Syntax:
$scope
Example 1: This example will illustrate the scope concept more clearly this example contain single scope.
html
<!DOCTYPE html><html> <head> <title> AngularJS | Scope </title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body> <div ng-app="gfg" ng-controller="control" align="center"> <h1 style="color:green;">{{organization}}</h1> <p>A Computer Science Portal</p> </div> <script> var geeks = angular.module('gfg', []); geeks.controller('control', function($scope) { $scope.organization = "GeeksforGeeks"; }); </script> </body> </html>
Output:
Example 2: In the above example there is only one scope in the below example you will see more than one scope.
html
<!DOCTYPE html><html> <head> <title> AngularJS | Scope </title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body> <div ng-app="gfg" ng-controller="control"> <ul> <li ng-repeat="x in names">{{x}}</li> </ul> </div> <script> var geeks = angular.module('gfg', []); geeks.controller('control', function($scope) { $scope.names = ["Python", "Machine Learning", "Artificial Intelligence"]; }); </script> </body> </html>
Output:
rootScope: If your variables contains the same name in the both rootscope and current scope then the controller or the application will use the current scope. Syntax:
$rootScope
Example 3: This example will show you what will happen if the variable name is same in controller’s scope and the rootscope.
html
<!DOCTYPE html><html> <head> <title> AngularJS | Scope </title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body ng-app="gfg"> <h1>GeeksforGeeks</h1> <p>Jack and Jones</p> <h3>{{relation}}</h3> <div ng-controller="control"> <p>Akbar and Antony </p> <h3>{{relation}}</h3> </div> <p>Jay and Viru</p> <h3>{{relation}}</h3> <script> var geeks = angular.module('gfg', []); geeks.run(function($rootScope) { $rootScope.relation = 'friend'; }); geeks.controller('control', function($scope) { $scope.relation = "brothers"; }); </script> </body> </html>
Output:
varshagumber28
sumitgumber28
AngularJS-Basics
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Angular File Upload
Angular | keyup event
Auth Guards in Angular 9/10/11
What is AOT and JIT Compiler in Angular ?
Angular PrimeNG Dropdown Component
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": 27880,
"s": 27852,
"text": "\n23 Feb, 2022"
},
{
"code": null,
"e": 28137,
"s": 27880,
"text": "Scope in AngularJS is the binding part of HTML view and JavaScript controller. When you add properties into the scope object in the JavaScript controller, only then the HTML view gets access to those properties. There are two types of Scope in AngularJS. "
},
{
"code": null,
"e": 28144,
"s": 28137,
"text": "$Scope"
},
{
"code": null,
"e": 28155,
"s": 28144,
"text": "$rootScope"
},
{
"code": null,
"e": 28227,
"s": 28155,
"text": "Scope: There is few specific features in Scope those are listed below "
},
{
"code": null,
"e": 28241,
"s": 28227,
"text": "The HTML view"
},
{
"code": null,
"e": 28305,
"s": 28241,
"text": "The data which is available for the current view known as Model"
},
{
"code": null,
"e": 28395,
"s": 28305,
"text": "The JavaScript function that makes/changes/removes/controls the data known as Controller."
},
{
"code": null,
"e": 28405,
"s": 28395,
"text": "Syntax: "
},
{
"code": null,
"e": 28412,
"s": 28405,
"text": "$scope"
},
{
"code": null,
"e": 28520,
"s": 28412,
"text": "Example 1: This example will illustrate the scope concept more clearly this example contain single scope. "
},
{
"code": null,
"e": 28525,
"s": 28520,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> AngularJS | Scope </title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body> <div ng-app=\"gfg\" ng-controller=\"control\" align=\"center\"> <h1 style=\"color:green;\">{{organization}}</h1> <p>A Computer Science Portal</p> </div> <script> var geeks = angular.module('gfg', []); geeks.controller('control', function($scope) { $scope.organization = \"GeeksforGeeks\"; }); </script> </body> </html>",
"e": 29084,
"s": 28525,
"text": null
},
{
"code": null,
"e": 29094,
"s": 29084,
"text": "Output: "
},
{
"code": null,
"e": 29207,
"s": 29094,
"text": "Example 2: In the above example there is only one scope in the below example you will see more than one scope. "
},
{
"code": null,
"e": 29212,
"s": 29207,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> AngularJS | Scope </title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body> <div ng-app=\"gfg\" ng-controller=\"control\"> <ul> <li ng-repeat=\"x in names\">{{x}}</li> </ul> </div> <script> var geeks = angular.module('gfg', []); geeks.controller('control', function($scope) { $scope.names = [\"Python\", \"Machine Learning\", \"Artificial Intelligence\"]; }); </script> </body> </html> ",
"e": 29824,
"s": 29212,
"text": null
},
{
"code": null,
"e": 29834,
"s": 29824,
"text": "Output: "
},
{
"code": null,
"e": 30003,
"s": 29834,
"text": "rootScope: If your variables contains the same name in the both rootscope and current scope then the controller or the application will use the current scope. Syntax: "
},
{
"code": null,
"e": 30014,
"s": 30003,
"text": "$rootScope"
},
{
"code": null,
"e": 30141,
"s": 30014,
"text": "Example 3: This example will show you what will happen if the variable name is same in controller’s scope and the rootscope. "
},
{
"code": null,
"e": 30146,
"s": 30141,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> AngularJS | Scope </title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body ng-app=\"gfg\"> <h1>GeeksforGeeks</h1> <p>Jack and Jones</p> <h3>{{relation}}</h3> <div ng-controller=\"control\"> <p>Akbar and Antony </p> <h3>{{relation}}</h3> </div> <p>Jay and Viru</p> <h3>{{relation}}</h3> <script> var geeks = angular.module('gfg', []); geeks.run(function($rootScope) { $rootScope.relation = 'friend'; }); geeks.controller('control', function($scope) { $scope.relation = \"brothers\"; }); </script> </body> </html>",
"e": 30870,
"s": 30146,
"text": null
},
{
"code": null,
"e": 30880,
"s": 30870,
"text": "Output: "
},
{
"code": null,
"e": 30897,
"s": 30882,
"text": "varshagumber28"
},
{
"code": null,
"e": 30911,
"s": 30897,
"text": "sumitgumber28"
},
{
"code": null,
"e": 30928,
"s": 30911,
"text": "AngularJS-Basics"
},
{
"code": null,
"e": 30935,
"s": 30928,
"text": "Picked"
},
{
"code": null,
"e": 30945,
"s": 30935,
"text": "AngularJS"
},
{
"code": null,
"e": 30962,
"s": 30945,
"text": "Web Technologies"
},
{
"code": null,
"e": 31060,
"s": 30962,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31069,
"s": 31060,
"text": "Comments"
},
{
"code": null,
"e": 31082,
"s": 31069,
"text": "Old Comments"
},
{
"code": null,
"e": 31102,
"s": 31082,
"text": "Angular File Upload"
},
{
"code": null,
"e": 31124,
"s": 31102,
"text": "Angular | keyup event"
},
{
"code": null,
"e": 31155,
"s": 31124,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 31197,
"s": 31155,
"text": "What is AOT and JIT Compiler in Angular ?"
},
{
"code": null,
"e": 31232,
"s": 31197,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 31288,
"s": 31232,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 31321,
"s": 31288,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31383,
"s": 31321,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 31426,
"s": 31383,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to parse JSON on Android using Kotlin?
|
This example demonstrates how to parse JSON on 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"
tools:context=".MainActivity">
<TextView
android:id="@+id/text2"
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" />
<TextView
android:textColor="@android:color/background_dark"
android:id="@+id/textViewName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="16sp"
android:textStyle="bold|italic" />
<TextView
android:id="@+id/textViewSal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textViewName"
android:layout_centerInParent="true"
android:textColor="@android:color/background_dark"
android:textSize="16sp"
android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import org.json.JSONException
import org.json.JSONObject
class MainActivity : AppCompatActivity() {
lateinit var textViewName: TextView
lateinit var textViewSal: TextView
var jsonString = "{\"employee\":{\"name\":\"adolf hitler\",\"salary\":65000}}"
lateinit var name:String
lateinit var salary:String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
textViewName = findViewById(R.id.textViewName)
textViewSal = findViewById(R.id.textViewSal)
try {
// get JSONObject from JSON file
val obj = JSONObject(jsonString)
// fetch JSONObject named employee
val employee: JSONObject = obj.getJSONObject("employee")
// get employee name and salary
name = employee.getString("name")
salary = employee.getString("salary")
// set employee name and salary in TextView's
textViewName.text = "Name: $name"
textViewSal.text = "Salary: $salary"
} catch (e: JSONException) {
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.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": 1130,
"s": 1062,
"text": "This example demonstrates how to parse JSON on Android using Kotlin"
},
{
"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": 2675,
"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/text2\"\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 <TextView\n android:textColor=\"@android:color/background_dark\"\n android:id=\"@+id/textViewName\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold|italic\" />\n <TextView\n android:id=\"@+id/textViewSal\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/textViewName\"\n android:layout_centerInParent=\"true\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2730,
"s": 2675,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3984,
"s": 2730,
"text": "import android.os.Bundle\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nimport org.json.JSONException\nimport org.json.JSONObject\nclass MainActivity : AppCompatActivity() {\n lateinit var textViewName: TextView\n lateinit var textViewSal: TextView\n var jsonString = \"{\\\"employee\\\":{\\\"name\\\":\\\"adolf hitler\\\",\\\"salary\\\":65000}}\"\n lateinit var name:String\n lateinit var salary:String\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n textViewName = findViewById(R.id.textViewName)\n textViewSal = findViewById(R.id.textViewSal)\n try {\n // get JSONObject from JSON file\n val obj = JSONObject(jsonString)\n // fetch JSONObject named employee\n val employee: JSONObject = obj.getJSONObject(\"employee\")\n // get employee name and salary\n name = employee.getString(\"name\")\n salary = employee.getString(\"salary\")\n // set employee name and salary in TextView's\n textViewName.text = \"Name: $name\"\n textViewSal.text = \"Salary: $salary\"\n } catch (e: JSONException) {\n e.printStackTrace()\n }\n }\n}\n"
},
{
"code": null,
"e": 4039,
"s": 3984,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4713,
"s": 4039,
"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": 5062,
"s": 4713,
"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."
}
] |
GATE | GATE-CS-2015 (Set 3) | Question 49 - GeeksforGeeks
|
28 Jun, 2021
Consider the following recursive C function. If get(6) function is being called in main() then how many times will the get() function be invoked before returning to the main()?
void get (int n){ if (n < 1) return; get(n-1); get(n-3); printf("%d", n);}
(A) 15(B) 25(C) 35(D) 45Answer: (B)Explanation:
get(6) [25 Calls]
/ \
[17 Calls] get(5) get(3) [7 Calls]
/ \
get(4) get(2)[5 Calls]
/ \
[7 Calls] get(3) get(1)[3 Calls]
/ \
get(2) get(0)
/ \
[3 Calls]get(1) get(-1)
/ \
get(0) get(-2)
We can verify the same by running below program.
# include <stdio.h>int count = 0; void get (int n){ count++; if (n < 1) return; get(n-1); get(n-3);}int main(){ get(6); printf("%d ", count);}
Output: 25Quiz of this Question
GATE-CS-2015 (Set 3)
GATE-GATE-CS-2015 (Set 3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2014-(Set-1) | Question 65
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 3) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE CS 2012 | Question 40
|
[
{
"code": null,
"e": 24057,
"s": 24029,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24234,
"s": 24057,
"text": "Consider the following recursive C function. If get(6) function is being called in main() then how many times will the get() function be invoked before returning to the main()?"
},
{
"code": "void get (int n){ if (n < 1) return; get(n-1); get(n-3); printf(\"%d\", n);}",
"e": 24317,
"s": 24234,
"text": null
},
{
"code": null,
"e": 24365,
"s": 24317,
"text": "(A) 15(B) 25(C) 35(D) 45Answer: (B)Explanation:"
},
{
"code": null,
"e": 24773,
"s": 24365,
"text": " get(6) [25 Calls]\n / \\\n [17 Calls] get(5) get(3) [7 Calls]\n / \\\n get(4) get(2)[5 Calls]\n / \\ \n [7 Calls] get(3) get(1)[3 Calls]\n / \\\n get(2) get(0)\n / \\\n[3 Calls]get(1) get(-1) \n / \\\nget(0) get(-2)"
},
{
"code": null,
"e": 24822,
"s": 24773,
"text": "We can verify the same by running below program."
},
{
"code": "# include <stdio.h>int count = 0; void get (int n){ count++; if (n < 1) return; get(n-1); get(n-3);}int main(){ get(6); printf(\"%d \", count);}",
"e": 24984,
"s": 24822,
"text": null
},
{
"code": null,
"e": 25016,
"s": 24984,
"text": "Output: 25Quiz of this Question"
},
{
"code": null,
"e": 25037,
"s": 25016,
"text": "GATE-CS-2015 (Set 3)"
},
{
"code": null,
"e": 25063,
"s": 25037,
"text": "GATE-GATE-CS-2015 (Set 3)"
},
{
"code": null,
"e": 25068,
"s": 25063,
"text": "GATE"
},
{
"code": null,
"e": 25166,
"s": 25068,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25175,
"s": 25166,
"text": "Comments"
},
{
"code": null,
"e": 25188,
"s": 25175,
"text": "Old Comments"
},
{
"code": null,
"e": 25230,
"s": 25188,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 25272,
"s": 25230,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 30"
},
{
"code": null,
"e": 25306,
"s": 25272,
"text": "GATE | GATE-CS-2001 | Question 23"
},
{
"code": null,
"e": 25348,
"s": 25306,
"text": "GATE | GATE-CS-2015 (Set 1) | Question 65"
},
{
"code": null,
"e": 25382,
"s": 25348,
"text": "GATE | GATE CS 2010 | Question 45"
},
{
"code": null,
"e": 25424,
"s": 25382,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 65"
},
{
"code": null,
"e": 25457,
"s": 25424,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 25499,
"s": 25457,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 25553,
"s": 25499,
"text": "C++ Program to count Vowels in a string using Pointer"
}
] |
MomentJS - Locale
|
This method helps to get/set the duration using locale. When used with humanize, you will see the difference in output for locale() method.
moment.duration().locale();
moment.duration().locale(String);
var hi = moment.duration(1, "day").locale("hi").humanize();
var en = moment.duration(1, "minutes").locale("en").humanize();
var ja = moment.duration(1, "seconds").locale("ja").humanize();
var it = moment.duration(1, "hours").locale("it").humanize();
var marathi = moment.duration(1, "day").locale("mr").humanize();
var konkani = moment.duration(1, "day").locale("gom-latn").humanize();
var kn = moment.duration(1, "day").locale("kn").humanize();
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2100,
"s": 1960,
"text": "This method helps to get/set the duration using locale. When used with humanize, you will see the difference in output for locale() method."
},
{
"code": null,
"e": 2163,
"s": 2100,
"text": "moment.duration().locale();\nmoment.duration().locale(String);\n"
},
{
"code": null,
"e": 2609,
"s": 2163,
"text": "var hi = moment.duration(1, \"day\").locale(\"hi\").humanize();\nvar en = moment.duration(1, \"minutes\").locale(\"en\").humanize();\nvar ja = moment.duration(1, \"seconds\").locale(\"ja\").humanize();\nvar it = moment.duration(1, \"hours\").locale(\"it\").humanize();\nvar marathi = moment.duration(1, \"day\").locale(\"mr\").humanize();\nvar konkani = moment.duration(1, \"day\").locale(\"gom-latn\").humanize();\nvar kn = moment.duration(1, \"day\").locale(\"kn\").humanize();"
},
{
"code": null,
"e": 2616,
"s": 2609,
"text": " Print"
},
{
"code": null,
"e": 2627,
"s": 2616,
"text": " Add Notes"
}
] |
C program to implement Euclid’ s algorithm
|
Implement Euclid’ s algorithm to find the greatest common divisor (GCD) and least common multiple (LCM) of two integers and to output the results along with the given integers.
The solution to implement Euclid’ s algorithm to find the greatest common divisor (GCD) and least common multiple (LCM) of two integers is as follows −
The logic used to find GCD and LCM is as follows −
if(firstno*secondno!=0){
gcd=gcd_rec(firstno,secondno);
printf("\nThe GCD of %d and %d is %d\n",firstno,secondno,gcd);
printf("\nThe LCM of %d and %d is %d\n",firstno,secondno,(firstno*secondno)/gcd);
}
The called function is as follows −
int gcd_rec(int x, int y){
if (y == 0)
return x;
return gcd_rec(y, x % y);
}
Following is the C program to implement Euclid’ s algorithm to find the greatest common divisor (GCD) and least common multiple (LCM) of two integers −
Live Demo
#include<stdio.h>
int gcd_rec(int,int);
void main(){
int firstno,secondno,gcd;
printf("Enter the two no.s to find GCD and LCM:");
scanf("%d%d",&firstno,&secondno);
if(firstno*secondno!=0){
gcd=gcd_rec(firstno,secondno);
printf("\nThe GCD of %d and %d is %d\n",firstno,secondno,gcd);
printf("\nThe LCM of %d and %d is %d\n",firstno,secondno,(firstno*secondno)/gcd);
}
else
printf("One of the entered no. is zero:Quitting\n");
}
/*Function for Euclid's Procedure*/
int gcd_rec(int x, int y){
if (y == 0)
return x;
return gcd_rec(y, x % y);
}
When the above program is executed, it produces the following result −
Enter the two no.s to find GCD and LCM:4 8
The GCD of 4 and 8 is 4
The LCM of 4 and 8 is 8
|
[
{
"code": null,
"e": 1239,
"s": 1062,
"text": "Implement Euclid’ s algorithm to find the greatest common divisor (GCD) and least common multiple (LCM) of two integers and to output the results along with the given integers."
},
{
"code": null,
"e": 1391,
"s": 1239,
"text": "The solution to implement Euclid’ s algorithm to find the greatest common divisor (GCD) and least common multiple (LCM) of two integers is as follows −"
},
{
"code": null,
"e": 1442,
"s": 1391,
"text": "The logic used to find GCD and LCM is as follows −"
},
{
"code": null,
"e": 1654,
"s": 1442,
"text": "if(firstno*secondno!=0){\n gcd=gcd_rec(firstno,secondno);\n printf(\"\\nThe GCD of %d and %d is %d\\n\",firstno,secondno,gcd);\n printf(\"\\nThe LCM of %d and %d is %d\\n\",firstno,secondno,(firstno*secondno)/gcd);\n}"
},
{
"code": null,
"e": 1690,
"s": 1654,
"text": "The called function is as follows −"
},
{
"code": null,
"e": 1779,
"s": 1690,
"text": "int gcd_rec(int x, int y){\n if (y == 0)\n return x;\n return gcd_rec(y, x % y);\n}"
},
{
"code": null,
"e": 1931,
"s": 1779,
"text": "Following is the C program to implement Euclid’ s algorithm to find the greatest common divisor (GCD) and least common multiple (LCM) of two integers −"
},
{
"code": null,
"e": 1942,
"s": 1931,
"text": " Live Demo"
},
{
"code": null,
"e": 2545,
"s": 1942,
"text": "#include<stdio.h>\nint gcd_rec(int,int);\nvoid main(){\n int firstno,secondno,gcd;\n printf(\"Enter the two no.s to find GCD and LCM:\");\n scanf(\"%d%d\",&firstno,&secondno);\n if(firstno*secondno!=0){\n gcd=gcd_rec(firstno,secondno);\n printf(\"\\nThe GCD of %d and %d is %d\\n\",firstno,secondno,gcd);\n printf(\"\\nThe LCM of %d and %d is %d\\n\",firstno,secondno,(firstno*secondno)/gcd);\n }\n else\n printf(\"One of the entered no. is zero:Quitting\\n\");\n }\n /*Function for Euclid's Procedure*/\n int gcd_rec(int x, int y){\n if (y == 0)\n return x;\n return gcd_rec(y, x % y);\n}"
},
{
"code": null,
"e": 2616,
"s": 2545,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 2709,
"s": 2616,
"text": "Enter the two no.s to find GCD and LCM:4 8\n\nThe GCD of 4 and 8 is 4\n\nThe LCM of 4 and 8 is 8"
}
] |
Login and Registration in Android using Firebase in Kotlin - GeeksforGeeks
|
28 Feb, 2022
Firebase is a mobile and web application development platform. It provides services that a web application or mobile application might require. Firebase provides email and password authentication without any overhead of building the backend for user authentication. In this article, we will learn the firebase authentication feature. Using it we can create a Login and Registration page in our app.
Step 1: First, We need to connect our project with Firebase. For that, we need to go to tools the select firebase option
.
Step 2: Now as we need the Firebase authentication feature, In authentication, we have different options. For this article, we will use Authenticate using a custom authentication system. We will click on connect. And add the firebase Authentication SDK to your app.
Step 3: Now we will create an XML layout for the Registration Activity.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:id="@+id/linearLayout" android:layout_width="0dp" android:layout_height="0dp" android:orientation="vertical" android:padding="15dp" android:paddingTop="40dp" android:paddingBottom="40dp" app:layout_constraintBottom_toTopOf="@+id/imageView2" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <EditText android:id="@+id/etSEmailAddress" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:layout_marginTop="30dp" android:layout_marginRight="15dp" android:autofillHints="emailAddress" android:ems="10" android:hint="@string/email" android:inputType="textEmailAddress" android:minHeight="48dp" android:textColorHint="#757575" /> <EditText android:id="@+id/etSPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:layout_marginTop="15dp" android:layout_marginRight="15dp" android:autofillHints="password" android:ems="10" android:hint="@string/password" android:inputType="textPassword" android:minHeight="48dp" android:textColorHint="#757575" /> <EditText android:id="@+id/etSConfPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:layout_marginTop="15dp" android:layout_marginRight="15dp" android:autofillHints="password" android:ems="10" android:hint="@string/confirm_password" android:inputType="textPassword" android:minHeight="48dp" android:textColorHint="#757575" tools:ignore="TextContrastCheck" /> <Button android:id="@+id/btnSSigned" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="15dp" android:background="@drawable/btn_primary" android:text="@string/signed" /> <TextView android:id="@+id/tvRedirectLogin" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:layout_margin="10dp" android:text="@string/already_have_an_account_login" android:textColor="#18206F" android:textSize="16sp" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>
Step 4: Now we will code for Registration activity
In the Registration activity, We will create a FirebaseAuth object, and using it we will call the createUserWithEmailAndPassword(email, pass) function. And check using addOnCompleteListener() function, if the response is successful then will display a Toast.
Kotlin
package com.ayush.quizapp.activity.activity import android.content.Intentimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.EditTextimport android.widget.TextViewimport android.widget.Toastimport com.ayush.quizapp.Rimport com.google.firebase.auth.FirebaseAuthimport com.google.firebase.auth.ktx.authimport com.google.firebase.ktx.Firebase class SignUpActivity : AppCompatActivity() { lateinit var etEmail: EditText lateinit var etConfPass: EditText private lateinit var etPass: EditText private lateinit var btnSignUp: Button lateinit var tvRedirectLogin: TextView // create Firebase authentication object private lateinit var auth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_sign_up) // View Bindings etEmail = findViewById(R.id.etSEmailAddress) etConfPass = findViewById(R.id.etSConfPassword) etPass = findViewById(R.id.etSPassword) btnSignUp = findViewById(R.id.btnSSigned) tvRedirectLogin = findViewById(R.id.tvRedirectLogin) // Initialising auth object auth = Firebase.auth btnSignUp.setOnClickListener { signUpUser() } // switching from signUp Activity to Login Activity tvRedirectLogin.setOnClickListener { val intent = Intent(this, LoginActivity::class.java) startActivity(intent) } } private fun signUpUser() { val email = etEmail.text.toString() val pass = etPass.text.toString() val confirmPassword = etConfPass.text.toString() // check pass if (email.isBlank() || pass.isBlank() || confirmPassword.isBlank()) { Toast.makeText(this, "Email and Password can't be blank", Toast.LENGTH_SHORT).show() return } if (pass != confirmPassword) { Toast.makeText(this, "Password and Confirm Password do not match", Toast.LENGTH_SHORT) .show() return } // If all credential are correct // We call createUserWithEmailAndPassword // using auth object and pass the // email and pass in it. auth.createUserWithEmailAndPassword(email, pass).addOnCompleteListener(this) { if (it.isSuccessful) { Toast.makeText(this, "Successfully Singed Up", Toast.LENGTH_SHORT).show() finish() } else { Toast.makeText(this, "Singed Up Failed!", Toast.LENGTH_SHORT).show() } } }}
Step 5: Now we will design the Login Activity page. Here is the XML code
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".activity.activity.LoginActivity"> <LinearLayout android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintBottom_toTopOf="@+id/imageView3" android:orientation="vertical" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <EditText android:id="@+id/etEmailAddress" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:layout_marginTop="30dp" android:layout_marginRight="15dp" android:autofillHints="emailAddress" android:ems="10" android:hint="@string/email" android:inputType="textEmailAddress" android:minHeight="48dp" android:textColorHint="#757575" /> <EditText android:id="@+id/etPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:layout_marginTop="15dp" android:layout_marginRight="15dp" android:autofillHints="password" android:ems="10" android:hint="@string/password" android:inputType="textPassword" android:minHeight="48dp" android:textColorHint="#757575" /> <Button android:id="@+id/btnLogin" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="15dp" android:background="@drawable/btn_primary" android:text="@string/login" /> <TextView android:id="@+id/tvRedirectSignUp" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="15dp" android:gravity="center_horizontal" android:text="@string/don_t_have_an_account_sign_in" android:textColor="#18206F" android:textSize="16sp" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>
Step 6: Now we will code for login activity
In login activity, We will create a FirebaseAuth object, and using it we will call the signInWithEmailAndPassword(email, pass) function. And check using the addOnCompleteListener() function, if the response is successful then will display a toast.
Kotlin
package com.ayush.quizapp.activity.activity import android.content.Intentimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.EditTextimport android.widget.TextViewimport android.widget.Toastimport com.ayush.quizapp.Rimport com.google.firebase.auth.FirebaseAuth class LoginActivity : AppCompatActivity() { private lateinit var tvRedirectSignUp: TextView lateinit var etEmail: EditText private lateinit var etPass: EditText lateinit var btnLogin: Button // Creating firebaseAuth object lateinit var auth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) // View Binding tvRedirectSignUp = findViewById(R.id.tvRedirectSignUp) btnLogin = findViewById(R.id.btnLogin) etEmail = findViewById(R.id.etEmailAddress) etPass = findViewById(R.id.etPassword) // initialising Firebase auth object auth = FirebaseAuth.getInstance() btnLogin.setOnClickListener { login() } tvRedirectSignUp.setOnClickListener { val intent = Intent(this, SignUpActivity::class.java) startActivity(intent) // using finish() to end the activity finish() } } private fun login() { val email = etEmail.text.toString() val pass = etPass.text.toString() // calling signInWithEmailAndPassword(email, pass) // function using Firebase auth object // On successful response Display a Toast auth.signInWithEmailAndPassword(email, pass).addOnCompleteListener(this) { if (it.isSuccessful) { Toast.makeText(this, "Successfully LoggedIn", Toast.LENGTH_SHORT).show() } else Toast.makeText(this, "Log In failed ", Toast.LENGTH_SHORT).show() } } }
Output:
sweetyty
nikhatkhan11
Firebase
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Android Listview in Java with Example
Retrofit with Kotlin Coroutine in Android
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
Kotlin Setters and Getters
|
[
{
"code": null,
"e": 24725,
"s": 24697,
"text": "\n28 Feb, 2022"
},
{
"code": null,
"e": 25124,
"s": 24725,
"text": "Firebase is a mobile and web application development platform. It provides services that a web application or mobile application might require. Firebase provides email and password authentication without any overhead of building the backend for user authentication. In this article, we will learn the firebase authentication feature. Using it we can create a Login and Registration page in our app."
},
{
"code": null,
"e": 25245,
"s": 25124,
"text": "Step 1: First, We need to connect our project with Firebase. For that, we need to go to tools the select firebase option"
},
{
"code": null,
"e": 25247,
"s": 25245,
"text": "."
},
{
"code": null,
"e": 25513,
"s": 25247,
"text": "Step 2: Now as we need the Firebase authentication feature, In authentication, we have different options. For this article, we will use Authenticate using a custom authentication system. We will click on connect. And add the firebase Authentication SDK to your app."
},
{
"code": null,
"e": 25585,
"s": 25513,
"text": "Step 3: Now we will create an XML layout for the Registration Activity."
},
{
"code": null,
"e": 25589,
"s": 25585,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <LinearLayout android:id=\"@+id/linearLayout\" android:layout_width=\"0dp\" android:layout_height=\"0dp\" android:orientation=\"vertical\" android:padding=\"15dp\" android:paddingTop=\"40dp\" android:paddingBottom=\"40dp\" app:layout_constraintBottom_toTopOf=\"@+id/imageView2\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"> <EditText android:id=\"@+id/etSEmailAddress\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginLeft=\"15dp\" android:layout_marginTop=\"30dp\" android:layout_marginRight=\"15dp\" android:autofillHints=\"emailAddress\" android:ems=\"10\" android:hint=\"@string/email\" android:inputType=\"textEmailAddress\" android:minHeight=\"48dp\" android:textColorHint=\"#757575\" /> <EditText android:id=\"@+id/etSPassword\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginLeft=\"15dp\" android:layout_marginTop=\"15dp\" android:layout_marginRight=\"15dp\" android:autofillHints=\"password\" android:ems=\"10\" android:hint=\"@string/password\" android:inputType=\"textPassword\" android:minHeight=\"48dp\" android:textColorHint=\"#757575\" /> <EditText android:id=\"@+id/etSConfPassword\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginLeft=\"15dp\" android:layout_marginTop=\"15dp\" android:layout_marginRight=\"15dp\" android:autofillHints=\"password\" android:ems=\"10\" android:hint=\"@string/confirm_password\" android:inputType=\"textPassword\" android:minHeight=\"48dp\" android:textColorHint=\"#757575\" tools:ignore=\"TextContrastCheck\" /> <Button android:id=\"@+id/btnSSigned\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"15dp\" android:background=\"@drawable/btn_primary\" android:text=\"@string/signed\" /> <TextView android:id=\"@+id/tvRedirectLogin\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:gravity=\"center_horizontal\" android:layout_margin=\"10dp\" android:text=\"@string/already_have_an_account_login\" android:textColor=\"#18206F\" android:textSize=\"16sp\" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 28793,
"s": 25589,
"text": null
},
{
"code": null,
"e": 28848,
"s": 28797,
"text": "Step 4: Now we will code for Registration activity"
},
{
"code": null,
"e": 29109,
"s": 28850,
"text": "In the Registration activity, We will create a FirebaseAuth object, and using it we will call the createUserWithEmailAndPassword(email, pass) function. And check using addOnCompleteListener() function, if the response is successful then will display a Toast."
},
{
"code": null,
"e": 29118,
"s": 29111,
"text": "Kotlin"
},
{
"code": "package com.ayush.quizapp.activity.activity import android.content.Intentimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.EditTextimport android.widget.TextViewimport android.widget.Toastimport com.ayush.quizapp.Rimport com.google.firebase.auth.FirebaseAuthimport com.google.firebase.auth.ktx.authimport com.google.firebase.ktx.Firebase class SignUpActivity : AppCompatActivity() { lateinit var etEmail: EditText lateinit var etConfPass: EditText private lateinit var etPass: EditText private lateinit var btnSignUp: Button lateinit var tvRedirectLogin: TextView // create Firebase authentication object private lateinit var auth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_sign_up) // View Bindings etEmail = findViewById(R.id.etSEmailAddress) etConfPass = findViewById(R.id.etSConfPassword) etPass = findViewById(R.id.etSPassword) btnSignUp = findViewById(R.id.btnSSigned) tvRedirectLogin = findViewById(R.id.tvRedirectLogin) // Initialising auth object auth = Firebase.auth btnSignUp.setOnClickListener { signUpUser() } // switching from signUp Activity to Login Activity tvRedirectLogin.setOnClickListener { val intent = Intent(this, LoginActivity::class.java) startActivity(intent) } } private fun signUpUser() { val email = etEmail.text.toString() val pass = etPass.text.toString() val confirmPassword = etConfPass.text.toString() // check pass if (email.isBlank() || pass.isBlank() || confirmPassword.isBlank()) { Toast.makeText(this, \"Email and Password can't be blank\", Toast.LENGTH_SHORT).show() return } if (pass != confirmPassword) { Toast.makeText(this, \"Password and Confirm Password do not match\", Toast.LENGTH_SHORT) .show() return } // If all credential are correct // We call createUserWithEmailAndPassword // using auth object and pass the // email and pass in it. auth.createUserWithEmailAndPassword(email, pass).addOnCompleteListener(this) { if (it.isSuccessful) { Toast.makeText(this, \"Successfully Singed Up\", Toast.LENGTH_SHORT).show() finish() } else { Toast.makeText(this, \"Singed Up Failed!\", Toast.LENGTH_SHORT).show() } } }}",
"e": 31788,
"s": 29118,
"text": null
},
{
"code": null,
"e": 31866,
"s": 31792,
"text": "Step 5: Now we will design the Login Activity page. Here is the XML code"
},
{
"code": null,
"e": 31872,
"s": 31868,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".activity.activity.LoginActivity\"> <LinearLayout android:layout_width=\"0dp\" android:layout_height=\"0dp\" app:layout_constraintBottom_toTopOf=\"@+id/imageView3\" android:orientation=\"vertical\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"> <EditText android:id=\"@+id/etEmailAddress\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginLeft=\"15dp\" android:layout_marginTop=\"30dp\" android:layout_marginRight=\"15dp\" android:autofillHints=\"emailAddress\" android:ems=\"10\" android:hint=\"@string/email\" android:inputType=\"textEmailAddress\" android:minHeight=\"48dp\" android:textColorHint=\"#757575\" /> <EditText android:id=\"@+id/etPassword\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginLeft=\"15dp\" android:layout_marginTop=\"15dp\" android:layout_marginRight=\"15dp\" android:autofillHints=\"password\" android:ems=\"10\" android:hint=\"@string/password\" android:inputType=\"textPassword\" android:minHeight=\"48dp\" android:textColorHint=\"#757575\" /> <Button android:id=\"@+id/btnLogin\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"15dp\" android:background=\"@drawable/btn_primary\" android:text=\"@string/login\" /> <TextView android:id=\"@+id/tvRedirectSignUp\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"15dp\" android:gravity=\"center_horizontal\" android:text=\"@string/don_t_have_an_account_sign_in\" android:textColor=\"#18206F\" android:textSize=\"16sp\" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 34405,
"s": 31872,
"text": null
},
{
"code": null,
"e": 34453,
"s": 34409,
"text": "Step 6: Now we will code for login activity"
},
{
"code": null,
"e": 34703,
"s": 34455,
"text": "In login activity, We will create a FirebaseAuth object, and using it we will call the signInWithEmailAndPassword(email, pass) function. And check using the addOnCompleteListener() function, if the response is successful then will display a toast."
},
{
"code": null,
"e": 34712,
"s": 34705,
"text": "Kotlin"
},
{
"code": "package com.ayush.quizapp.activity.activity import android.content.Intentimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.EditTextimport android.widget.TextViewimport android.widget.Toastimport com.ayush.quizapp.Rimport com.google.firebase.auth.FirebaseAuth class LoginActivity : AppCompatActivity() { private lateinit var tvRedirectSignUp: TextView lateinit var etEmail: EditText private lateinit var etPass: EditText lateinit var btnLogin: Button // Creating firebaseAuth object lateinit var auth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) // View Binding tvRedirectSignUp = findViewById(R.id.tvRedirectSignUp) btnLogin = findViewById(R.id.btnLogin) etEmail = findViewById(R.id.etEmailAddress) etPass = findViewById(R.id.etPassword) // initialising Firebase auth object auth = FirebaseAuth.getInstance() btnLogin.setOnClickListener { login() } tvRedirectSignUp.setOnClickListener { val intent = Intent(this, SignUpActivity::class.java) startActivity(intent) // using finish() to end the activity finish() } } private fun login() { val email = etEmail.text.toString() val pass = etPass.text.toString() // calling signInWithEmailAndPassword(email, pass) // function using Firebase auth object // On successful response Display a Toast auth.signInWithEmailAndPassword(email, pass).addOnCompleteListener(this) { if (it.isSuccessful) { Toast.makeText(this, \"Successfully LoggedIn\", Toast.LENGTH_SHORT).show() } else Toast.makeText(this, \"Log In failed \", Toast.LENGTH_SHORT).show() } } }",
"e": 36670,
"s": 34712,
"text": null
},
{
"code": null,
"e": 36682,
"s": 36674,
"text": "Output:"
},
{
"code": null,
"e": 36695,
"s": 36686,
"text": "sweetyty"
},
{
"code": null,
"e": 36708,
"s": 36695,
"text": "nikhatkhan11"
},
{
"code": null,
"e": 36717,
"s": 36708,
"text": "Firebase"
},
{
"code": null,
"e": 36725,
"s": 36717,
"text": "Android"
},
{
"code": null,
"e": 36732,
"s": 36725,
"text": "Kotlin"
},
{
"code": null,
"e": 36740,
"s": 36732,
"text": "Android"
},
{
"code": null,
"e": 36838,
"s": 36740,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36847,
"s": 36838,
"text": "Comments"
},
{
"code": null,
"e": 36860,
"s": 36847,
"text": "Old Comments"
},
{
"code": null,
"e": 36899,
"s": 36860,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 36949,
"s": 36899,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 37000,
"s": 36949,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 37038,
"s": 37000,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 37080,
"s": 37038,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 37099,
"s": 37080,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 37112,
"s": 37099,
"text": "Kotlin Array"
},
{
"code": null,
"e": 37154,
"s": 37112,
"text": "Retrofit with Kotlin Coroutine in Android"
}
] |
How to format date string in PowerShell?
|
By default the when you run the (Get-Date) cmdlet, its output is in the below format.
PS C:\WINDOWS\system32> Get-Date
18 March 2020 22:56:18
You can format the above output in the various format supported by PowerShell.
d – Short date pattern.
d – Short date pattern.
PS C:\WINDOWS\system32> Get-Date -Format d
18-03-2020
D – Long date pattern
D – Long date pattern
PS C:\WINDOWS\system32> Get-Date -Format D
18 March 2020
f – Full date pattern with a short time pattern.
f – Full date pattern with a short time pattern.
PS C:\WINDOWS\system32> Get-Date -Format f
18 March 2020 23:01
F – Full date pattern with a long time pattern.
F – Full date pattern with a long time pattern.
PS C:\WINDOWS\system32> Get-Date -Format F
18 March 2020 23:02:22
g – General date pattern with a short time pattern.
g – General date pattern with a short time pattern.
PS C:\WINDOWS\system32> Get-Date -Format g 18-03-2020 23:03
G – General date pattern with a long time pattern.
G – General date pattern with a long time pattern.
PS C:\WINDOWS\system32> Get-Date -Format G
18-03-2020 23:05:39
M/m – Month day pattern.
M/m – Month day pattern.
PS C:\WINDOWS\system32> Get-Date -Format M
18 March
PS C:\WINDOWS\system32> Get-Date -Format m
18 March
O,o – Round trip date/time pattern
O,o – Round trip date/time pattern
PS C:\WINDOWS\system32> Get-Date -Format O
2020-03-18T23:08:36.8098960+05:30
PS C:\WINDOWS\system32> Get-Date -Format o
2020-03-18T23:08:36.8098960+05:30
R,r – RFC1123 pattern
R,r – RFC1123 pattern
PS C:\WINDOWS\system32> Get-Date -Format R
Wed, 18 Mar 2020 23:10:06 GMT
PS C:\WINDOWS\system32> Get-Date -Format r
Wed, 18 Mar 2020 23:10:06 GMT
s – Sortable Date/Time pattern
s – Sortable Date/Time pattern
PS C:\WINDOWS\system32> Get-Date -Format s
2020-03-18T23:12:12
t – Short time pattern.
t – Short time pattern.
PS C:\WINDOWS\system32> Get-Date -Format t
23:13
T – Long time pattern.
T – Long time pattern.
PS C:\WINDOWS\system32> Get-Date -Format T
23:13:09
u – Universal Sortable date/time pattern.
u – Universal Sortable date/time pattern.
PS C:\WINDOWS\system32> Get-Date -Format u
2020-03-19 20:21:37Z
U – Universal Full date/time format.
U – Universal Full date/time format.
PS C:\WINDOWS\system32> Get-Date -Format U
19 March 2020 14:51:41
Y,y – Year month pattern.
Y,y – Year month pattern.
PS C:\WINDOWS\system32> Get-Date -Format y
March, 2020
PS C:\WINDOWS\system32> Get-Date -Format Y
March, 2020
You can also format Get-Date into the .NET format and for that, you need to use –Format parameter.
.NET format specifier can be used as below.
You can use any of the above combinations to format the date in the required format.
Get-Date -Format "dd/MM/yyyy"
19-03-2020
PS C:\WINDOWS\system32> Get-Date -Format "dd/MM/yyyy -- dddd"
19-03-2020 -- Thursday
PS C:\WINDOWS\system32> Get-Date -Format "HH:mm K"
20:44 +05:30
You can format the date string into the universal format as well and for that, you need to use –Uformat parameter. Below specifiers used for the universal format.
Get-Date -UFormat "%d %m %Y"
19 03 2020
Get-Date -UFormat %R
21:15
|
[
{
"code": null,
"e": 1148,
"s": 1062,
"text": "By default the when you run the (Get-Date) cmdlet, its output is in the below format."
},
{
"code": null,
"e": 1204,
"s": 1148,
"text": "PS C:\\WINDOWS\\system32> Get-Date\n18 March 2020 22:56:18"
},
{
"code": null,
"e": 1283,
"s": 1204,
"text": "You can format the above output in the various format supported by PowerShell."
},
{
"code": null,
"e": 1307,
"s": 1283,
"text": "d – Short date pattern."
},
{
"code": null,
"e": 1331,
"s": 1307,
"text": "d – Short date pattern."
},
{
"code": null,
"e": 1385,
"s": 1331,
"text": "PS C:\\WINDOWS\\system32> Get-Date -Format d\n18-03-2020"
},
{
"code": null,
"e": 1407,
"s": 1385,
"text": "D – Long date pattern"
},
{
"code": null,
"e": 1429,
"s": 1407,
"text": "D – Long date pattern"
},
{
"code": null,
"e": 1486,
"s": 1429,
"text": "PS C:\\WINDOWS\\system32> Get-Date -Format D\n18 March 2020"
},
{
"code": null,
"e": 1535,
"s": 1486,
"text": "f – Full date pattern with a short time pattern."
},
{
"code": null,
"e": 1584,
"s": 1535,
"text": "f – Full date pattern with a short time pattern."
},
{
"code": null,
"e": 1647,
"s": 1584,
"text": "PS C:\\WINDOWS\\system32> Get-Date -Format f\n18 March 2020 23:01"
},
{
"code": null,
"e": 1695,
"s": 1647,
"text": "F – Full date pattern with a long time pattern."
},
{
"code": null,
"e": 1743,
"s": 1695,
"text": "F – Full date pattern with a long time pattern."
},
{
"code": null,
"e": 1809,
"s": 1743,
"text": "PS C:\\WINDOWS\\system32> Get-Date -Format F\n18 March 2020 23:02:22"
},
{
"code": null,
"e": 1861,
"s": 1809,
"text": "g – General date pattern with a short time pattern."
},
{
"code": null,
"e": 1913,
"s": 1861,
"text": "g – General date pattern with a short time pattern."
},
{
"code": null,
"e": 1973,
"s": 1913,
"text": "PS C:\\WINDOWS\\system32> Get-Date -Format g 18-03-2020 23:03"
},
{
"code": null,
"e": 2024,
"s": 1973,
"text": "G – General date pattern with a long time pattern."
},
{
"code": null,
"e": 2075,
"s": 2024,
"text": "G – General date pattern with a long time pattern."
},
{
"code": null,
"e": 2138,
"s": 2075,
"text": "PS C:\\WINDOWS\\system32> Get-Date -Format G\n18-03-2020 23:05:39"
},
{
"code": null,
"e": 2163,
"s": 2138,
"text": "M/m – Month day pattern."
},
{
"code": null,
"e": 2188,
"s": 2163,
"text": "M/m – Month day pattern."
},
{
"code": null,
"e": 2292,
"s": 2188,
"text": "PS C:\\WINDOWS\\system32> Get-Date -Format M\n18 March\nPS C:\\WINDOWS\\system32> Get-Date -Format m\n18 March"
},
{
"code": null,
"e": 2327,
"s": 2292,
"text": "O,o – Round trip date/time pattern"
},
{
"code": null,
"e": 2362,
"s": 2327,
"text": "O,o – Round trip date/time pattern"
},
{
"code": null,
"e": 2516,
"s": 2362,
"text": "PS C:\\WINDOWS\\system32> Get-Date -Format O\n2020-03-18T23:08:36.8098960+05:30\nPS C:\\WINDOWS\\system32> Get-Date -Format o\n2020-03-18T23:08:36.8098960+05:30"
},
{
"code": null,
"e": 2538,
"s": 2516,
"text": "R,r – RFC1123 pattern"
},
{
"code": null,
"e": 2560,
"s": 2538,
"text": "R,r – RFC1123 pattern"
},
{
"code": null,
"e": 2706,
"s": 2560,
"text": "PS C:\\WINDOWS\\system32> Get-Date -Format R\nWed, 18 Mar 2020 23:10:06 GMT\nPS C:\\WINDOWS\\system32> Get-Date -Format r\nWed, 18 Mar 2020 23:10:06 GMT"
},
{
"code": null,
"e": 2737,
"s": 2706,
"text": "s – Sortable Date/Time pattern"
},
{
"code": null,
"e": 2768,
"s": 2737,
"text": "s – Sortable Date/Time pattern"
},
{
"code": null,
"e": 2831,
"s": 2768,
"text": "PS C:\\WINDOWS\\system32> Get-Date -Format s\n2020-03-18T23:12:12"
},
{
"code": null,
"e": 2855,
"s": 2831,
"text": "t – Short time pattern."
},
{
"code": null,
"e": 2879,
"s": 2855,
"text": "t – Short time pattern."
},
{
"code": null,
"e": 2928,
"s": 2879,
"text": "PS C:\\WINDOWS\\system32> Get-Date -Format t\n23:13"
},
{
"code": null,
"e": 2951,
"s": 2928,
"text": "T – Long time pattern."
},
{
"code": null,
"e": 2974,
"s": 2951,
"text": "T – Long time pattern."
},
{
"code": null,
"e": 3026,
"s": 2974,
"text": "PS C:\\WINDOWS\\system32> Get-Date -Format T\n23:13:09"
},
{
"code": null,
"e": 3068,
"s": 3026,
"text": "u – Universal Sortable date/time pattern."
},
{
"code": null,
"e": 3110,
"s": 3068,
"text": "u – Universal Sortable date/time pattern."
},
{
"code": null,
"e": 3174,
"s": 3110,
"text": "PS C:\\WINDOWS\\system32> Get-Date -Format u\n2020-03-19 20:21:37Z"
},
{
"code": null,
"e": 3211,
"s": 3174,
"text": "U – Universal Full date/time format."
},
{
"code": null,
"e": 3248,
"s": 3211,
"text": "U – Universal Full date/time format."
},
{
"code": null,
"e": 3314,
"s": 3248,
"text": "PS C:\\WINDOWS\\system32> Get-Date -Format U\n19 March 2020 14:51:41"
},
{
"code": null,
"e": 3340,
"s": 3314,
"text": "Y,y – Year month pattern."
},
{
"code": null,
"e": 3366,
"s": 3340,
"text": "Y,y – Year month pattern."
},
{
"code": null,
"e": 3476,
"s": 3366,
"text": "PS C:\\WINDOWS\\system32> Get-Date -Format y\nMarch, 2020\nPS C:\\WINDOWS\\system32> Get-Date -Format Y\nMarch, 2020"
},
{
"code": null,
"e": 3575,
"s": 3476,
"text": "You can also format Get-Date into the .NET format and for that, you need to use –Format parameter."
},
{
"code": null,
"e": 3619,
"s": 3575,
"text": ".NET format specifier can be used as below."
},
{
"code": null,
"e": 3704,
"s": 3619,
"text": "You can use any of the above combinations to format the date in the required format."
},
{
"code": null,
"e": 3745,
"s": 3704,
"text": "Get-Date -Format \"dd/MM/yyyy\"\n19-03-2020"
},
{
"code": null,
"e": 3830,
"s": 3745,
"text": "PS C:\\WINDOWS\\system32> Get-Date -Format \"dd/MM/yyyy -- dddd\"\n19-03-2020 -- Thursday"
},
{
"code": null,
"e": 3894,
"s": 3830,
"text": "PS C:\\WINDOWS\\system32> Get-Date -Format \"HH:mm K\"\n20:44 +05:30"
},
{
"code": null,
"e": 4057,
"s": 3894,
"text": "You can format the date string into the universal format as well and for that, you need to use –Uformat parameter. Below specifiers used for the universal format."
},
{
"code": null,
"e": 4097,
"s": 4057,
"text": "Get-Date -UFormat \"%d %m %Y\"\n19 03 2020"
},
{
"code": null,
"e": 4124,
"s": 4097,
"text": "Get-Date -UFormat %R\n21:15"
}
] |
DB2 - Databases
|
This chapter describes creating, activating and deactivating the databases with the associated syntax.
A database is a collection of Tables, Schemas, Bufferpools, Logs, Storage groups and Tablespaces working together to handle database operations efficiently.
Database directory is an organized repository of databases. When you create a database, all the details about database are stored in a database directory, such as details of default storage devices, configuration files, and temporary tables list etc.
Partition global directory is created in the instance folder. This directory contains all global information related to the database. This partition global directory is named as NODExxxx/SQLyyy, where xxxx is the data partition number and yyy is the database token.
In the partition-global directory, a member-specific directory is created. This directory contains local database information. The member-specific directory is named as MEMBERxxxx where xxxx is a member number. DB2 Enterprise Server Edition environment runs on a single member and has only one member specific directory. This member specific directory is uniquely named as MEMBER0000.
Directory Location : <instance>/NODExxx/SQLxxx
The partition-global directory contains database related files as listed below.
Global deadlock write-to-file event monitoring files
Table space information files [SQLSPCS.1, SQLSPCS.2]
Storage group control files [SQLSGF.1, SQLSGF.2]
Temporary table space container files. [/storage path//T0000011/C000000.TMP/SQL00002.MEMBER0001.TDA]
Global Configuration file [SQLDBCONF]
History files [DB2RHIST.ASC, DB2RHIST.BAK, DB2TSCHG.HIS, DB2TSCHG.HIS]
Logging-related files [SQLOGCTL.GLFH.1, SQLOGCTL.GLFH.2]
Locking files [SQLINSLK, SQLTMPLK]
Automatic Storage containers
Directory location : /NODExxxx/SQLxxxx/MEMBER0000
This directory contains:
Objects associated with databases
Buffer pool information files [SQLBP.1, SQLBP.2]
Local event monitoring files
Logging-related files [SQLOGCTL.LFH.1, SQLOGCTL.LFH.2, SQLOGMIR.LFH].
Local configuration files
Deadlocks event monitor file. The detailed deadlock events monitor files are stored in the database directory of the catalog node in case of ESE and partitioned database environment.
You can create a database in instance using the “CREATE DATABASE” command. All databases are created with the default storage group “IBMSTOGROUP”, which is created at the time of creating an instance. In DB2, all the database tables are stored in “tablespace”, which use their respective storage groups.
The privileges for database are automatically set as PUBLIC [CREATETAB, BINDADD, CONNECT, IMPLICIT_SCHEMA, and SELECT], however, if the RESTRICTIVE option is present, the privileges are not granted as PUBLIC.
This command is used to create a non-restrictive database.
Syntax: [To create a new Database. ‘database_name’ indicates a new database name, which you want to create.]
db2 create database <database name>
Example: [To create a new non-restrictive database with name ‘one’]
db2 create database one
Output:
DB20000I The CREATE DATABASE command completed successfully.
Restrictive database is created on invoking this command.
Syntax: [In the syntax below, “db_name” indicates the database name.]
db2 create database <db_name> restrictive
Example: [To create a new restrictive database with the name ‘two’]
db2 create database two restrictive
Create a database with default storage group “IBMSTOGROUP” on different path. Earlier, you invoked the command “create database” without any user-defined location to store or create database at a particular location. To create the database using user- defined database location, the following procedure is followed:
Syntax: [In the syntax below, ‘db_name’ indicates the ‘database name’ and ‘data_location’ indicates where have to store data in folders and ‘db_path_location’ indicates driver location of ‘data_location’.]
db2 create database '<db_name>' on '<data location>' dbpath on '<db_path_location>'
Example: [To create database named ‘four’, where data is stored in ‘data1’ and this folder is stored in ‘dbpath1’]
db2 create database four on '/data1' dbpath on '/dbpath1'
You execute this command to see the list of directories available in the current instance.
Syntax:
db2 list database directory
Example:
db2 list database directory
Output:
System Database Directory
Number of entries in the directory = 6
Database 1 entry:
Database alias = FOUR
Database name = FOUR
Local database directory =
/home/db2inst4/Desktop/dbpath
Database release level = f.00
Comment =
Directory entry type = Indirect
Catalog database partition number = 0
Alternate server hostname =
Alternate server port number =
Database 2 entry:
Database alias = SIX
Database name = SIX
Local database directory = /home/db2inst4
Database release level = f.00
Comment =
Directory entry type = Indirect
Catalog database partition number = 0
Alternate server hostname =
Alternate server port number =
This command starts up all necessary services for a particular database so that the database is available for application.
Syntax:[‘db_name’ indicates database name]
db2 activate db <db_name>
Example: [Activating the database ‘one’]
db2 activate db one
Using this command, you can stop the database services.
Syntax:
db2 deactivate db <db_name>
Example: [To Deactivate database ‘one’]
db2 deactivate db one
After creating a database, to put it into use, you need to connect or start database.
Syntax:
db2 connect to <database name>
Example: [To Connect Database one to current CLI]
db2 connect to one
Output:
Database Connection Information
Database server = DB2/LINUXX8664 10.1.0
SQL authorization ID = DB2INST4
Local database alias = ONE
To check if this database is restrictive or not, here is the syntax:
Syntax: [In the following syntax, ‘db’ indicates Database, ‘cfg’ indicates configuration, ‘db_name’ indicates database name]
db2 get db cfg for <db_name> | grep -i restrict
Example: [To check if ‘one’ database is restricted or not]
db2 get db cfg for one | grep -i restrict
Output:
Restrict access = NO
Instance configuration (Database manager configuration) is stored in a file named 'db2system' and the database related configuration is stored in a file named 'SQLDBCON'. These files cannot be edited directly. You can edit these files using tools which call API. Using the command line processor, you can use these commands.
Syntax: [To get the information of Instance Database manager]
db2 get database manager configuration
db2 get dbm cfg
Syntax: [To update instance database manager]
db2 update database manager configuration
db2 update dbm cfg
Syntax: [To reset previous configurations]
db2 reset database manager configuration
db2 reset dbm cfg
Syntax: [To get the information of Database]
db2 get database configuration
db2 get db cfg
Syntax: [To update the database configuration]
db2 update database configuration
db2 update db cfg
Syntax: [To reset the previously configured values in database configuration
db2 reset database configuration
db2 reset db cfg
Syntax: [To check the size of Current Active Database]
db2 "call get_dbsize_info(?,?,?,-1)"
Example: [To verify the size of Currently Activate Database]
db2 "call get_dbsize_info(?,?,?,-1)"
Output:
Value of output parameters
--------------------------
Parameter Name : SNAPSHOTTIMESTAMP
Parameter Value : 2014-07-02-10.27.15.556775
Parameter Name : DATABASESIZE
Parameter Value : 105795584
Parameter Name : DATABASECAPACITY
Parameter Value : 396784705536
Return Status = 0
To estimate the size of a database, the contribution of the following factors must be considered:
System Catalog Tables
User Table Data
Long Field Data
Large Object (LOB) Data
Index Space
Temporary Work Space
XML data
Log file space
Local database directory
System files
You can use the following syntax to check which database authorities are granted to PUBLIC on the non-restrictive database.
Step 1: connect to database with authentication user-id and password of instance.
Syntax: [To connect to database with username and password]
db2 connect to <db_name> user <userid> using <password>
Example: [To Connect “one” Database with the user id ‘db2inst4’ and password ‘db2inst4’]
db2 connect to one user db2inst4 using db2inst4
Output:
Database Connection Information
Database server = DB2/LINUXX8664 10.1.0
SQL authorization ID = DB2INST4
Local database alias = ONE
Step2: To verify the authorities of database.
Syntax: [The syntax below shows the result of authority services for current database]
db2 "select substr(authority,1,25) as authority, d_user, d_group,
d_public, role_user, role_group, role_public,d_role from table(
sysproc.auth_list_authorities_for_authid ('public','g'))as t
order by authority"
Example:
db2 "select substr(authority,1,25) as authority, d_user, d_group,
d_public, role_user, role_group, role_public,d_role from table(
sysproc.auth_list_authorities_for_authid ('PUBLIC','G'))as t
order by authority"
Output:
AUTHORITY D_USER D_GROUP D_PUBLIC ROLE_USER ROLE_GROUP ROLE_PUBLIC D_ROLE
------------------------- ------ ------- -------- --------- ---------- ----------- ------
ACCESSCTRL * * N * * N *
BINDADD * * Y * * N *
CONNECT * * Y * * N *
CREATETAB * * Y * * N *
CREATE_EXTERNAL_ROUTINE * * N * * N *
CREATE_NOT_FENCED_ROUTINE * * N * * N *
CREATE_SECURE_OBJECT * * N * * N *
DATAACCESS * * N * * N *
DBADM * * N * * N *
EXPLAIN * * N * * N *
IMPLICIT_SCHEMA * * Y * * N *
LOAD * * N * * N *
QUIESCE_CONNECT * * N * * N *
SECADM * * N * * N *
SQLADM * * N * * N *
SYSADM * * * * * * *
SYSCTRL * * * * * * *
SYSMAINT * * * * * * *
SYSMON * * * * * * *
WLMADM * * N * * N *
20 record(s) selected.
Using the Drop command, you can remove our database from instance database directory. This command can delete all its objects, table, spaces, containers and associated files.
Syntax: [To drop any database from an instance]
db2 drop database <db_name>
Example: [To drop ‘six’ database from instance]
db2 drop database six
Output:
DB20000I The DROP DATABASE command completed successfully
10 Lectures
1.5 hours
Nishant Malik
41 Lectures
8.5 hours
Parth Panjabi
53 Lectures
11.5 hours
Parth Panjabi
33 Lectures
7 hours
Parth Panjabi
44 Lectures
3 hours
Arnab Chakraborty
178 Lectures
14.5 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2031,
"s": 1928,
"text": "This chapter describes creating, activating and deactivating the databases with the associated syntax."
},
{
"code": null,
"e": 2188,
"s": 2031,
"text": "A database is a collection of Tables, Schemas, Bufferpools, Logs, Storage groups and Tablespaces working together to handle database operations efficiently."
},
{
"code": null,
"e": 2439,
"s": 2188,
"text": "Database directory is an organized repository of databases. When you create a database, all the details about database are stored in a database directory, such as details of default storage devices, configuration files, and temporary tables list etc."
},
{
"code": null,
"e": 2705,
"s": 2439,
"text": "Partition global directory is created in the instance folder. This directory contains all global information related to the database. This partition global directory is named as NODExxxx/SQLyyy, where xxxx is the data partition number and yyy is the database token."
},
{
"code": null,
"e": 3090,
"s": 2705,
"text": "In the partition-global directory, a member-specific directory is created. This directory contains local database information. The member-specific directory is named as MEMBERxxxx where xxxx is a member number. DB2 Enterprise Server Edition environment runs on a single member and has only one member specific directory. This member specific directory is uniquely named as MEMBER0000."
},
{
"code": null,
"e": 3137,
"s": 3090,
"text": "Directory Location : <instance>/NODExxx/SQLxxx"
},
{
"code": null,
"e": 3217,
"s": 3137,
"text": "The partition-global directory contains database related files as listed below."
},
{
"code": null,
"e": 3270,
"s": 3217,
"text": "Global deadlock write-to-file event monitoring files"
},
{
"code": null,
"e": 3323,
"s": 3270,
"text": "Table space information files [SQLSPCS.1, SQLSPCS.2]"
},
{
"code": null,
"e": 3372,
"s": 3323,
"text": "Storage group control files [SQLSGF.1, SQLSGF.2]"
},
{
"code": null,
"e": 3473,
"s": 3372,
"text": "Temporary table space container files. [/storage path//T0000011/C000000.TMP/SQL00002.MEMBER0001.TDA]"
},
{
"code": null,
"e": 3511,
"s": 3473,
"text": "Global Configuration file [SQLDBCONF]"
},
{
"code": null,
"e": 3582,
"s": 3511,
"text": "History files [DB2RHIST.ASC, DB2RHIST.BAK, DB2TSCHG.HIS, DB2TSCHG.HIS]"
},
{
"code": null,
"e": 3639,
"s": 3582,
"text": "Logging-related files [SQLOGCTL.GLFH.1, SQLOGCTL.GLFH.2]"
},
{
"code": null,
"e": 3674,
"s": 3639,
"text": "Locking files [SQLINSLK, SQLTMPLK]"
},
{
"code": null,
"e": 3703,
"s": 3674,
"text": "Automatic Storage containers"
},
{
"code": null,
"e": 3753,
"s": 3703,
"text": "Directory location : /NODExxxx/SQLxxxx/MEMBER0000"
},
{
"code": null,
"e": 3778,
"s": 3753,
"text": "This directory contains:"
},
{
"code": null,
"e": 3812,
"s": 3778,
"text": "Objects associated with databases"
},
{
"code": null,
"e": 3861,
"s": 3812,
"text": "Buffer pool information files [SQLBP.1, SQLBP.2]"
},
{
"code": null,
"e": 3890,
"s": 3861,
"text": "Local event monitoring files"
},
{
"code": null,
"e": 3960,
"s": 3890,
"text": "Logging-related files [SQLOGCTL.LFH.1, SQLOGCTL.LFH.2, SQLOGMIR.LFH]."
},
{
"code": null,
"e": 3986,
"s": 3960,
"text": "Local configuration files"
},
{
"code": null,
"e": 4169,
"s": 3986,
"text": "Deadlocks event monitor file. The detailed deadlock events monitor files are stored in the database directory of the catalog node in case of ESE and partitioned database environment."
},
{
"code": null,
"e": 4473,
"s": 4169,
"text": "You can create a database in instance using the “CREATE DATABASE” command. All databases are created with the default storage group “IBMSTOGROUP”, which is created at the time of creating an instance. In DB2, all the database tables are stored in “tablespace”, which use their respective storage groups."
},
{
"code": null,
"e": 4682,
"s": 4473,
"text": "The privileges for database are automatically set as PUBLIC [CREATETAB, BINDADD, CONNECT, IMPLICIT_SCHEMA, and SELECT], however, if the RESTRICTIVE option is present, the privileges are not granted as PUBLIC."
},
{
"code": null,
"e": 4741,
"s": 4682,
"text": "This command is used to create a non-restrictive database."
},
{
"code": null,
"e": 4850,
"s": 4741,
"text": "Syntax: [To create a new Database. ‘database_name’ indicates a new database name, which you want to create.]"
},
{
"code": null,
"e": 4886,
"s": 4850,
"text": "db2 create database <database name>"
},
{
"code": null,
"e": 4954,
"s": 4886,
"text": "Example: [To create a new non-restrictive database with name ‘one’]"
},
{
"code": null,
"e": 4978,
"s": 4954,
"text": "db2 create database one"
},
{
"code": null,
"e": 4986,
"s": 4978,
"text": "Output:"
},
{
"code": null,
"e": 5047,
"s": 4986,
"text": "DB20000I The CREATE DATABASE command completed successfully."
},
{
"code": null,
"e": 5105,
"s": 5047,
"text": "Restrictive database is created on invoking this command."
},
{
"code": null,
"e": 5175,
"s": 5105,
"text": "Syntax: [In the syntax below, “db_name” indicates the database name.]"
},
{
"code": null,
"e": 5218,
"s": 5175,
"text": "db2 create database <db_name> restrictive "
},
{
"code": null,
"e": 5286,
"s": 5218,
"text": "Example: [To create a new restrictive database with the name ‘two’]"
},
{
"code": null,
"e": 5323,
"s": 5286,
"text": "db2 create database two restrictive "
},
{
"code": null,
"e": 5640,
"s": 5323,
"text": "Create a database with default storage group “IBMSTOGROUP” on different path. Earlier, you invoked the command “create database” without any user-defined location to store or create database at a particular location. To create the database using user- defined database location, the following procedure is followed:"
},
{
"code": null,
"e": 5847,
"s": 5640,
"text": "Syntax: [In the syntax below, ‘db_name’ indicates the ‘database name’ and ‘data_location’ indicates where have to store data in folders and ‘db_path_location’ indicates driver location of ‘data_location’.]"
},
{
"code": null,
"e": 5933,
"s": 5847,
"text": "db2 create database '<db_name>' on '<data location>' dbpath on '<db_path_location>' "
},
{
"code": null,
"e": 6049,
"s": 5933,
"text": "Example: [To create database named ‘four’, where data is stored in ‘data1’ and this folder is stored in ‘dbpath1’]"
},
{
"code": null,
"e": 6107,
"s": 6049,
"text": "db2 create database four on '/data1' dbpath on '/dbpath1'"
},
{
"code": null,
"e": 6198,
"s": 6107,
"text": "You execute this command to see the list of directories available in the current instance."
},
{
"code": null,
"e": 6206,
"s": 6198,
"text": "Syntax:"
},
{
"code": null,
"e": 6235,
"s": 6206,
"text": "db2 list database directory "
},
{
"code": null,
"e": 6244,
"s": 6235,
"text": "Example:"
},
{
"code": null,
"e": 6273,
"s": 6244,
"text": "db2 list database directory "
},
{
"code": null,
"e": 6281,
"s": 6273,
"text": "Output:"
},
{
"code": null,
"e": 7235,
"s": 6281,
"text": " System Database Directory \n Number of entries in the directory = 6 \n Database 1 entry: \n Database alias = FOUR \n Database name = FOUR \n Local database directory = \n /home/db2inst4/Desktop/dbpath \n Database release level = f.00 \n Comment = \n Directory entry type = Indirect \n Catalog database partition number = 0 \n Alternate server hostname = \n Alternate server port number = \nDatabase 2 entry: \nDatabase alias = SIX \nDatabase name = SIX \nLocal database directory = /home/db2inst4 \nDatabase release level = f.00 \nComment = \nDirectory entry type = Indirect \nCatalog database partition number = 0 \nAlternate server hostname = \nAlternate server port number = "
},
{
"code": null,
"e": 7358,
"s": 7235,
"text": "This command starts up all necessary services for a particular database so that the database is available for application."
},
{
"code": null,
"e": 7401,
"s": 7358,
"text": "Syntax:[‘db_name’ indicates database name]"
},
{
"code": null,
"e": 7428,
"s": 7401,
"text": "db2 activate db <db_name> "
},
{
"code": null,
"e": 7469,
"s": 7428,
"text": "Example: [Activating the database ‘one’]"
},
{
"code": null,
"e": 7491,
"s": 7469,
"text": "db2 activate db one "
},
{
"code": null,
"e": 7547,
"s": 7491,
"text": "Using this command, you can stop the database services."
},
{
"code": null,
"e": 7555,
"s": 7547,
"text": "Syntax:"
},
{
"code": null,
"e": 7583,
"s": 7555,
"text": "db2 deactivate db <db_name>"
},
{
"code": null,
"e": 7623,
"s": 7583,
"text": "Example: [To Deactivate database ‘one’]"
},
{
"code": null,
"e": 7645,
"s": 7623,
"text": "db2 deactivate db one"
},
{
"code": null,
"e": 7731,
"s": 7645,
"text": "After creating a database, to put it into use, you need to connect or start database."
},
{
"code": null,
"e": 7739,
"s": 7731,
"text": "Syntax:"
},
{
"code": null,
"e": 7771,
"s": 7739,
"text": "db2 connect to <database name> "
},
{
"code": null,
"e": 7821,
"s": 7771,
"text": "Example: [To Connect Database one to current CLI]"
},
{
"code": null,
"e": 7841,
"s": 7821,
"text": "db2 connect to one "
},
{
"code": null,
"e": 7849,
"s": 7841,
"text": "Output:"
},
{
"code": null,
"e": 8003,
"s": 7849,
"text": " Database Connection Information \n Database server = DB2/LINUXX8664 10.1.0 \n SQL authorization ID = DB2INST4 \n Local database alias = ONE "
},
{
"code": null,
"e": 8072,
"s": 8003,
"text": "To check if this database is restrictive or not, here is the syntax:"
},
{
"code": null,
"e": 8197,
"s": 8072,
"text": "Syntax: [In the following syntax, ‘db’ indicates Database, ‘cfg’ indicates configuration, ‘db_name’ indicates database name]"
},
{
"code": null,
"e": 8246,
"s": 8197,
"text": "db2 get db cfg for <db_name> | grep -i restrict "
},
{
"code": null,
"e": 8305,
"s": 8246,
"text": "Example: [To check if ‘one’ database is restricted or not]"
},
{
"code": null,
"e": 8349,
"s": 8305,
"text": "db2 get db cfg for one | grep -i restrict "
},
{
"code": null,
"e": 8357,
"s": 8349,
"text": "Output:"
},
{
"code": null,
"e": 8403,
"s": 8357,
"text": "Restrict access = NO "
},
{
"code": null,
"e": 8730,
"s": 8403,
"text": "Instance configuration (Database manager configuration) is stored in a file named 'db2system' and the database related configuration is stored in a file named 'SQLDBCON'. These files cannot be edited directly. You can edit these files using tools which call API. Using the command line processor, you can use these commands."
},
{
"code": null,
"e": 8792,
"s": 8730,
"text": "Syntax: [To get the information of Instance Database manager]"
},
{
"code": null,
"e": 8834,
"s": 8792,
"text": "db2 get database manager configuration "
},
{
"code": null,
"e": 8853,
"s": 8834,
"text": "db2 get dbm cfg "
},
{
"code": null,
"e": 8899,
"s": 8853,
"text": "Syntax: [To update instance database manager]"
},
{
"code": null,
"e": 8944,
"s": 8899,
"text": "db2 update database manager configuration "
},
{
"code": null,
"e": 8965,
"s": 8944,
"text": "db2 update dbm cfg "
},
{
"code": null,
"e": 9008,
"s": 8965,
"text": "Syntax: [To reset previous configurations]"
},
{
"code": null,
"e": 9051,
"s": 9008,
"text": "db2 reset database manager configuration "
},
{
"code": null,
"e": 9071,
"s": 9051,
"text": "db2 reset dbm cfg "
},
{
"code": null,
"e": 9116,
"s": 9071,
"text": "Syntax: [To get the information of Database]"
},
{
"code": null,
"e": 9150,
"s": 9116,
"text": "db2 get database configuration "
},
{
"code": null,
"e": 9167,
"s": 9150,
"text": "db2 get db cfg "
},
{
"code": null,
"e": 9214,
"s": 9167,
"text": "Syntax: [To update the database configuration]"
},
{
"code": null,
"e": 9252,
"s": 9214,
"text": "db2 update database configuration "
},
{
"code": null,
"e": 9272,
"s": 9252,
"text": "db2 update db cfg "
},
{
"code": null,
"e": 9349,
"s": 9272,
"text": "Syntax: [To reset the previously configured values in database configuration"
},
{
"code": null,
"e": 9387,
"s": 9349,
"text": "db2 reset database configuration "
},
{
"code": null,
"e": 9407,
"s": 9387,
"text": "db2 reset db cfg "
},
{
"code": null,
"e": 9462,
"s": 9407,
"text": "Syntax: [To check the size of Current Active Database]"
},
{
"code": null,
"e": 9505,
"s": 9462,
"text": "db2 \"call get_dbsize_info(?,?,?,-1)\" "
},
{
"code": null,
"e": 9566,
"s": 9505,
"text": "Example: [To verify the size of Currently Activate Database]"
},
{
"code": null,
"e": 9609,
"s": 9566,
"text": "db2 \"call get_dbsize_info(?,?,?,-1)\" "
},
{
"code": null,
"e": 9617,
"s": 9609,
"text": "Output:"
},
{
"code": null,
"e": 9920,
"s": 9617,
"text": "Value of output parameters \n-------------------------- \nParameter Name : SNAPSHOTTIMESTAMP \nParameter Value : 2014-07-02-10.27.15.556775 \nParameter Name : DATABASESIZE \nParameter Value : 105795584 \nParameter Name : DATABASECAPACITY \nParameter Value : 396784705536 \nReturn Status = 0 "
},
{
"code": null,
"e": 10018,
"s": 9920,
"text": "To estimate the size of a database, the contribution of the following factors must be considered:"
},
{
"code": null,
"e": 10040,
"s": 10018,
"text": "System Catalog Tables"
},
{
"code": null,
"e": 10056,
"s": 10040,
"text": "User Table Data"
},
{
"code": null,
"e": 10072,
"s": 10056,
"text": "Long Field Data"
},
{
"code": null,
"e": 10096,
"s": 10072,
"text": "Large Object (LOB) Data"
},
{
"code": null,
"e": 10108,
"s": 10096,
"text": "Index Space"
},
{
"code": null,
"e": 10129,
"s": 10108,
"text": "Temporary Work Space"
},
{
"code": null,
"e": 10138,
"s": 10129,
"text": "XML data"
},
{
"code": null,
"e": 10153,
"s": 10138,
"text": "Log file space"
},
{
"code": null,
"e": 10178,
"s": 10153,
"text": "Local database directory"
},
{
"code": null,
"e": 10191,
"s": 10178,
"text": "System files"
},
{
"code": null,
"e": 10315,
"s": 10191,
"text": "You can use the following syntax to check which database authorities are granted to PUBLIC on the non-restrictive database."
},
{
"code": null,
"e": 10397,
"s": 10315,
"text": "Step 1: connect to database with authentication user-id and password of instance."
},
{
"code": null,
"e": 10457,
"s": 10397,
"text": "Syntax: [To connect to database with username and password]"
},
{
"code": null,
"e": 10519,
"s": 10457,
"text": "db2 connect to <db_name> user <userid> using <password> "
},
{
"code": null,
"e": 10608,
"s": 10519,
"text": "Example: [To Connect “one” Database with the user id ‘db2inst4’ and password ‘db2inst4’]"
},
{
"code": null,
"e": 10663,
"s": 10608,
"text": "db2 connect to one user db2inst4 using db2inst4 "
},
{
"code": null,
"e": 10671,
"s": 10663,
"text": "Output:"
},
{
"code": null,
"e": 10831,
"s": 10671,
"text": " Database Connection Information \n Database server = DB2/LINUXX8664 10.1.0 \n SQL authorization ID = DB2INST4 \n Local database alias = ONE "
},
{
"code": null,
"e": 10877,
"s": 10831,
"text": "Step2: To verify the authorities of database."
},
{
"code": null,
"e": 10964,
"s": 10877,
"text": "Syntax: [The syntax below shows the result of authority services for current database]"
},
{
"code": null,
"e": 11184,
"s": 10964,
"text": "db2 \"select substr(authority,1,25) as authority, d_user, d_group, \nd_public, role_user, role_group, role_public,d_role from table( \nsysproc.auth_list_authorities_for_authid ('public','g'))as t \norder by authority\" "
},
{
"code": null,
"e": 11193,
"s": 11184,
"text": "Example:"
},
{
"code": null,
"e": 11414,
"s": 11193,
"text": "db2 \"select substr(authority,1,25) as authority, d_user, d_group, \nd_public, role_user, role_group, role_public,d_role from table( \nsysproc.auth_list_authorities_for_authid ('PUBLIC','G'))as t \norder by authority\" "
},
{
"code": null,
"e": 11422,
"s": 11414,
"text": "Output:"
},
{
"code": null,
"e": 13472,
"s": 11422,
"text": "AUTHORITY D_USER D_GROUP D_PUBLIC ROLE_USER ROLE_GROUP ROLE_PUBLIC D_ROLE \n------------------------- ------ ------- -------- --------- ---------- ----------- ------ \nACCESSCTRL * * N * * N * \nBINDADD * * Y * * N * \nCONNECT * * Y * * N * \nCREATETAB * * Y * * N * \nCREATE_EXTERNAL_ROUTINE * * N * * N * \nCREATE_NOT_FENCED_ROUTINE * * N * * N * \nCREATE_SECURE_OBJECT * * N * * N * \nDATAACCESS * * N * * N * \nDBADM * * N * * N * \nEXPLAIN * * N * * N * \nIMPLICIT_SCHEMA * * Y * * N * \nLOAD * * N * * N * \nQUIESCE_CONNECT * * N * * N * \nSECADM * * N * * N * \nSQLADM * * N * * N * \nSYSADM * * * * * * * \nSYSCTRL * * * * * * * \nSYSMAINT * * * * * * * \nSYSMON * * * * * * * \nWLMADM * * N * * N * \n20 record(s) selected. "
},
{
"code": null,
"e": 13647,
"s": 13472,
"text": "Using the Drop command, you can remove our database from instance database directory. This command can delete all its objects, table, spaces, containers and associated files."
},
{
"code": null,
"e": 13695,
"s": 13647,
"text": "Syntax: [To drop any database from an instance]"
},
{
"code": null,
"e": 13723,
"s": 13695,
"text": "db2 drop database <db_name>"
},
{
"code": null,
"e": 13771,
"s": 13723,
"text": "Example: [To drop ‘six’ database from instance]"
},
{
"code": null,
"e": 13795,
"s": 13771,
"text": "db2 drop database six "
},
{
"code": null,
"e": 13803,
"s": 13795,
"text": "Output:"
},
{
"code": null,
"e": 13862,
"s": 13803,
"text": "DB20000I The DROP DATABASE command completed successfully "
},
{
"code": null,
"e": 13897,
"s": 13862,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 13912,
"s": 13897,
"text": " Nishant Malik"
},
{
"code": null,
"e": 13947,
"s": 13912,
"text": "\n 41 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 13962,
"s": 13947,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 13998,
"s": 13962,
"text": "\n 53 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 14013,
"s": 13998,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 14046,
"s": 14013,
"text": "\n 33 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 14061,
"s": 14046,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 14094,
"s": 14061,
"text": "\n 44 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 14113,
"s": 14094,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 14150,
"s": 14113,
"text": "\n 178 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 14169,
"s": 14150,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 14176,
"s": 14169,
"text": " Print"
},
{
"code": null,
"e": 14187,
"s": 14176,
"text": " Add Notes"
}
] |
Imbalanced Classification in Python: SMOTE-Tomek Links Method | by Raden Aurelius Andhika Viadinugroho | Towards Data Science
|
In a real-world application, classification modeling often encountered with an imbalanced dataset problem, where the number of majority class is much bigger than the minority class, thus make the model unable to learn from minority class well. This becomes a serious problem when the information in the dataset from the minority class is more important, for example, like disease detection dataset, churn dataset, and fraud detection dataset.
One of the popular approaches to solve this imbalance dataset problem is either to oversample the minority class or undersample the majority class. These approaches, however, have their own weakness. In the vanilla oversampling method, the idea is to duplicate some random examples from the minority class — thus this technique does not add any new information from the data. On the contrary, the undersampling method is conducted by removing some random examples from the majority class, at cost of some information in the original data are removed as well.
One of the solutions to overcome that weakness is to generate new examples that are synthesized from the existing minority class. This method is well known as Synthetic Minority Oversampling Technique or SMOTE. There are many variations of SMOTE but in this article, I will explain the SMOTE-Tomek Links method and its implementation using Python, where this method combines oversampling method from SMOTE and the undersampling method from Tomek Links.
SMOTE is one of the most popular oversampling techniques that is developed by Chawla et al. (2002). Unlike random oversampling that only duplicates some random examples from the minority class, SMOTE generates examples based on the distance of each data (usually using Euclidean distance) and the minority class nearest neighbors, so the generated examples are different from the original minority class.
In short, the process to generate the synthetic samples are as follows.
Choose random data from the minority class.Calculate the Euclidean distance between the random data and its k nearest neighbors.Multiply the difference with a random number between 0 and 1, then add the result to the minority class as a synthetic sample.Repeat the procedure until the desired proportion of minority class is met.
Choose random data from the minority class.
Calculate the Euclidean distance between the random data and its k nearest neighbors.
Multiply the difference with a random number between 0 and 1, then add the result to the minority class as a synthetic sample.
Repeat the procedure until the desired proportion of minority class is met.
This method is effective because the synthetic data that are generated are relatively close with the feature space on the minority class, thus adding new “information” on the data, unlike the original oversampling method.
Tomek Links is one of a modification from Condensed Nearest Neighbors (CNN, not to be confused with Convolutional Neural Network) undersampling technique that is developed by Tomek (1976). Unlike the CNN method that are only randomly select the samples with its k nearest neighbors from the majority class that wants to be removed, the Tomek Links method uses the rule to selects the pair of observation (say, a and b) that are fulfilled these properties:
The observation a’s nearest neighbor is b.The observation b’s nearest neighbor is a.Observation a and b belong to a different class. That is, a and b belong to the minority and majority class (or vice versa), respectively.
The observation a’s nearest neighbor is b.
The observation b’s nearest neighbor is a.
Observation a and b belong to a different class. That is, a and b belong to the minority and majority class (or vice versa), respectively.
Mathematically, it can be expressed as follows.
Let d(x_i, x_j) denotes the Euclidean distance between x_i and x_j, where x_i denotes sample that belongs to the minority class and x_j denotes sample that belongs to the majority class. If there is no sample x_k satisfies the following condition:
1. d(x_i, x_k) < d(x_i, x_j), or2. d(x_j, x_k) < d(x_i, x_j)
then the pair of (x_i, x_j) is a Tomek Link.
This method can be used to find desired samples of data from the majority class that is having the lowest Euclidean distance with the minority class data (i.e. the data from the majority class that is closest with the minority class data, thus make it ambiguous to distinct), and then remove it.
Introduced first by Batista et al. (2003), this method combines the SMOTE ability to generate synthetic data for minority class and Tomek Links ability to remove the data that are identified as Tomek links from the majority class (that is, samples of data from the majority class that is closest with the minority class data). The process of SMOTE-Tomek Links is as follows.
(Start of SMOTE) Choose random data from the minority class.Calculate the distance between the random data and its k nearest neighbors.Multiply the difference with a random number between 0 and 1, then add the result to the minority class as a synthetic sample.Repeat step number 2–3 until the desired proportion of minority class is met. (End of SMOTE)(Start of Tomek Links) Choose random data from the majority class.If the random data’s nearest neighbor is the data from the minority class (i.e. create the Tomek Link), then remove the Tomek Link.
(Start of SMOTE) Choose random data from the minority class.
Calculate the distance between the random data and its k nearest neighbors.
Multiply the difference with a random number between 0 and 1, then add the result to the minority class as a synthetic sample.
Repeat step number 2–3 until the desired proportion of minority class is met. (End of SMOTE)
(Start of Tomek Links) Choose random data from the majority class.
If the random data’s nearest neighbor is the data from the minority class (i.e. create the Tomek Link), then remove the Tomek Link.
To understand more about this method in practice, here I will give some example of how to implement SMOTE-Tomek Links in Python using imbalanced-learn library (or imblearn , in short). The model that we will use is Random Forest by using RandomForestClassifier . For the evaluation procedure, here I will use the Repeated Stratified K-fold Cross Validation method to ensure that we preserve the percentages of samples for each class in each fold (i.e. each fold must have some samples in each class) with different randomization in each repetition.
For the first example, I will use a synthetic dataset that is generated using make_classification from sklearn.datasets library. First of all, we need to import the libraries (these libraries will be used in the second example as well).
import pandas as pdimport numpy as npfrom imblearn.pipeline import Pipelineimport matplotlib.pyplot as pltfrom sklearn.datasets import make_classificationfrom sklearn.model_selection import cross_validatefrom sklearn.model_selection import RepeatedStratifiedKFoldfrom sklearn.ensemble import RandomForestClassifierfrom imblearn.combine import SMOTETomekfrom imblearn.under_sampling import TomekLinks
Next, we generate the synthetic data that we want to use by writing these lines of code.
#Dummy dataset study caseX, Y = make_classification(n_samples=10000, n_features=4, n_redundant=0, n_clusters_per_class=1, weights=[0.99], flip_y=0, random_state=1)
We can see from the weights parameter that the dataset will consist of 99% data that belong to the majority class, while the rest belong to the minority class.
Here I create two models — the first one is without using any imbalance data handling, while the other is using the SMOTE-Tomek Links method — to give you some performance comparison without and with the SMOTE-Tomek Links imbalance handling method.
## No Imbalance Handling# Define modelmodel_ori=RandomForestClassifier(criterion='entropy')# Define evaluation procedure (here we use Repeated Stratified K-Fold CV)cv_ori=RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)# Evaluate modelscoring=['accuracy','precision_macro','recall_macro']scores_ori = cross_validate(model_ori, X, Y, scoring=scoring, cv=cv_ori, n_jobs=-1)# summarize performanceprint('Mean Accuracy: %.4f' % np.mean(scores_ori['test_accuracy']))print('Mean Precision: %.4f' % np.mean(scores_ori['test_precision_macro']))print('Mean Recall: %.4f' % np.mean(scores_ori['test_recall_macro']))
Without SMOTE-Tomek Links, the model performance that is produced is as follows.
Mean Accuracy: 0.9943Mean Precision: 0.9416Mean Recall: 0.7480
As we can expect from the imbalanced dataset, the accuracy metric score is very high, but the recall metric score is pretty low (around 0.748). This means that the model failed to “learn” the minority class well, thus failed to correctly predict the minority class label.
Let’s see if we can improve the model’s performance by using SMOTE-Tomek Links to handle the imbalanced data.
## With SMOTE-Tomek Links method# Define modelmodel=RandomForestClassifier(criterion='entropy')# Define SMOTE-Tomek Linksresample=SMOTETomek(tomek=TomekLinks(sampling_strategy='majority'))# Define pipelinepipeline=Pipeline(steps=[('r', resample), ('m', model)])# Define evaluation procedure (here we use Repeated Stratified K-Fold CV)cv=RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)# Evaluate modelscoring=['accuracy','precision_macro','recall_macro']scores = cross_validate(pipeline, X, Y, scoring=scoring, cv=cv, n_jobs=-1)# summarize performanceprint('Mean Accuracy: %.4f' % np.mean(scores['test_accuracy']))print('Mean Precision: %.4f' % np.mean(scores['test_precision_macro']))print('Mean Recall: %.4f' % np.mean(scores['test_recall_macro']))
The result is as follows.
Mean Accuracy: 0.9805Mean Precision: 0.6499Mean Recall: 0.8433
The accuracy and precision metrics might decrease, but we can see that the recall metric are higher, it means that the model performs better to correctly predict the minority class label by using SMOTE-Tomek Links to handle the imbalanced data.
For the second example, here I use the Telecom Churn Dataset from Kaggle. There are two data file in this dataset, but in this article, I will use churn-bigml-80.csv data file.
First, we import the library (just like the first example) and the data as follows.
data=pd.read_csv("churn-bigml-80.csv")data.head()
Let’s see the data description to find out the type of each variable.
> data.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 2666 entries, 0 to 2665Data columns (total 20 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 State 2666 non-null object 1 Account length 2666 non-null int64 2 Area code 2666 non-null int64 3 International plan 2666 non-null object 4 Voice mail plan 2666 non-null object 5 Number vmail messages 2666 non-null int64 6 Total day minutes 2666 non-null float64 7 Total day calls 2666 non-null int64 8 Total day charge 2666 non-null float64 9 Total eve minutes 2666 non-null float64 10 Total eve calls 2666 non-null int64 11 Total eve charge 2666 non-null float64 12 Total night minutes 2666 non-null float64 13 Total night calls 2666 non-null int64 14 Total night charge 2666 non-null float64 15 Total intl minutes 2666 non-null float64 16 Total intl calls 2666 non-null int64 17 Total intl charge 2666 non-null float64 18 Customer service calls 2666 non-null int64 19 Churn 2666 non-null bool dtypes: bool(1), float64(8), int64(8), object(3)memory usage: 398.5+ KB
Then, we check whether there are exist missing values in the data as follows.
> data.isnull().sum()State 0Account length 0Area code 0International plan 0Voice mail plan 0Number vmail messages 0Total day minutes 0Total day calls 0Total day charge 0Total eve minutes 0Total eve calls 0Total eve charge 0Total night minutes 0Total night calls 0Total night charge 0Total intl minutes 0Total intl calls 0Total intl charge 0Customer service calls 0Churn 0dtype: int64
No missing values! Next, we calculate the number of data that belong to each class in Churnvariable by writing the line of code as follows.
> data['Churn'].value_counts()False 2278True 388
The data are pretty imbalanced, where the majority class belongs to False label (we will label it as 0) and the minority class belongs to True label (we will label it as 1).
For the next preprocessing step, we drop the State variable (since it contains too many categories), then we recode the Churn variable (False=0, True=1), and create the dummy variables by writing these lines of code.
data=data.drop('State',axis=1)data['Churn'].replace(to_replace=True, value=1, inplace=True)data['Churn'].replace(to_replace=False, value=0, inplace=True)df_dummies=pd.get_dummies(data)df_dummies.head()#Churn dataset study caseY_churn=df_dummies['Churn'].valuesX_churn=df_dummies.drop('Churn',axis=1)
The data preprocessing is complete. Now, we jump to the modeling with the same approach as the first example.
## No Imbalance Handling# Define modelmodel2_ori=RandomForestClassifier(criterion='entropy')# Define evaluation procedure (here we use Repeated Stratified K-Fold CV)cv2_ori=RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)# Evaluate modelscoring=['accuracy','precision_macro','recall_macro']scores2_ori = cross_validate(model2_ori, X_churn, Y_churn, scoring=scoring, cv=cv2_ori, n_jobs=-1)# summarize performanceprint('Mean Accuracy: %.4f' % np.mean(scores2_ori['test_accuracy']))print('Mean Precision: %.4f' % np.mean(scores2_ori['test_precision_macro']))print('Mean Recall: %.4f' % np.mean(scores2_ori['test_recall_macro']))
Without imbalanced data handling, the result is as follows.
Mean Accuracy: 0.9534Mean Precision: 0.9503Mean Recall: 0.8572
Remember that the data that we use are imbalanced, so we cannot simply say that the model performance is good just by observing the accuracy metric. Although that the accuracy metric score is pretty high, the recall metric score still not high enough, which means that the model is struggling to correctly predict the minority class label (that is, the True label that is recoded to 1).
Now let’s conduct the SMOTE-Tomek Links method for the data to see the performance improvements.
## With SMOTE-Tomek Links method# Define modelmodel2=RandomForestClassifier(criterion='entropy')# Define SMOTE-Tomek Linksresample2=SMOTETomek(tomek=TomekLinks(sampling_strategy='majority'))# Define pipelinepipeline2=Pipeline(steps=[('r', resample2), ('m', model2)])# Define evaluation procedure (here we use Repeated Stratified K-Fold CV)cv2=RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)# Evaluate modelscoring=['accuracy','precision_macro','recall_macro']scores2 = cross_validate(pipeline2, X_churn, Y_churn, scoring=scoring, cv=cv2, n_jobs=-1)# summarize performanceprint('Mean Accuracy: %.4f' % np.mean(scores2['test_accuracy']))print('Mean Precision: %.4f' % np.mean(scores2['test_precision_macro']))print('Mean Recall: %.4f' % np.mean(scores2['test_recall_macro']))
The result is as follows.
Mean Accuracy: 0.9449Mean Precision: 0.8981Mean Recall: 0.8768
The accuracy and precision score might slightly decrease, but the recall score is increased! That means that the model performs better to correctly predict the minority class label in this Churn dataset.
And that’s it! Now you learn how to use the SMOTE-Tomek Links method in Python to increase your classification model performance in the imbalanced dataset. As usual, feel free to ask and/or discuss if you have any questions!
See you in my next article! Stay safe and stay healthy!
LinkedIn: Raden Aurelius Andhika Viadinugroho
Medium: https://medium.com/@radenaurelius
[1] Chawla, N. V., Bowyer, K. W., Hall, L. O., and Kegelmeyer, W. P. (2002). SMOTE: Synthetic Minority Over-sampling Technique. Journal of Artificial Intelligence Research, vol. 16, pp. 321–357.
[2] https://www.kaggle.com/mnassrib/telecom-churn-datasets
[3] Tomek, I. (1976). Two Modifications of CNN. IEEE Transactions on Systems, Man, and Cybernetics, vol. 6, no. 11, pp. 769–772.
[4] He, H. and Ma, Y. (2013). Imbalanced Learning: Foundations, Algorithms, and Applications. 1st ed. Wiley.
[5] Zeng, M., Zou, B., Wei, F., Liu, X., and Wang, L. (2016). Effective prediction of three common diseases by combining SMOTE with Tomek links technique for imbalanced medical data. 2016 IEEE International Conference of Online Analysis and Computing Science (ICOACS), pp. 225–228.
[6] Batista, G. E. A. P. A., Bazzan, A. L. C., and Monard, M. A. (2003). Balancing Training Data for Automated Annotation of Keywords: Case Study. Proceedings of the Second Brazilian Workshop on Bioinformatics, pp. 35–43.
|
[
{
"code": null,
"e": 615,
"s": 172,
"text": "In a real-world application, classification modeling often encountered with an imbalanced dataset problem, where the number of majority class is much bigger than the minority class, thus make the model unable to learn from minority class well. This becomes a serious problem when the information in the dataset from the minority class is more important, for example, like disease detection dataset, churn dataset, and fraud detection dataset."
},
{
"code": null,
"e": 1174,
"s": 615,
"text": "One of the popular approaches to solve this imbalance dataset problem is either to oversample the minority class or undersample the majority class. These approaches, however, have their own weakness. In the vanilla oversampling method, the idea is to duplicate some random examples from the minority class — thus this technique does not add any new information from the data. On the contrary, the undersampling method is conducted by removing some random examples from the majority class, at cost of some information in the original data are removed as well."
},
{
"code": null,
"e": 1627,
"s": 1174,
"text": "One of the solutions to overcome that weakness is to generate new examples that are synthesized from the existing minority class. This method is well known as Synthetic Minority Oversampling Technique or SMOTE. There are many variations of SMOTE but in this article, I will explain the SMOTE-Tomek Links method and its implementation using Python, where this method combines oversampling method from SMOTE and the undersampling method from Tomek Links."
},
{
"code": null,
"e": 2032,
"s": 1627,
"text": "SMOTE is one of the most popular oversampling techniques that is developed by Chawla et al. (2002). Unlike random oversampling that only duplicates some random examples from the minority class, SMOTE generates examples based on the distance of each data (usually using Euclidean distance) and the minority class nearest neighbors, so the generated examples are different from the original minority class."
},
{
"code": null,
"e": 2104,
"s": 2032,
"text": "In short, the process to generate the synthetic samples are as follows."
},
{
"code": null,
"e": 2434,
"s": 2104,
"text": "Choose random data from the minority class.Calculate the Euclidean distance between the random data and its k nearest neighbors.Multiply the difference with a random number between 0 and 1, then add the result to the minority class as a synthetic sample.Repeat the procedure until the desired proportion of minority class is met."
},
{
"code": null,
"e": 2478,
"s": 2434,
"text": "Choose random data from the minority class."
},
{
"code": null,
"e": 2564,
"s": 2478,
"text": "Calculate the Euclidean distance between the random data and its k nearest neighbors."
},
{
"code": null,
"e": 2691,
"s": 2564,
"text": "Multiply the difference with a random number between 0 and 1, then add the result to the minority class as a synthetic sample."
},
{
"code": null,
"e": 2767,
"s": 2691,
"text": "Repeat the procedure until the desired proportion of minority class is met."
},
{
"code": null,
"e": 2989,
"s": 2767,
"text": "This method is effective because the synthetic data that are generated are relatively close with the feature space on the minority class, thus adding new “information” on the data, unlike the original oversampling method."
},
{
"code": null,
"e": 3445,
"s": 2989,
"text": "Tomek Links is one of a modification from Condensed Nearest Neighbors (CNN, not to be confused with Convolutional Neural Network) undersampling technique that is developed by Tomek (1976). Unlike the CNN method that are only randomly select the samples with its k nearest neighbors from the majority class that wants to be removed, the Tomek Links method uses the rule to selects the pair of observation (say, a and b) that are fulfilled these properties:"
},
{
"code": null,
"e": 3668,
"s": 3445,
"text": "The observation a’s nearest neighbor is b.The observation b’s nearest neighbor is a.Observation a and b belong to a different class. That is, a and b belong to the minority and majority class (or vice versa), respectively."
},
{
"code": null,
"e": 3711,
"s": 3668,
"text": "The observation a’s nearest neighbor is b."
},
{
"code": null,
"e": 3754,
"s": 3711,
"text": "The observation b’s nearest neighbor is a."
},
{
"code": null,
"e": 3893,
"s": 3754,
"text": "Observation a and b belong to a different class. That is, a and b belong to the minority and majority class (or vice versa), respectively."
},
{
"code": null,
"e": 3941,
"s": 3893,
"text": "Mathematically, it can be expressed as follows."
},
{
"code": null,
"e": 4189,
"s": 3941,
"text": "Let d(x_i, x_j) denotes the Euclidean distance between x_i and x_j, where x_i denotes sample that belongs to the minority class and x_j denotes sample that belongs to the majority class. If there is no sample x_k satisfies the following condition:"
},
{
"code": null,
"e": 4250,
"s": 4189,
"text": "1. d(x_i, x_k) < d(x_i, x_j), or2. d(x_j, x_k) < d(x_i, x_j)"
},
{
"code": null,
"e": 4295,
"s": 4250,
"text": "then the pair of (x_i, x_j) is a Tomek Link."
},
{
"code": null,
"e": 4591,
"s": 4295,
"text": "This method can be used to find desired samples of data from the majority class that is having the lowest Euclidean distance with the minority class data (i.e. the data from the majority class that is closest with the minority class data, thus make it ambiguous to distinct), and then remove it."
},
{
"code": null,
"e": 4966,
"s": 4591,
"text": "Introduced first by Batista et al. (2003), this method combines the SMOTE ability to generate synthetic data for minority class and Tomek Links ability to remove the data that are identified as Tomek links from the majority class (that is, samples of data from the majority class that is closest with the minority class data). The process of SMOTE-Tomek Links is as follows."
},
{
"code": null,
"e": 5517,
"s": 4966,
"text": "(Start of SMOTE) Choose random data from the minority class.Calculate the distance between the random data and its k nearest neighbors.Multiply the difference with a random number between 0 and 1, then add the result to the minority class as a synthetic sample.Repeat step number 2–3 until the desired proportion of minority class is met. (End of SMOTE)(Start of Tomek Links) Choose random data from the majority class.If the random data’s nearest neighbor is the data from the minority class (i.e. create the Tomek Link), then remove the Tomek Link."
},
{
"code": null,
"e": 5578,
"s": 5517,
"text": "(Start of SMOTE) Choose random data from the minority class."
},
{
"code": null,
"e": 5654,
"s": 5578,
"text": "Calculate the distance between the random data and its k nearest neighbors."
},
{
"code": null,
"e": 5781,
"s": 5654,
"text": "Multiply the difference with a random number between 0 and 1, then add the result to the minority class as a synthetic sample."
},
{
"code": null,
"e": 5874,
"s": 5781,
"text": "Repeat step number 2–3 until the desired proportion of minority class is met. (End of SMOTE)"
},
{
"code": null,
"e": 5941,
"s": 5874,
"text": "(Start of Tomek Links) Choose random data from the majority class."
},
{
"code": null,
"e": 6073,
"s": 5941,
"text": "If the random data’s nearest neighbor is the data from the minority class (i.e. create the Tomek Link), then remove the Tomek Link."
},
{
"code": null,
"e": 6622,
"s": 6073,
"text": "To understand more about this method in practice, here I will give some example of how to implement SMOTE-Tomek Links in Python using imbalanced-learn library (or imblearn , in short). The model that we will use is Random Forest by using RandomForestClassifier . For the evaluation procedure, here I will use the Repeated Stratified K-fold Cross Validation method to ensure that we preserve the percentages of samples for each class in each fold (i.e. each fold must have some samples in each class) with different randomization in each repetition."
},
{
"code": null,
"e": 6859,
"s": 6622,
"text": "For the first example, I will use a synthetic dataset that is generated using make_classification from sklearn.datasets library. First of all, we need to import the libraries (these libraries will be used in the second example as well)."
},
{
"code": null,
"e": 7259,
"s": 6859,
"text": "import pandas as pdimport numpy as npfrom imblearn.pipeline import Pipelineimport matplotlib.pyplot as pltfrom sklearn.datasets import make_classificationfrom sklearn.model_selection import cross_validatefrom sklearn.model_selection import RepeatedStratifiedKFoldfrom sklearn.ensemble import RandomForestClassifierfrom imblearn.combine import SMOTETomekfrom imblearn.under_sampling import TomekLinks"
},
{
"code": null,
"e": 7348,
"s": 7259,
"text": "Next, we generate the synthetic data that we want to use by writing these lines of code."
},
{
"code": null,
"e": 7538,
"s": 7348,
"text": "#Dummy dataset study caseX, Y = make_classification(n_samples=10000, n_features=4, n_redundant=0, n_clusters_per_class=1, weights=[0.99], flip_y=0, random_state=1)"
},
{
"code": null,
"e": 7698,
"s": 7538,
"text": "We can see from the weights parameter that the dataset will consist of 99% data that belong to the majority class, while the rest belong to the minority class."
},
{
"code": null,
"e": 7947,
"s": 7698,
"text": "Here I create two models — the first one is without using any imbalance data handling, while the other is using the SMOTE-Tomek Links method — to give you some performance comparison without and with the SMOTE-Tomek Links imbalance handling method."
},
{
"code": null,
"e": 8570,
"s": 7947,
"text": "## No Imbalance Handling# Define modelmodel_ori=RandomForestClassifier(criterion='entropy')# Define evaluation procedure (here we use Repeated Stratified K-Fold CV)cv_ori=RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)# Evaluate modelscoring=['accuracy','precision_macro','recall_macro']scores_ori = cross_validate(model_ori, X, Y, scoring=scoring, cv=cv_ori, n_jobs=-1)# summarize performanceprint('Mean Accuracy: %.4f' % np.mean(scores_ori['test_accuracy']))print('Mean Precision: %.4f' % np.mean(scores_ori['test_precision_macro']))print('Mean Recall: %.4f' % np.mean(scores_ori['test_recall_macro']))"
},
{
"code": null,
"e": 8651,
"s": 8570,
"text": "Without SMOTE-Tomek Links, the model performance that is produced is as follows."
},
{
"code": null,
"e": 8714,
"s": 8651,
"text": "Mean Accuracy: 0.9943Mean Precision: 0.9416Mean Recall: 0.7480"
},
{
"code": null,
"e": 8986,
"s": 8714,
"text": "As we can expect from the imbalanced dataset, the accuracy metric score is very high, but the recall metric score is pretty low (around 0.748). This means that the model failed to “learn” the minority class well, thus failed to correctly predict the minority class label."
},
{
"code": null,
"e": 9096,
"s": 8986,
"text": "Let’s see if we can improve the model’s performance by using SMOTE-Tomek Links to handle the imbalanced data."
},
{
"code": null,
"e": 9864,
"s": 9096,
"text": "## With SMOTE-Tomek Links method# Define modelmodel=RandomForestClassifier(criterion='entropy')# Define SMOTE-Tomek Linksresample=SMOTETomek(tomek=TomekLinks(sampling_strategy='majority'))# Define pipelinepipeline=Pipeline(steps=[('r', resample), ('m', model)])# Define evaluation procedure (here we use Repeated Stratified K-Fold CV)cv=RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)# Evaluate modelscoring=['accuracy','precision_macro','recall_macro']scores = cross_validate(pipeline, X, Y, scoring=scoring, cv=cv, n_jobs=-1)# summarize performanceprint('Mean Accuracy: %.4f' % np.mean(scores['test_accuracy']))print('Mean Precision: %.4f' % np.mean(scores['test_precision_macro']))print('Mean Recall: %.4f' % np.mean(scores['test_recall_macro']))"
},
{
"code": null,
"e": 9890,
"s": 9864,
"text": "The result is as follows."
},
{
"code": null,
"e": 9953,
"s": 9890,
"text": "Mean Accuracy: 0.9805Mean Precision: 0.6499Mean Recall: 0.8433"
},
{
"code": null,
"e": 10198,
"s": 9953,
"text": "The accuracy and precision metrics might decrease, but we can see that the recall metric are higher, it means that the model performs better to correctly predict the minority class label by using SMOTE-Tomek Links to handle the imbalanced data."
},
{
"code": null,
"e": 10375,
"s": 10198,
"text": "For the second example, here I use the Telecom Churn Dataset from Kaggle. There are two data file in this dataset, but in this article, I will use churn-bigml-80.csv data file."
},
{
"code": null,
"e": 10459,
"s": 10375,
"text": "First, we import the library (just like the first example) and the data as follows."
},
{
"code": null,
"e": 10509,
"s": 10459,
"text": "data=pd.read_csv(\"churn-bigml-80.csv\")data.head()"
},
{
"code": null,
"e": 10579,
"s": 10509,
"text": "Let’s see the data description to find out the type of each variable."
},
{
"code": null,
"e": 11912,
"s": 10579,
"text": "> data.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 2666 entries, 0 to 2665Data columns (total 20 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 State 2666 non-null object 1 Account length 2666 non-null int64 2 Area code 2666 non-null int64 3 International plan 2666 non-null object 4 Voice mail plan 2666 non-null object 5 Number vmail messages 2666 non-null int64 6 Total day minutes 2666 non-null float64 7 Total day calls 2666 non-null int64 8 Total day charge 2666 non-null float64 9 Total eve minutes 2666 non-null float64 10 Total eve calls 2666 non-null int64 11 Total eve charge 2666 non-null float64 12 Total night minutes 2666 non-null float64 13 Total night calls 2666 non-null int64 14 Total night charge 2666 non-null float64 15 Total intl minutes 2666 non-null float64 16 Total intl calls 2666 non-null int64 17 Total intl charge 2666 non-null float64 18 Customer service calls 2666 non-null int64 19 Churn 2666 non-null bool dtypes: bool(1), float64(8), int64(8), object(3)memory usage: 398.5+ KB"
},
{
"code": null,
"e": 11990,
"s": 11912,
"text": "Then, we check whether there are exist missing values in the data as follows."
},
{
"code": null,
"e": 12564,
"s": 11990,
"text": "> data.isnull().sum()State 0Account length 0Area code 0International plan 0Voice mail plan 0Number vmail messages 0Total day minutes 0Total day calls 0Total day charge 0Total eve minutes 0Total eve calls 0Total eve charge 0Total night minutes 0Total night calls 0Total night charge 0Total intl minutes 0Total intl calls 0Total intl charge 0Customer service calls 0Churn 0dtype: int64"
},
{
"code": null,
"e": 12704,
"s": 12564,
"text": "No missing values! Next, we calculate the number of data that belong to each class in Churnvariable by writing the line of code as follows."
},
{
"code": null,
"e": 12761,
"s": 12704,
"text": "> data['Churn'].value_counts()False 2278True 388"
},
{
"code": null,
"e": 12935,
"s": 12761,
"text": "The data are pretty imbalanced, where the majority class belongs to False label (we will label it as 0) and the minority class belongs to True label (we will label it as 1)."
},
{
"code": null,
"e": 13152,
"s": 12935,
"text": "For the next preprocessing step, we drop the State variable (since it contains too many categories), then we recode the Churn variable (False=0, True=1), and create the dummy variables by writing these lines of code."
},
{
"code": null,
"e": 13453,
"s": 13152,
"text": "data=data.drop('State',axis=1)data['Churn'].replace(to_replace=True, value=1, inplace=True)data['Churn'].replace(to_replace=False, value=0, inplace=True)df_dummies=pd.get_dummies(data)df_dummies.head()#Churn dataset study caseY_churn=df_dummies['Churn'].valuesX_churn=df_dummies.drop('Churn',axis=1)"
},
{
"code": null,
"e": 13563,
"s": 13453,
"text": "The data preprocessing is complete. Now, we jump to the modeling with the same approach as the first example."
},
{
"code": null,
"e": 14206,
"s": 13563,
"text": "## No Imbalance Handling# Define modelmodel2_ori=RandomForestClassifier(criterion='entropy')# Define evaluation procedure (here we use Repeated Stratified K-Fold CV)cv2_ori=RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)# Evaluate modelscoring=['accuracy','precision_macro','recall_macro']scores2_ori = cross_validate(model2_ori, X_churn, Y_churn, scoring=scoring, cv=cv2_ori, n_jobs=-1)# summarize performanceprint('Mean Accuracy: %.4f' % np.mean(scores2_ori['test_accuracy']))print('Mean Precision: %.4f' % np.mean(scores2_ori['test_precision_macro']))print('Mean Recall: %.4f' % np.mean(scores2_ori['test_recall_macro']))"
},
{
"code": null,
"e": 14266,
"s": 14206,
"text": "Without imbalanced data handling, the result is as follows."
},
{
"code": null,
"e": 14329,
"s": 14266,
"text": "Mean Accuracy: 0.9534Mean Precision: 0.9503Mean Recall: 0.8572"
},
{
"code": null,
"e": 14716,
"s": 14329,
"text": "Remember that the data that we use are imbalanced, so we cannot simply say that the model performance is good just by observing the accuracy metric. Although that the accuracy metric score is pretty high, the recall metric score still not high enough, which means that the model is struggling to correctly predict the minority class label (that is, the True label that is recoded to 1)."
},
{
"code": null,
"e": 14813,
"s": 14716,
"text": "Now let’s conduct the SMOTE-Tomek Links method for the data to see the performance improvements."
},
{
"code": null,
"e": 15605,
"s": 14813,
"text": "## With SMOTE-Tomek Links method# Define modelmodel2=RandomForestClassifier(criterion='entropy')# Define SMOTE-Tomek Linksresample2=SMOTETomek(tomek=TomekLinks(sampling_strategy='majority'))# Define pipelinepipeline2=Pipeline(steps=[('r', resample2), ('m', model2)])# Define evaluation procedure (here we use Repeated Stratified K-Fold CV)cv2=RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)# Evaluate modelscoring=['accuracy','precision_macro','recall_macro']scores2 = cross_validate(pipeline2, X_churn, Y_churn, scoring=scoring, cv=cv2, n_jobs=-1)# summarize performanceprint('Mean Accuracy: %.4f' % np.mean(scores2['test_accuracy']))print('Mean Precision: %.4f' % np.mean(scores2['test_precision_macro']))print('Mean Recall: %.4f' % np.mean(scores2['test_recall_macro']))"
},
{
"code": null,
"e": 15631,
"s": 15605,
"text": "The result is as follows."
},
{
"code": null,
"e": 15694,
"s": 15631,
"text": "Mean Accuracy: 0.9449Mean Precision: 0.8981Mean Recall: 0.8768"
},
{
"code": null,
"e": 15898,
"s": 15694,
"text": "The accuracy and precision score might slightly decrease, but the recall score is increased! That means that the model performs better to correctly predict the minority class label in this Churn dataset."
},
{
"code": null,
"e": 16123,
"s": 15898,
"text": "And that’s it! Now you learn how to use the SMOTE-Tomek Links method in Python to increase your classification model performance in the imbalanced dataset. As usual, feel free to ask and/or discuss if you have any questions!"
},
{
"code": null,
"e": 16179,
"s": 16123,
"text": "See you in my next article! Stay safe and stay healthy!"
},
{
"code": null,
"e": 16225,
"s": 16179,
"text": "LinkedIn: Raden Aurelius Andhika Viadinugroho"
},
{
"code": null,
"e": 16267,
"s": 16225,
"text": "Medium: https://medium.com/@radenaurelius"
},
{
"code": null,
"e": 16462,
"s": 16267,
"text": "[1] Chawla, N. V., Bowyer, K. W., Hall, L. O., and Kegelmeyer, W. P. (2002). SMOTE: Synthetic Minority Over-sampling Technique. Journal of Artificial Intelligence Research, vol. 16, pp. 321–357."
},
{
"code": null,
"e": 16521,
"s": 16462,
"text": "[2] https://www.kaggle.com/mnassrib/telecom-churn-datasets"
},
{
"code": null,
"e": 16650,
"s": 16521,
"text": "[3] Tomek, I. (1976). Two Modifications of CNN. IEEE Transactions on Systems, Man, and Cybernetics, vol. 6, no. 11, pp. 769–772."
},
{
"code": null,
"e": 16759,
"s": 16650,
"text": "[4] He, H. and Ma, Y. (2013). Imbalanced Learning: Foundations, Algorithms, and Applications. 1st ed. Wiley."
},
{
"code": null,
"e": 17041,
"s": 16759,
"text": "[5] Zeng, M., Zou, B., Wei, F., Liu, X., and Wang, L. (2016). Effective prediction of three common diseases by combining SMOTE with Tomek links technique for imbalanced medical data. 2016 IEEE International Conference of Online Analysis and Computing Science (ICOACS), pp. 225–228."
}
] |
Building A Movie Recommendation Engine Using Pandas | by Nishit Jain | Towards Data Science
|
Recommendation Engines are the programs which basically compute the similarities between two entities and on that basis, they give us the targeted output. If we look at the root of any recommendation engine, they all are trying to find out the amount of similarity between two entities. Then, the computed similarities can be used to deduce various kinds of recommendations and relationships between them.
Recommendation Engines are mostly based on the following techniques:
Popularity Based Filtering.Collaborative Filtering (User Based / Item Based).Hybrid User-Item Based Collaborative Filtering.Content Based Filtering.
Popularity Based Filtering.
Collaborative Filtering (User Based / Item Based).
Hybrid User-Item Based Collaborative Filtering.
Content Based Filtering.
The most basic form of a recommendation engine would be where the engine recommends the most popular items to all the users. That would be generalized as everyone would be getting similar recommendations as we didn’t personalize the recommendations. These kinds of recommendation engines are based on the Popularity Based Filtering. The use case for this model would be the ‘Top News’ Section for the day on a news website where the most popular new for everyone is same irrespective of the interests of every user because that makes a logical sense because News is a generalized thing and it has got nothing to do with user’s interests.
In collaborative filtering, two entities collaborate to deduce recommendations on the basis of certain similarities between them. These filtering techniques are broadly of two types:
User Based Collaborative Filtering: In user based collaborative filtering, we find out the similarity score between the two users. On the basis of similarity score, we recommend the items bought/liked by one user to other user assuming that he might like these items on the basis of similarity. This will be more clear when we go ahead and implement this. Major online streaming service, Netflix have their recommendation engine based on user based collaborative filtering.Item Based Collaborative Filtering: In item based collaborative filtering, the similarity of an item is calculated with the existing item being consumed by the existing users. Then on the basis of amount of similarity, we can say that if user X likes item A and a new item P is most similar to item A then it highly makes sense for us to recommend item P to user X.Hybrid User-Item Based Collaborative Filtering: This technique is basically a proper mixture of both the above techniques wherein the recommendations are not solely based on either. E-commerce websites like Amazon employ this technique to recommend item(s) to their customer.Content Based Filtering: In this technique, the users are recommended the similar content which they have used/watched/liked the most before. For example, if a user has been mostly listening to songs of similar type (bit rate, bps, tunes etc.), he will be recommended the songs falling under the same category decided based on certain features. The best example of this category would be Pandora Radio which is a music streaming and automated music recommendation internet radio service.
User Based Collaborative Filtering: In user based collaborative filtering, we find out the similarity score between the two users. On the basis of similarity score, we recommend the items bought/liked by one user to other user assuming that he might like these items on the basis of similarity. This will be more clear when we go ahead and implement this. Major online streaming service, Netflix have their recommendation engine based on user based collaborative filtering.
Item Based Collaborative Filtering: In item based collaborative filtering, the similarity of an item is calculated with the existing item being consumed by the existing users. Then on the basis of amount of similarity, we can say that if user X likes item A and a new item P is most similar to item A then it highly makes sense for us to recommend item P to user X.
Hybrid User-Item Based Collaborative Filtering: This technique is basically a proper mixture of both the above techniques wherein the recommendations are not solely based on either. E-commerce websites like Amazon employ this technique to recommend item(s) to their customer.
Content Based Filtering: In this technique, the users are recommended the similar content which they have used/watched/liked the most before. For example, if a user has been mostly listening to songs of similar type (bit rate, bps, tunes etc.), he will be recommended the songs falling under the same category decided based on certain features. The best example of this category would be Pandora Radio which is a music streaming and automated music recommendation internet radio service.
We have a movie lens database and our objective is to apply various kinds of recommendation techniques from scratch using pandas and find out similarities between the users, most popular movies, and personalized recommendations for the targeted user based on user based collaborative filtering. (We are exploring only one of the types because these article is about getting the basic intuition behind the recommendation engines.)
We are importing pandas and some basic mathematical functions from math library and importing the dataset into a dataframe object.
# Importing the required libraries.import pandas as pdfrom math import pow, sqrt# Reading ratings dataset into a pandas dataframe object.r_cols = ['user_id', 'movie_id', 'rating', 'unix_timestamp']ratings = pd.read_csv('data/ratings.dat', sep='::', names=r_cols, encoding='latin-1')# Getting number of users and movies from the dataset.user_ids = ratings.user_id.unique().tolist()movie_ids = ratings.movie_id.unique().tolist()print('Number of Users: {}'.format(len(user_ids)))print('Number of Movies: {}'.format(len(movie_ids)))Output:Number of Users: 6040Number of Movies: 3706
Here is how the first 5 rows of our dataset look like.
In this dataset, we have 4 columns and around 1M rows. Except, unix_timestamp, all the columns are self explanatory. We anyway won’t be using this column in our code. Next, we let’s see out how our movies dataset looks like.
# Reading movies dataset into a pandas dataframe object.m_cols = ['movie_id', 'movie_title', 'genre']movies = pd.read_csv('data/movies.dat', sep='::', names=m_cols, encoding='latin-1')
All the column names are self explanatory. As seen in the above dataframe, the genre column has data with pipe separators which cannot be processed for recommendations as such. Hence, we need to generate columns for every genre type such that if the movie belongs to that genre its value will be 1 otherwise 0 (Sort of one hot encoding). Also, we need to split the release of year out of the movie_title column and generate a new column for it which is again a new and an important feature.
# Getting series of lists by applying split operation.movies.genre = movies.genre.str.split('|')# Getting distinct genre types for generating columns of genre type.genre_columns = list(set([j for i in movies['genre'].tolist() for j in i]))# Iterating over every list to create and fill values into columns.for j in genre_columns: movies[j] = 0for i in range(movies.shape[0]): for j in genre_columns: if(j in movies['genre'].iloc[i]): movies.loc[i,j] = 1# Separting movie title and year part using split function.split_values = movies['movie_title'].str.split("(", n = 1, expand = True)# setting 'movie_title' values to title part.movies.movie_title = split_values[0]# creating 'release_year' column.movies['release_year'] = split_values[1]# Cleaning the release_year series.movies['release_year'] = movies.release_year.str.replace(')','')# dropping 'genre' columns as it has already been one hot encoded.movies.drop('genre',axis=1,inplace=True)
Here’s how the dataframe looks like after processing it:
Now, let us write down a few getter functions which will be frequently used in our code so that we do not need to write them again and again and it also increases readability and re-usability of the code.
# Getting the rating given by a user to a movie.def get_rating_(userid,movieid): return (ratings.loc[(ratings.user_id==userid) & (ratings.movie_id == movieid),'rating'].iloc[0])# Getting the list of all movie ids the specified user has rated.def get_movieids_(userid): return (ratings.loc[(ratings.user_id==userid),'movie_id'].tolist())# Getting the movie titles against the movie id.def get_movie_title_(movieid): return (movies.loc[(movies.movie_id == movieid),'movie_title'].iloc[0])
In this implementation the similarity between the two users will be calculated on the basis of the distance between the two users (i.e. Euclidean distances) and by calculating Pearson Correlation between the two users.
We will write two functions, one to calculate the similarity on the basis of euclidean distances and other on the basis of Pearson correlation and you will know why we are writing two functions.
def distance_similarity_score(user1,user2): ''' user1 & user2 : user ids of two users between which similarity score is to be calculated. ''' # Count of movies watched by both the users. both_watch_count = 0 for element in ratings.loc[ratings.user_id==user1,'movie_id'].tolist(): if element in ratings.loc[ratings.user_id==user2,'movie_id'].tolist(): both_watch_count += 1 if both_watch_count == 0 : return 0 # Calculating distance based similarity between both the users. distance = [] for element in ratings.loc[ratings.user_id==user1,'movie_id'].tolist(): if element in ratings.loc[ratings.user_id==user2,'movie_id'].tolist(): rating1 = get_rating_(user1,element) rating2 = get_rating_(user2,element) distance.append(pow(rating1 - rating2, 2)) total_distance = sum(distance) # Adding one to the denominator to avoid divide by zero error. return 1/(1+sqrt(total_distance))print('Distance based similarity between user ids 1 & 310: {}'.format(distance_similarity_score(1,310)))Output:Distance based similarity between user ids 1 & 310: 0.14459058185587106
Calculating similarity scores based on the distances have an inherent problem. We do not have a threshold to decide how much distance between two users is to be considered for calculating whether the users are close enough or far enough. On the other side, this problem is resolved by pearson correlation method as it always returns a value between -1 & 1 which clearly provides us with the boundaries for closeness as we prefer.
def pearson_correlation_score(user1,user2): ''' user1 & user2 : user ids of two users between which similarity score is to be calculated. ''' # A list of movies watched by both the users. both_watch_count = [] # Finding movies watched by both the users. for element in ratings.loc[ratings.user_id==user1,'movie_id'].tolist(): if element in ratings.loc[ratings.user_id==user2,'movie_id'].tolist(): both_watch_count.append(element) # Returning '0' correlation for bo common movies. if len(both_watch_count) == 0 : return 0 # Calculating Co-Variances. rating_sum_1 = sum([get_rating_(user1,element) for element in both_watch_count]) rating_sum_2 = sum([get_rating_(user2,element) for element in both_watch_count]) rating_squared_sum_1 = sum([pow(get_rating_(user1,element),2) for element in both_watch_count]) rating_squared_sum_2 = sum([pow(get_rating_(user2,element),2) for element in both_watch_count]) product_sum_rating = sum([get_rating_(user1,element) * get_rating_(user2,element) for element in both_watch_count]) # Returning pearson correlation between both the users. numerator = product_sum_rating - ((rating_sum_1 * rating_sum_2) / len(both_watch_count)) denominator = sqrt((rating_squared_sum_1 - pow(rating_sum_1,2) / len(both_watch_count)) * (rating_squared_sum_2 - pow(rating_sum_2,2) / len(both_watch_count))) # Handling 'Divide by Zero' error. if denominator == 0: return 0 return numerator/denominatorprint('Pearson Corelation between user ids 11 & 30: {}'.format(pearson_correlation_score(11,30)))Output:Pearson Corelation between user ids 11 & 30: 0.2042571684752679
The objective is to find out Most Similar Users to the targeted user. Here we have two metrics to find the score i.e. distance and correlation. Now, we will write a function for this.
def most_similar_users_(user1,number_of_users,metric='pearson'): ''' user1 : Targeted User number_of_users : number of most similar users you want to user1. metric : metric to be used to calculate inter-user similarity score. ('pearson' or else) ''' # Getting distinct user ids. user_ids = ratings.user_id.unique().tolist() # Getting similarity score between targeted and every other suer in the list(or subset of the list). if(metric == 'pearson'): similarity_score = [(pearson_correlation_score(user1,nth_user),nth_user) for nth_user in user_ids[:100] if nth_user != user1] else: similarity_score = [(distance_similarity_score(user1,nth_user),nth_user) for nth_user in user_ids[:100] if nth_user != user1] # Sorting in descending order. similarity_score.sort() similarity_score.reverse() # Returning the top most 'number_of_users' similar users. return similarity_score[:number_of_users]print(most_similar_users_(23,5))Output:[(0.936585811581694, 61), (0.7076731463403717, 41), (0.6123724356957956, 21), (0.5970863767331771, 25), (0.5477225575051661, 64)]
As we can see, the output is list of tuples indicating the similarity scores of the top 5 similar number of the users asked for with user id against the targeted user. The metric used here is Pearson Correlation.
I don’t know if few of the people have noticed that the most similar users’ logic can be strengthened more by considering other factors as well such as age, sex, occupation etc. Here, we have created our logic on the basis of only one feature i.e. rating.
The concept is very simple. First, we need to iterate over only those movies not watched(or rated) by the targeted user and the sub-setting items based on the users highly correlated with targeted user. Here, we have used a weighted similarity approach where we have taken product of rating and score into account to make sure that the highly similar users affect the recommendations more than those less similar. Then, we have sorted the list on the basis of score along with movie ids and returned the movie titles against those movie ids. Let us write a function for the same.
def get_recommendation_(userid): user_ids = ratings.user_id.unique().tolist() total = {} similariy_sum = {} # Iterating over subset of user ids. for user in user_ids[:100]: # not comparing the user to itself (obviously!) if user == userid: continue # Getting similarity score between the users. score = pearson_correlation_score(userid,user) # not considering users having zero or less similarity score. if score <= 0: continue # Getting weighted similarity score and sum of similarities between both the users. for movieid in get_movieids_(user): # Only considering not watched/rated movies if movieid not in get_movieids_(userid) or get_rating_(userid,movieid) == 0: total[movieid] = 0 total[movieid] += get_rating_(user,movieid) * score similariy_sum[movieid] = 0 similariy_sum[movieid] += score # Normalizing ratings ranking = [(tot/similariy_sum[movieid],movieid) for movieid,tot in total.items()] ranking.sort() ranking.reverse() # Getting movie titles against the movie ids. recommendations = [get_movie_title_(movieid) for score,movieid in ranking] return recommendations[:10]print(get_recommendation_(32))Output:['Invisible Man, The ', 'Creature From the Black Lagoon, The ', 'Hellraiser ', 'Almost Famous ', 'Way of the Gun, The ', 'Shane ', 'Naked Gun 2 1/2: The Smell of Fear, The ', "Kelly's Heroes ", 'Official Story, The ', 'Everything You Always Wanted to Know About Sex ']
As we can see in the output, we have got the top 10 highly recommended movie for the user with user id 32 using the metric Pearson Correlation. You can do the same exercise with the euclidean distances as metric and I’m sure the results will differ.
We implemented a movie recommendation engine by just using Pandas and basic math library functions. Also, we got to know the basic intuition behind the recommendation engines. Obviously, there’s a lot more to the recommendation engines than this as there are multiple features and factors which influence the recommendations and not just the ratings. Further more, we will be implementing and deducing our recommendations also based on other features of the users and the movies in the next blog and also explore the infamous technique for recommendation engines i.e. Matrix Factorization using the turicreate library.
The GitHub repository for the code in the blog can be found here.
|
[
{
"code": null,
"e": 578,
"s": 172,
"text": "Recommendation Engines are the programs which basically compute the similarities between two entities and on that basis, they give us the targeted output. If we look at the root of any recommendation engine, they all are trying to find out the amount of similarity between two entities. Then, the computed similarities can be used to deduce various kinds of recommendations and relationships between them."
},
{
"code": null,
"e": 647,
"s": 578,
"text": "Recommendation Engines are mostly based on the following techniques:"
},
{
"code": null,
"e": 796,
"s": 647,
"text": "Popularity Based Filtering.Collaborative Filtering (User Based / Item Based).Hybrid User-Item Based Collaborative Filtering.Content Based Filtering."
},
{
"code": null,
"e": 824,
"s": 796,
"text": "Popularity Based Filtering."
},
{
"code": null,
"e": 875,
"s": 824,
"text": "Collaborative Filtering (User Based / Item Based)."
},
{
"code": null,
"e": 923,
"s": 875,
"text": "Hybrid User-Item Based Collaborative Filtering."
},
{
"code": null,
"e": 948,
"s": 923,
"text": "Content Based Filtering."
},
{
"code": null,
"e": 1586,
"s": 948,
"text": "The most basic form of a recommendation engine would be where the engine recommends the most popular items to all the users. That would be generalized as everyone would be getting similar recommendations as we didn’t personalize the recommendations. These kinds of recommendation engines are based on the Popularity Based Filtering. The use case for this model would be the ‘Top News’ Section for the day on a news website where the most popular new for everyone is same irrespective of the interests of every user because that makes a logical sense because News is a generalized thing and it has got nothing to do with user’s interests."
},
{
"code": null,
"e": 1769,
"s": 1586,
"text": "In collaborative filtering, two entities collaborate to deduce recommendations on the basis of certain similarities between them. These filtering techniques are broadly of two types:"
},
{
"code": null,
"e": 3370,
"s": 1769,
"text": "User Based Collaborative Filtering: In user based collaborative filtering, we find out the similarity score between the two users. On the basis of similarity score, we recommend the items bought/liked by one user to other user assuming that he might like these items on the basis of similarity. This will be more clear when we go ahead and implement this. Major online streaming service, Netflix have their recommendation engine based on user based collaborative filtering.Item Based Collaborative Filtering: In item based collaborative filtering, the similarity of an item is calculated with the existing item being consumed by the existing users. Then on the basis of amount of similarity, we can say that if user X likes item A and a new item P is most similar to item A then it highly makes sense for us to recommend item P to user X.Hybrid User-Item Based Collaborative Filtering: This technique is basically a proper mixture of both the above techniques wherein the recommendations are not solely based on either. E-commerce websites like Amazon employ this technique to recommend item(s) to their customer.Content Based Filtering: In this technique, the users are recommended the similar content which they have used/watched/liked the most before. For example, if a user has been mostly listening to songs of similar type (bit rate, bps, tunes etc.), he will be recommended the songs falling under the same category decided based on certain features. The best example of this category would be Pandora Radio which is a music streaming and automated music recommendation internet radio service."
},
{
"code": null,
"e": 3844,
"s": 3370,
"text": "User Based Collaborative Filtering: In user based collaborative filtering, we find out the similarity score between the two users. On the basis of similarity score, we recommend the items bought/liked by one user to other user assuming that he might like these items on the basis of similarity. This will be more clear when we go ahead and implement this. Major online streaming service, Netflix have their recommendation engine based on user based collaborative filtering."
},
{
"code": null,
"e": 4210,
"s": 3844,
"text": "Item Based Collaborative Filtering: In item based collaborative filtering, the similarity of an item is calculated with the existing item being consumed by the existing users. Then on the basis of amount of similarity, we can say that if user X likes item A and a new item P is most similar to item A then it highly makes sense for us to recommend item P to user X."
},
{
"code": null,
"e": 4486,
"s": 4210,
"text": "Hybrid User-Item Based Collaborative Filtering: This technique is basically a proper mixture of both the above techniques wherein the recommendations are not solely based on either. E-commerce websites like Amazon employ this technique to recommend item(s) to their customer."
},
{
"code": null,
"e": 4974,
"s": 4486,
"text": "Content Based Filtering: In this technique, the users are recommended the similar content which they have used/watched/liked the most before. For example, if a user has been mostly listening to songs of similar type (bit rate, bps, tunes etc.), he will be recommended the songs falling under the same category decided based on certain features. The best example of this category would be Pandora Radio which is a music streaming and automated music recommendation internet radio service."
},
{
"code": null,
"e": 5404,
"s": 4974,
"text": "We have a movie lens database and our objective is to apply various kinds of recommendation techniques from scratch using pandas and find out similarities between the users, most popular movies, and personalized recommendations for the targeted user based on user based collaborative filtering. (We are exploring only one of the types because these article is about getting the basic intuition behind the recommendation engines.)"
},
{
"code": null,
"e": 5535,
"s": 5404,
"text": "We are importing pandas and some basic mathematical functions from math library and importing the dataset into a dataframe object."
},
{
"code": null,
"e": 6114,
"s": 5535,
"text": "# Importing the required libraries.import pandas as pdfrom math import pow, sqrt# Reading ratings dataset into a pandas dataframe object.r_cols = ['user_id', 'movie_id', 'rating', 'unix_timestamp']ratings = pd.read_csv('data/ratings.dat', sep='::', names=r_cols, encoding='latin-1')# Getting number of users and movies from the dataset.user_ids = ratings.user_id.unique().tolist()movie_ids = ratings.movie_id.unique().tolist()print('Number of Users: {}'.format(len(user_ids)))print('Number of Movies: {}'.format(len(movie_ids)))Output:Number of Users: 6040Number of Movies: 3706"
},
{
"code": null,
"e": 6169,
"s": 6114,
"text": "Here is how the first 5 rows of our dataset look like."
},
{
"code": null,
"e": 6394,
"s": 6169,
"text": "In this dataset, we have 4 columns and around 1M rows. Except, unix_timestamp, all the columns are self explanatory. We anyway won’t be using this column in our code. Next, we let’s see out how our movies dataset looks like."
},
{
"code": null,
"e": 6579,
"s": 6394,
"text": "# Reading movies dataset into a pandas dataframe object.m_cols = ['movie_id', 'movie_title', 'genre']movies = pd.read_csv('data/movies.dat', sep='::', names=m_cols, encoding='latin-1')"
},
{
"code": null,
"e": 7070,
"s": 6579,
"text": "All the column names are self explanatory. As seen in the above dataframe, the genre column has data with pipe separators which cannot be processed for recommendations as such. Hence, we need to generate columns for every genre type such that if the movie belongs to that genre its value will be 1 otherwise 0 (Sort of one hot encoding). Also, we need to split the release of year out of the movie_title column and generate a new column for it which is again a new and an important feature."
},
{
"code": null,
"e": 8039,
"s": 7070,
"text": "# Getting series of lists by applying split operation.movies.genre = movies.genre.str.split('|')# Getting distinct genre types for generating columns of genre type.genre_columns = list(set([j for i in movies['genre'].tolist() for j in i]))# Iterating over every list to create and fill values into columns.for j in genre_columns: movies[j] = 0for i in range(movies.shape[0]): for j in genre_columns: if(j in movies['genre'].iloc[i]): movies.loc[i,j] = 1# Separting movie title and year part using split function.split_values = movies['movie_title'].str.split(\"(\", n = 1, expand = True)# setting 'movie_title' values to title part.movies.movie_title = split_values[0]# creating 'release_year' column.movies['release_year'] = split_values[1]# Cleaning the release_year series.movies['release_year'] = movies.release_year.str.replace(')','')# dropping 'genre' columns as it has already been one hot encoded.movies.drop('genre',axis=1,inplace=True)"
},
{
"code": null,
"e": 8096,
"s": 8039,
"text": "Here’s how the dataframe looks like after processing it:"
},
{
"code": null,
"e": 8301,
"s": 8096,
"text": "Now, let us write down a few getter functions which will be frequently used in our code so that we do not need to write them again and again and it also increases readability and re-usability of the code."
},
{
"code": null,
"e": 8797,
"s": 8301,
"text": "# Getting the rating given by a user to a movie.def get_rating_(userid,movieid): return (ratings.loc[(ratings.user_id==userid) & (ratings.movie_id == movieid),'rating'].iloc[0])# Getting the list of all movie ids the specified user has rated.def get_movieids_(userid): return (ratings.loc[(ratings.user_id==userid),'movie_id'].tolist())# Getting the movie titles against the movie id.def get_movie_title_(movieid): return (movies.loc[(movies.movie_id == movieid),'movie_title'].iloc[0])"
},
{
"code": null,
"e": 9016,
"s": 8797,
"text": "In this implementation the similarity between the two users will be calculated on the basis of the distance between the two users (i.e. Euclidean distances) and by calculating Pearson Correlation between the two users."
},
{
"code": null,
"e": 9211,
"s": 9016,
"text": "We will write two functions, one to calculate the similarity on the basis of euclidean distances and other on the basis of Pearson correlation and you will know why we are writing two functions."
},
{
"code": null,
"e": 10387,
"s": 9211,
"text": "def distance_similarity_score(user1,user2): ''' user1 & user2 : user ids of two users between which similarity score is to be calculated. ''' # Count of movies watched by both the users. both_watch_count = 0 for element in ratings.loc[ratings.user_id==user1,'movie_id'].tolist(): if element in ratings.loc[ratings.user_id==user2,'movie_id'].tolist(): both_watch_count += 1 if both_watch_count == 0 : return 0 # Calculating distance based similarity between both the users. distance = [] for element in ratings.loc[ratings.user_id==user1,'movie_id'].tolist(): if element in ratings.loc[ratings.user_id==user2,'movie_id'].tolist(): rating1 = get_rating_(user1,element) rating2 = get_rating_(user2,element) distance.append(pow(rating1 - rating2, 2)) total_distance = sum(distance) # Adding one to the denominator to avoid divide by zero error. return 1/(1+sqrt(total_distance))print('Distance based similarity between user ids 1 & 310: {}'.format(distance_similarity_score(1,310)))Output:Distance based similarity between user ids 1 & 310: 0.14459058185587106"
},
{
"code": null,
"e": 10817,
"s": 10387,
"text": "Calculating similarity scores based on the distances have an inherent problem. We do not have a threshold to decide how much distance between two users is to be considered for calculating whether the users are close enough or far enough. On the other side, this problem is resolved by pearson correlation method as it always returns a value between -1 & 1 which clearly provides us with the boundaries for closeness as we prefer."
},
{
"code": null,
"e": 12517,
"s": 10817,
"text": "def pearson_correlation_score(user1,user2): ''' user1 & user2 : user ids of two users between which similarity score is to be calculated. ''' # A list of movies watched by both the users. both_watch_count = [] # Finding movies watched by both the users. for element in ratings.loc[ratings.user_id==user1,'movie_id'].tolist(): if element in ratings.loc[ratings.user_id==user2,'movie_id'].tolist(): both_watch_count.append(element) # Returning '0' correlation for bo common movies. if len(both_watch_count) == 0 : return 0 # Calculating Co-Variances. rating_sum_1 = sum([get_rating_(user1,element) for element in both_watch_count]) rating_sum_2 = sum([get_rating_(user2,element) for element in both_watch_count]) rating_squared_sum_1 = sum([pow(get_rating_(user1,element),2) for element in both_watch_count]) rating_squared_sum_2 = sum([pow(get_rating_(user2,element),2) for element in both_watch_count]) product_sum_rating = sum([get_rating_(user1,element) * get_rating_(user2,element) for element in both_watch_count]) # Returning pearson correlation between both the users. numerator = product_sum_rating - ((rating_sum_1 * rating_sum_2) / len(both_watch_count)) denominator = sqrt((rating_squared_sum_1 - pow(rating_sum_1,2) / len(both_watch_count)) * (rating_squared_sum_2 - pow(rating_sum_2,2) / len(both_watch_count))) # Handling 'Divide by Zero' error. if denominator == 0: return 0 return numerator/denominatorprint('Pearson Corelation between user ids 11 & 30: {}'.format(pearson_correlation_score(11,30)))Output:Pearson Corelation between user ids 11 & 30: 0.2042571684752679"
},
{
"code": null,
"e": 12701,
"s": 12517,
"text": "The objective is to find out Most Similar Users to the targeted user. Here we have two metrics to find the score i.e. distance and correlation. Now, we will write a function for this."
},
{
"code": null,
"e": 13831,
"s": 12701,
"text": "def most_similar_users_(user1,number_of_users,metric='pearson'): ''' user1 : Targeted User number_of_users : number of most similar users you want to user1. metric : metric to be used to calculate inter-user similarity score. ('pearson' or else) ''' # Getting distinct user ids. user_ids = ratings.user_id.unique().tolist() # Getting similarity score between targeted and every other suer in the list(or subset of the list). if(metric == 'pearson'): similarity_score = [(pearson_correlation_score(user1,nth_user),nth_user) for nth_user in user_ids[:100] if nth_user != user1] else: similarity_score = [(distance_similarity_score(user1,nth_user),nth_user) for nth_user in user_ids[:100] if nth_user != user1] # Sorting in descending order. similarity_score.sort() similarity_score.reverse() # Returning the top most 'number_of_users' similar users. return similarity_score[:number_of_users]print(most_similar_users_(23,5))Output:[(0.936585811581694, 61), (0.7076731463403717, 41), (0.6123724356957956, 21), (0.5970863767331771, 25), (0.5477225575051661, 64)]"
},
{
"code": null,
"e": 14044,
"s": 13831,
"text": "As we can see, the output is list of tuples indicating the similarity scores of the top 5 similar number of the users asked for with user id against the targeted user. The metric used here is Pearson Correlation."
},
{
"code": null,
"e": 14300,
"s": 14044,
"text": "I don’t know if few of the people have noticed that the most similar users’ logic can be strengthened more by considering other factors as well such as age, sex, occupation etc. Here, we have created our logic on the basis of only one feature i.e. rating."
},
{
"code": null,
"e": 14880,
"s": 14300,
"text": "The concept is very simple. First, we need to iterate over only those movies not watched(or rated) by the targeted user and the sub-setting items based on the users highly correlated with targeted user. Here, we have used a weighted similarity approach where we have taken product of rating and score into account to make sure that the highly similar users affect the recommendations more than those less similar. Then, we have sorted the list on the basis of score along with movie ids and returned the movie titles against those movie ids. Let us write a function for the same."
},
{
"code": null,
"e": 16510,
"s": 14880,
"text": "def get_recommendation_(userid): user_ids = ratings.user_id.unique().tolist() total = {} similariy_sum = {} # Iterating over subset of user ids. for user in user_ids[:100]: # not comparing the user to itself (obviously!) if user == userid: continue # Getting similarity score between the users. score = pearson_correlation_score(userid,user) # not considering users having zero or less similarity score. if score <= 0: continue # Getting weighted similarity score and sum of similarities between both the users. for movieid in get_movieids_(user): # Only considering not watched/rated movies if movieid not in get_movieids_(userid) or get_rating_(userid,movieid) == 0: total[movieid] = 0 total[movieid] += get_rating_(user,movieid) * score similariy_sum[movieid] = 0 similariy_sum[movieid] += score # Normalizing ratings ranking = [(tot/similariy_sum[movieid],movieid) for movieid,tot in total.items()] ranking.sort() ranking.reverse() # Getting movie titles against the movie ids. recommendations = [get_movie_title_(movieid) for score,movieid in ranking] return recommendations[:10]print(get_recommendation_(32))Output:['Invisible Man, The ', 'Creature From the Black Lagoon, The ', 'Hellraiser ', 'Almost Famous ', 'Way of the Gun, The ', 'Shane ', 'Naked Gun 2 1/2: The Smell of Fear, The ', \"Kelly's Heroes \", 'Official Story, The ', 'Everything You Always Wanted to Know About Sex ']"
},
{
"code": null,
"e": 16760,
"s": 16510,
"text": "As we can see in the output, we have got the top 10 highly recommended movie for the user with user id 32 using the metric Pearson Correlation. You can do the same exercise with the euclidean distances as metric and I’m sure the results will differ."
},
{
"code": null,
"e": 17379,
"s": 16760,
"text": "We implemented a movie recommendation engine by just using Pandas and basic math library functions. Also, we got to know the basic intuition behind the recommendation engines. Obviously, there’s a lot more to the recommendation engines than this as there are multiple features and factors which influence the recommendations and not just the ratings. Further more, we will be implementing and deducing our recommendations also based on other features of the users and the movies in the next blog and also explore the infamous technique for recommendation engines i.e. Matrix Factorization using the turicreate library."
}
] |
How to get a Docker Container IP address?
|
We all know that we can run our application in a packaged environment called container using Docker. When you want containers to talk to each other, the network they create can be assumed to be a bridge network. Run the following command to get a list of networks.
sudo docker network ls
Each network of containers has a subnet mask and can be used to distribute IP addresses to its containers. This also means that each container in the docker network is assigned an IP address. The default subnet for a docker network is 172.17.0.0/16.
Knowing these, we will now see the different methods that can be used to find out the IP address of a docker container in a network.
Using Docker inspect
Using Docker inspect
Inspect command is used to get low level information about all the running docker containers in the host machine. It is shown in JSON format. We can use the format option with the command to get only a handful of important information.
Use the following commands below to get the container IP address using inspect.
sudo docker ps −a
sudo docker inspect −−format '{{ .NetworkSettings.IPAddress }}' <CONTAINER_ID>
First command is used to get a list of container IDs of all the running containers. This can be used on the second command to find the IP addresses.
In case of a single container
In case of a single container
In case you only have a single container running, you can directly return the last container ID by parsing it
sudo docker inspect −−format '{{ .NetworkSettings.IPAddress }}' $(docker ps −q)
Using the bash
Using the bash
You can also get a container’s network ID by attaching a bash shell to the container. Use the commands below.
To start the bash of the container, use −
sudo docker exec −it <CONTAINER_ID> bash
Once you are inside the bash, you can use the following command to access the IP address.
apt−get −y update
apt−get install iproute2
ip addr | grep global
Exporting the environment variable of the container
Exporting the environment variable of the container
For a particular docker container, you can export the environment variable. The following command returns the IP address of the last running container.
sudo docker exec −it $(docker ps −l −q) env | grep ADDR
Using the IP address command
Using the IP address command
You can also access the IP address of the container by running the IP address command. Check out the command below.
sudo docker exec −it <container−id> ip addr | grep global
Using the bashrc file
Using the bashrc file
You can access the IP address of a particular container by creating your own custom command. You just need to add a method inside your bashrc file that would take an argument which will be the container ID and then return the IP address of that container. Check out the command below.
containerip() {
sudo docker inspect −−format '{{ .NetworkSettings.IPAddress }}' "$@"
}
Paste the above code at the end of your ∽/.bashrc file.
Reload the file by using the command −
source ∽/.bashrc
Now, get the container ID using the following command.
sudo docker ps −a
Copy the container ID and use it in the following command to get the container’s IP address.
sudo containerip <CONTAINER_ID>
In this article, we have seen six different ways to get a docker container’s IP address. However, the best and probably the easiest one is using the inspect command and this makes it one of the most widely used one too.
|
[
{
"code": null,
"e": 1327,
"s": 1062,
"text": "We all know that we can run our application in a packaged environment called container using Docker. When you want containers to talk to each other, the network they create can be assumed to be a bridge network. Run the following command to get a list of networks."
},
{
"code": null,
"e": 1350,
"s": 1327,
"text": "sudo docker network ls"
},
{
"code": null,
"e": 1600,
"s": 1350,
"text": "Each network of containers has a subnet mask and can be used to distribute IP addresses to its containers. This also means that each container in the docker network is assigned an IP address. The default subnet for a docker network is 172.17.0.0/16."
},
{
"code": null,
"e": 1733,
"s": 1600,
"text": "Knowing these, we will now see the different methods that can be used to find out the IP address of a docker container in a network."
},
{
"code": null,
"e": 1754,
"s": 1733,
"text": "Using Docker inspect"
},
{
"code": null,
"e": 1775,
"s": 1754,
"text": "Using Docker inspect"
},
{
"code": null,
"e": 2011,
"s": 1775,
"text": "Inspect command is used to get low level information about all the running docker containers in the host machine. It is shown in JSON format. We can use the format option with the command to get only a handful of important information."
},
{
"code": null,
"e": 2091,
"s": 2011,
"text": "Use the following commands below to get the container IP address using inspect."
},
{
"code": null,
"e": 2188,
"s": 2091,
"text": "sudo docker ps −a\nsudo docker inspect −−format '{{ .NetworkSettings.IPAddress }}' <CONTAINER_ID>"
},
{
"code": null,
"e": 2337,
"s": 2188,
"text": "First command is used to get a list of container IDs of all the running containers. This can be used on the second command to find the IP addresses."
},
{
"code": null,
"e": 2367,
"s": 2337,
"text": "In case of a single container"
},
{
"code": null,
"e": 2397,
"s": 2367,
"text": "In case of a single container"
},
{
"code": null,
"e": 2507,
"s": 2397,
"text": "In case you only have a single container running, you can directly return the last container ID by parsing it"
},
{
"code": null,
"e": 2587,
"s": 2507,
"text": "sudo docker inspect −−format '{{ .NetworkSettings.IPAddress }}' $(docker ps −q)"
},
{
"code": null,
"e": 2602,
"s": 2587,
"text": "Using the bash"
},
{
"code": null,
"e": 2617,
"s": 2602,
"text": "Using the bash"
},
{
"code": null,
"e": 2727,
"s": 2617,
"text": "You can also get a container’s network ID by attaching a bash shell to the container. Use the commands below."
},
{
"code": null,
"e": 2769,
"s": 2727,
"text": "To start the bash of the container, use −"
},
{
"code": null,
"e": 2810,
"s": 2769,
"text": "sudo docker exec −it <CONTAINER_ID> bash"
},
{
"code": null,
"e": 2900,
"s": 2810,
"text": "Once you are inside the bash, you can use the following command to access the IP address."
},
{
"code": null,
"e": 2965,
"s": 2900,
"text": "apt−get −y update\napt−get install iproute2\nip addr | grep global"
},
{
"code": null,
"e": 3017,
"s": 2965,
"text": "Exporting the environment variable of the container"
},
{
"code": null,
"e": 3069,
"s": 3017,
"text": "Exporting the environment variable of the container"
},
{
"code": null,
"e": 3221,
"s": 3069,
"text": "For a particular docker container, you can export the environment variable. The following command returns the IP address of the last running container."
},
{
"code": null,
"e": 3277,
"s": 3221,
"text": "sudo docker exec −it $(docker ps −l −q) env | grep ADDR"
},
{
"code": null,
"e": 3306,
"s": 3277,
"text": "Using the IP address command"
},
{
"code": null,
"e": 3335,
"s": 3306,
"text": "Using the IP address command"
},
{
"code": null,
"e": 3451,
"s": 3335,
"text": "You can also access the IP address of the container by running the IP address command. Check out the command below."
},
{
"code": null,
"e": 3509,
"s": 3451,
"text": "sudo docker exec −it <container−id> ip addr | grep global"
},
{
"code": null,
"e": 3531,
"s": 3509,
"text": "Using the bashrc file"
},
{
"code": null,
"e": 3553,
"s": 3531,
"text": "Using the bashrc file"
},
{
"code": null,
"e": 3838,
"s": 3553,
"text": "You can access the IP address of a particular container by creating your own custom command. You just need to add a method inside your bashrc file that would take an argument which will be the container ID and then return the IP address of that container. Check out the command below."
},
{
"code": null,
"e": 3928,
"s": 3838,
"text": "containerip() {\n sudo docker inspect −−format '{{ .NetworkSettings.IPAddress }}' \"$@\"\n}"
},
{
"code": null,
"e": 3984,
"s": 3928,
"text": "Paste the above code at the end of your ∽/.bashrc file."
},
{
"code": null,
"e": 4023,
"s": 3984,
"text": "Reload the file by using the command −"
},
{
"code": null,
"e": 4040,
"s": 4023,
"text": "source ∽/.bashrc"
},
{
"code": null,
"e": 4095,
"s": 4040,
"text": "Now, get the container ID using the following command."
},
{
"code": null,
"e": 4113,
"s": 4095,
"text": "sudo docker ps −a"
},
{
"code": null,
"e": 4206,
"s": 4113,
"text": "Copy the container ID and use it in the following command to get the container’s IP address."
},
{
"code": null,
"e": 4238,
"s": 4206,
"text": "sudo containerip <CONTAINER_ID>"
},
{
"code": null,
"e": 4458,
"s": 4238,
"text": "In this article, we have seen six different ways to get a docker container’s IP address. However, the best and probably the easiest one is using the inspect command and this makes it one of the most widely used one too."
}
] |
How do I split a multi-line string into multiple lines?
|
We can use the method splitlines() in string class to achieve this.
>>> """some
multi line
string""".splitlines()
['some', 'multi line', 'string']
We can also specify the delimiter '\n' in the split() method as follows −
>>> """some
multi line
string""".split('\n')
['some', 'multi line', 'string']
|
[
{
"code": null,
"e": 1131,
"s": 1062,
"text": "We can use the method splitlines() in string class to achieve this. "
},
{
"code": null,
"e": 1210,
"s": 1131,
"text": ">>> \"\"\"some\nmulti line\nstring\"\"\".splitlines()\n['some', 'multi line', 'string']"
},
{
"code": null,
"e": 1284,
"s": 1210,
"text": "We can also specify the delimiter '\\n' in the split() method as follows −"
},
{
"code": null,
"e": 1362,
"s": 1284,
"text": ">>> \"\"\"some\nmulti line\nstring\"\"\".split('\\n')\n['some', 'multi line', 'string']"
}
] |
Building your own Covid-19 Epidemic Simple Model Using Python | by Sadegh Maghsoudi | Towards Data Science
|
If you live in this world, there is a very small chance you may have not yet heard of this novel Coronavirus Covid-19 and the pandemic it caused literally all over the world. Actually, it is a good chance that you are reading this while self quarantined at your home, social distancing from public and like many, have very much of extra time to deal with. So, if you are familiar with programming, why not try this: build your own epidemic model at home. Which helps you boost your programming abilities, and, helps you understand the concepts and basic dynamics of epidemics.
But first of all, please note that it is simply an article to show how to use Python to prepare a basic model for Covid-19 epidemic. Which on the other hand means: It Is Not a model you could use to predict what's to come. It is Not your DIY model which brings you the ability to simply ignore what official authorities recommend you to do. Neither it is a visualization tool to prove others on social media how doomed we are! If you’r OK with these disclaimers now let’s start our coding.
The main concepts we assume here, is to model a finite number of individuals of a sample society interacting with each other on a daily basis and the chance of contamination which each interaction brings. For the sake of simplicity, I generated the group randomly, with proximities represents the amount of interaction each person has with it’s nearest neighbors. Note that a person’s neighbor may be his/her family, colleagues, classmates or anybody else who he/she is in contact with every day. I assumed that this interaction remains the same for most persons in the sample, but to make things more interesting, let’s assume a fraction of group,I took 10%, which we call them Transporters, move randomly each day in the model; which means their neighbors change each day. I’ve added these group to represent those shopkeepers, taxi drivers, police officers, etc. who interact with new individuals each day. I’ve marked transporters with a circle and their number to keep track of each.And finally, to complete our Day Zero initialization, what we need more is a Patient Zero! which I colored red.
After initialization, the simulations goes like this on each day:
Transporters move randomly.
People interact with their neighbors.
Infection spreads randomly with a predefined chance of contamination from a patient to a healthy guy during interaction.
A certain fraction of patients, Covid-19 (+), randomly hospitalize, assuming their symptoms got worst.
A certain fraction of hospitalized patients, randomly selected, die.
Patients who has endured the period of disease, let’s say 14 days, with mild symptoms will be cured and immune against the disease.
And tomorrow . . . we repeat all above again. And that goes on until no new infection could be possible.
Coding the above mentioned algorithm would be an easy task for like all programming languages, but for visualization purposes, Python has a lot to offer using matplotlib.
Let’s see what happens if we run this simulation with a random dataset of 1000 individuals and infection chance of 25% in each interaction:
Let’s see what the statistics looked like during that simulation:
Since the simulation takes some time, I had python to report me what is exactly going on with my society during the simulation in a log:
-------------------------------Day: 0- - - - - - - - - - - - - - - - Healthy 999Covid-19(+) 1Hospitalized 0Cured 0Dead 0Name: 0, dtype: int64-------------------------------Day: 1- - - - - - - - - - - - - - - - Healthy 987.0Covid-19(+) 13.0Hospitalized 0.0Cured 0.0Dead 0.0Name: 1, dtype: float64-------------------------------Day: 2- - - - - - - - - - - - - - - - Healthy 977.0Covid-19(+) 23.0Hospitalized 0.0Cured 0.0Dead 0.0Name: 2, dtype: float64-------------------------------.. . . . . . . . . -------------------------------Day: 53- - - - - - - - - - - - - - - - Healthy 1.0Covid-19(+) 0.0Hospitalized 0.0Cured 951.0Dead 48.0Name: 53, dtype: float64
And I had python to automatically do all the job to make all those charts and list and video and save it on the format I chose. But note that it may take some simulation run time if you choose big numbers for quantity and change some of the assumptions in a wrong way.
For example, simulating 10,000 individuals took me around 24 hours until day 34 which you may see the simulation results below:
Now that you have developed your own sample model, you may find it interesting to search for more scientific models developed by professional epidemiologists or you may see one here from Washington Post.
Below, you may find my python code to above illustrated model in which you can change parameters easily and see what happens with different assumptions.
# -*- coding: utf-8 -*-"""Created on Sat Feb 29 21:57:53 2020@author: Sadegh Maghsoudi"""# Functions --------------------------------------------------def point(xlimit,ylimit): import random x = random.uniform(0,xlimit) y = random.uniform(0,ylimit) return x,ydef Generate(GrupSize,xlimit,ylimit): import pandas as pd import math df = pd.DataFrame(columns='X,Y,Covid-19,Day'.split(',')) for i in range(GrupSize): df.loc[i,'X'], df.loc[i,'Y'] = point(xlimit,ylimit) df.loc[i,'Covid-19'] = False samplesize = math.floor(GrupSize/100) MoversList = df.sample(n = samplesize).index.values.tolist() StatofDay = pd.DataFrame(columns='Healthy,Covid-19(+),Hospitalized,Cured,Dead'.split(',')) return df , StatofDay, MoversList def plt1color(df): cols=[] for l in df.index: if df.loc[l,'Covid-19']==True: #Infected cols.append('red') elif df.loc[l,'Covid-19']==666: #Dead cols.append('black') elif df.loc[l,'Covid-19']==115: #Hospitalized cols.append('yellow') elif df.loc[l,'Covid-19']==7: #Cured cols.append('green') else: cols.append('blue') #Healthy return colsdef plt2color(Stat): cols=[] for i in Stat.columns: if i=='Covid-19(+)': #Infected cols.append('red') elif i=='Dead': #Dead cols.append('black') elif i=='Hospitalized': #Hospitalized cols.append('yellow') elif i=='Cured': #Cured cols.append('green') else: cols.append('blue') #Healthy return colsdef Plot(): import matplotlib.pyplot as plt global df, fig, Stat, Day, Moverslist cols=plt1color(df) ld = ['Healthy','Covid-19(+)','Hospitalized','Cured','Death Toll'] axs[0].cla() axs[0].scatter(df['X'],df['Y'],s=1,c=cols) for i in MoversList: axs[0].scatter(df.loc[i,'X'],df.loc[i,'Y'],s=6,facecolors='none', edgecolors='black') axs[0].text(df.loc[i,'X']+0.02, df.loc[i,'Y']+0.02, str(i), fontsize=5) cols=plt2color(Stat) sDay = str(Day) title = 'Day' + sDay axs[0].set_title(title,loc='left') axs[0].set_yticklabels([]) axs[0].set_xticklabels([]) axs[0].tick_params(# axis='both', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom=False, # ticks along the bottom edge are off top=False, # ticks along the top edge are off right=False, # ticks along the right edge are off left=False, # ticks along the left edge are off labelbottom=False) # labels along the bottom edge are off axs[1].cla() axs[1].plot(Stat.Healthy,label=ld[0],color=cols[0]) axs[1].plot(Stat['Covid-19(+)'],label=ld[1],color=cols[1]) axs[1].plot(Stat.Hospitalized,label=ld[2],color=cols[2]) axs[1].plot(Stat.Cured,label=ld[3],color=cols[3]) axs[1].plot(Stat.Dead,label=ld[4],color=cols[4])# axs[1].set_prop_cycle(color=cols) axs[1].legend(bbox_to_anchor=(0, 1), loc='upper left', borderaxespad=0.) plt.xlabel('Days') plt.show() if Day<10 : sDay = '0' + sDay title = 'Day' + sDay + '.png' plt.savefig(title)returndef Png_to_gif(): from PIL import Image import glob # Create frames frames = [] imgs = glob.glob("*.png") for i in imgs: new_frame = Image.open(i) frames.append(new_frame) # Save into GIF frames[0].save('png_to_gif.gif', format='GIF', append_images=frames[1:], save_all=True, duration=500, loop=0)def infect(Person): import random global df,Day if random.random()>0.25 and Day>3 : return if df.loc[Person,'Covid-19']==False: df.loc[Person,'Covid-19'], df.loc[Person,'Day'] = True, Day def Move(xlimit,ylimit): """ Move Movers Randomly """ import random global df, MoversList for i in MoversList: if (df.loc[i,'Covid-19']==115) or (df.loc[i,'Covid-19']==666) : MoversList.remove(i) df.loc[i,'X'], df.loc[i,'Y'] = (df.loc[i,'X']+random.uniform(1,xlimit/3))%xlimit, (df.loc[i,'Y']+random.uniform(1,ylimit/3))%ylimitdef check(i,j): import math global df, YesterdayPatients, Distlimit Dist = math.sqrt((df.loc[i,'X']-df.loc[j,'X'])**2+(df.loc[i,'Y']-df.loc[j,'Y'])**2) flag = ((YesterdayPatients[i]==True) ^ (YesterdayPatients[j]==True)) and Dist<Distlimit return flag def interact(): global Day, df for i in range(len(df)): for j in range(i): if check(i,j): if (df.loc[i,'Covid-19']==False) : infect(i) else: infect(j)def kill(): import math global df samplesize = math.floor(len(df[df['Covid-19']==True])*.005+len(df[df['Covid-19']==115])*.005) if samplesize>len(df[df['Covid-19']==True]): return df.loc[df[df['Covid-19']==True].sample(n = samplesize).index.values.tolist(),'Covid-19']=666 returndef hospitilize(): import math global df samplesize = math.floor(len(df[df['Covid-19']==True])*0.03) if samplesize>len(df[df['Covid-19']==True]): return df.loc[df[df['Covid-19']==True].sample(n = samplesize).index.values.tolist(),'Covid-19']=115 returndef cure(): global df, Day df.loc[(df['Day']<Day-10) & (df['Covid-19']==True) ,'Covid-19'] = 7 df.loc[(df['Day']<Day-21) & (df['Covid-19']==115) ,'Covid-19'] = 7 return def Tomorrow(): # To Be checked and Resolved!!! global df, Day Day +=1 kill() hospitilize() cure() Move(xlimit,ylimit) interact()def Count(Day): global df, Stat List = list(df['Covid-19']) Stat.loc[Day,'Healthy'] = List.count(False) Stat.loc[Day,'Covid-19(+)'] = List.count(True) Stat.loc[Day,'Hospitalized'] = List.count(115) Stat.loc[Day,'Cured'] = List.count(7) Stat.loc[Day,'Dead'] = List.count(666) return def write_log(*args): global log_file line = ' '.join([str(a) for a in args]) log_file.write(line+'\n') print(line) # Main -------------------------------------------------------------------import matplotlib.pyplot as pltimport randomlog_file = open("Log.txt","w+")# -------------------------------------------# I N P U T V A R I A B L E S H E R E |# -------------------------------------------# |n = 1000 # |xlimit,ylimit=30,30 # |Distlimit = 1.5 # |# |# -------------------------------------------write_log(31*'-')write_log("Here's the Input Data:")write_log(8*'- - ') write_log('Numper of Sample:',n)write_log('X & Y limites: ',xlimit,', ',ylimit)write_log('Distance required for Contamination:', Distlimit)# Day = 0, Generating Model...Day = 0df, Stat, MoversList = Generate(n,xlimit,ylimit)infect(random.randrange(n))fig, axs = plt.subplots(2)fig.suptitle('Covid-19 Epidemic Sample Model', fontsize=16)Plot()Count(Day)write_log(31*'-')write_log('Day:',Day)write_log(8*'- - ') write_log(Stat.loc[Day])# Day=1YesterdayPatients = list(df['Covid-19'])Tomorrow()Plot()Count(Day)write_log(31*'-')write_log('Day:',Day)write_log(8*'- - ') write_log(Stat.loc[Day]) #Main Loop . . .countsames = 0while Stat.loc[Day, 'Healthy']>0 and Day<100: log_file = open("Log.txt","a+") if (list(Stat.loc[Day])==list(Stat.loc[Day-1])): countsames +=1 if countsames>2 : break else : countsames = 0 YesterdayPatients = list(df['Covid-19']) Tomorrow() Plot() Count(Day) write_log(31*'-') write_log('Day:',Day) write_log(8*'- - ') write_log(Stat.loc[Day]) log_file.close()Png_to_gif()Stat.to_excel('Stat.xlsx')Stat.plot(title='Statistical Data Vs. Days Passed')plt.savefig('Stat')
Note from the editors: Towards Data Science is a Medium publication primarily based on the study of data science and machine learning. We are not health professionals or epidemiologists, and the opinions of this article should not be interpreted as professional advice. To learn more about the coronavirus pandemic, you can click here.
|
[
{
"code": null,
"e": 749,
"s": 172,
"text": "If you live in this world, there is a very small chance you may have not yet heard of this novel Coronavirus Covid-19 and the pandemic it caused literally all over the world. Actually, it is a good chance that you are reading this while self quarantined at your home, social distancing from public and like many, have very much of extra time to deal with. So, if you are familiar with programming, why not try this: build your own epidemic model at home. Which helps you boost your programming abilities, and, helps you understand the concepts and basic dynamics of epidemics."
},
{
"code": null,
"e": 1239,
"s": 749,
"text": "But first of all, please note that it is simply an article to show how to use Python to prepare a basic model for Covid-19 epidemic. Which on the other hand means: It Is Not a model you could use to predict what's to come. It is Not your DIY model which brings you the ability to simply ignore what official authorities recommend you to do. Neither it is a visualization tool to prove others on social media how doomed we are! If you’r OK with these disclaimers now let’s start our coding."
},
{
"code": null,
"e": 2339,
"s": 1239,
"text": "The main concepts we assume here, is to model a finite number of individuals of a sample society interacting with each other on a daily basis and the chance of contamination which each interaction brings. For the sake of simplicity, I generated the group randomly, with proximities represents the amount of interaction each person has with it’s nearest neighbors. Note that a person’s neighbor may be his/her family, colleagues, classmates or anybody else who he/she is in contact with every day. I assumed that this interaction remains the same for most persons in the sample, but to make things more interesting, let’s assume a fraction of group,I took 10%, which we call them Transporters, move randomly each day in the model; which means their neighbors change each day. I’ve added these group to represent those shopkeepers, taxi drivers, police officers, etc. who interact with new individuals each day. I’ve marked transporters with a circle and their number to keep track of each.And finally, to complete our Day Zero initialization, what we need more is a Patient Zero! which I colored red."
},
{
"code": null,
"e": 2405,
"s": 2339,
"text": "After initialization, the simulations goes like this on each day:"
},
{
"code": null,
"e": 2433,
"s": 2405,
"text": "Transporters move randomly."
},
{
"code": null,
"e": 2471,
"s": 2433,
"text": "People interact with their neighbors."
},
{
"code": null,
"e": 2592,
"s": 2471,
"text": "Infection spreads randomly with a predefined chance of contamination from a patient to a healthy guy during interaction."
},
{
"code": null,
"e": 2695,
"s": 2592,
"text": "A certain fraction of patients, Covid-19 (+), randomly hospitalize, assuming their symptoms got worst."
},
{
"code": null,
"e": 2764,
"s": 2695,
"text": "A certain fraction of hospitalized patients, randomly selected, die."
},
{
"code": null,
"e": 2896,
"s": 2764,
"text": "Patients who has endured the period of disease, let’s say 14 days, with mild symptoms will be cured and immune against the disease."
},
{
"code": null,
"e": 3001,
"s": 2896,
"text": "And tomorrow . . . we repeat all above again. And that goes on until no new infection could be possible."
},
{
"code": null,
"e": 3172,
"s": 3001,
"text": "Coding the above mentioned algorithm would be an easy task for like all programming languages, but for visualization purposes, Python has a lot to offer using matplotlib."
},
{
"code": null,
"e": 3312,
"s": 3172,
"text": "Let’s see what happens if we run this simulation with a random dataset of 1000 individuals and infection chance of 25% in each interaction:"
},
{
"code": null,
"e": 3378,
"s": 3312,
"text": "Let’s see what the statistics looked like during that simulation:"
},
{
"code": null,
"e": 3515,
"s": 3378,
"text": "Since the simulation takes some time, I had python to report me what is exactly going on with my society during the simulation in a log:"
},
{
"code": null,
"e": 4344,
"s": 3515,
"text": "-------------------------------Day: 0- - - - - - - - - - - - - - - - Healthy 999Covid-19(+) 1Hospitalized 0Cured 0Dead 0Name: 0, dtype: int64-------------------------------Day: 1- - - - - - - - - - - - - - - - Healthy 987.0Covid-19(+) 13.0Hospitalized 0.0Cured 0.0Dead 0.0Name: 1, dtype: float64-------------------------------Day: 2- - - - - - - - - - - - - - - - Healthy 977.0Covid-19(+) 23.0Hospitalized 0.0Cured 0.0Dead 0.0Name: 2, dtype: float64-------------------------------.. . . . . . . . . -------------------------------Day: 53- - - - - - - - - - - - - - - - Healthy 1.0Covid-19(+) 0.0Hospitalized 0.0Cured 951.0Dead 48.0Name: 53, dtype: float64"
},
{
"code": null,
"e": 4613,
"s": 4344,
"text": "And I had python to automatically do all the job to make all those charts and list and video and save it on the format I chose. But note that it may take some simulation run time if you choose big numbers for quantity and change some of the assumptions in a wrong way."
},
{
"code": null,
"e": 4741,
"s": 4613,
"text": "For example, simulating 10,000 individuals took me around 24 hours until day 34 which you may see the simulation results below:"
},
{
"code": null,
"e": 4945,
"s": 4741,
"text": "Now that you have developed your own sample model, you may find it interesting to search for more scientific models developed by professional epidemiologists or you may see one here from Washington Post."
},
{
"code": null,
"e": 5098,
"s": 4945,
"text": "Below, you may find my python code to above illustrated model in which you can change parameters easily and see what happens with different assumptions."
},
{
"code": null,
"e": 12919,
"s": 5098,
"text": "# -*- coding: utf-8 -*-\"\"\"Created on Sat Feb 29 21:57:53 2020@author: Sadegh Maghsoudi\"\"\"# Functions --------------------------------------------------def point(xlimit,ylimit): import random x = random.uniform(0,xlimit) y = random.uniform(0,ylimit) return x,ydef Generate(GrupSize,xlimit,ylimit): import pandas as pd import math df = pd.DataFrame(columns='X,Y,Covid-19,Day'.split(',')) for i in range(GrupSize): df.loc[i,'X'], df.loc[i,'Y'] = point(xlimit,ylimit) df.loc[i,'Covid-19'] = False samplesize = math.floor(GrupSize/100) MoversList = df.sample(n = samplesize).index.values.tolist() StatofDay = pd.DataFrame(columns='Healthy,Covid-19(+),Hospitalized,Cured,Dead'.split(',')) return df , StatofDay, MoversList def plt1color(df): cols=[] for l in df.index: if df.loc[l,'Covid-19']==True: #Infected cols.append('red') elif df.loc[l,'Covid-19']==666: #Dead cols.append('black') elif df.loc[l,'Covid-19']==115: #Hospitalized cols.append('yellow') elif df.loc[l,'Covid-19']==7: #Cured cols.append('green') else: cols.append('blue') #Healthy return colsdef plt2color(Stat): cols=[] for i in Stat.columns: if i=='Covid-19(+)': #Infected cols.append('red') elif i=='Dead': #Dead cols.append('black') elif i=='Hospitalized': #Hospitalized cols.append('yellow') elif i=='Cured': #Cured cols.append('green') else: cols.append('blue') #Healthy return colsdef Plot(): import matplotlib.pyplot as plt global df, fig, Stat, Day, Moverslist cols=plt1color(df) ld = ['Healthy','Covid-19(+)','Hospitalized','Cured','Death Toll'] axs[0].cla() axs[0].scatter(df['X'],df['Y'],s=1,c=cols) for i in MoversList: axs[0].scatter(df.loc[i,'X'],df.loc[i,'Y'],s=6,facecolors='none', edgecolors='black') axs[0].text(df.loc[i,'X']+0.02, df.loc[i,'Y']+0.02, str(i), fontsize=5) cols=plt2color(Stat) sDay = str(Day) title = 'Day' + sDay axs[0].set_title(title,loc='left') axs[0].set_yticklabels([]) axs[0].set_xticklabels([]) axs[0].tick_params(# axis='both', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom=False, # ticks along the bottom edge are off top=False, # ticks along the top edge are off right=False, # ticks along the right edge are off left=False, # ticks along the left edge are off labelbottom=False) # labels along the bottom edge are off axs[1].cla() axs[1].plot(Stat.Healthy,label=ld[0],color=cols[0]) axs[1].plot(Stat['Covid-19(+)'],label=ld[1],color=cols[1]) axs[1].plot(Stat.Hospitalized,label=ld[2],color=cols[2]) axs[1].plot(Stat.Cured,label=ld[3],color=cols[3]) axs[1].plot(Stat.Dead,label=ld[4],color=cols[4])# axs[1].set_prop_cycle(color=cols) axs[1].legend(bbox_to_anchor=(0, 1), loc='upper left', borderaxespad=0.) plt.xlabel('Days') plt.show() if Day<10 : sDay = '0' + sDay title = 'Day' + sDay + '.png' plt.savefig(title)returndef Png_to_gif(): from PIL import Image import glob # Create frames frames = [] imgs = glob.glob(\"*.png\") for i in imgs: new_frame = Image.open(i) frames.append(new_frame) # Save into GIF frames[0].save('png_to_gif.gif', format='GIF', append_images=frames[1:], save_all=True, duration=500, loop=0)def infect(Person): import random global df,Day if random.random()>0.25 and Day>3 : return if df.loc[Person,'Covid-19']==False: df.loc[Person,'Covid-19'], df.loc[Person,'Day'] = True, Day def Move(xlimit,ylimit): \"\"\" Move Movers Randomly \"\"\" import random global df, MoversList for i in MoversList: if (df.loc[i,'Covid-19']==115) or (df.loc[i,'Covid-19']==666) : MoversList.remove(i) df.loc[i,'X'], df.loc[i,'Y'] = (df.loc[i,'X']+random.uniform(1,xlimit/3))%xlimit, (df.loc[i,'Y']+random.uniform(1,ylimit/3))%ylimitdef check(i,j): import math global df, YesterdayPatients, Distlimit Dist = math.sqrt((df.loc[i,'X']-df.loc[j,'X'])**2+(df.loc[i,'Y']-df.loc[j,'Y'])**2) flag = ((YesterdayPatients[i]==True) ^ (YesterdayPatients[j]==True)) and Dist<Distlimit return flag def interact(): global Day, df for i in range(len(df)): for j in range(i): if check(i,j): if (df.loc[i,'Covid-19']==False) : infect(i) else: infect(j)def kill(): import math global df samplesize = math.floor(len(df[df['Covid-19']==True])*.005+len(df[df['Covid-19']==115])*.005) if samplesize>len(df[df['Covid-19']==True]): return df.loc[df[df['Covid-19']==True].sample(n = samplesize).index.values.tolist(),'Covid-19']=666 returndef hospitilize(): import math global df samplesize = math.floor(len(df[df['Covid-19']==True])*0.03) if samplesize>len(df[df['Covid-19']==True]): return df.loc[df[df['Covid-19']==True].sample(n = samplesize).index.values.tolist(),'Covid-19']=115 returndef cure(): global df, Day df.loc[(df['Day']<Day-10) & (df['Covid-19']==True) ,'Covid-19'] = 7 df.loc[(df['Day']<Day-21) & (df['Covid-19']==115) ,'Covid-19'] = 7 return def Tomorrow(): # To Be checked and Resolved!!! global df, Day Day +=1 kill() hospitilize() cure() Move(xlimit,ylimit) interact()def Count(Day): global df, Stat List = list(df['Covid-19']) Stat.loc[Day,'Healthy'] = List.count(False) Stat.loc[Day,'Covid-19(+)'] = List.count(True) Stat.loc[Day,'Hospitalized'] = List.count(115) Stat.loc[Day,'Cured'] = List.count(7) Stat.loc[Day,'Dead'] = List.count(666) return def write_log(*args): global log_file line = ' '.join([str(a) for a in args]) log_file.write(line+'\\n') print(line) # Main -------------------------------------------------------------------import matplotlib.pyplot as pltimport randomlog_file = open(\"Log.txt\",\"w+\")# -------------------------------------------# I N P U T V A R I A B L E S H E R E |# -------------------------------------------# |n = 1000 # |xlimit,ylimit=30,30 # |Distlimit = 1.5 # |# |# -------------------------------------------write_log(31*'-')write_log(\"Here's the Input Data:\")write_log(8*'- - ') write_log('Numper of Sample:',n)write_log('X & Y limites: ',xlimit,', ',ylimit)write_log('Distance required for Contamination:', Distlimit)# Day = 0, Generating Model...Day = 0df, Stat, MoversList = Generate(n,xlimit,ylimit)infect(random.randrange(n))fig, axs = plt.subplots(2)fig.suptitle('Covid-19 Epidemic Sample Model', fontsize=16)Plot()Count(Day)write_log(31*'-')write_log('Day:',Day)write_log(8*'- - ') write_log(Stat.loc[Day])# Day=1YesterdayPatients = list(df['Covid-19'])Tomorrow()Plot()Count(Day)write_log(31*'-')write_log('Day:',Day)write_log(8*'- - ') write_log(Stat.loc[Day]) #Main Loop . . .countsames = 0while Stat.loc[Day, 'Healthy']>0 and Day<100: log_file = open(\"Log.txt\",\"a+\") if (list(Stat.loc[Day])==list(Stat.loc[Day-1])): countsames +=1 if countsames>2 : break else : countsames = 0 YesterdayPatients = list(df['Covid-19']) Tomorrow() Plot() Count(Day) write_log(31*'-') write_log('Day:',Day) write_log(8*'- - ') write_log(Stat.loc[Day]) log_file.close()Png_to_gif()Stat.to_excel('Stat.xlsx')Stat.plot(title='Statistical Data Vs. Days Passed')plt.savefig('Stat')"
}
] |
ElegantRL-Helloworld: A Lightweight and Stable Deep Reinforcement Learning Library | by Xiao-Yang Liu | Towards Data Science
|
This article by Xiao-Yang Liu, Steven Li and Yiyan Zeng (J. Zheng) describes the ElegantRL library (Twitter and Github).
One sentence summary of reinforcement learning (RL): in RL, an agent learns by continuously interacting with an environment, in a trial-and-error manner, making sequential decisions under uncertainty and achieving a balance between exploration (new territory) and exploitation (using knowledge learned from experiences).
Deep reinforcement learning (DRL) has great potential to solve real-world problems that are challenging to humans, such as self-driving cars, gaming, natural language processing (NLP), and financial trading. Starting from the success of AlphaGo, various DRL algorithms and applications are emerging in a disruptive manner. The ElegantRL library enables researchers and practitioners to pipeline the disruptive “design, development and deployment” of DRL technology.
The library to be presented is featured with “elegant” in the following aspects:
Lightweight: core codes have less than 1,000 lines, e.g., tutorial.
Efficient: the performance is comparable with Ray RLlib.
Stable: more stable than Stable Baseline 3.
ElegantRL supports state-of-the-art DRL algorithms, including discrete and continuous ones, and provides user-friendly tutorials in Jupyter notebooks.
The ElegantRL implements DRL algorithms under the Actor-Critic framework, where an Agent (a.k.a, a DRL algorithm) consists of an Actor network and a Critic network. Due to the completeness and simplicity of code structure, users are able to easily customize their own agents.
The file structure of ElegantRL is shown in Fig. 1:
Env.py: it contains the environments, with which the agent interacts.
Env.py: it contains the environments, with which the agent interacts.
A PreprocessEnv class for gym-environment modification.
A self-created stock trading environment as an example for user customization.
2. Net.py: There are three types of networks:
Q-Net,
Actor Network,
Critic Network,
Each includes a base network for inheritance and a set of variations for different algorithms.
3. Agent.py: it contains agents for different DRL algorithms.
4. Run.py: it provides basic functions for the training and evaluating process:
Parameter initialization,
Training loop,
Evaluator.
As a high-level overview, the relations among the files are as follows. Initialize an environment in Env.py and an agent in Agent.py. The agent is constructed with Actor and Critic networks in Net.py. In each training step in Run.py, the agent interacts with the environment, generating transitions that are stored into a Replay Buffer. Then, the agent fetches transitions from the Replay Buffer to train its networks. After each update, an evaluator evaluates the agent’s performance and saves the agent if the performance is good.
This part describes DQN-series algorithms and DDPG-series algorithms, respectively. Each DRL algorithm agent follows a hierarchy from its base class.
As shown in Fig. 2, the inheritance hierarchy of the DQN-series algorithms is as follows:
AgentDQN: a standard DQN agent.
AgentDoubleDQN: a Double-DQN agent with two Q-Nets for reducing overestimation, inheriting from AgentDQN.
AgentDuelingDQN: a DQN agent with a different Q-value calculation, inheriting from AgentDQN.
AgentD3QN: a combination of AgentDoubleDQN and AgentDuelingDQN, inheriting from AgentDoubleDQN.
class AgentBase: def init(self); def select_action(states); # states = (state, ...) def explore_env(env, buffer, target_step, reward_scale, gamma); def update_net(buffer, max_step, batch_size, repeat_times); def save_load_model(cwd, if_save); def soft_update(target_net, current_net);class AgentDQN: def init(net_dim, state_dim, action_dim); def select_action(states); # for discrete action space def explore_env(env, buffer, target_step, reward_scale, gamma); def update_net(buffer, max_step, batch_size, repeat_times); def save_or_load_model(cwd, if_save);class AgentDuelingDQN(AgentDQN): def init(net_dim, state_dim, action_dim);class AgentDoubleDQN(AgentDQN): def init(self, net_dim, state_dim, action_dim); def select_action(states); def update_net(buffer, max_step, batch_size, repeat_times);class AgentD3QN(AgentDoubleDQN): # D3QN: Dueling Double DQN def init(net_dim, state_dim, action_dim);
As shown in Fig. 3, the inheritance hierarchy of the DDPG-series algorithms is as follows
AgentBase: a base class for all Actor-Critic agents.
AgentDDPG: a DDPG agent, inheriting from AgentBase.
class AgentBase: def init(self); def select_action(states); # states = (state, ...) def explore_env(env, buffer, target_step, reward_scale, gamma); def update_net(buffer, max_step, batch_size, repeat_times); def save_load_model(cwd, if_save); def soft_update(target_net, current_net);class AgentDDPG(AgentBase): def init(net_dim, state_dim, action_dim); def select_action(states); def update_net(buffer, max_step, batch_size, repeat_times);
Applying such a hierarchy in building DRL agents effectively improves lightweightness and effectiveness. Users can easily design and implement new agents in a similar flow.
Basically, an agent has two fundamental functions, and the data flow is shown in Fig. 4:
explore_env(): it allows the agent to interact with the environment and generates transitions for training networks.
update_net(): it first fetches a batch of transitions from the Replay Buffer, and then train the network with backpropagation.
Two major steps to train an agent:
Initialization:
Initialization:
hyper-parameters args.
env = PreprocessEnv() : creates an environment (in the OpenAI gym format).
agent = AgentXXX() : creates an agent for a DRL algorithm.
evaluator = Evaluator() : evaluates and stores the trained model.
buffer = ReplayBuffer() : stores the transitions.
2. Then, the training process is controlled by a while-loop:
agent.explore_env(...): the agent explores the environment within target steps, generates transitions, and stores them into the ReplayBuffer.
agent.update_net(...): the agent uses a batch from the ReplayBuffer to update the network parameters.
evaluator.evaluate_save(...): evaluates the agent’s performance and keeps the trained model with the highest score.
The while-loop will terminate when the conditions are met, e.g., achieving a target score, maximum steps, or manually breaks.
BipedalWalker-v3 is a classic task in robotics that performs a fundamental skill: moving. The goal is to get a 2D biped walker to walk through rough terrain. BipedalWalker is considered to be a difficult task in the continuous action space, and there are only a few RL implementations that can reach the target reward.
pip install git+https://github.com/AI4Finance-LLC/ElegantRL.git
ElegantRL
OpenAI Gym: a toolkit for developing and comparing reinforcement learning algorithms.
PyBullet Gym: an open-source implementation of the OpenAI Gym MuJoCo environments.
from elegantrl.run import *from elegantrl.agent import AgentGaePPOfrom elegantrl.env import PreprocessEnvimport gymgym.logger.set_level(40) # Block warning
args.agent: firstly chooses a DRL algorithm, and the user is able to choose one from a set of agents in agent.py
args.env: creates and preprocesses an environment, and the user can either customize own environment or preprocess environments from OpenAI Gym and PyBullet Gym in env.py.
args = Arguments(if_on_policy=False)args.agent = AgentGaePPO() # AgentSAC(), AgentTD3(), AgentDDPG()args.env = PreprocessEnv(env=gym.make(‘BipedalWalker-v3’))args.reward_scale = 2 ** -1 # RewardRange: -200 < -150 < 300 < 334args.gamma = 0.95args.rollout_num = 2 # the number of rollout workers (larger is not always faster)
The training and evaluating processes are inside function train_and_evaluate__multiprocessing(args), and the parameter is args. It includes two fundamental objects in DRL:
agent,
environment (env).
And the parameters for training:
batch_size,
target_step,
reward_scale,
gamma, etc.
Also the parameters for evaluation:
break_step,
random_seed, etc.
train_and_evaluate__multiprocessing(args) # the training process will terminate once it reaches the target reward.
After reaching the target reward, we generate the frame for each state and compose frames as a video result. From the video, the walker is able to move forward constantly.
for i in range(1024): frame = gym_env.render('rgb_array') cv2.imwrite(f'{save_dir}/{i:06}.png', frame) states = torch.as_tensor((state,), dtype=torch.float32, device=device) actions = agent.act(states) action = actions.detach().cpu().numpy()[0] next_state, reward, done, _ = env.step(action) if done: state = env.reset() else: state = next_state
Check out the Colab codes for this BipedalWalker-v3 demo.
|
[
{
"code": null,
"e": 292,
"s": 171,
"text": "This article by Xiao-Yang Liu, Steven Li and Yiyan Zeng (J. Zheng) describes the ElegantRL library (Twitter and Github)."
},
{
"code": null,
"e": 613,
"s": 292,
"text": "One sentence summary of reinforcement learning (RL): in RL, an agent learns by continuously interacting with an environment, in a trial-and-error manner, making sequential decisions under uncertainty and achieving a balance between exploration (new territory) and exploitation (using knowledge learned from experiences)."
},
{
"code": null,
"e": 1079,
"s": 613,
"text": "Deep reinforcement learning (DRL) has great potential to solve real-world problems that are challenging to humans, such as self-driving cars, gaming, natural language processing (NLP), and financial trading. Starting from the success of AlphaGo, various DRL algorithms and applications are emerging in a disruptive manner. The ElegantRL library enables researchers and practitioners to pipeline the disruptive “design, development and deployment” of DRL technology."
},
{
"code": null,
"e": 1160,
"s": 1079,
"text": "The library to be presented is featured with “elegant” in the following aspects:"
},
{
"code": null,
"e": 1228,
"s": 1160,
"text": "Lightweight: core codes have less than 1,000 lines, e.g., tutorial."
},
{
"code": null,
"e": 1285,
"s": 1228,
"text": "Efficient: the performance is comparable with Ray RLlib."
},
{
"code": null,
"e": 1329,
"s": 1285,
"text": "Stable: more stable than Stable Baseline 3."
},
{
"code": null,
"e": 1480,
"s": 1329,
"text": "ElegantRL supports state-of-the-art DRL algorithms, including discrete and continuous ones, and provides user-friendly tutorials in Jupyter notebooks."
},
{
"code": null,
"e": 1756,
"s": 1480,
"text": "The ElegantRL implements DRL algorithms under the Actor-Critic framework, where an Agent (a.k.a, a DRL algorithm) consists of an Actor network and a Critic network. Due to the completeness and simplicity of code structure, users are able to easily customize their own agents."
},
{
"code": null,
"e": 1808,
"s": 1756,
"text": "The file structure of ElegantRL is shown in Fig. 1:"
},
{
"code": null,
"e": 1878,
"s": 1808,
"text": "Env.py: it contains the environments, with which the agent interacts."
},
{
"code": null,
"e": 1948,
"s": 1878,
"text": "Env.py: it contains the environments, with which the agent interacts."
},
{
"code": null,
"e": 2004,
"s": 1948,
"text": "A PreprocessEnv class for gym-environment modification."
},
{
"code": null,
"e": 2083,
"s": 2004,
"text": "A self-created stock trading environment as an example for user customization."
},
{
"code": null,
"e": 2129,
"s": 2083,
"text": "2. Net.py: There are three types of networks:"
},
{
"code": null,
"e": 2136,
"s": 2129,
"text": "Q-Net,"
},
{
"code": null,
"e": 2151,
"s": 2136,
"text": "Actor Network,"
},
{
"code": null,
"e": 2167,
"s": 2151,
"text": "Critic Network,"
},
{
"code": null,
"e": 2262,
"s": 2167,
"text": "Each includes a base network for inheritance and a set of variations for different algorithms."
},
{
"code": null,
"e": 2324,
"s": 2262,
"text": "3. Agent.py: it contains agents for different DRL algorithms."
},
{
"code": null,
"e": 2404,
"s": 2324,
"text": "4. Run.py: it provides basic functions for the training and evaluating process:"
},
{
"code": null,
"e": 2430,
"s": 2404,
"text": "Parameter initialization,"
},
{
"code": null,
"e": 2445,
"s": 2430,
"text": "Training loop,"
},
{
"code": null,
"e": 2456,
"s": 2445,
"text": "Evaluator."
},
{
"code": null,
"e": 2989,
"s": 2456,
"text": "As a high-level overview, the relations among the files are as follows. Initialize an environment in Env.py and an agent in Agent.py. The agent is constructed with Actor and Critic networks in Net.py. In each training step in Run.py, the agent interacts with the environment, generating transitions that are stored into a Replay Buffer. Then, the agent fetches transitions from the Replay Buffer to train its networks. After each update, an evaluator evaluates the agent’s performance and saves the agent if the performance is good."
},
{
"code": null,
"e": 3139,
"s": 2989,
"text": "This part describes DQN-series algorithms and DDPG-series algorithms, respectively. Each DRL algorithm agent follows a hierarchy from its base class."
},
{
"code": null,
"e": 3229,
"s": 3139,
"text": "As shown in Fig. 2, the inheritance hierarchy of the DQN-series algorithms is as follows:"
},
{
"code": null,
"e": 3261,
"s": 3229,
"text": "AgentDQN: a standard DQN agent."
},
{
"code": null,
"e": 3367,
"s": 3261,
"text": "AgentDoubleDQN: a Double-DQN agent with two Q-Nets for reducing overestimation, inheriting from AgentDQN."
},
{
"code": null,
"e": 3460,
"s": 3367,
"text": "AgentDuelingDQN: a DQN agent with a different Q-value calculation, inheriting from AgentDQN."
},
{
"code": null,
"e": 3556,
"s": 3460,
"text": "AgentD3QN: a combination of AgentDoubleDQN and AgentDuelingDQN, inheriting from AgentDoubleDQN."
},
{
"code": null,
"e": 4515,
"s": 3556,
"text": "class AgentBase: def init(self); def select_action(states); # states = (state, ...) def explore_env(env, buffer, target_step, reward_scale, gamma); def update_net(buffer, max_step, batch_size, repeat_times); def save_load_model(cwd, if_save); def soft_update(target_net, current_net);class AgentDQN: def init(net_dim, state_dim, action_dim); def select_action(states); # for discrete action space def explore_env(env, buffer, target_step, reward_scale, gamma); def update_net(buffer, max_step, batch_size, repeat_times); def save_or_load_model(cwd, if_save);class AgentDuelingDQN(AgentDQN): def init(net_dim, state_dim, action_dim);class AgentDoubleDQN(AgentDQN): def init(self, net_dim, state_dim, action_dim); def select_action(states); def update_net(buffer, max_step, batch_size, repeat_times);class AgentD3QN(AgentDoubleDQN): # D3QN: Dueling Double DQN def init(net_dim, state_dim, action_dim);"
},
{
"code": null,
"e": 4605,
"s": 4515,
"text": "As shown in Fig. 3, the inheritance hierarchy of the DDPG-series algorithms is as follows"
},
{
"code": null,
"e": 4658,
"s": 4605,
"text": "AgentBase: a base class for all Actor-Critic agents."
},
{
"code": null,
"e": 4710,
"s": 4658,
"text": "AgentDDPG: a DDPG agent, inheriting from AgentBase."
},
{
"code": null,
"e": 5182,
"s": 4710,
"text": "class AgentBase: def init(self); def select_action(states); # states = (state, ...) def explore_env(env, buffer, target_step, reward_scale, gamma); def update_net(buffer, max_step, batch_size, repeat_times); def save_load_model(cwd, if_save); def soft_update(target_net, current_net);class AgentDDPG(AgentBase): def init(net_dim, state_dim, action_dim); def select_action(states); def update_net(buffer, max_step, batch_size, repeat_times);"
},
{
"code": null,
"e": 5355,
"s": 5182,
"text": "Applying such a hierarchy in building DRL agents effectively improves lightweightness and effectiveness. Users can easily design and implement new agents in a similar flow."
},
{
"code": null,
"e": 5444,
"s": 5355,
"text": "Basically, an agent has two fundamental functions, and the data flow is shown in Fig. 4:"
},
{
"code": null,
"e": 5561,
"s": 5444,
"text": "explore_env(): it allows the agent to interact with the environment and generates transitions for training networks."
},
{
"code": null,
"e": 5688,
"s": 5561,
"text": "update_net(): it first fetches a batch of transitions from the Replay Buffer, and then train the network with backpropagation."
},
{
"code": null,
"e": 5723,
"s": 5688,
"text": "Two major steps to train an agent:"
},
{
"code": null,
"e": 5739,
"s": 5723,
"text": "Initialization:"
},
{
"code": null,
"e": 5755,
"s": 5739,
"text": "Initialization:"
},
{
"code": null,
"e": 5778,
"s": 5755,
"text": "hyper-parameters args."
},
{
"code": null,
"e": 5853,
"s": 5778,
"text": "env = PreprocessEnv() : creates an environment (in the OpenAI gym format)."
},
{
"code": null,
"e": 5912,
"s": 5853,
"text": "agent = AgentXXX() : creates an agent for a DRL algorithm."
},
{
"code": null,
"e": 5978,
"s": 5912,
"text": "evaluator = Evaluator() : evaluates and stores the trained model."
},
{
"code": null,
"e": 6028,
"s": 5978,
"text": "buffer = ReplayBuffer() : stores the transitions."
},
{
"code": null,
"e": 6089,
"s": 6028,
"text": "2. Then, the training process is controlled by a while-loop:"
},
{
"code": null,
"e": 6231,
"s": 6089,
"text": "agent.explore_env(...): the agent explores the environment within target steps, generates transitions, and stores them into the ReplayBuffer."
},
{
"code": null,
"e": 6333,
"s": 6231,
"text": "agent.update_net(...): the agent uses a batch from the ReplayBuffer to update the network parameters."
},
{
"code": null,
"e": 6449,
"s": 6333,
"text": "evaluator.evaluate_save(...): evaluates the agent’s performance and keeps the trained model with the highest score."
},
{
"code": null,
"e": 6575,
"s": 6449,
"text": "The while-loop will terminate when the conditions are met, e.g., achieving a target score, maximum steps, or manually breaks."
},
{
"code": null,
"e": 6894,
"s": 6575,
"text": "BipedalWalker-v3 is a classic task in robotics that performs a fundamental skill: moving. The goal is to get a 2D biped walker to walk through rough terrain. BipedalWalker is considered to be a difficult task in the continuous action space, and there are only a few RL implementations that can reach the target reward."
},
{
"code": null,
"e": 6958,
"s": 6894,
"text": "pip install git+https://github.com/AI4Finance-LLC/ElegantRL.git"
},
{
"code": null,
"e": 6968,
"s": 6958,
"text": "ElegantRL"
},
{
"code": null,
"e": 7054,
"s": 6968,
"text": "OpenAI Gym: a toolkit for developing and comparing reinforcement learning algorithms."
},
{
"code": null,
"e": 7137,
"s": 7054,
"text": "PyBullet Gym: an open-source implementation of the OpenAI Gym MuJoCo environments."
},
{
"code": null,
"e": 7293,
"s": 7137,
"text": "from elegantrl.run import *from elegantrl.agent import AgentGaePPOfrom elegantrl.env import PreprocessEnvimport gymgym.logger.set_level(40) # Block warning"
},
{
"code": null,
"e": 7406,
"s": 7293,
"text": "args.agent: firstly chooses a DRL algorithm, and the user is able to choose one from a set of agents in agent.py"
},
{
"code": null,
"e": 7578,
"s": 7406,
"text": "args.env: creates and preprocesses an environment, and the user can either customize own environment or preprocess environments from OpenAI Gym and PyBullet Gym in env.py."
},
{
"code": null,
"e": 7902,
"s": 7578,
"text": "args = Arguments(if_on_policy=False)args.agent = AgentGaePPO() # AgentSAC(), AgentTD3(), AgentDDPG()args.env = PreprocessEnv(env=gym.make(‘BipedalWalker-v3’))args.reward_scale = 2 ** -1 # RewardRange: -200 < -150 < 300 < 334args.gamma = 0.95args.rollout_num = 2 # the number of rollout workers (larger is not always faster)"
},
{
"code": null,
"e": 8074,
"s": 7902,
"text": "The training and evaluating processes are inside function train_and_evaluate__multiprocessing(args), and the parameter is args. It includes two fundamental objects in DRL:"
},
{
"code": null,
"e": 8081,
"s": 8074,
"text": "agent,"
},
{
"code": null,
"e": 8100,
"s": 8081,
"text": "environment (env)."
},
{
"code": null,
"e": 8133,
"s": 8100,
"text": "And the parameters for training:"
},
{
"code": null,
"e": 8145,
"s": 8133,
"text": "batch_size,"
},
{
"code": null,
"e": 8158,
"s": 8145,
"text": "target_step,"
},
{
"code": null,
"e": 8172,
"s": 8158,
"text": "reward_scale,"
},
{
"code": null,
"e": 8184,
"s": 8172,
"text": "gamma, etc."
},
{
"code": null,
"e": 8220,
"s": 8184,
"text": "Also the parameters for evaluation:"
},
{
"code": null,
"e": 8232,
"s": 8220,
"text": "break_step,"
},
{
"code": null,
"e": 8250,
"s": 8232,
"text": "random_seed, etc."
},
{
"code": null,
"e": 8365,
"s": 8250,
"text": "train_and_evaluate__multiprocessing(args) # the training process will terminate once it reaches the target reward."
},
{
"code": null,
"e": 8537,
"s": 8365,
"text": "After reaching the target reward, we generate the frame for each state and compose frames as a video result. From the video, the walker is able to move forward constantly."
},
{
"code": null,
"e": 8925,
"s": 8537,
"text": "for i in range(1024): frame = gym_env.render('rgb_array') cv2.imwrite(f'{save_dir}/{i:06}.png', frame) states = torch.as_tensor((state,), dtype=torch.float32, device=device) actions = agent.act(states) action = actions.detach().cpu().numpy()[0] next_state, reward, done, _ = env.step(action) if done: state = env.reset() else: state = next_state"
}
] |
Synonyms and Antonyms in Python. Text Mining — Extracting Synonyms and... | by Dhilip Subramanian | Towards Data Science
|
Language analysis can be carried out in many ways. In this blog, we will see how to extract Synonyms and Antonyms from the text using Natural Language Processing(NLTK) WordNet library.
The WordNet is a part of Python’s Natural Language Toolkit. It is a large collection of words and vocabulary from the English language that are related to each other and are grouped in some way. A collection of similar words is called lemmas. Also, It’s a combination of dictionary and thesaurus. It is used for automatic text analysis and artificial intelligence applications. It supports many other languages in its collection. Please check for more information about WordNet here
Nouns, verbs, adjectives, and adverbs are grouped into sets of cognitive synonyms (synsets), each expressing a distinct concept. Synsets are interlinked by means of conceptual-semantic and lexical relations. Let’s see some examples
Import NLTK library and install Wordnet
import nltknltk.download('wordnet')
In this example, we will see how wordnet returns meaning and other details of the word. Let’s go ahead and look up the word “travel”
Sometimes, if some examples are available, it may also provide that.
#Checking the word "Teaching"syn = wordnet.synsets(“teaching”)syn
[Synset('teaching.n.01'), Synset('teaching.n.02'), Synset('education.n.01'), Synset('teach.v.01'), Synset('teach.v.02')]
We can see that “TEACHING” has five meanings. Let’s find the first sense to get a better understanding of the kind of information each synset contains. We can do this by indexing the first element at its name. n, v represents Parts of speech tagging.
# Printing the Synonym, meaning and example of "teaching" for the first two indexes#First Indexprint(‘Word and Type : ‘ + syn[0].name())print(‘Synonym of teaching is: ‘ + syn[0].lemmas()[0].name())print(‘The meaning of the teaching: ‘ + syn[0].definition())print(‘Example of teaching : ‘ + str(syn[0].examples()))#Second Indexprint(‘Word and Type : ‘ + syn[1].name())print(‘Synonym of teaching is: ‘ + syn[1].lemmas()[0].name())print(‘The meaning of the teaching : ‘ + syn[1].definition())print(‘Example of teaching : ‘ + str(syn[1].examples()))
# Output for first indexWord and Type : teaching.n.01Synonym of Teaching is: teachingThe meaning of the Teaching: the profession of a teacherExample of Teaching : ['he prepared for teaching while still in college', 'pedagogy is recognized as an important profession']# Output for second indexWord and Type : teaching.n.02Synonym of Teaching is: teachingThe meaning of the Teaching : a doctrine that is taughtExample of Teaching : ['the teachings of religion', 'he believed all the Christian precepts']
We can use lemmas() function of the synset. It returns synonyms as well as antonyms of that particular synset.
#Checking synonym for the word "travel"from nltk.corpus import wordnet#Creating a list synonyms = []for syn in wordnet.synsets("travel"): for lm in syn.lemmas(): synonyms.append(lm.name())#adding into synonymsprint (set(synonyms))
{'trip', 'locomote', 'jaunt', 'change_of_location', 'go', 'traveling', 'travelling', 'locomotion', 'travel', 'move', 'journey', 'move_around'}
We can see the synonyms for the word ‘travel’ from the above output.
#Checking antonym for the word "increase"from nltk.corpus import wordnetantonyms = []for syn in wordnet.synsets("increase"): for lm in syn.lemmas(): if lm.antonyms(): antonyms.append(lm.antonyms()[0].name()) #adding into antonymsprint(set(antonyms))
{'decrement', 'decrease'}
WordNet has other feature called word similarity. It helps us check the similarity between two words that I didn’t cover in this blog.
Thanks for reading. Keep learning and stay tuned for more!
|
[
{
"code": null,
"e": 357,
"s": 172,
"text": "Language analysis can be carried out in many ways. In this blog, we will see how to extract Synonyms and Antonyms from the text using Natural Language Processing(NLTK) WordNet library."
},
{
"code": null,
"e": 840,
"s": 357,
"text": "The WordNet is a part of Python’s Natural Language Toolkit. It is a large collection of words and vocabulary from the English language that are related to each other and are grouped in some way. A collection of similar words is called lemmas. Also, It’s a combination of dictionary and thesaurus. It is used for automatic text analysis and artificial intelligence applications. It supports many other languages in its collection. Please check for more information about WordNet here"
},
{
"code": null,
"e": 1072,
"s": 840,
"text": "Nouns, verbs, adjectives, and adverbs are grouped into sets of cognitive synonyms (synsets), each expressing a distinct concept. Synsets are interlinked by means of conceptual-semantic and lexical relations. Let’s see some examples"
},
{
"code": null,
"e": 1112,
"s": 1072,
"text": "Import NLTK library and install Wordnet"
},
{
"code": null,
"e": 1148,
"s": 1112,
"text": "import nltknltk.download('wordnet')"
},
{
"code": null,
"e": 1281,
"s": 1148,
"text": "In this example, we will see how wordnet returns meaning and other details of the word. Let’s go ahead and look up the word “travel”"
},
{
"code": null,
"e": 1350,
"s": 1281,
"text": "Sometimes, if some examples are available, it may also provide that."
},
{
"code": null,
"e": 1416,
"s": 1350,
"text": "#Checking the word \"Teaching\"syn = wordnet.synsets(“teaching”)syn"
},
{
"code": null,
"e": 1537,
"s": 1416,
"text": "[Synset('teaching.n.01'), Synset('teaching.n.02'), Synset('education.n.01'), Synset('teach.v.01'), Synset('teach.v.02')]"
},
{
"code": null,
"e": 1788,
"s": 1537,
"text": "We can see that “TEACHING” has five meanings. Let’s find the first sense to get a better understanding of the kind of information each synset contains. We can do this by indexing the first element at its name. n, v represents Parts of speech tagging."
},
{
"code": null,
"e": 2334,
"s": 1788,
"text": "# Printing the Synonym, meaning and example of \"teaching\" for the first two indexes#First Indexprint(‘Word and Type : ‘ + syn[0].name())print(‘Synonym of teaching is: ‘ + syn[0].lemmas()[0].name())print(‘The meaning of the teaching: ‘ + syn[0].definition())print(‘Example of teaching : ‘ + str(syn[0].examples()))#Second Indexprint(‘Word and Type : ‘ + syn[1].name())print(‘Synonym of teaching is: ‘ + syn[1].lemmas()[0].name())print(‘The meaning of the teaching : ‘ + syn[1].definition())print(‘Example of teaching : ‘ + str(syn[1].examples()))"
},
{
"code": null,
"e": 2836,
"s": 2334,
"text": "# Output for first indexWord and Type : teaching.n.01Synonym of Teaching is: teachingThe meaning of the Teaching: the profession of a teacherExample of Teaching : ['he prepared for teaching while still in college', 'pedagogy is recognized as an important profession']# Output for second indexWord and Type : teaching.n.02Synonym of Teaching is: teachingThe meaning of the Teaching : a doctrine that is taughtExample of Teaching : ['the teachings of religion', 'he believed all the Christian precepts']"
},
{
"code": null,
"e": 2947,
"s": 2836,
"text": "We can use lemmas() function of the synset. It returns synonyms as well as antonyms of that particular synset."
},
{
"code": null,
"e": 3193,
"s": 2947,
"text": "#Checking synonym for the word \"travel\"from nltk.corpus import wordnet#Creating a list synonyms = []for syn in wordnet.synsets(\"travel\"): for lm in syn.lemmas(): synonyms.append(lm.name())#adding into synonymsprint (set(synonyms))"
},
{
"code": null,
"e": 3336,
"s": 3193,
"text": "{'trip', 'locomote', 'jaunt', 'change_of_location', 'go', 'traveling', 'travelling', 'locomotion', 'travel', 'move', 'journey', 'move_around'}"
},
{
"code": null,
"e": 3405,
"s": 3336,
"text": "We can see the synonyms for the word ‘travel’ from the above output."
},
{
"code": null,
"e": 3676,
"s": 3405,
"text": "#Checking antonym for the word \"increase\"from nltk.corpus import wordnetantonyms = []for syn in wordnet.synsets(\"increase\"): for lm in syn.lemmas(): if lm.antonyms(): antonyms.append(lm.antonyms()[0].name()) #adding into antonymsprint(set(antonyms))"
},
{
"code": null,
"e": 3702,
"s": 3676,
"text": "{'decrement', 'decrease'}"
},
{
"code": null,
"e": 3837,
"s": 3702,
"text": "WordNet has other feature called word similarity. It helps us check the similarity between two words that I didn’t cover in this blog."
}
] |
Count of ways to distribute N items among 3 people with one person receiving maximum - GeeksforGeeks
|
19 Jul, 2021
Given an integer N, the task is to find the total number of ways to distribute N among 3 people such that:
Exactly one person gets the maximum number of items among all the 3 people.
Each person gets at least 1 item.
Examples:
Input: N = 5 Output: 3 Explanation: 3 way distribute the item among 3 people are {1, 1, 3}, {1, 3, 1} and {3, 1, 1}. Distributions like {1, 2, 2} or {2, 1, 2} are not valid as two persons are getting the maximum.Input: N = 10 Output: 33 Explanation: For the Input N = 10 there are 33 ways of distribution.
Approach: To solve the problem mentioned above, we have to observe that if N < 4, then such a distribution is not possible. For all values of N ≥ 4, follow the steps to solve the problem:
Total no of ways to distribute N items among 3 people is given by (N – 1) * (N – 2) / 2.
Initialize a variable s = 0 which stores the count of ways the distribution is not possible.
Iterate two nested loops, where i ranges between [2, N – 3] and j ranging upto i: For each iteration, check if N = 2 * i + j, that is 2 persons can receive the maximum number of elementsIf so, then increment s by 1. If N is divisible by 3, update s by 3 * s + 1. Otherwise, update to 3 * s.
For each iteration, check if N = 2 * i + j, that is 2 persons can receive the maximum number of elements
If so, then increment s by 1. If N is divisible by 3, update s by 3 * s + 1. Otherwise, update to 3 * s.
Finally, return ans – s as the total number of ways to distribute N items among three people.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the number// of ways to distribute N item// among three people such// that one person always gets// the maximum value #include <bits/stdc++.h>using namespace std; // Function to find the number// of ways to distribute N// items among 3 peopleint countWays(int N){ // No distribution // possible if (N < 4) return 0; // Total number of ways to // distribute N items // among 3 people int ans = ((N - 1) * (N - 2)) / 2; // Store the number of // distributions which // are not possible int s = 0; for (int i = 2; i <= N - 3; i++) { for (int j = 1; j < i; j++) { // Count possibilities // of two persons // receiving the // maximum if (N == 2 * i + j) s++; } } // If N is divisible by 3 if (N % 3 == 0) s = 3 * s + 1; else s = 3 * s; // Return the final // count of ways // to distribute return ans - s;} // Driver Codeint main(){ int N = 10; cout << countWays(N); return 0;}
// Java program to find the number// of ways to distribute N item// among three people such// that one person always gets// the maximum valueclass GFG{ // Function to find the number// of ways to distribute N// items among 3 peoplestatic int countWays(int N){ // No distribution // possible if (N < 4) return 0; // Total number of ways to // distribute N items // among 3 people int ans = ((N - 1) * (N - 2)) / 2; // Store the number of // distributions which // are not possible int s = 0; for (int i = 2; i <= N - 3; i++) { for (int j = 1; j < i; j++) { // Count possibilities // of two persons // receiving the // maximum if (N == 2 * i + j) s++; } } // If N is divisible by 3 if (N % 3 == 0) s = 3 * s + 1; else s = 3 * s; // Return the final // count of ways // to distribute return ans - s;} // Driver Codepublic static void main(String[] args){ int N = 10; System.out.println(countWays(N));}} // This code is contributed by rock_cool
# Python3 program to find the number# of ways to distribute N item# among three people such# that one person always gets# the maximum value # Function to find the number# of ways to distribute N# items among 3 peopledef countWays(N): # No distribution # possible if (N < 4): return 0 # Total number of ways to # distribute N items # among 3 people ans = ((N - 1) * (N - 2)) // 2 # Store the number of # distributions which # are not possible s = 0 for i in range( 2, N - 2, 1): for j in range( 1, i, 1): # Count possibilities # of two persons # receiving the # maximum if (N == 2 * i + j): s += 1 # If N is divisible by 3 if (N % 3 == 0): s = 3 * s + 1 else: s = 3 * s # Return the final # count of ways # to distribute return ans - s # Driver CodeN = 10 print (countWays(N)) # This code is contributed by sanjoy_62
// C# program to find the number// of ways to distribute N item// among three people such// that one person always gets// the maximum valueusing System;class GFG{ // Function to find the number// of ways to distribute N// items among 3 peoplestatic int countWays(int N){ // No distribution // possible if (N < 4) return 0; // Total number of ways to // distribute N items // among 3 people int ans = ((N - 1) * (N - 2)) / 2; // Store the number of // distributions which // are not possible int s = 0; for (int i = 2; i <= N - 3; i++) { for (int j = 1; j < i; j++) { // Count possibilities // of two persons // receiving the // maximum if (N == 2 * i + j) s++; } } // If N is divisible by 3 if (N % 3 == 0) s = 3 * s + 1; else s = 3 * s; // Return the final // count of ways // to distribute return ans - s;} // Driver Codepublic static void Main(){ int N = 10; Console.Write(countWays(N));}} // This code is contributed by Code_Mech
<script> // Javascript program to find the number // of ways to distribute N item // among three people such // that one person always gets // the maximum value // Function to find the number // of ways to distribute N // items among 3 people function countWays(N) { // No distribution // possible if (N < 4) return 0; // Total number of ways to // distribute N items // among 3 people let ans = ((N - 1) * (N - 2)) / 2; // Store the number of // distributions which // are not possible let s = 0; for (let i = 2; i <= N - 3; i++) { for (let j = 1; j < i; j++) { // Count possibilities // of two persons // receiving the // maximum if (N == 2 * i + j) s++; } } // If N is divisible by 3 if (N % 3 == 0) s = 3 * s + 1; else s = 3 * s; // Return the final // count of ways // to distribute return ans - s; } let N = 10; document.write(countWays(N)); </script>
33
Time complexity: O(N2) Auxiliary Space: O(1)
rock_cool
Code_Mech
sanjoy_62
divyeshrabadiya07
varshagumber28
Permutation and Combination
Algorithms
Combinatorial
Competitive Programming
Mathematical
Mathematical
Combinatorial
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DSA Sheet by Love Babbar
Quadratic Probing in Hashing
K means Clustering - Introduction
SCAN (Elevator) Disk Scheduling Algorithms
Difference between Informed and Uninformed Search in AI
Write a program to print all permutations of a given string
Permutation and Combination in Python
itertools.combinations() module in Python to print all possible combinations
Count ways to reach the nth stair using step 1, 2 or 3
|
[
{
"code": null,
"e": 24612,
"s": 24584,
"text": "\n19 Jul, 2021"
},
{
"code": null,
"e": 24721,
"s": 24612,
"text": "Given an integer N, the task is to find the total number of ways to distribute N among 3 people such that: "
},
{
"code": null,
"e": 24797,
"s": 24721,
"text": "Exactly one person gets the maximum number of items among all the 3 people."
},
{
"code": null,
"e": 24831,
"s": 24797,
"text": "Each person gets at least 1 item."
},
{
"code": null,
"e": 24843,
"s": 24831,
"text": "Examples: "
},
{
"code": null,
"e": 25151,
"s": 24843,
"text": "Input: N = 5 Output: 3 Explanation: 3 way distribute the item among 3 people are {1, 1, 3}, {1, 3, 1} and {3, 1, 1}. Distributions like {1, 2, 2} or {2, 1, 2} are not valid as two persons are getting the maximum.Input: N = 10 Output: 33 Explanation: For the Input N = 10 there are 33 ways of distribution. "
},
{
"code": null,
"e": 25343,
"s": 25153,
"text": "Approach: To solve the problem mentioned above, we have to observe that if N < 4, then such a distribution is not possible. For all values of N ≥ 4, follow the steps to solve the problem: "
},
{
"code": null,
"e": 25432,
"s": 25343,
"text": "Total no of ways to distribute N items among 3 people is given by (N – 1) * (N – 2) / 2."
},
{
"code": null,
"e": 25525,
"s": 25432,
"text": "Initialize a variable s = 0 which stores the count of ways the distribution is not possible."
},
{
"code": null,
"e": 25816,
"s": 25525,
"text": "Iterate two nested loops, where i ranges between [2, N – 3] and j ranging upto i: For each iteration, check if N = 2 * i + j, that is 2 persons can receive the maximum number of elementsIf so, then increment s by 1. If N is divisible by 3, update s by 3 * s + 1. Otherwise, update to 3 * s."
},
{
"code": null,
"e": 25921,
"s": 25816,
"text": "For each iteration, check if N = 2 * i + j, that is 2 persons can receive the maximum number of elements"
},
{
"code": null,
"e": 26026,
"s": 25921,
"text": "If so, then increment s by 1. If N is divisible by 3, update s by 3 * s + 1. Otherwise, update to 3 * s."
},
{
"code": null,
"e": 26120,
"s": 26026,
"text": "Finally, return ans – s as the total number of ways to distribute N items among three people."
},
{
"code": null,
"e": 26172,
"s": 26120,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26176,
"s": 26172,
"text": "C++"
},
{
"code": null,
"e": 26181,
"s": 26176,
"text": "Java"
},
{
"code": null,
"e": 26189,
"s": 26181,
"text": "Python3"
},
{
"code": null,
"e": 26192,
"s": 26189,
"text": "C#"
},
{
"code": null,
"e": 26203,
"s": 26192,
"text": "Javascript"
},
{
"code": "// C++ program to find the number// of ways to distribute N item// among three people such// that one person always gets// the maximum value #include <bits/stdc++.h>using namespace std; // Function to find the number// of ways to distribute N// items among 3 peopleint countWays(int N){ // No distribution // possible if (N < 4) return 0; // Total number of ways to // distribute N items // among 3 people int ans = ((N - 1) * (N - 2)) / 2; // Store the number of // distributions which // are not possible int s = 0; for (int i = 2; i <= N - 3; i++) { for (int j = 1; j < i; j++) { // Count possibilities // of two persons // receiving the // maximum if (N == 2 * i + j) s++; } } // If N is divisible by 3 if (N % 3 == 0) s = 3 * s + 1; else s = 3 * s; // Return the final // count of ways // to distribute return ans - s;} // Driver Codeint main(){ int N = 10; cout << countWays(N); return 0;}",
"e": 27338,
"s": 26203,
"text": null
},
{
"code": "// Java program to find the number// of ways to distribute N item// among three people such// that one person always gets// the maximum valueclass GFG{ // Function to find the number// of ways to distribute N// items among 3 peoplestatic int countWays(int N){ // No distribution // possible if (N < 4) return 0; // Total number of ways to // distribute N items // among 3 people int ans = ((N - 1) * (N - 2)) / 2; // Store the number of // distributions which // are not possible int s = 0; for (int i = 2; i <= N - 3; i++) { for (int j = 1; j < i; j++) { // Count possibilities // of two persons // receiving the // maximum if (N == 2 * i + j) s++; } } // If N is divisible by 3 if (N % 3 == 0) s = 3 * s + 1; else s = 3 * s; // Return the final // count of ways // to distribute return ans - s;} // Driver Codepublic static void main(String[] args){ int N = 10; System.out.println(countWays(N));}} // This code is contributed by rock_cool",
"e": 28466,
"s": 27338,
"text": null
},
{
"code": "# Python3 program to find the number# of ways to distribute N item# among three people such# that one person always gets# the maximum value # Function to find the number# of ways to distribute N# items among 3 peopledef countWays(N): # No distribution # possible if (N < 4): return 0 # Total number of ways to # distribute N items # among 3 people ans = ((N - 1) * (N - 2)) // 2 # Store the number of # distributions which # are not possible s = 0 for i in range( 2, N - 2, 1): for j in range( 1, i, 1): # Count possibilities # of two persons # receiving the # maximum if (N == 2 * i + j): s += 1 # If N is divisible by 3 if (N % 3 == 0): s = 3 * s + 1 else: s = 3 * s # Return the final # count of ways # to distribute return ans - s # Driver CodeN = 10 print (countWays(N)) # This code is contributed by sanjoy_62",
"e": 29465,
"s": 28466,
"text": null
},
{
"code": "// C# program to find the number// of ways to distribute N item// among three people such// that one person always gets// the maximum valueusing System;class GFG{ // Function to find the number// of ways to distribute N// items among 3 peoplestatic int countWays(int N){ // No distribution // possible if (N < 4) return 0; // Total number of ways to // distribute N items // among 3 people int ans = ((N - 1) * (N - 2)) / 2; // Store the number of // distributions which // are not possible int s = 0; for (int i = 2; i <= N - 3; i++) { for (int j = 1; j < i; j++) { // Count possibilities // of two persons // receiving the // maximum if (N == 2 * i + j) s++; } } // If N is divisible by 3 if (N % 3 == 0) s = 3 * s + 1; else s = 3 * s; // Return the final // count of ways // to distribute return ans - s;} // Driver Codepublic static void Main(){ int N = 10; Console.Write(countWays(N));}} // This code is contributed by Code_Mech",
"e": 30586,
"s": 29465,
"text": null
},
{
"code": "<script> // Javascript program to find the number // of ways to distribute N item // among three people such // that one person always gets // the maximum value // Function to find the number // of ways to distribute N // items among 3 people function countWays(N) { // No distribution // possible if (N < 4) return 0; // Total number of ways to // distribute N items // among 3 people let ans = ((N - 1) * (N - 2)) / 2; // Store the number of // distributions which // are not possible let s = 0; for (let i = 2; i <= N - 3; i++) { for (let j = 1; j < i; j++) { // Count possibilities // of two persons // receiving the // maximum if (N == 2 * i + j) s++; } } // If N is divisible by 3 if (N % 3 == 0) s = 3 * s + 1; else s = 3 * s; // Return the final // count of ways // to distribute return ans - s; } let N = 10; document.write(countWays(N)); </script>",
"e": 31790,
"s": 30586,
"text": null
},
{
"code": null,
"e": 31793,
"s": 31790,
"text": "33"
},
{
"code": null,
"e": 31841,
"s": 31795,
"text": "Time complexity: O(N2) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 31851,
"s": 31841,
"text": "rock_cool"
},
{
"code": null,
"e": 31861,
"s": 31851,
"text": "Code_Mech"
},
{
"code": null,
"e": 31871,
"s": 31861,
"text": "sanjoy_62"
},
{
"code": null,
"e": 31889,
"s": 31871,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 31904,
"s": 31889,
"text": "varshagumber28"
},
{
"code": null,
"e": 31932,
"s": 31904,
"text": "Permutation and Combination"
},
{
"code": null,
"e": 31943,
"s": 31932,
"text": "Algorithms"
},
{
"code": null,
"e": 31957,
"s": 31943,
"text": "Combinatorial"
},
{
"code": null,
"e": 31981,
"s": 31957,
"text": "Competitive Programming"
},
{
"code": null,
"e": 31994,
"s": 31981,
"text": "Mathematical"
},
{
"code": null,
"e": 32007,
"s": 31994,
"text": "Mathematical"
},
{
"code": null,
"e": 32021,
"s": 32007,
"text": "Combinatorial"
},
{
"code": null,
"e": 32032,
"s": 32021,
"text": "Algorithms"
},
{
"code": null,
"e": 32130,
"s": 32032,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32139,
"s": 32130,
"text": "Comments"
},
{
"code": null,
"e": 32152,
"s": 32139,
"text": "Old Comments"
},
{
"code": null,
"e": 32177,
"s": 32152,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 32206,
"s": 32177,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 32240,
"s": 32206,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 32283,
"s": 32240,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 32339,
"s": 32283,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 32399,
"s": 32339,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 32437,
"s": 32399,
"text": "Permutation and Combination in Python"
},
{
"code": null,
"e": 32514,
"s": 32437,
"text": "itertools.combinations() module in Python to print all possible combinations"
}
] |
Python Pandas - Draw a Bar Plot and use median as the estimate of central tendency
|
Bar Plot in Seaborn is used to show point estimates and confidence intervals as rectangular bars. The seaborn.barplot() is used for this. Plotting horizontal bar plots with dataset columns as x and y values. Use the estimator parameter to set median as the estimate of central tendency.
Let’s say the following is our dataset in the form of a CSV file − Cricketers2.csv
At first, import the required libraries −
import seaborn as sb
import pandas as pd
import matplotlib.pyplot as plt
from numpy import median
Load data from a CSV file into a Pandas DataFrame −
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\Cricketers2.csv")
Plotting horizontal bar plots with Matches and Academy using the estimator parameter to set median as the estimate of central tendency −
sb.barplot(x = dataFrame["Academy"], y = dataFrame["Matches"], estimator = median)
Following is the code −
import seaborn as sb
import pandas as pd
import matplotlib.pyplot as plt
from numpy import median
# Load data from a CSV file into a Pandas DataFrame
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\Cricketers2.csv")
# plotting horizontal bar plots with Matches and Academy
# using the estimator parameter to set median as the estimate of central tendency
sb.barplot(x = dataFrame["Academy"], y = dataFrame["Matches"], estimator = median)
# display
plt.show()
This will produce the following output −
|
[
{
"code": null,
"e": 1349,
"s": 1062,
"text": "Bar Plot in Seaborn is used to show point estimates and confidence intervals as rectangular bars. The seaborn.barplot() is used for this. Plotting horizontal bar plots with dataset columns as x and y values. Use the estimator parameter to set median as the estimate of central tendency."
},
{
"code": null,
"e": 1432,
"s": 1349,
"text": "Let’s say the following is our dataset in the form of a CSV file − Cricketers2.csv"
},
{
"code": null,
"e": 1474,
"s": 1432,
"text": "At first, import the required libraries −"
},
{
"code": null,
"e": 1572,
"s": 1474,
"text": "import seaborn as sb\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom numpy import median"
},
{
"code": null,
"e": 1624,
"s": 1572,
"text": "Load data from a CSV file into a Pandas DataFrame −"
},
{
"code": null,
"e": 1695,
"s": 1624,
"text": "dataFrame = pd.read_csv(\"C:\\\\Users\\\\amit_\\\\Desktop\\\\Cricketers2.csv\")\n"
},
{
"code": null,
"e": 1832,
"s": 1695,
"text": "Plotting horizontal bar plots with Matches and Academy using the estimator parameter to set median as the estimate of central tendency −"
},
{
"code": null,
"e": 1915,
"s": 1832,
"text": "sb.barplot(x = dataFrame[\"Academy\"], y = dataFrame[\"Matches\"], estimator = median)"
},
{
"code": null,
"e": 1939,
"s": 1915,
"text": "Following is the code −"
},
{
"code": null,
"e": 2405,
"s": 1939,
"text": "import seaborn as sb\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom numpy import median\n\n# Load data from a CSV file into a Pandas DataFrame\ndataFrame = pd.read_csv(\"C:\\\\Users\\\\amit_\\\\Desktop\\\\Cricketers2.csv\")\n\n# plotting horizontal bar plots with Matches and Academy\n# using the estimator parameter to set median as the estimate of central tendency\nsb.barplot(x = dataFrame[\"Academy\"], y = dataFrame[\"Matches\"], estimator = median)\n\n# display\nplt.show()"
},
{
"code": null,
"e": 2446,
"s": 2405,
"text": "This will produce the following output −"
}
] |
SAP HANA - SQL Functions
|
There are various SQL functions provided by SAP HANA database −
Numeric Functions
String Functions
Fulltext Functions
Datetime Functions
Aggregate Functions
Data Type Conversion Functions
Window Functions
Series Data Functions
Miscellaneous Functions
These are inbuilt numeric functions in SQL and use in scripting. It takes numeric values or strings with numeric characters and return numeric values.
ABS − It returns the absolute value of a numeric argument.
ABS − It returns the absolute value of a numeric argument.
Example − SELECT ABS (-1) "abs" FROM TEST;
abs
1
ACOS, ASIN, ATAN, ATAN2 (These functions return trigonometric value of the argument)
BINTOHEX − It converts a Binary value to a hexadecimal value.
BINTOHEX − It converts a Binary value to a hexadecimal value.
BITAND − It performs an AND operation on bits of passed argument.
BITAND − It performs an AND operation on bits of passed argument.
BITCOUNT − It performs the count of number of set bits in an argument.
BITCOUNT − It performs the count of number of set bits in an argument.
BITNOT − It performs a bitwise NOT operation on the bits of argument.
BITNOT − It performs a bitwise NOT operation on the bits of argument.
BITOR − It perform an OR operation on bits of passed argument.
BITOR − It perform an OR operation on bits of passed argument.
BITSET − It is used to set bits to 1 in <target_num> from the <start_bit> position.
BITSET − It is used to set bits to 1 in <target_num> from the <start_bit> position.
BITUNSET − It is used to set bits to 0 in <target_num> from the <start_bit> position.
BITUNSET − It is used to set bits to 0 in <target_num> from the <start_bit> position.
BITXOR − It performs XOR operation on bits of passed argument.
BITXOR − It performs XOR operation on bits of passed argument.
CEIL − It returns the first integer that is greater or equal to the passed value.
CEIL − It returns the first integer that is greater or equal to the passed value.
COS, COSH, COT ((These functions return trigonometric value of the argument)
COS, COSH, COT ((These functions return trigonometric value of the argument)
EXP − It returns the result of the base of natural logarithms e raised to the power of passed value.
EXP − It returns the result of the base of natural logarithms e raised to the power of passed value.
FLOOR − It returns the largest integer not greater than the numeric argument.
FLOOR − It returns the largest integer not greater than the numeric argument.
HEXTOBIN − It converts a hexadecimal value to a binary value.
HEXTOBIN − It converts a hexadecimal value to a binary value.
LN − It returns the natural logarithm of the argument.
LN − It returns the natural logarithm of the argument.
LOG − It returns the algorithm value of a passed positive value. Both base and log value should be positive.
LOG − It returns the algorithm value of a passed positive value. Both base and log value should be positive.
Various other numeric functions can also be used − MOD, POWER, RAND, ROUND, SIGN, SIN, SINH, SQRT, TAN, TANH, UMINUS
Various SQL string functions can be used in HANA with SQL scripting. Most common string functions are −
ASCII − It returns integer ASCII value of passed string.
ASCII − It returns integer ASCII value of passed string.
CHAR − It returns the character associated with passed ASCII value.
CHAR − It returns the character associated with passed ASCII value.
CONCAT − It is Concatenation operator and returns the combined passed strings.
CONCAT − It is Concatenation operator and returns the combined passed strings.
LCASE − It converts all character of a string to Lower case.
LCASE − It converts all character of a string to Lower case.
LEFT − It returns the first characters of a passed string as per mentioned value.
LEFT − It returns the first characters of a passed string as per mentioned value.
LENGTH − It returns the number of characters in passed string.
LENGTH − It returns the number of characters in passed string.
LOCATE − It returns the position of substring within passed string.
LOCATE − It returns the position of substring within passed string.
LOWER − It converts all characters in string to lowercase.
LOWER − It converts all characters in string to lowercase.
NCHAR − It returns the Unicode character with passed integer value.
NCHAR − It returns the Unicode character with passed integer value.
REPLACE − It searches in passed original string for all occurrences of search string and replaces them with replace string.
REPLACE − It searches in passed original string for all occurrences of search string and replaces them with replace string.
RIGHT − It returns the rightmost passed value characters of mentioned string.
RIGHT − It returns the rightmost passed value characters of mentioned string.
UPPER − It converts all characters in passed string to uppercase.
UPPER − It converts all characters in passed string to uppercase.
UCASE − It is identical to UPPER function. It converts all characters in passed string to uppercase.
UCASE − It is identical to UPPER function. It converts all characters in passed string to uppercase.
Other string functions that can be used are − LPAD, LTRIM, RTRIM, STRTOBIN, SUBSTR_AFTER, SUBSTR_BEFORE, SUBSTRING, TRIM, UNICODE, RPAD, BINTOSTR
There are various Date Time functions that can be used in HANA in SQL scripts. Most common Date Time functions are −
CURRENT_DATE − It returns the current local system date.
CURRENT_DATE − It returns the current local system date.
CURRENT_TIME − It returns the current local system time.
CURRENT_TIME − It returns the current local system time.
CURRENT_TIMESTAMP − It returns the current local system timestamp details (YYYY-MM-DD HH:MM:SS:FF).
CURRENT_TIMESTAMP − It returns the current local system timestamp details (YYYY-MM-DD HH:MM:SS:FF).
CURRENT_UTCDATE − It returns current UTC (Greenwich Mean date) date.
CURRENT_UTCDATE − It returns current UTC (Greenwich Mean date) date.
CURRENT_UTCTIME − It returns current UTC (Greenwich Mean Time) time.
CURRENT_UTCTIME − It returns current UTC (Greenwich Mean Time) time.
CURRENT_UTCTIMESTAMP
CURRENT_UTCTIMESTAMP
DAYOFMONTH − It returns the integer value of day in passed date in argument.
DAYOFMONTH − It returns the integer value of day in passed date in argument.
HOUR − It returns integer value of hour in passed time in argument.
HOUR − It returns integer value of hour in passed time in argument.
YEAR − It returns the year value of passed date.
YEAR − It returns the year value of passed date.
Other Date Time functions are − DAYOFYEAR, DAYNAME, DAYS_BETWEEN, EXTRACT, NANO100_BETWEEN, NEXT_DAY, NOW, QUARTER, SECOND, SECONDS_BETWEEN, UTCTOLOCAL, WEEK, WEEKDAY, WORKDAYS_BETWEEN, ISOWEEK, LAST_DAY, LOCALTOUTC, MINUTE, MONTH, MONTHNAME, ADD_DAYS, ADD_MONTHS, ADD_SECONDS, ADD_WORKDAYS
These functions are used to convert one data type to other or to perform a check if conversion is possible or not.
Most common data type conversion functions used in HANA in SQL scripts −
CAST − It returns the value of an expression converted to a supplied data type.
CAST − It returns the value of an expression converted to a supplied data type.
TO_ALPHANUM − It converts a passed value to an ALPHANUM data type
TO_ALPHANUM − It converts a passed value to an ALPHANUM data type
TO_REAL − It converts a value to a REAL data type.
TO_REAL − It converts a value to a REAL data type.
TO_TIME − It converts a passed time string to the TIME data type.
TO_TIME − It converts a passed time string to the TIME data type.
TO_CLOB − It converts a value to a CLOB data type.
TO_CLOB − It converts a value to a CLOB data type.
Other similar Data Type conversion functions are − TO_BIGINT, TO_BINARY, TO_BLOB, TO_DATE, TO_DATS, TO_DECIMAL, TO_DOUBLE, TO_FIXEDCHAR, TO_INT, TO_INTEGER, TO_NCLOB, TO_NVARCHAR, TO_TIMESTAMP, TO_TINYINT, TO_VARCHAR, TO_SECONDDATE, TO_SMALLDECIMAL, TO_SMALLINT
There are also various Windows and other miscellaneous functions that can be used in HANA SQL scripts.
Current_Schema − It returns a string containing the current schema name.
Current_Schema − It returns a string containing the current schema name.
Session_User − It returns the user name of current session
Session_User − It returns the user name of current session
25 Lectures
6 hours
Sanjo Thomas
26 Lectures
2 hours
Neha Gupta
30 Lectures
2.5 hours
Sumit Agarwal
30 Lectures
4 hours
Sumit Agarwal
14 Lectures
1.5 hours
Neha Malik
13 Lectures
1.5 hours
Neha Malik
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3171,
"s": 3107,
"text": "There are various SQL functions provided by SAP HANA database −"
},
{
"code": null,
"e": 3189,
"s": 3171,
"text": "Numeric Functions"
},
{
"code": null,
"e": 3206,
"s": 3189,
"text": "String Functions"
},
{
"code": null,
"e": 3225,
"s": 3206,
"text": "Fulltext Functions"
},
{
"code": null,
"e": 3244,
"s": 3225,
"text": "Datetime Functions"
},
{
"code": null,
"e": 3264,
"s": 3244,
"text": "Aggregate Functions"
},
{
"code": null,
"e": 3295,
"s": 3264,
"text": "Data Type Conversion Functions"
},
{
"code": null,
"e": 3312,
"s": 3295,
"text": "Window Functions"
},
{
"code": null,
"e": 3334,
"s": 3312,
"text": "Series Data Functions"
},
{
"code": null,
"e": 3358,
"s": 3334,
"text": "Miscellaneous Functions"
},
{
"code": null,
"e": 3509,
"s": 3358,
"text": "These are inbuilt numeric functions in SQL and use in scripting. It takes numeric values or strings with numeric characters and return numeric values."
},
{
"code": null,
"e": 3568,
"s": 3509,
"text": "ABS − It returns the absolute value of a numeric argument."
},
{
"code": null,
"e": 3627,
"s": 3568,
"text": "ABS − It returns the absolute value of a numeric argument."
},
{
"code": null,
"e": 3676,
"s": 3627,
"text": "Example − SELECT ABS (-1) \"abs\" FROM TEST;\nabs\n1"
},
{
"code": null,
"e": 3761,
"s": 3676,
"text": "ACOS, ASIN, ATAN, ATAN2 (These functions return trigonometric value of the argument)"
},
{
"code": null,
"e": 3823,
"s": 3761,
"text": "BINTOHEX − It converts a Binary value to a hexadecimal value."
},
{
"code": null,
"e": 3885,
"s": 3823,
"text": "BINTOHEX − It converts a Binary value to a hexadecimal value."
},
{
"code": null,
"e": 3951,
"s": 3885,
"text": "BITAND − It performs an AND operation on bits of passed argument."
},
{
"code": null,
"e": 4017,
"s": 3951,
"text": "BITAND − It performs an AND operation on bits of passed argument."
},
{
"code": null,
"e": 4088,
"s": 4017,
"text": "BITCOUNT − It performs the count of number of set bits in an argument."
},
{
"code": null,
"e": 4159,
"s": 4088,
"text": "BITCOUNT − It performs the count of number of set bits in an argument."
},
{
"code": null,
"e": 4229,
"s": 4159,
"text": "BITNOT − It performs a bitwise NOT operation on the bits of argument."
},
{
"code": null,
"e": 4299,
"s": 4229,
"text": "BITNOT − It performs a bitwise NOT operation on the bits of argument."
},
{
"code": null,
"e": 4362,
"s": 4299,
"text": "BITOR − It perform an OR operation on bits of passed argument."
},
{
"code": null,
"e": 4425,
"s": 4362,
"text": "BITOR − It perform an OR operation on bits of passed argument."
},
{
"code": null,
"e": 4509,
"s": 4425,
"text": "BITSET − It is used to set bits to 1 in <target_num> from the <start_bit> position."
},
{
"code": null,
"e": 4593,
"s": 4509,
"text": "BITSET − It is used to set bits to 1 in <target_num> from the <start_bit> position."
},
{
"code": null,
"e": 4679,
"s": 4593,
"text": "BITUNSET − It is used to set bits to 0 in <target_num> from the <start_bit> position."
},
{
"code": null,
"e": 4765,
"s": 4679,
"text": "BITUNSET − It is used to set bits to 0 in <target_num> from the <start_bit> position."
},
{
"code": null,
"e": 4828,
"s": 4765,
"text": "BITXOR − It performs XOR operation on bits of passed argument."
},
{
"code": null,
"e": 4891,
"s": 4828,
"text": "BITXOR − It performs XOR operation on bits of passed argument."
},
{
"code": null,
"e": 4973,
"s": 4891,
"text": "CEIL − It returns the first integer that is greater or equal to the passed value."
},
{
"code": null,
"e": 5055,
"s": 4973,
"text": "CEIL − It returns the first integer that is greater or equal to the passed value."
},
{
"code": null,
"e": 5132,
"s": 5055,
"text": "COS, COSH, COT ((These functions return trigonometric value of the argument)"
},
{
"code": null,
"e": 5209,
"s": 5132,
"text": "COS, COSH, COT ((These functions return trigonometric value of the argument)"
},
{
"code": null,
"e": 5310,
"s": 5209,
"text": "EXP − It returns the result of the base of natural logarithms e raised to the power of passed value."
},
{
"code": null,
"e": 5411,
"s": 5310,
"text": "EXP − It returns the result of the base of natural logarithms e raised to the power of passed value."
},
{
"code": null,
"e": 5489,
"s": 5411,
"text": "FLOOR − It returns the largest integer not greater than the numeric argument."
},
{
"code": null,
"e": 5567,
"s": 5489,
"text": "FLOOR − It returns the largest integer not greater than the numeric argument."
},
{
"code": null,
"e": 5629,
"s": 5567,
"text": "HEXTOBIN − It converts a hexadecimal value to a binary value."
},
{
"code": null,
"e": 5691,
"s": 5629,
"text": "HEXTOBIN − It converts a hexadecimal value to a binary value."
},
{
"code": null,
"e": 5746,
"s": 5691,
"text": "LN − It returns the natural logarithm of the argument."
},
{
"code": null,
"e": 5801,
"s": 5746,
"text": "LN − It returns the natural logarithm of the argument."
},
{
"code": null,
"e": 5910,
"s": 5801,
"text": "LOG − It returns the algorithm value of a passed positive value. Both base and log value should be positive."
},
{
"code": null,
"e": 6019,
"s": 5910,
"text": "LOG − It returns the algorithm value of a passed positive value. Both base and log value should be positive."
},
{
"code": null,
"e": 6136,
"s": 6019,
"text": "Various other numeric functions can also be used − MOD, POWER, RAND, ROUND, SIGN, SIN, SINH, SQRT, TAN, TANH, UMINUS"
},
{
"code": null,
"e": 6240,
"s": 6136,
"text": "Various SQL string functions can be used in HANA with SQL scripting. Most common string functions are −"
},
{
"code": null,
"e": 6297,
"s": 6240,
"text": "ASCII − It returns integer ASCII value of passed string."
},
{
"code": null,
"e": 6354,
"s": 6297,
"text": "ASCII − It returns integer ASCII value of passed string."
},
{
"code": null,
"e": 6422,
"s": 6354,
"text": "CHAR − It returns the character associated with passed ASCII value."
},
{
"code": null,
"e": 6490,
"s": 6422,
"text": "CHAR − It returns the character associated with passed ASCII value."
},
{
"code": null,
"e": 6569,
"s": 6490,
"text": "CONCAT − It is Concatenation operator and returns the combined passed strings."
},
{
"code": null,
"e": 6648,
"s": 6569,
"text": "CONCAT − It is Concatenation operator and returns the combined passed strings."
},
{
"code": null,
"e": 6709,
"s": 6648,
"text": "LCASE − It converts all character of a string to Lower case."
},
{
"code": null,
"e": 6770,
"s": 6709,
"text": "LCASE − It converts all character of a string to Lower case."
},
{
"code": null,
"e": 6852,
"s": 6770,
"text": "LEFT − It returns the first characters of a passed string as per mentioned value."
},
{
"code": null,
"e": 6934,
"s": 6852,
"text": "LEFT − It returns the first characters of a passed string as per mentioned value."
},
{
"code": null,
"e": 6997,
"s": 6934,
"text": "LENGTH − It returns the number of characters in passed string."
},
{
"code": null,
"e": 7060,
"s": 6997,
"text": "LENGTH − It returns the number of characters in passed string."
},
{
"code": null,
"e": 7128,
"s": 7060,
"text": "LOCATE − It returns the position of substring within passed string."
},
{
"code": null,
"e": 7196,
"s": 7128,
"text": "LOCATE − It returns the position of substring within passed string."
},
{
"code": null,
"e": 7255,
"s": 7196,
"text": "LOWER − It converts all characters in string to lowercase."
},
{
"code": null,
"e": 7314,
"s": 7255,
"text": "LOWER − It converts all characters in string to lowercase."
},
{
"code": null,
"e": 7382,
"s": 7314,
"text": "NCHAR − It returns the Unicode character with passed integer value."
},
{
"code": null,
"e": 7450,
"s": 7382,
"text": "NCHAR − It returns the Unicode character with passed integer value."
},
{
"code": null,
"e": 7574,
"s": 7450,
"text": "REPLACE − It searches in passed original string for all occurrences of search string and replaces them with replace string."
},
{
"code": null,
"e": 7698,
"s": 7574,
"text": "REPLACE − It searches in passed original string for all occurrences of search string and replaces them with replace string."
},
{
"code": null,
"e": 7776,
"s": 7698,
"text": "RIGHT − It returns the rightmost passed value characters of mentioned string."
},
{
"code": null,
"e": 7854,
"s": 7776,
"text": "RIGHT − It returns the rightmost passed value characters of mentioned string."
},
{
"code": null,
"e": 7920,
"s": 7854,
"text": "UPPER − It converts all characters in passed string to uppercase."
},
{
"code": null,
"e": 7986,
"s": 7920,
"text": "UPPER − It converts all characters in passed string to uppercase."
},
{
"code": null,
"e": 8087,
"s": 7986,
"text": "UCASE − It is identical to UPPER function. It converts all characters in passed string to uppercase."
},
{
"code": null,
"e": 8188,
"s": 8087,
"text": "UCASE − It is identical to UPPER function. It converts all characters in passed string to uppercase."
},
{
"code": null,
"e": 8334,
"s": 8188,
"text": "Other string functions that can be used are − LPAD, LTRIM, RTRIM, STRTOBIN, SUBSTR_AFTER, SUBSTR_BEFORE, SUBSTRING, TRIM, UNICODE, RPAD, BINTOSTR"
},
{
"code": null,
"e": 8451,
"s": 8334,
"text": "There are various Date Time functions that can be used in HANA in SQL scripts. Most common Date Time functions are −"
},
{
"code": null,
"e": 8508,
"s": 8451,
"text": "CURRENT_DATE − It returns the current local system date."
},
{
"code": null,
"e": 8565,
"s": 8508,
"text": "CURRENT_DATE − It returns the current local system date."
},
{
"code": null,
"e": 8622,
"s": 8565,
"text": "CURRENT_TIME − It returns the current local system time."
},
{
"code": null,
"e": 8679,
"s": 8622,
"text": "CURRENT_TIME − It returns the current local system time."
},
{
"code": null,
"e": 8779,
"s": 8679,
"text": "CURRENT_TIMESTAMP − It returns the current local system timestamp details (YYYY-MM-DD HH:MM:SS:FF)."
},
{
"code": null,
"e": 8879,
"s": 8779,
"text": "CURRENT_TIMESTAMP − It returns the current local system timestamp details (YYYY-MM-DD HH:MM:SS:FF)."
},
{
"code": null,
"e": 8948,
"s": 8879,
"text": "CURRENT_UTCDATE − It returns current UTC (Greenwich Mean date) date."
},
{
"code": null,
"e": 9017,
"s": 8948,
"text": "CURRENT_UTCDATE − It returns current UTC (Greenwich Mean date) date."
},
{
"code": null,
"e": 9086,
"s": 9017,
"text": "CURRENT_UTCTIME − It returns current UTC (Greenwich Mean Time) time."
},
{
"code": null,
"e": 9155,
"s": 9086,
"text": "CURRENT_UTCTIME − It returns current UTC (Greenwich Mean Time) time."
},
{
"code": null,
"e": 9176,
"s": 9155,
"text": "CURRENT_UTCTIMESTAMP"
},
{
"code": null,
"e": 9197,
"s": 9176,
"text": "CURRENT_UTCTIMESTAMP"
},
{
"code": null,
"e": 9274,
"s": 9197,
"text": "DAYOFMONTH − It returns the integer value of day in passed date in argument."
},
{
"code": null,
"e": 9351,
"s": 9274,
"text": "DAYOFMONTH − It returns the integer value of day in passed date in argument."
},
{
"code": null,
"e": 9419,
"s": 9351,
"text": "HOUR − It returns integer value of hour in passed time in argument."
},
{
"code": null,
"e": 9487,
"s": 9419,
"text": "HOUR − It returns integer value of hour in passed time in argument."
},
{
"code": null,
"e": 9536,
"s": 9487,
"text": "YEAR − It returns the year value of passed date."
},
{
"code": null,
"e": 9585,
"s": 9536,
"text": "YEAR − It returns the year value of passed date."
},
{
"code": null,
"e": 9876,
"s": 9585,
"text": "Other Date Time functions are − DAYOFYEAR, DAYNAME, DAYS_BETWEEN, EXTRACT, NANO100_BETWEEN, NEXT_DAY, NOW, QUARTER, SECOND, SECONDS_BETWEEN, UTCTOLOCAL, WEEK, WEEKDAY, WORKDAYS_BETWEEN, ISOWEEK, LAST_DAY, LOCALTOUTC, MINUTE, MONTH, MONTHNAME, ADD_DAYS, ADD_MONTHS, ADD_SECONDS, ADD_WORKDAYS"
},
{
"code": null,
"e": 9991,
"s": 9876,
"text": "These functions are used to convert one data type to other or to perform a check if conversion is possible or not."
},
{
"code": null,
"e": 10064,
"s": 9991,
"text": "Most common data type conversion functions used in HANA in SQL scripts −"
},
{
"code": null,
"e": 10144,
"s": 10064,
"text": "CAST − It returns the value of an expression converted to a supplied data type."
},
{
"code": null,
"e": 10224,
"s": 10144,
"text": "CAST − It returns the value of an expression converted to a supplied data type."
},
{
"code": null,
"e": 10290,
"s": 10224,
"text": "TO_ALPHANUM − It converts a passed value to an ALPHANUM data type"
},
{
"code": null,
"e": 10356,
"s": 10290,
"text": "TO_ALPHANUM − It converts a passed value to an ALPHANUM data type"
},
{
"code": null,
"e": 10407,
"s": 10356,
"text": "TO_REAL − It converts a value to a REAL data type."
},
{
"code": null,
"e": 10458,
"s": 10407,
"text": "TO_REAL − It converts a value to a REAL data type."
},
{
"code": null,
"e": 10524,
"s": 10458,
"text": "TO_TIME − It converts a passed time string to the TIME data type."
},
{
"code": null,
"e": 10590,
"s": 10524,
"text": "TO_TIME − It converts a passed time string to the TIME data type."
},
{
"code": null,
"e": 10641,
"s": 10590,
"text": "TO_CLOB − It converts a value to a CLOB data type."
},
{
"code": null,
"e": 10692,
"s": 10641,
"text": "TO_CLOB − It converts a value to a CLOB data type."
},
{
"code": null,
"e": 10954,
"s": 10692,
"text": "Other similar Data Type conversion functions are − TO_BIGINT, TO_BINARY, TO_BLOB, TO_DATE, TO_DATS, TO_DECIMAL, TO_DOUBLE, TO_FIXEDCHAR, TO_INT, TO_INTEGER, TO_NCLOB, TO_NVARCHAR, TO_TIMESTAMP, TO_TINYINT, TO_VARCHAR, TO_SECONDDATE, TO_SMALLDECIMAL, TO_SMALLINT"
},
{
"code": null,
"e": 11057,
"s": 10954,
"text": "There are also various Windows and other miscellaneous functions that can be used in HANA SQL scripts."
},
{
"code": null,
"e": 11130,
"s": 11057,
"text": "Current_Schema − It returns a string containing the current schema name."
},
{
"code": null,
"e": 11203,
"s": 11130,
"text": "Current_Schema − It returns a string containing the current schema name."
},
{
"code": null,
"e": 11262,
"s": 11203,
"text": "Session_User − It returns the user name of current session"
},
{
"code": null,
"e": 11321,
"s": 11262,
"text": "Session_User − It returns the user name of current session"
},
{
"code": null,
"e": 11354,
"s": 11321,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 11368,
"s": 11354,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 11401,
"s": 11368,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 11413,
"s": 11401,
"text": " Neha Gupta"
},
{
"code": null,
"e": 11448,
"s": 11413,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 11463,
"s": 11448,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 11496,
"s": 11463,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 11511,
"s": 11496,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 11546,
"s": 11511,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 11558,
"s": 11546,
"text": " Neha Malik"
},
{
"code": null,
"e": 11593,
"s": 11558,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 11605,
"s": 11593,
"text": " Neha Malik"
},
{
"code": null,
"e": 11612,
"s": 11605,
"text": " Print"
},
{
"code": null,
"e": 11623,
"s": 11612,
"text": " Add Notes"
}
] |
How to read data from *.CSV file using JavaScript?
|
To read .CSV using JavaScript, use the open-source CSV parser, Papa Parser. The following are the features −
Open Source
Parse millions of data using multi-threaded CSV parser
Supports multiple web browsers
Using the parser, you can easily skip commented characters
Let’s say your CSV file isn’t on your system. What will you do? Well, just use the following code snippet to get the file to parse from any link −
Papa.parse("http://example.com/myfile.csv", {
download: true,
complete: function(results) {
document.write(results);
}
});
|
[
{
"code": null,
"e": 1171,
"s": 1062,
"text": "To read .CSV using JavaScript, use the open-source CSV parser, Papa Parser. The following are the features −"
},
{
"code": null,
"e": 1183,
"s": 1171,
"text": "Open Source"
},
{
"code": null,
"e": 1238,
"s": 1183,
"text": "Parse millions of data using multi-threaded CSV parser"
},
{
"code": null,
"e": 1269,
"s": 1238,
"text": "Supports multiple web browsers"
},
{
"code": null,
"e": 1328,
"s": 1269,
"text": "Using the parser, you can easily skip commented characters"
},
{
"code": null,
"e": 1475,
"s": 1328,
"text": "Let’s say your CSV file isn’t on your system. What will you do? Well, just use the following code snippet to get the file to parse from any link −"
},
{
"code": null,
"e": 1614,
"s": 1475,
"text": "Papa.parse(\"http://example.com/myfile.csv\", {\n\n download: true,\n complete: function(results) {\n document.write(results);\n }\n});"
}
] |
NavigationView in ActionBar in Android
|
Before getting into the Navigation view example, we should know about navigation view. Navigation view is just like a sliding menu in HTML. Navigation view is extended by navigatoin drawer. Most of use cases of Navigation view is used to redirect different activities or show profile information.
This example demonstrate about how to integrate NavigationView in ActionBar
Step 1 − Create a new project in Android Studio,go to File ⇒ New Project and fill all required details to create a new project.
Step2 − While creating project we should select Navigation drawer activity as shown below
After selecting navigation drawer activity click on next button to finish project creation.
Step3 − Open your project structure for layout folder. Android studio generates different layout as shown below
activity_main.xml − It is a MainActivity layout. It going to create drawer layout as a parent layout and child layout contains navigationview as shown below
<?xml version = "1.0" encoding = "utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id = "@+id/drawer_layout"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:fitsSystemWindows = "true"
tools:openDrawer = "start">
<include
layout = "@layout/app_bar_main"
android:layout_width = "match_parent"
android:layout_height = "match_parent" />
<android.support.design.widget.NavigationView
android:id = "@+id/nav_view"
android:layout_width = "wrap_content"
android:layout_height = "match_parent"
android:layout_gravity = "start"
android:fitsSystemWindows = "true"
app:headerLayout = "@layout/nav_header_main"
app:menu = "@menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
In the navigationview it contains two layouts as Header Layout and menu layout. Header layout contains information about header of navigationview and menu layout is contains information about menu list.
app_bar_main.xml − It is layout file as we see normal layout. But it contains information about app bar layout( action bar) , center layout.
<?xml version = "1.0" encoding = "utf-8"?>
<android.support.design.widget.CoordinatorLayout 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">
<android.support.design.widget.AppBarLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:theme = "@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id = "@+id/toolbar"
android:layout_width = "match_parent"
android:layout_height = "?attr/actionBarSize"
android:background = "?attr/colorPrimary"
app:popupTheme = "@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout = "@layout/content_main" />
</android.support.design.widget.CoordinatorLayout>
In the above layout we have included content_main layout. it is mainlayout where user can customize own views as shown below
<?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"
app:layout_behavior = "@string/appbar_scrolling_view_behavior"
tools:context = ".MainActivity"
tools:showIn = "@layout/app_bar_main">
<TextView
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Hello World!"
app:layout_constraintBottom_toBottomOf = "parent"
app:layout_constraintLeft_toLeftOf = "parent"
app:layout_constraintRight_toRightOf = "parent"
app:layout_constraintTop_toTopOf = "parent" />
</android.support.constraint.ConstraintLayout>
nav_header_main − It is a navigation header view, it contains information about navigation header. we have customized navigation header as shown below
<?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"
android:layout_width = "match_parent"
android:layout_height = "@dimen/nav_header_height"
android:background = "@drawable/side_nav_bar"
android:gravity = "bottom"
android:orientation = "vertical"
android:paddingLeft = "@dimen/activity_horizontal_margin"
android:paddingTop = "@dimen/activity_vertical_margin"
android:paddingRight = "@dimen/activity_horizontal_margin"
android:paddingBottom = "@dimen/activity_vertical_margin"
android:theme = "@style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id = "@+id/imageView"
android:layout_width = "wrap_content"
android:layout_height = "100dp"
android:contentDescription = "@string/nav_header_desc"
android:paddingTop = "@dimen/nav_header_vertical_spacing"
app:srcCompat = "@drawable/logo" />
<TextView
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:paddingTop = "@dimen/nav_header_vertical_spacing"
android:textColor = "#FFF"
android:textStyle = "bold"
android:text = "Tutorials Point"
android:textAppearance = "@style/TextAppearance.AppCompat.Body1" />
<TextView
android:id = "@+id/textView"
android:textColor = "#FFF"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Father of all educational website" />
</LinearLayout>
Note − we have added drawable/logo, while your are developing application please add your own logo.
activity_main_drawer − It is a menu layout which is available at menu/activity_main_drawer.xml as shown below
<?xml version = "1.0" encoding = "utf-8"?>
<menu xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
tools:showIn = "navigation_view">
<group android:checkableBehavior = "single">
<item
android:id = "@+id/nav_camera"
android:icon = "@drawable/ic_menu_camera"
android:title = "Import" />
<item
android:id = "@+id/nav_gallery"
android:icon = "@drawable/ic_menu_gallery"
android:title = "Gallery" />
<item
android:id = "@+id/nav_slideshow"
android:icon = "@drawable/ic_menu_slideshow"
android:title = "Slideshow" />
<item
android:id = "@+id/nav_manage"
android:icon = "@drawable/ic_menu_manage"
android:title = "Tools" />
</group>
<item android:title = "Communicate">
<menu>
<item
android:id = "@+id/nav_share"
android:icon = "@drawable/ic_menu_share"
android:title = "Share" />
<item
android:id = "@+id/nav_send"
android:icon = "@drawable/ic_menu_send"
android:title = "Send" />
</menu>
</item>
</menu>
Step 4 − Add the following code to src/MainActivity.java
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
To close navigation view, we have to close drawer as shown below
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
To change navigationview position, user the following code
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.END);
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": 1359,
"s": 1062,
"text": "Before getting into the Navigation view example, we should know about navigation view. Navigation view is just like a sliding menu in HTML. Navigation view is extended by navigatoin drawer. Most of use cases of Navigation view is used to redirect different activities or show profile information."
},
{
"code": null,
"e": 1435,
"s": 1359,
"text": "This example demonstrate about how to integrate NavigationView in ActionBar"
},
{
"code": null,
"e": 1563,
"s": 1435,
"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": 1653,
"s": 1563,
"text": "Step2 − While creating project we should select Navigation drawer activity as shown below"
},
{
"code": null,
"e": 1745,
"s": 1653,
"text": "After selecting navigation drawer activity click on next button to finish project creation."
},
{
"code": null,
"e": 1857,
"s": 1745,
"text": "Step3 − Open your project structure for layout folder. Android studio generates different layout as shown below"
},
{
"code": null,
"e": 2014,
"s": 1857,
"text": "activity_main.xml − It is a MainActivity layout. It going to create drawer layout as a parent layout and child layout contains navigationview as shown below"
},
{
"code": null,
"e": 2993,
"s": 2014,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.v4.widget.DrawerLayout 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:id = \"@+id/drawer_layout\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:fitsSystemWindows = \"true\"\n tools:openDrawer = \"start\">\n <include\n layout = \"@layout/app_bar_main\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n <android.support.design.widget.NavigationView\n android:id = \"@+id/nav_view\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"match_parent\"\n android:layout_gravity = \"start\"\n android:fitsSystemWindows = \"true\"\n app:headerLayout = \"@layout/nav_header_main\"\n app:menu = \"@menu/activity_main_drawer\" />\n</android.support.v4.widget.DrawerLayout>"
},
{
"code": null,
"e": 3196,
"s": 2993,
"text": "In the navigationview it contains two layouts as Header Layout and menu layout. Header layout contains information about header of navigationview and menu layout is contains information about menu list."
},
{
"code": null,
"e": 3337,
"s": 3196,
"text": "app_bar_main.xml − It is layout file as we see normal layout. But it contains information about app bar layout( action bar) , center layout."
},
{
"code": null,
"e": 4329,
"s": 3337,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.design.widget.CoordinatorLayout 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 <android.support.design.widget.AppBarLayout\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:theme = \"@style/AppTheme.AppBarOverlay\">\n <android.support.v7.widget.Toolbar\n android:id = \"@+id/toolbar\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"?attr/actionBarSize\"\n android:background = \"?attr/colorPrimary\"\n app:popupTheme = \"@style/AppTheme.PopupOverlay\" />\n </android.support.design.widget.AppBarLayout>\n <include layout = \"@layout/content_main\" />\n</android.support.design.widget.CoordinatorLayout>"
},
{
"code": null,
"e": 4454,
"s": 4329,
"text": "In the above layout we have included content_main layout. it is mainlayout where user can customize own views as shown below"
},
{
"code": null,
"e": 5338,
"s": 4454,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout 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 app:layout_behavior = \"@string/appbar_scrolling_view_behavior\"\n tools:context = \".MainActivity\"\n tools:showIn = \"@layout/app_bar_main\">\n <TextView\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:text = \"Hello World!\"\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": 5489,
"s": 5338,
"text": "nav_header_main − It is a navigation header view, it contains information about navigation header. we have customized navigation header as shown below"
},
{
"code": null,
"e": 7063,
"s": 5489,
"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 android:layout_width = \"match_parent\"\n android:layout_height = \"@dimen/nav_header_height\"\n android:background = \"@drawable/side_nav_bar\"\n android:gravity = \"bottom\"\n android:orientation = \"vertical\"\n android:paddingLeft = \"@dimen/activity_horizontal_margin\"\n android:paddingTop = \"@dimen/activity_vertical_margin\"\n android:paddingRight = \"@dimen/activity_horizontal_margin\"\n android:paddingBottom = \"@dimen/activity_vertical_margin\"\n android:theme = \"@style/ThemeOverlay.AppCompat.Dark\">\n <ImageView\n android:id = \"@+id/imageView\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"100dp\"\n android:contentDescription = \"@string/nav_header_desc\"\n android:paddingTop = \"@dimen/nav_header_vertical_spacing\"\n app:srcCompat = \"@drawable/logo\" />\n <TextView\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:paddingTop = \"@dimen/nav_header_vertical_spacing\"\n android:textColor = \"#FFF\"\n android:textStyle = \"bold\"\n android:text = \"Tutorials Point\"\n android:textAppearance = \"@style/TextAppearance.AppCompat.Body1\" />\n <TextView\n android:id = \"@+id/textView\"\n android:textColor = \"#FFF\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:text = \"Father of all educational website\" />\n</LinearLayout>"
},
{
"code": null,
"e": 7163,
"s": 7063,
"text": "Note − we have added drawable/logo, while your are developing application please add your own logo."
},
{
"code": null,
"e": 7273,
"s": 7163,
"text": "activity_main_drawer − It is a menu layout which is available at menu/activity_main_drawer.xml as shown below"
},
{
"code": null,
"e": 8484,
"s": 7273,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<menu xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n tools:showIn = \"navigation_view\">\n <group android:checkableBehavior = \"single\">\n <item\n android:id = \"@+id/nav_camera\"\n android:icon = \"@drawable/ic_menu_camera\"\n android:title = \"Import\" />\n <item\n android:id = \"@+id/nav_gallery\"\n android:icon = \"@drawable/ic_menu_gallery\"\n android:title = \"Gallery\" />\n <item\n android:id = \"@+id/nav_slideshow\"\n android:icon = \"@drawable/ic_menu_slideshow\"\n android:title = \"Slideshow\" />\n <item\n android:id = \"@+id/nav_manage\"\n android:icon = \"@drawable/ic_menu_manage\"\n android:title = \"Tools\" />\n </group>\n <item android:title = \"Communicate\">\n <menu>\n <item\n android:id = \"@+id/nav_share\"\n android:icon = \"@drawable/ic_menu_share\"\n android:title = \"Share\" />\n <item\n android:id = \"@+id/nav_send\"\n android:icon = \"@drawable/ic_menu_send\"\n android:title = \"Send\" />\n </menu>\n </item>\n</menu>"
},
{
"code": null,
"e": 8541,
"s": 8484,
"text": "Step 4 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 11488,
"s": 8541,
"text": "import android.os.Bundle;\nimport android.support.design.widget.FloatingActionButton;\nimport android.support.design.widget.Snackbar;\nimport android.view.View;\nimport android.support.design.widget.NavigationView;\nimport android.support.v4.view.GravityCompat;\nimport android.support.v4.widget.DrawerLayout;\nimport android.support.v7.app.ActionBarDrawerToggle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.Toolbar;\nimport android.view.Menu;\nimport android.view.MenuItem;\npublic class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);\n setSupportActionBar(toolbar);\n DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);\n ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(\n this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);\n drawer.addDrawerListener(toggle);\n toggle.syncState();\n NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);\n navigationView.setNavigationItemSelectedListener(this);\n }\n @Override\n public void onBackPressed() {\n DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);\n if (drawer.isDrawerOpen(GravityCompat.START)) {\n drawer.closeDrawer(GravityCompat.START);\n } else {\n super.onBackPressed();\n }\n }\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n // Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n // Handle action bar item clicks here. The action bar will\n // automatically handle clicks on the Home/Up button, so long\n // as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n //noinspection SimplifiableIfStatement\n if (id == R.id.action_settings) {\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n @SuppressWarnings(\"StatementWithEmptyBody\")\n @Override\n public boolean onNavigationItemSelected(MenuItem item) {\n // Handle navigation view item clicks here.\n int id = item.getItemId();\n if (id == R.id.nav_camera) {\n // Handle the camera action\n } else if (id == R.id.nav_gallery) {\n } else if (id == R.id.nav_slideshow) {\n } else if (id == R.id.nav_manage) {\n } else if (id == R.id.nav_share) {\n } else if (id == R.id.nav_send) {\n }\n DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);\n drawer.closeDrawer(GravityCompat.START);\n return true;\n }\n}"
},
{
"code": null,
"e": 11553,
"s": 11488,
"text": "To close navigation view, we have to close drawer as shown below"
},
{
"code": null,
"e": 11647,
"s": 11553,
"text": "if (drawer.isDrawerOpen(GravityCompat.START)) {\n drawer.closeDrawer(GravityCompat.START);\n}"
},
{
"code": null,
"e": 11706,
"s": 11647,
"text": "To change navigationview position, user the following code"
},
{
"code": null,
"e": 11816,
"s": 11706,
"text": "DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);\ndrawer.closeDrawer(GravityCompat.END);"
},
{
"code": null,
"e": 12162,
"s": 11816,
"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": 12202,
"s": 12162,
"text": "Click here to download the project code"
}
] |
C Program to Multiply two Floating Point Numbers?
|
Float is a shortened term for "floating-point." By definition, it's a fundamental data type built into the compiler that's used to define numeric values with floating decimal points. A floating-point type variable is a variable that can hold a real number, such as 4320.0, -3.33, or 0.01226. The floating part of the name floating point refers to the fact that the decimal point can “float”; that is, it can support a variable number of digits before and after the decimal point.
Input − a=11.23 b=6.7
Output − 75.241
Explanation − Use of Float variables. In this program, the user has two numbers (floating point numbers)means float variables. Then, the product of those two numbers is stored in a variable and displayed on the screen.
#include <stdio.h>
int main() {
float a, b, c;
a=11.23; b=6.7;
c = (float)(a*b);
// Displaying result up to 3 decimal places.
printf("%3f", c);
return 0;
}
75.241
|
[
{
"code": null,
"e": 1542,
"s": 1062,
"text": "Float is a shortened term for \"floating-point.\" By definition, it's a fundamental data type built into the compiler that's used to define numeric values with floating decimal points. A floating-point type variable is a variable that can hold a real number, such as 4320.0, -3.33, or 0.01226. The floating part of the name floating point refers to the fact that the decimal point can “float”; that is, it can support a variable number of digits before and after the decimal point."
},
{
"code": null,
"e": 1565,
"s": 1542,
"text": "Input − a=11.23 b=6.7 "
},
{
"code": null,
"e": 1582,
"s": 1565,
"text": "Output − 75.241 "
},
{
"code": null,
"e": 1801,
"s": 1582,
"text": "Explanation − Use of Float variables. In this program, the user has two numbers (floating point numbers)means float variables. Then, the product of those two numbers is stored in a variable and displayed on the screen."
},
{
"code": null,
"e": 1975,
"s": 1801,
"text": "#include <stdio.h>\nint main() {\n float a, b, c;\n a=11.23; b=6.7;\n c = (float)(a*b);\n // Displaying result up to 3 decimal places.\n printf(\"%3f\", c);\n return 0;\n}"
},
{
"code": null,
"e": 1982,
"s": 1975,
"text": "75.241"
}
] |
How to get Characters Count in Python from a File - onlinetutorialspoint
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we will see how to get characters count in python where characters are reading from a file.
Simple source code to get distinct characters count in a file.
I Love my country, make in India !
Reading each character from a file and counting each distinct character.
document_text = open('data','r')
string = document_text.read().lower()
freq = [None] * len(string);
for i in range(0, len(string)):
freq[i] = 1;
for j in range(i+1, len(string)):
if(string[i] == string[j]):
freq[i] = freq[i] + 1;
string = string[ : j] + '0' + string[j+1 : ];
print("Characters and their frequencies");
print("--------------------------------")
for i in range(0, len(freq)):
if(string[i] != ' ' and string[i] != '0'):
print(string[i] + "-> " + str(freq[i]));
Output:
Characters and their frequencies
---------------------------------
i-> 4
l-> 1
o-> 2
v-> 1
e-> 2
m-> 2
y-> 2
c-> 1
u-> 1
n-> 3
t-> 1
r-> 1
,-> 1
a-> 2
k-> 1
d-> 1
!-> 1
Done!
Happy Learning 🙂
count number of lines characters and words in a file Java
How to Search a file in a Directory using Java
How to get Words Count in Python from a File
Java Program To Count number of words in a String
Rules to define Python Identifiers
Python Tuple Data Structure in Depth
What are different Python Data Types
Java Program to Find the characters count in String
How to Read CSV File in Python
How to Find Duplicate Words Count in a File
Python – How to create Zip File in Python ?
How to check whether a file exists python ?
How to read a text file in Python ?
How to Convert Python List Of Objects to CSV File
Python – Selenium Download a File in Headless Mode
count number of lines characters and words in a file Java
How to Search a file in a Directory using Java
How to get Words Count in Python from a File
Java Program To Count number of words in a String
Rules to define Python Identifiers
Python Tuple Data Structure in Depth
What are different Python Data Types
Java Program to Find the characters count in String
How to Read CSV File in Python
How to Find Duplicate Words Count in a File
Python – How to create Zip File in Python ?
How to check whether a file exists python ?
How to read a text file in Python ?
How to Convert Python List Of Objects to CSV File
Python – Selenium Download a File in Headless Mode
Δ
Python – Introduction
Python – Features
Python – Install on Windows
Python – Modes of Program
Python – Number System
Python – Identifiers
Python – Operators
Python – Ternary Operator
Python – Command Line Arguments
Python – Keywords
Python – Data Types
Python – Upgrade Python PIP
Python – Virtual Environment
Pyhton – Type Casting
Python – String to Int
Python – Conditional Statements
Python – if statement
Python – *args and **kwargs
Python – Date Formatting
Python – Read input from keyboard
Python – raw_input
Python – List In Depth
Python – List Comprehension
Python – Set in Depth
Python – Dictionary in Depth
Python – Tuple in Depth
Python – Stack Datastructure
Python – Classes and Objects
Python – Constructors
Python – Object Introspection
Python – Inheritance
Python – Decorators
Python – Serialization with Pickle
Python – Exceptions Handling
Python – User defined Exceptions
Python – Multiprocessing
Python – Default function parameters
Python – Lambdas Functions
Python – NumPy Library
Python – MySQL Connector
Python – MySQL Create Database
Python – MySQL Read Data
Python – MySQL Insert Data
Python – MySQL Update Records
Python – MySQL Delete Records
Python – String Case Conversion
Howto – Find biggest of 2 numbers
Howto – Remove duplicates from List
Howto – Convert any Number to Binary
Howto – Merge two Lists
Howto – Merge two dicts
Howto – Get Characters Count in a File
Howto – Get Words Count in a File
Howto – Remove Spaces from String
Howto – Read Env variables
Howto – Read a text File
Howto – Read a JSON File
Howto – Read Config.ini files
Howto – Iterate Dictionary
Howto – Convert List Of Objects to CSV
Howto – Merge two dict in Python
Howto – create Zip File
Howto – Get OS info
Howto – Get size of Directory
Howto – Check whether a file exists
Howto – Remove key from dictionary
Howto – Sort Objects
Howto – Create or Delete Directories
Howto – Read CSV File
Howto – Create Python Iterable class
Howto – Access for loop index
Howto – Clear all elements from List
Howto – Remove empty lists from a List
Howto – Remove special characters from String
Howto – Sort dictionary by key
Howto – Filter a list
|
[
{
"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": 508,
"s": 398,
"text": "In this tutorial, we will see how to get characters count in python where characters are reading from a file."
},
{
"code": null,
"e": 571,
"s": 508,
"text": "Simple source code to get distinct characters count in a file."
},
{
"code": null,
"e": 606,
"s": 571,
"text": "I Love my country, make in India !"
},
{
"code": null,
"e": 679,
"s": 606,
"text": "Reading each character from a file and counting each distinct character."
},
{
"code": null,
"e": 1206,
"s": 679,
"text": "document_text = open('data','r')\nstring = document_text.read().lower()\nfreq = [None] * len(string);\nfor i in range(0, len(string)):\n freq[i] = 1;\n for j in range(i+1, len(string)):\n if(string[i] == string[j]):\n freq[i] = freq[i] + 1;\n string = string[ : j] + '0' + string[j+1 : ];\nprint(\"Characters and their frequencies\");\nprint(\"--------------------------------\")\nfor i in range(0, len(freq)):\n if(string[i] != ' ' and string[i] != '0'):\n print(string[i] + \"-> \" + str(freq[i]));"
},
{
"code": null,
"e": 1214,
"s": 1206,
"text": "Output:"
},
{
"code": null,
"e": 1383,
"s": 1214,
"text": "Characters and their frequencies\n---------------------------------\ni-> 4\nl-> 1\no-> 2\nv-> 1\ne-> 2\nm-> 2\ny-> 2\nc-> 1\nu-> 1\nn-> 3\nt-> 1\nr-> 1\n,-> 1\na-> 2\nk-> 1\nd-> 1\n!-> 1"
},
{
"code": null,
"e": 1389,
"s": 1383,
"text": "Done!"
},
{
"code": null,
"e": 1406,
"s": 1389,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 2070,
"s": 1406,
"text": "\ncount number of lines characters and words in a file Java\nHow to Search a file in a Directory using Java\nHow to get Words Count in Python from a File\nJava Program To Count number of words in a String\nRules to define Python Identifiers\nPython Tuple Data Structure in Depth\nWhat are different Python Data Types\nJava Program to Find the characters count in String\nHow to Read CSV File in Python\nHow to Find Duplicate Words Count in a File\nPython – How to create Zip File in Python ?\nHow to check whether a file exists python ?\nHow to read a text file in Python ?\nHow to Convert Python List Of Objects to CSV File\nPython – Selenium Download a File in Headless Mode\n"
},
{
"code": null,
"e": 2128,
"s": 2070,
"text": "count number of lines characters and words in a file Java"
},
{
"code": null,
"e": 2175,
"s": 2128,
"text": "How to Search a file in a Directory using Java"
},
{
"code": null,
"e": 2220,
"s": 2175,
"text": "How to get Words Count in Python from a File"
},
{
"code": null,
"e": 2271,
"s": 2220,
"text": "Java Program To Count number of words in a String"
},
{
"code": null,
"e": 2306,
"s": 2271,
"text": "Rules to define Python Identifiers"
},
{
"code": null,
"e": 2343,
"s": 2306,
"text": "Python Tuple Data Structure in Depth"
},
{
"code": null,
"e": 2380,
"s": 2343,
"text": "What are different Python Data Types"
},
{
"code": null,
"e": 2432,
"s": 2380,
"text": "Java Program to Find the characters count in String"
},
{
"code": null,
"e": 2463,
"s": 2432,
"text": "How to Read CSV File in Python"
},
{
"code": null,
"e": 2507,
"s": 2463,
"text": "How to Find Duplicate Words Count in a File"
},
{
"code": null,
"e": 2551,
"s": 2507,
"text": "Python – How to create Zip File in Python ?"
},
{
"code": null,
"e": 2595,
"s": 2551,
"text": "How to check whether a file exists python ?"
},
{
"code": null,
"e": 2631,
"s": 2595,
"text": "How to read a text file in Python ?"
},
{
"code": null,
"e": 2681,
"s": 2631,
"text": "How to Convert Python List Of Objects to CSV File"
},
{
"code": null,
"e": 2732,
"s": 2681,
"text": "Python – Selenium Download a File in Headless Mode"
},
{
"code": null,
"e": 2738,
"s": 2736,
"text": "Δ"
},
{
"code": null,
"e": 2761,
"s": 2738,
"text": " Python – Introduction"
},
{
"code": null,
"e": 2780,
"s": 2761,
"text": " Python – Features"
},
{
"code": null,
"e": 2809,
"s": 2780,
"text": " Python – Install on Windows"
},
{
"code": null,
"e": 2836,
"s": 2809,
"text": " Python – Modes of Program"
},
{
"code": null,
"e": 2860,
"s": 2836,
"text": " Python – Number System"
},
{
"code": null,
"e": 2882,
"s": 2860,
"text": " Python – Identifiers"
},
{
"code": null,
"e": 2902,
"s": 2882,
"text": " Python – Operators"
},
{
"code": null,
"e": 2929,
"s": 2902,
"text": " Python – Ternary Operator"
},
{
"code": null,
"e": 2962,
"s": 2929,
"text": " Python – Command Line Arguments"
},
{
"code": null,
"e": 2981,
"s": 2962,
"text": " Python – Keywords"
},
{
"code": null,
"e": 3002,
"s": 2981,
"text": " Python – Data Types"
},
{
"code": null,
"e": 3031,
"s": 3002,
"text": " Python – Upgrade Python PIP"
},
{
"code": null,
"e": 3061,
"s": 3031,
"text": " Python – Virtual Environment"
},
{
"code": null,
"e": 3084,
"s": 3061,
"text": " Pyhton – Type Casting"
},
{
"code": null,
"e": 3108,
"s": 3084,
"text": " Python – String to Int"
},
{
"code": null,
"e": 3141,
"s": 3108,
"text": " Python – Conditional Statements"
},
{
"code": null,
"e": 3164,
"s": 3141,
"text": " Python – if statement"
},
{
"code": null,
"e": 3193,
"s": 3164,
"text": " Python – *args and **kwargs"
},
{
"code": null,
"e": 3219,
"s": 3193,
"text": " Python – Date Formatting"
},
{
"code": null,
"e": 3254,
"s": 3219,
"text": " Python – Read input from keyboard"
},
{
"code": null,
"e": 3274,
"s": 3254,
"text": " Python – raw_input"
},
{
"code": null,
"e": 3298,
"s": 3274,
"text": " Python – List In Depth"
},
{
"code": null,
"e": 3327,
"s": 3298,
"text": " Python – List Comprehension"
},
{
"code": null,
"e": 3350,
"s": 3327,
"text": " Python – Set in Depth"
},
{
"code": null,
"e": 3380,
"s": 3350,
"text": " Python – Dictionary in Depth"
},
{
"code": null,
"e": 3405,
"s": 3380,
"text": " Python – Tuple in Depth"
},
{
"code": null,
"e": 3435,
"s": 3405,
"text": " Python – Stack Datastructure"
},
{
"code": null,
"e": 3465,
"s": 3435,
"text": " Python – Classes and Objects"
},
{
"code": null,
"e": 3488,
"s": 3465,
"text": " Python – Constructors"
},
{
"code": null,
"e": 3519,
"s": 3488,
"text": " Python – Object Introspection"
},
{
"code": null,
"e": 3541,
"s": 3519,
"text": " Python – Inheritance"
},
{
"code": null,
"e": 3562,
"s": 3541,
"text": " Python – Decorators"
},
{
"code": null,
"e": 3598,
"s": 3562,
"text": " Python – Serialization with Pickle"
},
{
"code": null,
"e": 3628,
"s": 3598,
"text": " Python – Exceptions Handling"
},
{
"code": null,
"e": 3662,
"s": 3628,
"text": " Python – User defined Exceptions"
},
{
"code": null,
"e": 3688,
"s": 3662,
"text": " Python – Multiprocessing"
},
{
"code": null,
"e": 3726,
"s": 3688,
"text": " Python – Default function parameters"
},
{
"code": null,
"e": 3754,
"s": 3726,
"text": " Python – Lambdas Functions"
},
{
"code": null,
"e": 3778,
"s": 3754,
"text": " Python – NumPy Library"
},
{
"code": null,
"e": 3804,
"s": 3778,
"text": " Python – MySQL Connector"
},
{
"code": null,
"e": 3836,
"s": 3804,
"text": " Python – MySQL Create Database"
},
{
"code": null,
"e": 3862,
"s": 3836,
"text": " Python – MySQL Read Data"
},
{
"code": null,
"e": 3890,
"s": 3862,
"text": " Python – MySQL Insert Data"
},
{
"code": null,
"e": 3921,
"s": 3890,
"text": " Python – MySQL Update Records"
},
{
"code": null,
"e": 3952,
"s": 3921,
"text": " Python – MySQL Delete Records"
},
{
"code": null,
"e": 3985,
"s": 3952,
"text": " Python – String Case Conversion"
},
{
"code": null,
"e": 4020,
"s": 3985,
"text": " Howto – Find biggest of 2 numbers"
},
{
"code": null,
"e": 4057,
"s": 4020,
"text": " Howto – Remove duplicates from List"
},
{
"code": null,
"e": 4095,
"s": 4057,
"text": " Howto – Convert any Number to Binary"
},
{
"code": null,
"e": 4121,
"s": 4095,
"text": " Howto – Merge two Lists"
},
{
"code": null,
"e": 4146,
"s": 4121,
"text": " Howto – Merge two dicts"
},
{
"code": null,
"e": 4186,
"s": 4146,
"text": " Howto – Get Characters Count in a File"
},
{
"code": null,
"e": 4221,
"s": 4186,
"text": " Howto – Get Words Count in a File"
},
{
"code": null,
"e": 4256,
"s": 4221,
"text": " Howto – Remove Spaces from String"
},
{
"code": null,
"e": 4285,
"s": 4256,
"text": " Howto – Read Env variables"
},
{
"code": null,
"e": 4311,
"s": 4285,
"text": " Howto – Read a text File"
},
{
"code": null,
"e": 4337,
"s": 4311,
"text": " Howto – Read a JSON File"
},
{
"code": null,
"e": 4369,
"s": 4337,
"text": " Howto – Read Config.ini files"
},
{
"code": null,
"e": 4397,
"s": 4369,
"text": " Howto – Iterate Dictionary"
},
{
"code": null,
"e": 4437,
"s": 4397,
"text": " Howto – Convert List Of Objects to CSV"
},
{
"code": null,
"e": 4471,
"s": 4437,
"text": " Howto – Merge two dict in Python"
},
{
"code": null,
"e": 4496,
"s": 4471,
"text": " Howto – create Zip File"
},
{
"code": null,
"e": 4517,
"s": 4496,
"text": " Howto – Get OS info"
},
{
"code": null,
"e": 4548,
"s": 4517,
"text": " Howto – Get size of Directory"
},
{
"code": null,
"e": 4585,
"s": 4548,
"text": " Howto – Check whether a file exists"
},
{
"code": null,
"e": 4622,
"s": 4585,
"text": " Howto – Remove key from dictionary"
},
{
"code": null,
"e": 4644,
"s": 4622,
"text": " Howto – Sort Objects"
},
{
"code": null,
"e": 4682,
"s": 4644,
"text": " Howto – Create or Delete Directories"
},
{
"code": null,
"e": 4705,
"s": 4682,
"text": " Howto – Read CSV File"
},
{
"code": null,
"e": 4743,
"s": 4705,
"text": " Howto – Create Python Iterable class"
},
{
"code": null,
"e": 4774,
"s": 4743,
"text": " Howto – Access for loop index"
},
{
"code": null,
"e": 4812,
"s": 4774,
"text": " Howto – Clear all elements from List"
},
{
"code": null,
"e": 4852,
"s": 4812,
"text": " Howto – Remove empty lists from a List"
},
{
"code": null,
"e": 4899,
"s": 4852,
"text": " Howto – Remove special characters from String"
},
{
"code": null,
"e": 4931,
"s": 4899,
"text": " Howto – Sort dictionary by key"
}
] |
What are auto and decltype in C++?
|
Auto is a keyword in C++11 and later that is used for automatic type deduction. Type inference or deduction refers to the automatic detection of the data type of an expression in a programming language. It is a feature present in some strongly statically typed languages. For example, you want to create an iterator to iterate over a vector, you can simply use auto for that purpose.
#include<iostream>
#include<vector>
using namespace std;
int main() {
vector<int> arr(10);
for(auto it = arr.begin(); it != arr.end(); it ++) {
cin >> *it;
}
return 0;
}
In the above program, it will automatically get the type std:: vector<int>:: iterator.
The decltype type specifier yields the type of a specified expression. Unlike auto that deduces types based on values being assigned to the variable, decltype deduces the type from an expression passed to it. The value returned by decltype can directly be used to define another variable. For example, the above code can be written as the following using decltype −
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> arr(10);
for (decltype(arr.begin()) it = arr.begin(); it != arr.end(); it++) {
cin >> *it;
}
return 0;
}
Note that The type denoted by decltype can be different from the type deduced by auto. You can read more about these subtle differences in this 12-page explanation of type deduction in C++ −http://thbecker.net/articles/auto_and_decltype/section_01.html
|
[
{
"code": null,
"e": 1447,
"s": 1062,
"text": "Auto is a keyword in C++11 and later that is used for automatic type deduction. Type inference or deduction refers to the automatic detection of the data type of an expression in a programming language. It is a feature present in some strongly statically typed languages. For example, you want to create an iterator to iterate over a vector, you can simply use auto for that purpose. "
},
{
"code": null,
"e": 1635,
"s": 1447,
"text": "#include<iostream>\n#include<vector>\nusing namespace std;\nint main() {\n vector<int> arr(10);\n for(auto it = arr.begin(); it != arr.end(); it ++) {\n cin >> *it;\n }\n return 0;\n}"
},
{
"code": null,
"e": 1722,
"s": 1635,
"text": "In the above program, it will automatically get the type std:: vector<int>:: iterator."
},
{
"code": null,
"e": 2088,
"s": 1722,
"text": "The decltype type specifier yields the type of a specified expression. Unlike auto that deduces types based on values being assigned to the variable, decltype deduces the type from an expression passed to it. The value returned by decltype can directly be used to define another variable. For example, the above code can be written as the following using decltype −"
},
{
"code": null,
"e": 2296,
"s": 2088,
"text": "#include <iostream>\n#include <vector>\nusing namespace std;\nint main() {\n vector<int> arr(10);\n for (decltype(arr.begin()) it = arr.begin(); it != arr.end(); it++) {\n cin >> *it;\n }\n return 0;\n}\n"
},
{
"code": null,
"e": 2549,
"s": 2296,
"text": "Note that The type denoted by decltype can be different from the type deduced by auto. You can read more about these subtle differences in this 12-page explanation of type deduction in C++ −http://thbecker.net/articles/auto_and_decltype/section_01.html"
}
] |
One-tailed or two-tailed test, that is the question | by Eryk Lewinson | Towards Data Science
|
In data science/econometrics we see statistical tests in many places: correlation analysis, ANOVA, A/B testing, linear regression results, etc. Therefore, for the practitioners, it is very important to thoroughly understand their meaning and know why a given test was used in a particular place. In this article, I would like to provide some intuition for picking an appropriate version of a statistical test — one-tailed or two-tailed — that fits the stated hypotheses.
The crucial step in conducting any statistical testing is choosing the right hypotheses, as they not only determine the kind of statistical test that should be used but also influence the version of it.
In case the considered test statistic is symmetrically distributed, we can select one of three alternative hypotheses:
x is greater than y
x is smaller than y
x is not equal to y
The first two correspond to one-tailed tests, while the last one corresponds to a two-tailed test.
Let’s dive deeper into the differences between the two variants of a test and show some examples in Python!
Let’s assume we have selected 0.05 (or 5%) as our significance level. Working with a one-tailed test means that the critical region is located in the top/bottom 5% of the test statistic’s probability distribution. If the test statistic falls into this region, we reject the null hypothesis. We are effectively testing the possibility of the relationship in one direction (significantly greater OR less) and disregarding the possibility of a relationship in the other direction.
An important characteristic of the one-tailed test is that it provides more power to detect an effect in one direction, as it does not test the other one. However, this also poses some threats, which I illustrate in the following example.
Let’s imagine that we manufactured a new drug and want to test its effectiveness against the current solution. We may be tempted to use the one-tailed test, as it maximizes the chances of detecting the improvement (clearly specified direction of effect). But this exposes us to the possibility of missing the fact that our drug is actually less effective than the current one.
This example shows that we should select the one-tailed test when the consequences of missing an effect are negligible, which is not the case in the example above. We should never select the one-tailed test for the sole purpose of obtaining statistical significance, as this can lead to an invalid conclusion and in some cases dire consequences.
In the case of the two-tailed tests, we are testing a hypothesis that does not include a directional relationship. If we wanted to test whether the sample mean is equal to x (null hypothesis of a t-test), then the alternative one states that the mean is not equal to x. To test it, we consider the case of the mean being significantly greater AND significantly less than x. With a 5% significance level, the sample mean is considered significantly different from x when the test statistic falls into the critical region — the bottom AND top 2.5% of the test statistic’s probability distribution. This results in a p-value of less than 0.05 and indicates we should reject the null hypothesis in favor of the alternative one.
Let’s assume that we are working with data regarding school exams. Students from two schools wrote the same standardized exam and now we would like to investigate if there is a statistical difference between the average results.
For simplicity, we assume that the schools have 100 students each and the scores from the exams come from Gaussian distribution with different parameters.
In the one-sample t-test, we test the mean of a sample against a particular value. We start with the two-tailed variant of the test, with the following hypotheses:
H_0: the mean result of students from school #1 is 70H_1: the mean result of students from school #1 is not 70
stats.ttest_1samp(school_1, 70)# Ttest_1sampResult(statistic=42.90122143039788, pvalue=9.063698741097363e-66)
The p-value of the test is below 0.05, so we can reject the null hypothesis in favor of the alternative one.
In the second test, we check if the mean result of students from school #2 is greater than 90.
H_0: the mean result of students in school #2 is greater or equal to 90H_1: the mean result of students in school #2 is less than 90
As this is a directional test, we are doing a one-tailed variant of the t-test.
test_2 = stats.ttest_1samp(school_2, 90)# Ttest_1sampResult(statistic=-10.251936967846719, pvalue=3.087893244277984e-17)
In scipythere is no direct way to indicate that we want to run a one-tailed variant of the test. However, to obtain the desired results we adjust the output ourselves. In the case of this setting, we simply need to divide the p-value by 2 (the test statistic stays the same).
test_2.pvalue / 2# 1.543946622138992e-17
With the obtained p-value < 0.05we have reasons to reject the null hypothesis in favor of the alternative.
To be thorough, we also run the last variant of the test.
H_0: the mean result of students in school #2 is less or equal to 90H_1: the mean result of students in school #2 is greater than 90
test_3 = stats.ttest_1samp(school_2, 90)
We also need to correct the p-value, this time in a slightly different way:
1 - test_3.pvalue / 2# 1.0
With the obtained p-value=1we have no reason to reject the null hypothesis. The way of correcting the p-value depends on the alternative hypothesis we consider, whether it concerns a test for being ‘greater’ or ‘less’.
In the two-sample test, we test the equality of two sample means against each other.
H_0: the mean result of students from school #1 is the same as the mean result from school #2H_1: the mean result of students from school #1 and #2 are not equal
By default, stats.ttest_ind assumes that the populations have identical variances (which is true in this case, see data generation).
stats.ttest_ind(school_1, school_2)# Ttest_indResult(statistic=6.635596055724986, pvalue=3.0230309820272883e-10)
The results indicate that we should reject the null hypothesis about equal average results in the two schools, which is in line with our expectations.
To keep the article brief, we only consider the two-tailed variant of the test, as the one-tailed calculations are analogous to the code used for the one-sample t-test.
In this article, I presented some intuition about the one- and two-tailed variants of statistical tests. By default, most statistical software produces two-tailed results. That is why it is also important to be able to convert these results into the one-tailed equivalents.
If you liked the topic of this article, you might also be interested in the one describing power analysis.
As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments. The code for the article can be found here.
|
[
{
"code": null,
"e": 643,
"s": 172,
"text": "In data science/econometrics we see statistical tests in many places: correlation analysis, ANOVA, A/B testing, linear regression results, etc. Therefore, for the practitioners, it is very important to thoroughly understand their meaning and know why a given test was used in a particular place. In this article, I would like to provide some intuition for picking an appropriate version of a statistical test — one-tailed or two-tailed — that fits the stated hypotheses."
},
{
"code": null,
"e": 846,
"s": 643,
"text": "The crucial step in conducting any statistical testing is choosing the right hypotheses, as they not only determine the kind of statistical test that should be used but also influence the version of it."
},
{
"code": null,
"e": 965,
"s": 846,
"text": "In case the considered test statistic is symmetrically distributed, we can select one of three alternative hypotheses:"
},
{
"code": null,
"e": 985,
"s": 965,
"text": "x is greater than y"
},
{
"code": null,
"e": 1005,
"s": 985,
"text": "x is smaller than y"
},
{
"code": null,
"e": 1025,
"s": 1005,
"text": "x is not equal to y"
},
{
"code": null,
"e": 1124,
"s": 1025,
"text": "The first two correspond to one-tailed tests, while the last one corresponds to a two-tailed test."
},
{
"code": null,
"e": 1232,
"s": 1124,
"text": "Let’s dive deeper into the differences between the two variants of a test and show some examples in Python!"
},
{
"code": null,
"e": 1710,
"s": 1232,
"text": "Let’s assume we have selected 0.05 (or 5%) as our significance level. Working with a one-tailed test means that the critical region is located in the top/bottom 5% of the test statistic’s probability distribution. If the test statistic falls into this region, we reject the null hypothesis. We are effectively testing the possibility of the relationship in one direction (significantly greater OR less) and disregarding the possibility of a relationship in the other direction."
},
{
"code": null,
"e": 1949,
"s": 1710,
"text": "An important characteristic of the one-tailed test is that it provides more power to detect an effect in one direction, as it does not test the other one. However, this also poses some threats, which I illustrate in the following example."
},
{
"code": null,
"e": 2326,
"s": 1949,
"text": "Let’s imagine that we manufactured a new drug and want to test its effectiveness against the current solution. We may be tempted to use the one-tailed test, as it maximizes the chances of detecting the improvement (clearly specified direction of effect). But this exposes us to the possibility of missing the fact that our drug is actually less effective than the current one."
},
{
"code": null,
"e": 2672,
"s": 2326,
"text": "This example shows that we should select the one-tailed test when the consequences of missing an effect are negligible, which is not the case in the example above. We should never select the one-tailed test for the sole purpose of obtaining statistical significance, as this can lead to an invalid conclusion and in some cases dire consequences."
},
{
"code": null,
"e": 3396,
"s": 2672,
"text": "In the case of the two-tailed tests, we are testing a hypothesis that does not include a directional relationship. If we wanted to test whether the sample mean is equal to x (null hypothesis of a t-test), then the alternative one states that the mean is not equal to x. To test it, we consider the case of the mean being significantly greater AND significantly less than x. With a 5% significance level, the sample mean is considered significantly different from x when the test statistic falls into the critical region — the bottom AND top 2.5% of the test statistic’s probability distribution. This results in a p-value of less than 0.05 and indicates we should reject the null hypothesis in favor of the alternative one."
},
{
"code": null,
"e": 3625,
"s": 3396,
"text": "Let’s assume that we are working with data regarding school exams. Students from two schools wrote the same standardized exam and now we would like to investigate if there is a statistical difference between the average results."
},
{
"code": null,
"e": 3780,
"s": 3625,
"text": "For simplicity, we assume that the schools have 100 students each and the scores from the exams come from Gaussian distribution with different parameters."
},
{
"code": null,
"e": 3944,
"s": 3780,
"text": "In the one-sample t-test, we test the mean of a sample against a particular value. We start with the two-tailed variant of the test, with the following hypotheses:"
},
{
"code": null,
"e": 4055,
"s": 3944,
"text": "H_0: the mean result of students from school #1 is 70H_1: the mean result of students from school #1 is not 70"
},
{
"code": null,
"e": 4165,
"s": 4055,
"text": "stats.ttest_1samp(school_1, 70)# Ttest_1sampResult(statistic=42.90122143039788, pvalue=9.063698741097363e-66)"
},
{
"code": null,
"e": 4274,
"s": 4165,
"text": "The p-value of the test is below 0.05, so we can reject the null hypothesis in favor of the alternative one."
},
{
"code": null,
"e": 4369,
"s": 4274,
"text": "In the second test, we check if the mean result of students from school #2 is greater than 90."
},
{
"code": null,
"e": 4502,
"s": 4369,
"text": "H_0: the mean result of students in school #2 is greater or equal to 90H_1: the mean result of students in school #2 is less than 90"
},
{
"code": null,
"e": 4582,
"s": 4502,
"text": "As this is a directional test, we are doing a one-tailed variant of the t-test."
},
{
"code": null,
"e": 4703,
"s": 4582,
"text": "test_2 = stats.ttest_1samp(school_2, 90)# Ttest_1sampResult(statistic=-10.251936967846719, pvalue=3.087893244277984e-17)"
},
{
"code": null,
"e": 4979,
"s": 4703,
"text": "In scipythere is no direct way to indicate that we want to run a one-tailed variant of the test. However, to obtain the desired results we adjust the output ourselves. In the case of this setting, we simply need to divide the p-value by 2 (the test statistic stays the same)."
},
{
"code": null,
"e": 5020,
"s": 4979,
"text": "test_2.pvalue / 2# 1.543946622138992e-17"
},
{
"code": null,
"e": 5127,
"s": 5020,
"text": "With the obtained p-value < 0.05we have reasons to reject the null hypothesis in favor of the alternative."
},
{
"code": null,
"e": 5185,
"s": 5127,
"text": "To be thorough, we also run the last variant of the test."
},
{
"code": null,
"e": 5318,
"s": 5185,
"text": "H_0: the mean result of students in school #2 is less or equal to 90H_1: the mean result of students in school #2 is greater than 90"
},
{
"code": null,
"e": 5359,
"s": 5318,
"text": "test_3 = stats.ttest_1samp(school_2, 90)"
},
{
"code": null,
"e": 5435,
"s": 5359,
"text": "We also need to correct the p-value, this time in a slightly different way:"
},
{
"code": null,
"e": 5462,
"s": 5435,
"text": "1 - test_3.pvalue / 2# 1.0"
},
{
"code": null,
"e": 5681,
"s": 5462,
"text": "With the obtained p-value=1we have no reason to reject the null hypothesis. The way of correcting the p-value depends on the alternative hypothesis we consider, whether it concerns a test for being ‘greater’ or ‘less’."
},
{
"code": null,
"e": 5766,
"s": 5681,
"text": "In the two-sample test, we test the equality of two sample means against each other."
},
{
"code": null,
"e": 5928,
"s": 5766,
"text": "H_0: the mean result of students from school #1 is the same as the mean result from school #2H_1: the mean result of students from school #1 and #2 are not equal"
},
{
"code": null,
"e": 6061,
"s": 5928,
"text": "By default, stats.ttest_ind assumes that the populations have identical variances (which is true in this case, see data generation)."
},
{
"code": null,
"e": 6174,
"s": 6061,
"text": "stats.ttest_ind(school_1, school_2)# Ttest_indResult(statistic=6.635596055724986, pvalue=3.0230309820272883e-10)"
},
{
"code": null,
"e": 6325,
"s": 6174,
"text": "The results indicate that we should reject the null hypothesis about equal average results in the two schools, which is in line with our expectations."
},
{
"code": null,
"e": 6494,
"s": 6325,
"text": "To keep the article brief, we only consider the two-tailed variant of the test, as the one-tailed calculations are analogous to the code used for the one-sample t-test."
},
{
"code": null,
"e": 6768,
"s": 6494,
"text": "In this article, I presented some intuition about the one- and two-tailed variants of statistical tests. By default, most statistical software produces two-tailed results. That is why it is also important to be able to convert these results into the one-tailed equivalents."
},
{
"code": null,
"e": 6875,
"s": 6768,
"text": "If you liked the topic of this article, you might also be interested in the one describing power analysis."
}
] |
DB2 - with XML
|
This chapter describes use of XML with DB2.
PureXML feature allows you to store well-formed XML documents in columns of database tables. Those columns have XML database. Data is kept in its native hierarchical form by storing XML data in XML column. The stored XML data can be accessed and managed by DB2 database server functionality. The storage of XML data in its native hierarchical form enables efficient search, retrieval, and update of XML. To update a value in XML data, you need to use XQuery, SQL or combination of both.
Create a database by issuing the following syntax:
Syntax:
db2 create database xmldb
By default, databases use UTF-8 (UNICODE) code set. Activate the database and connect to it:
Syntax:
db2 activate db <db_name>
db2 connect to <db_name>
Example:
db2 activate db xmldb
db2 connect to xmldb
Create a well-formed XML file and create a table with data type of the column as ‘XML’. It is mandatory to pass the SQL query containing XML syntax within double quotation marks.
Syntax:
db2 “create table <schema>.<table>(col <datatype>,
col <xml datatype>)”
Example:
db2 "create table shope.books(id bigint not null
primary key, book XML)"
Insert xml values into table, well-formed XML documents are inserted into XML type column using SQL statement ‘INSERT’.
Syntax:
db2 “insert into <table_name> values(value1, value2)”
Example:
db2 "insert into shope.books values(1000, '<catalog>
<book>
<author> Gambardella Matthew</author>
<title>XML Developers Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating application
with XML</description>
</book>
</catalog>')"
You can update XML data in a table by using the following syntax:
Syntax:
db2 “update <table_name> set <column>=<value> where
<column>=<value>”
Example:
db2 "update shope.books set book='<catalog>
<book>
<author> Gambardella, Matthew</author>
<title>XML Developers Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth XML</description>
</book>
</catalog>' where id=1000"
10 Lectures
1.5 hours
Nishant Malik
41 Lectures
8.5 hours
Parth Panjabi
53 Lectures
11.5 hours
Parth Panjabi
33 Lectures
7 hours
Parth Panjabi
44 Lectures
3 hours
Arnab Chakraborty
178 Lectures
14.5 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1972,
"s": 1928,
"text": "This chapter describes use of XML with DB2."
},
{
"code": null,
"e": 2460,
"s": 1972,
"text": "PureXML feature allows you to store well-formed XML documents in columns of database tables. Those columns have XML database. Data is kept in its native hierarchical form by storing XML data in XML column. The stored XML data can be accessed and managed by DB2 database server functionality. The storage of XML data in its native hierarchical form enables efficient search, retrieval, and update of XML. To update a value in XML data, you need to use XQuery, SQL or combination of both."
},
{
"code": null,
"e": 2511,
"s": 2460,
"text": "Create a database by issuing the following syntax:"
},
{
"code": null,
"e": 2519,
"s": 2511,
"text": "Syntax:"
},
{
"code": null,
"e": 2546,
"s": 2519,
"text": "db2 create database xmldb "
},
{
"code": null,
"e": 2639,
"s": 2546,
"text": "By default, databases use UTF-8 (UNICODE) code set. Activate the database and connect to it:"
},
{
"code": null,
"e": 2647,
"s": 2639,
"text": "Syntax:"
},
{
"code": null,
"e": 2699,
"s": 2647,
"text": "db2 activate db <db_name>\ndb2 connect to <db_name> "
},
{
"code": null,
"e": 2708,
"s": 2699,
"text": "Example:"
},
{
"code": null,
"e": 2754,
"s": 2708,
"text": "db2 activate db xmldb \ndb2 connect to xmldb "
},
{
"code": null,
"e": 2933,
"s": 2754,
"text": "Create a well-formed XML file and create a table with data type of the column as ‘XML’. It is mandatory to pass the SQL query containing XML syntax within double quotation marks."
},
{
"code": null,
"e": 2941,
"s": 2933,
"text": "Syntax:"
},
{
"code": null,
"e": 3015,
"s": 2941,
"text": "db2 “create table <schema>.<table>(col <datatype>, \ncol <xml datatype>)” "
},
{
"code": null,
"e": 3024,
"s": 3015,
"text": "Example:"
},
{
"code": null,
"e": 3101,
"s": 3024,
"text": "db2 \"create table shope.books(id bigint not null \nprimary key, book XML)\" "
},
{
"code": null,
"e": 3221,
"s": 3101,
"text": "Insert xml values into table, well-formed XML documents are inserted into XML type column using SQL statement ‘INSERT’."
},
{
"code": null,
"e": 3229,
"s": 3221,
"text": "Syntax:"
},
{
"code": null,
"e": 3284,
"s": 3229,
"text": "db2 “insert into <table_name> values(value1, value2)” "
},
{
"code": null,
"e": 3293,
"s": 3284,
"text": "Example:"
},
{
"code": null,
"e": 3627,
"s": 3293,
"text": "db2 \"insert into shope.books values(1000, '<catalog> \n<book> \n\n<author> Gambardella Matthew</author> \n<title>XML Developers Guide</title> \n<genre>Computer</genre> \n<price>44.95</price> \n<publish_date>2000-10-01</publish_date> \n<description>An in-depth look at creating application \nwith XML</description> \n</book> \n\n</catalog>')\" "
},
{
"code": null,
"e": 3693,
"s": 3627,
"text": "You can update XML data in a table by using the following syntax:"
},
{
"code": null,
"e": 3701,
"s": 3693,
"text": "Syntax:"
},
{
"code": null,
"e": 3774,
"s": 3701,
"text": "db2 “update <table_name> set <column>=<value> where \n<column>=<value>” "
},
{
"code": null,
"e": 3783,
"s": 3774,
"text": "Example:"
},
{
"code": null,
"e": 4094,
"s": 3783,
"text": "db2 \"update shope.books set book='<catalog> \n\n<book> \n<author> Gambardella, Matthew</author> \n<title>XML Developers Guide</title> \n<genre>Computer</genre> \n<price>44.95</price> \n<publish_date>2000-10-01</publish_date> \n<description>An in-depth XML</description>\n \n</book> \n \n</catalog>' where id=1000\" "
},
{
"code": null,
"e": 4129,
"s": 4094,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4144,
"s": 4129,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4179,
"s": 4144,
"text": "\n 41 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4194,
"s": 4179,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 4230,
"s": 4194,
"text": "\n 53 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 4245,
"s": 4230,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 4278,
"s": 4245,
"text": "\n 33 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4293,
"s": 4278,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 4326,
"s": 4293,
"text": "\n 44 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4345,
"s": 4326,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4382,
"s": 4345,
"text": "\n 178 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 4401,
"s": 4382,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4408,
"s": 4401,
"text": " Print"
},
{
"code": null,
"e": 4419,
"s": 4408,
"text": " Add Notes"
}
] |
Image Similarity Detection in Action with Tensorflow 2.0 | by Erdem Isbilen | Towards Data Science
|
In this post, I will show you how I implemented the ‘Image Similarity Detection’ task in my ‘Fashion Price Comparison’ web application. I will use image similarity to suggest users visually similar products based on what they searched.
The full source code of the implementation is available in my GitHub repository.
Throughout the post, there will be dedicated sections for each one of the following subjects;
How to use Tensorflow 2.0 and Tensorflow Hub to generate ‘image feature vectors’ of the product images.
How to use Spotify/annoy library and image feature vectors to calculate the image similarity scores.
Storing similarity scores and related product identification numbers in a JSON file to enable visual search in our web application.
Image similarity detection is used to quantify the degree of visual and semantic similarity of the images.
Duplicate product detection, image clustering, visual search, and recommendation tasks are performed with this technology in modern applications.
“The future of search will be about pictures rather than keywords.” — Ben Silbermann, Pinterest CEO
“An advantage of visual search is that it relies entirely on item appearance. There is no need for other data such as bar codes, QR codes, product names, or other product metadata.” — Brent Rabowsky, Amazon Web Services
“Customers are increasingly using social media platforms, such as Instagram and Pinterest, as a source of inspiration so the visual search has the potential to transform how we shop for the home.” — Mark Steel, Digital Director, Argos
Tensorflow 2.0 and Tensorflow Hub
Tensorflow is an end-to-end open-source platform for machine learning developed by Google. It has tools, libraries and community resources that let developers easily build and deploy machine learning applications.
TensorFlow Hub provides many reusable machine learning models. It makes transfer learning very easy as it provides pre-trained models for different problem domains and different tasks such as image classification, image segmentation, pose detection, text embeddings, text classification, video generation, etc.
For further information about the transfer learning, you can check my previous article.
towardsdatascience.com
What is an image feature vector?
An image feature vector is a list of numbers that represents a whole image, typically used for image similarity calculations or image classification tasks.
In general, low-level image features are minor details of the image, such as lines, edges, corners or dots. High-level features are built on top of low-level features to detect objects and larger shapes in the image.
We can extract both types of features using convolutional neural networks: the first couple of convolutional layers will learn filters for finding low-level features while the later layers will learn to recognize common shapes and objects.
In our case, we will extract high-level features of product images using a pre-trained convolutional neural network which is mobilenet_v2_140_224 stored in Tensorflow Hub.
MobilenetV2 is a simple neural network architecture suitable for mobile and resource-constrained applications. Follow this link to the original paper for further information on MobilenetV2.
Before start coding, it is required to install the Tensorflow 2.0, Tensorflow Hub and Spotify/Annoy libraries on our local computer.
$ virtualenv --system-site-packages -p python3 ./TFvenv$ source ./TFvenv/bin/activate$ pip install tensorflow$ pip install tensorflow-hub$ pip install annoy
The main purpose of this script is to generate image feature vectors by reading image files located in a local folder.
It has two functions: load_img() and get_image_feature_vectors().
load_img(path) gets file names which are provided as an argument of the function. Then loads and pre-process the images so that we can use them in our MobilenetV2 CNN model.
Pre-processing steps are as follows;
Decoding the image to W x H x 3 shape tensor with the data type of integer.
Resizing the image to 224 x 224 x 3 shape tensor as the version of the MobilenetV2 model we use expects that specific image size.
Converting the data type of tensor to float and adding a new axis to make tensor shape 1 x 224 x 224 x 3. This is the exact input shape expected by the model.
get_image_feature_vectors() function is where I extract the image feature vectors. You can see below, step by step definition of what this function does;
Loads the MobilenetV2 model using Tensorflow Hub
Loops through all images in a local folder and passing them to load_img(path) function
Infers the image feature vectors
Saves each one of the feature vectors to a separate file for later use
# get_image_feature_vectors.py################################################## Imports and function definitions################################################## For running inference on the TF-Hub module with Tensorflowimport tensorflow as tfimport tensorflow_hub as hub# For saving 'feature vectors' into a txt fileimport numpy as np# Glob for reading file names in a folderimport globimport os.path################################################################################################### This function:# Loads the JPEG image at the given path# Decodes the JPEG image to a uint8 W X H X 3 tensor# Resizes the image to 224 x 224 x 3 tensor# Returns the pre processed image as 224 x 224 x 3 tensor#################################################def load_img(path):# Reads the image file and returns data type of string img = tf.io.read_file(path)# Decodes the image to W x H x 3 shape tensor with type of uint8 img = tf.io.decode_jpeg(img, channels=3)# Resizes the image to 224 x 224 x 3 shape tensor img = tf.image.resize_with_pad(img, 224, 224)# Converts the data type of uint8 to float32 by adding a new axis # img becomes 1 x 224 x 224 x 3 tensor with data type of float32 # This is required for the mobilenet model we are using img = tf.image.convert_image_dtype(img,tf.float32)[tf.newaxis, ...] return img################################################## This function:# Loads the mobilenet model in TF.HUB# Makes an inference for all images stored in a local folder# Saves each of the feature vectors in a file#################################################def get_image_feature_vectors(): # Definition of module with using tfhub.dev module_handle = "https://tfhub.dev/google/imagenet/ mobilenet_v2_140_224/feature_vector/4" # Loads the module module = hub.load(module_handle)# Loops through all images in a local folder for filename in glob.glob('/Users/erdemisbilen/Angular/ fashionWebScraping/images_scraped/full/*.jpg'): print(filename)# Loads and pre-process the image img = load_img(filename)# Calculate the image feature vector of the img features = module(img)# Remove single-dimensional entries from the 'features' array feature_set = np.squeeze(features) # Saves the image feature vectors into a file for later use outfile_name = os.path.basename(filename) + ".npz" out_path = os.path.join('/Users/erdemisbilen/Angular/ fashionWebScraping/images_scraped/feature-vectors/', outfile_name)# Saves the 'feature_set' to a text file np.savetxt(out_path, feature_set, delimiter=',')get_image_feature_vectors()
What is Spotify/Annoy Library?
Annoy (Approximate Nearest Neighbor Oh Yeah), is an open-sourced library for approximate nearest neighbor implementation.
I will use it to find the image feature vectors in a given set that is closest (or most similar) to a given feature vector.
There are just two main parameters needed to tune Annoy: the number of trees n_trees and the number of nodes to inspect during searching search_k.
n_trees is provided during build time and affects the build time and the index size. A larger value will give more accurate results, but larger indexes.
search_k is provided in runtime and affects the search performance. A larger value will give more accurate results, but will take longer time to return.
from Spotify/Annoy
The main purpose of this script is to calculate image similarity scores using image feature vectors we have just generated in the previous chapter.
It has two functions: match_id(filename) and cluster().
cluster() function does the image similarity calculation with the following process flow:
Builds an annoy index by appending all image feature vectors stored in the local folder
Calculates the nearest neighbors and similarity scores
Saves and stores the information in a JSON file for later use.
match_id(filename) is a helper function as I need to match images with the product id’s to enable visual product search in my web application. There is a JSON file that contains all the product id information matched with the product image names. This function retrieves the product id information for a given image file name using that JSON file.
# cluster_image_feature_vectors.py################################################## Imports and function definitions################################################## Numpy for loading image feature vectors from fileimport numpy as np# Time for measuring the process timeimport time# Glob for reading file names in a folderimport globimport os.path# json for storing data in json fileimport json# Annoy and Scipy for similarity calculationfrom annoy import AnnoyIndexfrom scipy import spatial################################################################################################### This function reads from 'image_data.json' file# Looks for a specific 'filename' value# Returns the product id when product image names are matched# So it is used to find product id based on the product image name#################################################def match_id(filename): with open('/Users/erdemisbilen/Angular/fashionWebScraping /jsonFiles/image_data.json') as json_file:for file in json_file: seen = json.loads(file)for line in seen: if filename==line['imageName']: print(line) return line['productId'] break################################################################################################### This function:# Reads all image feature vectores stored in /feature-vectors/*.npz# Adds them all in Annoy Index# Builds ANNOY index# Calculates the nearest neighbors and image similarity metrics# Stores image similarity scores with productID in a json file#################################################def cluster(): start_time = time.time() print("---------------------------------") print ("Step.1 - ANNOY index generation - Started at %s" %time.ctime()) print("---------------------------------")# Defining data structures as empty dict file_index_to_file_name = {} file_index_to_file_vector = {} file_index_to_product_id = {}# Configuring annoy parameters dims = 1792 n_nearest_neighbors = 20 trees = 10000# Reads all file names which stores feature vectors allfiles = glob.glob('/Users/erdemisbilen/Angular /fashionWebScraping/images_scraped/feature-vectors/*.npz') t = AnnoyIndex(dims, metric='angular')for file_index, i in enumerate(allfiles):# Reads feature vectors and assigns them into the file_vector file_vector = np.loadtxt(i)# Assigns file_name, feature_vectors and corresponding product_id file_name = os.path.basename(i).split('.')[0] file_index_to_file_name[file_index] = file_name file_index_to_file_vector[file_index] = file_vector file_index_to_product_id[file_index] = match_id(file_name)# Adds image feature vectors into annoy index t.add_item(file_index, file_vector)print("---------------------------------") print("Annoy index : %s" %file_index) print("Image file name : %s" %file_name) print("Product id : %s" %file_index_to_product_id[file_index]) print("--- %.2f minutes passed ---------" % ((time.time() - start_time)/60))# Builds annoy index t.build(trees)print ("Step.1 - ANNOY index generation - Finished") print ("Step.2 - Similarity score calculation - Started ")named_nearest_neighbors = []# Loops through all indexed items for i in file_index_to_file_name.keys(): # Assigns master file_name, image feature vectors # and product id values master_file_name = file_index_to_file_name[i] master_vector = file_index_to_file_vector[i] master_product_id = file_index_to_product_id[i]# Calculates the nearest neighbors of the master item nearest_neighbors = t.get_nns_by_item(i, n_nearest_neighbors)# Loops through the nearest neighbors of the master item for j in nearest_neighbors: print(j)# Assigns file_name, image feature vectors and # product id values of the similar item neighbor_file_name = file_index_to_file_name[j] neighbor_file_vector = file_index_to_file_vector[j] neighbor_product_id = file_index_to_product_id[j]# Calculates the similarity score of the similar item similarity = 1 - spatial.distance.cosine(master_vector, neighbor_file_vector)rounded_similarity = int((similarity * 10000)) / 10000.0# Appends master product id with the similarity score # and the product id of the similar items named_nearest_neighbors.append({ 'similarity': rounded_similarity, 'master_pi': master_product_id, 'similar_pi': neighbor_product_id})print("---------------------------------") print("Similarity index : %s" %i) print("Master Image file name : %s" %file_index_to_file_name[i]) print("Nearest Neighbors. : %s" %nearest_neighbors) print("--- %.2f minutes passed ---------" % ((time.time() - start_time)/60))print ("Step.2 - Similarity score calculation - Finished ")# Writes the 'named_nearest_neighbors' to a json file with open('nearest_neighbors.json', 'w') as out: json.dump(named_nearest_neighbors, out)print ("Step.3 - Data stored in 'nearest_neighbors.json' file ") print("--- Prosess completed in %.2f minutes ---------" % ((time.time() - start_time)/60))cluster()
As you can see, I saved the highest 20 similarity scores for each product image in a JSON file with matching product id information. This is because I don’t what to do the similarity calculation on the client-side to eliminate the effort required.
With the similarity scores stored in the JSON file, I can easily populate Elasticsearch clusters, or populate a database to enable near real-time visual search experience on the browser on my price comparison web application.
To develop such an application, web scraping plays an important role to develop and maintain product datasets daily basis. If you are interested in this subject, check my related article below.
towardsdatascience.com
As you can see above, MobileNetV2 and Annoy together do a pretty good job of finding visual similar products.
One disadvantage of this implementation is that it only works at the whole image level. It does not provide good results if the backgrounds of the images are different, even if the objects are similar.
This application can be further improved to achieve an object-level similarity search like the one on Pinterest or Houzz.
|
[
{
"code": null,
"e": 408,
"s": 172,
"text": "In this post, I will show you how I implemented the ‘Image Similarity Detection’ task in my ‘Fashion Price Comparison’ web application. I will use image similarity to suggest users visually similar products based on what they searched."
},
{
"code": null,
"e": 489,
"s": 408,
"text": "The full source code of the implementation is available in my GitHub repository."
},
{
"code": null,
"e": 583,
"s": 489,
"text": "Throughout the post, there will be dedicated sections for each one of the following subjects;"
},
{
"code": null,
"e": 687,
"s": 583,
"text": "How to use Tensorflow 2.0 and Tensorflow Hub to generate ‘image feature vectors’ of the product images."
},
{
"code": null,
"e": 788,
"s": 687,
"text": "How to use Spotify/annoy library and image feature vectors to calculate the image similarity scores."
},
{
"code": null,
"e": 920,
"s": 788,
"text": "Storing similarity scores and related product identification numbers in a JSON file to enable visual search in our web application."
},
{
"code": null,
"e": 1027,
"s": 920,
"text": "Image similarity detection is used to quantify the degree of visual and semantic similarity of the images."
},
{
"code": null,
"e": 1173,
"s": 1027,
"text": "Duplicate product detection, image clustering, visual search, and recommendation tasks are performed with this technology in modern applications."
},
{
"code": null,
"e": 1273,
"s": 1173,
"text": "“The future of search will be about pictures rather than keywords.” — Ben Silbermann, Pinterest CEO"
},
{
"code": null,
"e": 1493,
"s": 1273,
"text": "“An advantage of visual search is that it relies entirely on item appearance. There is no need for other data such as bar codes, QR codes, product names, or other product metadata.” — Brent Rabowsky, Amazon Web Services"
},
{
"code": null,
"e": 1728,
"s": 1493,
"text": "“Customers are increasingly using social media platforms, such as Instagram and Pinterest, as a source of inspiration so the visual search has the potential to transform how we shop for the home.” — Mark Steel, Digital Director, Argos"
},
{
"code": null,
"e": 1762,
"s": 1728,
"text": "Tensorflow 2.0 and Tensorflow Hub"
},
{
"code": null,
"e": 1976,
"s": 1762,
"text": "Tensorflow is an end-to-end open-source platform for machine learning developed by Google. It has tools, libraries and community resources that let developers easily build and deploy machine learning applications."
},
{
"code": null,
"e": 2287,
"s": 1976,
"text": "TensorFlow Hub provides many reusable machine learning models. It makes transfer learning very easy as it provides pre-trained models for different problem domains and different tasks such as image classification, image segmentation, pose detection, text embeddings, text classification, video generation, etc."
},
{
"code": null,
"e": 2375,
"s": 2287,
"text": "For further information about the transfer learning, you can check my previous article."
},
{
"code": null,
"e": 2398,
"s": 2375,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2431,
"s": 2398,
"text": "What is an image feature vector?"
},
{
"code": null,
"e": 2587,
"s": 2431,
"text": "An image feature vector is a list of numbers that represents a whole image, typically used for image similarity calculations or image classification tasks."
},
{
"code": null,
"e": 2804,
"s": 2587,
"text": "In general, low-level image features are minor details of the image, such as lines, edges, corners or dots. High-level features are built on top of low-level features to detect objects and larger shapes in the image."
},
{
"code": null,
"e": 3044,
"s": 2804,
"text": "We can extract both types of features using convolutional neural networks: the first couple of convolutional layers will learn filters for finding low-level features while the later layers will learn to recognize common shapes and objects."
},
{
"code": null,
"e": 3216,
"s": 3044,
"text": "In our case, we will extract high-level features of product images using a pre-trained convolutional neural network which is mobilenet_v2_140_224 stored in Tensorflow Hub."
},
{
"code": null,
"e": 3406,
"s": 3216,
"text": "MobilenetV2 is a simple neural network architecture suitable for mobile and resource-constrained applications. Follow this link to the original paper for further information on MobilenetV2."
},
{
"code": null,
"e": 3539,
"s": 3406,
"text": "Before start coding, it is required to install the Tensorflow 2.0, Tensorflow Hub and Spotify/Annoy libraries on our local computer."
},
{
"code": null,
"e": 3696,
"s": 3539,
"text": "$ virtualenv --system-site-packages -p python3 ./TFvenv$ source ./TFvenv/bin/activate$ pip install tensorflow$ pip install tensorflow-hub$ pip install annoy"
},
{
"code": null,
"e": 3815,
"s": 3696,
"text": "The main purpose of this script is to generate image feature vectors by reading image files located in a local folder."
},
{
"code": null,
"e": 3881,
"s": 3815,
"text": "It has two functions: load_img() and get_image_feature_vectors()."
},
{
"code": null,
"e": 4055,
"s": 3881,
"text": "load_img(path) gets file names which are provided as an argument of the function. Then loads and pre-process the images so that we can use them in our MobilenetV2 CNN model."
},
{
"code": null,
"e": 4092,
"s": 4055,
"text": "Pre-processing steps are as follows;"
},
{
"code": null,
"e": 4168,
"s": 4092,
"text": "Decoding the image to W x H x 3 shape tensor with the data type of integer."
},
{
"code": null,
"e": 4298,
"s": 4168,
"text": "Resizing the image to 224 x 224 x 3 shape tensor as the version of the MobilenetV2 model we use expects that specific image size."
},
{
"code": null,
"e": 4457,
"s": 4298,
"text": "Converting the data type of tensor to float and adding a new axis to make tensor shape 1 x 224 x 224 x 3. This is the exact input shape expected by the model."
},
{
"code": null,
"e": 4611,
"s": 4457,
"text": "get_image_feature_vectors() function is where I extract the image feature vectors. You can see below, step by step definition of what this function does;"
},
{
"code": null,
"e": 4660,
"s": 4611,
"text": "Loads the MobilenetV2 model using Tensorflow Hub"
},
{
"code": null,
"e": 4747,
"s": 4660,
"text": "Loops through all images in a local folder and passing them to load_img(path) function"
},
{
"code": null,
"e": 4780,
"s": 4747,
"text": "Infers the image feature vectors"
},
{
"code": null,
"e": 4851,
"s": 4780,
"text": "Saves each one of the feature vectors to a separate file for later use"
},
{
"code": null,
"e": 7450,
"s": 4851,
"text": "# get_image_feature_vectors.py################################################## Imports and function definitions################################################## For running inference on the TF-Hub module with Tensorflowimport tensorflow as tfimport tensorflow_hub as hub# For saving 'feature vectors' into a txt fileimport numpy as np# Glob for reading file names in a folderimport globimport os.path################################################################################################### This function:# Loads the JPEG image at the given path# Decodes the JPEG image to a uint8 W X H X 3 tensor# Resizes the image to 224 x 224 x 3 tensor# Returns the pre processed image as 224 x 224 x 3 tensor#################################################def load_img(path):# Reads the image file and returns data type of string img = tf.io.read_file(path)# Decodes the image to W x H x 3 shape tensor with type of uint8 img = tf.io.decode_jpeg(img, channels=3)# Resizes the image to 224 x 224 x 3 shape tensor img = tf.image.resize_with_pad(img, 224, 224)# Converts the data type of uint8 to float32 by adding a new axis # img becomes 1 x 224 x 224 x 3 tensor with data type of float32 # This is required for the mobilenet model we are using img = tf.image.convert_image_dtype(img,tf.float32)[tf.newaxis, ...] return img################################################## This function:# Loads the mobilenet model in TF.HUB# Makes an inference for all images stored in a local folder# Saves each of the feature vectors in a file#################################################def get_image_feature_vectors(): # Definition of module with using tfhub.dev module_handle = \"https://tfhub.dev/google/imagenet/ mobilenet_v2_140_224/feature_vector/4\" # Loads the module module = hub.load(module_handle)# Loops through all images in a local folder for filename in glob.glob('/Users/erdemisbilen/Angular/ fashionWebScraping/images_scraped/full/*.jpg'): print(filename)# Loads and pre-process the image img = load_img(filename)# Calculate the image feature vector of the img features = module(img)# Remove single-dimensional entries from the 'features' array feature_set = np.squeeze(features) # Saves the image feature vectors into a file for later use outfile_name = os.path.basename(filename) + \".npz\" out_path = os.path.join('/Users/erdemisbilen/Angular/ fashionWebScraping/images_scraped/feature-vectors/', outfile_name)# Saves the 'feature_set' to a text file np.savetxt(out_path, feature_set, delimiter=',')get_image_feature_vectors()"
},
{
"code": null,
"e": 7481,
"s": 7450,
"text": "What is Spotify/Annoy Library?"
},
{
"code": null,
"e": 7603,
"s": 7481,
"text": "Annoy (Approximate Nearest Neighbor Oh Yeah), is an open-sourced library for approximate nearest neighbor implementation."
},
{
"code": null,
"e": 7727,
"s": 7603,
"text": "I will use it to find the image feature vectors in a given set that is closest (or most similar) to a given feature vector."
},
{
"code": null,
"e": 7874,
"s": 7727,
"text": "There are just two main parameters needed to tune Annoy: the number of trees n_trees and the number of nodes to inspect during searching search_k."
},
{
"code": null,
"e": 8027,
"s": 7874,
"text": "n_trees is provided during build time and affects the build time and the index size. A larger value will give more accurate results, but larger indexes."
},
{
"code": null,
"e": 8180,
"s": 8027,
"text": "search_k is provided in runtime and affects the search performance. A larger value will give more accurate results, but will take longer time to return."
},
{
"code": null,
"e": 8199,
"s": 8180,
"text": "from Spotify/Annoy"
},
{
"code": null,
"e": 8347,
"s": 8199,
"text": "The main purpose of this script is to calculate image similarity scores using image feature vectors we have just generated in the previous chapter."
},
{
"code": null,
"e": 8403,
"s": 8347,
"text": "It has two functions: match_id(filename) and cluster()."
},
{
"code": null,
"e": 8493,
"s": 8403,
"text": "cluster() function does the image similarity calculation with the following process flow:"
},
{
"code": null,
"e": 8581,
"s": 8493,
"text": "Builds an annoy index by appending all image feature vectors stored in the local folder"
},
{
"code": null,
"e": 8636,
"s": 8581,
"text": "Calculates the nearest neighbors and similarity scores"
},
{
"code": null,
"e": 8699,
"s": 8636,
"text": "Saves and stores the information in a JSON file for later use."
},
{
"code": null,
"e": 9047,
"s": 8699,
"text": "match_id(filename) is a helper function as I need to match images with the product id’s to enable visual product search in my web application. There is a JSON file that contains all the product id information matched with the product image names. This function retrieves the product id information for a given image file name using that JSON file."
},
{
"code": null,
"e": 13979,
"s": 9047,
"text": "# cluster_image_feature_vectors.py################################################## Imports and function definitions################################################## Numpy for loading image feature vectors from fileimport numpy as np# Time for measuring the process timeimport time# Glob for reading file names in a folderimport globimport os.path# json for storing data in json fileimport json# Annoy and Scipy for similarity calculationfrom annoy import AnnoyIndexfrom scipy import spatial################################################################################################### This function reads from 'image_data.json' file# Looks for a specific 'filename' value# Returns the product id when product image names are matched# So it is used to find product id based on the product image name#################################################def match_id(filename): with open('/Users/erdemisbilen/Angular/fashionWebScraping /jsonFiles/image_data.json') as json_file:for file in json_file: seen = json.loads(file)for line in seen: if filename==line['imageName']: print(line) return line['productId'] break################################################################################################### This function:# Reads all image feature vectores stored in /feature-vectors/*.npz# Adds them all in Annoy Index# Builds ANNOY index# Calculates the nearest neighbors and image similarity metrics# Stores image similarity scores with productID in a json file#################################################def cluster(): start_time = time.time() print(\"---------------------------------\") print (\"Step.1 - ANNOY index generation - Started at %s\" %time.ctime()) print(\"---------------------------------\")# Defining data structures as empty dict file_index_to_file_name = {} file_index_to_file_vector = {} file_index_to_product_id = {}# Configuring annoy parameters dims = 1792 n_nearest_neighbors = 20 trees = 10000# Reads all file names which stores feature vectors allfiles = glob.glob('/Users/erdemisbilen/Angular /fashionWebScraping/images_scraped/feature-vectors/*.npz') t = AnnoyIndex(dims, metric='angular')for file_index, i in enumerate(allfiles):# Reads feature vectors and assigns them into the file_vector file_vector = np.loadtxt(i)# Assigns file_name, feature_vectors and corresponding product_id file_name = os.path.basename(i).split('.')[0] file_index_to_file_name[file_index] = file_name file_index_to_file_vector[file_index] = file_vector file_index_to_product_id[file_index] = match_id(file_name)# Adds image feature vectors into annoy index t.add_item(file_index, file_vector)print(\"---------------------------------\") print(\"Annoy index : %s\" %file_index) print(\"Image file name : %s\" %file_name) print(\"Product id : %s\" %file_index_to_product_id[file_index]) print(\"--- %.2f minutes passed ---------\" % ((time.time() - start_time)/60))# Builds annoy index t.build(trees)print (\"Step.1 - ANNOY index generation - Finished\") print (\"Step.2 - Similarity score calculation - Started \")named_nearest_neighbors = []# Loops through all indexed items for i in file_index_to_file_name.keys(): # Assigns master file_name, image feature vectors # and product id values master_file_name = file_index_to_file_name[i] master_vector = file_index_to_file_vector[i] master_product_id = file_index_to_product_id[i]# Calculates the nearest neighbors of the master item nearest_neighbors = t.get_nns_by_item(i, n_nearest_neighbors)# Loops through the nearest neighbors of the master item for j in nearest_neighbors: print(j)# Assigns file_name, image feature vectors and # product id values of the similar item neighbor_file_name = file_index_to_file_name[j] neighbor_file_vector = file_index_to_file_vector[j] neighbor_product_id = file_index_to_product_id[j]# Calculates the similarity score of the similar item similarity = 1 - spatial.distance.cosine(master_vector, neighbor_file_vector)rounded_similarity = int((similarity * 10000)) / 10000.0# Appends master product id with the similarity score # and the product id of the similar items named_nearest_neighbors.append({ 'similarity': rounded_similarity, 'master_pi': master_product_id, 'similar_pi': neighbor_product_id})print(\"---------------------------------\") print(\"Similarity index : %s\" %i) print(\"Master Image file name : %s\" %file_index_to_file_name[i]) print(\"Nearest Neighbors. : %s\" %nearest_neighbors) print(\"--- %.2f minutes passed ---------\" % ((time.time() - start_time)/60))print (\"Step.2 - Similarity score calculation - Finished \")# Writes the 'named_nearest_neighbors' to a json file with open('nearest_neighbors.json', 'w') as out: json.dump(named_nearest_neighbors, out)print (\"Step.3 - Data stored in 'nearest_neighbors.json' file \") print(\"--- Prosess completed in %.2f minutes ---------\" % ((time.time() - start_time)/60))cluster()"
},
{
"code": null,
"e": 14227,
"s": 13979,
"text": "As you can see, I saved the highest 20 similarity scores for each product image in a JSON file with matching product id information. This is because I don’t what to do the similarity calculation on the client-side to eliminate the effort required."
},
{
"code": null,
"e": 14453,
"s": 14227,
"text": "With the similarity scores stored in the JSON file, I can easily populate Elasticsearch clusters, or populate a database to enable near real-time visual search experience on the browser on my price comparison web application."
},
{
"code": null,
"e": 14647,
"s": 14453,
"text": "To develop such an application, web scraping plays an important role to develop and maintain product datasets daily basis. If you are interested in this subject, check my related article below."
},
{
"code": null,
"e": 14670,
"s": 14647,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 14780,
"s": 14670,
"text": "As you can see above, MobileNetV2 and Annoy together do a pretty good job of finding visual similar products."
},
{
"code": null,
"e": 14982,
"s": 14780,
"text": "One disadvantage of this implementation is that it only works at the whole image level. It does not provide good results if the backgrounds of the images are different, even if the objects are similar."
}
] |
Remove duplicate elements from sorted Array | Practice | GeeksforGeeks
|
Given a sorted array A[] of size N, delete all the duplicates elements from A[].
Note: Don't use set or HashMap to solve the problem.
Example 1:
Input:
N = 5
Array = {2, 2, 2, 2, 2}
Output: 2
Explanation: After removing all the duplicates
only one instance of 2 will remain.
Example 2:
Input:
N = 3
Array = {1, 2, 2}
Output: 1 2
Your Task:
You don't need to read input or print anything. Complete the function remove_duplicate() which takes the array A[] and its size N as input parameters and modifies it in place to delete all the duplicates. The function must return an integer X denoting the new modified size of the array.
Note: The generated output will print all the elements of the modified array from index 0 to X-1.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 104
1 ≤ A[i] ≤ 106
0
aravindmn75832 days ago
//c++ solution;
class Solution{public: int remove_duplicate(int a[],int n){ // code here int res = 0; for(int i=0; i<n; i++){ if(a[i]!=a[i+1]){ a[res] = a[i]; res++; } } return res; }};
0
sahum67033 days ago
easiest c++ solution || rumtime 0.48/1.38
int remove_duplicate(int arr[],int n){
int ans=n;
int k=arr[0];
for(int i=1;i<n;i++){
if(arr[i]==k){
arr[i]=INT_MAX;
ans--;
}
else
k=arr[i];
}
sort(arr,arr+n);
return ans;
}
0
animesh10311 week ago
int remove_duplicate(int a[],int n){ // code here int K = 1; int current = a[0]; for(int i = 1; i < n; i++) { if(current != a[i]) { a[K] = a[i]; K++; current = a[i]; } else { a[i] = 999; } } return K; }
0
shyampatel21 week ago
Python ! Not O(n) solution but it passed all tests lol def remove_duplicate(self, A, N): # code here A[:] = sorted(set(A)) return len(A)
0
vinayakmagd96alt2 weeks ago
JAVA | Easy solution | Time complexity O(n)
int remove_duplicate(int A[],int N){
int index = 1;
int prev = A[0];
for(int i = 1; i < N; i++) {
if(prev != A[i]) {
A[index] = A[i];
index++;
prev = A[i];
} else {
A[i] = 0;
}
}
return index;
}
0
achaudhary1732 weeks ago
//User function Template for Java
class Solution { int remove_duplicate(int A[],int N){ if(N == 0){ return 0; } int j = 1; for(int i =0; i < A.length - 1; i++ ){ if (A[i] != A[i + 1]){ A[j] = A[i + 1]; j++; } } return j; }}
0
vaishalisonvane282 weeks ago
class Solution { int remove_duplicate(int A[],int N){ Arrays.sort(A); int j=0; for(int i=0; i<N-1; i++){ if(A[i]!=A[i+1]){ A[j++] = A[i]; } } A[j++] = A[N-1]; return j; } }
+1
harshitjinodiya4 weeks ago
Java Solution
class Solution { int remove_duplicate(int A[],int N){ int res=1; for(int i=1;i<N;i++) { if(A[i]!=A[res-1]) { A[res] = A[i]; res++; } } return res; }}
+3
swapniltayal4221 month ago
class Solution{public: int remove_duplicate(int a[],int n){ // code here int k = 1; for (int i=1; i<n; i++){ if (a[i] != a[k-1]){ a[k] = a[i]; k++; } }return k; }};
0
sheikhsa21 month ago
def remove_duplicate(self, A, N): # code here i = 0 while len(A) - 1 > i: if A[i+1] == A[i]: A.pop(i+1) else: i += 1 return len(A)
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": 372,
"s": 238,
"text": "Given a sorted array A[] of size N, delete all the duplicates elements from A[].\nNote: Don't use set or HashMap to solve the problem."
},
{
"code": null,
"e": 384,
"s": 372,
"text": "\nExample 1:"
},
{
"code": null,
"e": 516,
"s": 384,
"text": "Input:\nN = 5\nArray = {2, 2, 2, 2, 2}\nOutput: 2\nExplanation: After removing all the duplicates \nonly one instance of 2 will remain.\n"
},
{
"code": null,
"e": 527,
"s": 516,
"text": "Example 2:"
},
{
"code": null,
"e": 571,
"s": 527,
"text": "Input:\nN = 3\nArray = {1, 2, 2}\nOutput: 1 2 "
},
{
"code": null,
"e": 972,
"s": 571,
"text": "\nYour Task: \nYou don't need to read input or print anything. Complete the function remove_duplicate() which takes the array A[] and its size N as input parameters and modifies it in place to delete all the duplicates. The function must return an integer X denoting the new modified size of the array. \nNote: The generated output will print all the elements of the modified array from index 0 to X-1."
},
{
"code": null,
"e": 1035,
"s": 972,
"text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1076,
"s": 1035,
"text": "\nConstraints:\n1 ≤ N ≤ 104\n1 ≤ A[i] ≤ 106"
},
{
"code": null,
"e": 1078,
"s": 1076,
"text": "0"
},
{
"code": null,
"e": 1102,
"s": 1078,
"text": "aravindmn75832 days ago"
},
{
"code": null,
"e": 1118,
"s": 1102,
"text": "//c++ solution;"
},
{
"code": null,
"e": 1377,
"s": 1118,
"text": "class Solution{public: int remove_duplicate(int a[],int n){ // code here int res = 0; for(int i=0; i<n; i++){ if(a[i]!=a[i+1]){ a[res] = a[i]; res++; } } return res; }};"
},
{
"code": null,
"e": 1379,
"s": 1377,
"text": "0"
},
{
"code": null,
"e": 1399,
"s": 1379,
"text": "sahum67033 days ago"
},
{
"code": null,
"e": 1441,
"s": 1399,
"text": "easiest c++ solution || rumtime 0.48/1.38"
},
{
"code": null,
"e": 1753,
"s": 1443,
"text": "int remove_duplicate(int arr[],int n){\n int ans=n;\n int k=arr[0];\n for(int i=1;i<n;i++){\n if(arr[i]==k){\n arr[i]=INT_MAX;\n ans--;\n }\n else\n k=arr[i];\n }\n sort(arr,arr+n);\n return ans;\n }"
},
{
"code": null,
"e": 1755,
"s": 1753,
"text": "0"
},
{
"code": null,
"e": 1777,
"s": 1755,
"text": "animesh10311 week ago"
},
{
"code": null,
"e": 2135,
"s": 1777,
"text": "int remove_duplicate(int a[],int n){ // code here int K = 1; int current = a[0]; for(int i = 1; i < n; i++) { if(current != a[i]) { a[K] = a[i]; K++; current = a[i]; } else { a[i] = 999; } } return K; }"
},
{
"code": null,
"e": 2137,
"s": 2135,
"text": "0"
},
{
"code": null,
"e": 2159,
"s": 2137,
"text": "shyampatel21 week ago"
},
{
"code": null,
"e": 2296,
"s": 2159,
"text": "Python ! Not O(n) solution but it passed all tests lol def remove_duplicate(self, A, N): # code here A[:] = sorted(set(A)) return len(A)"
},
{
"code": null,
"e": 2298,
"s": 2296,
"text": "0"
},
{
"code": null,
"e": 2326,
"s": 2298,
"text": "vinayakmagd96alt2 weeks ago"
},
{
"code": null,
"e": 2370,
"s": 2326,
"text": "JAVA | Easy solution | Time complexity O(n)"
},
{
"code": null,
"e": 2704,
"s": 2372,
"text": "int remove_duplicate(int A[],int N){\n int index = 1;\n int prev = A[0];\n for(int i = 1; i < N; i++) {\n if(prev != A[i]) {\n A[index] = A[i];\n index++;\n prev = A[i];\n } else {\n A[i] = 0;\n }\n }\n return index;\n }"
},
{
"code": null,
"e": 2706,
"s": 2704,
"text": "0"
},
{
"code": null,
"e": 2731,
"s": 2706,
"text": "achaudhary1732 weeks ago"
},
{
"code": null,
"e": 2765,
"s": 2731,
"text": "//User function Template for Java"
},
{
"code": null,
"e": 3112,
"s": 2765,
"text": "class Solution { int remove_duplicate(int A[],int N){ if(N == 0){ return 0; } int j = 1; for(int i =0; i < A.length - 1; i++ ){ if (A[i] != A[i + 1]){ A[j] = A[i + 1]; j++; } } return j; }}"
},
{
"code": null,
"e": 3114,
"s": 3112,
"text": "0"
},
{
"code": null,
"e": 3143,
"s": 3114,
"text": "vaishalisonvane282 weeks ago"
},
{
"code": null,
"e": 3413,
"s": 3143,
"text": "class Solution { int remove_duplicate(int A[],int N){ Arrays.sort(A); int j=0; for(int i=0; i<N-1; i++){ if(A[i]!=A[i+1]){ A[j++] = A[i]; } } A[j++] = A[N-1]; return j; } } "
},
{
"code": null,
"e": 3416,
"s": 3413,
"text": "+1"
},
{
"code": null,
"e": 3443,
"s": 3416,
"text": "harshitjinodiya4 weeks ago"
},
{
"code": null,
"e": 3457,
"s": 3443,
"text": "Java Solution"
},
{
"code": null,
"e": 3701,
"s": 3459,
"text": "class Solution { int remove_duplicate(int A[],int N){ int res=1; for(int i=1;i<N;i++) { if(A[i]!=A[res-1]) { A[res] = A[i]; res++; } } return res; }}"
},
{
"code": null,
"e": 3704,
"s": 3701,
"text": "+3"
},
{
"code": null,
"e": 3731,
"s": 3704,
"text": "swapniltayal4221 month ago"
},
{
"code": null,
"e": 3972,
"s": 3731,
"text": "class Solution{public: int remove_duplicate(int a[],int n){ // code here int k = 1; for (int i=1; i<n; i++){ if (a[i] != a[k-1]){ a[k] = a[i]; k++; } }return k; }};"
},
{
"code": null,
"e": 3974,
"s": 3972,
"text": "0"
},
{
"code": null,
"e": 3995,
"s": 3974,
"text": "sheikhsa21 month ago"
},
{
"code": null,
"e": 4156,
"s": 3995,
"text": " def remove_duplicate(self, A, N): # code here i = 0 while len(A) - 1 > i: if A[i+1] == A[i]: A.pop(i+1) else: i += 1 return len(A) "
},
{
"code": null,
"e": 4302,
"s": 4156,
"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": 4338,
"s": 4302,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4348,
"s": 4338,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4358,
"s": 4348,
"text": "\nContest\n"
},
{
"code": null,
"e": 4421,
"s": 4358,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4569,
"s": 4421,
"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": 4777,
"s": 4569,
"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": 4883,
"s": 4777,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Java Examples - Swing applet in JAVA?
|
How to use swing applet in JAVA?
Following example demonstrates how to go use Swing Applet in JAVA by implementing ActionListener & by creating JLabels.
import javax.swing.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class SApplet extends Applet implements ActionListener {
TextField input,output;
Label label1,label2;
Button b1;
JLabel lbl;
int num, sum = 0;
public void init() {
label1 = new Label("please enter number : ");
add(label1);
label1.setBackground(Color.yellow);
label1.setForeground(Color.magenta);
input = new TextField(5);
add(input);
label2 = new Label("Sum : ");
add(label2);
label2.setBackground(Color.yellow);
label2.setForeground(Color.magenta);
output = new TextField(20);
add(output);
b1 = new Button("Add");
add(b1);
b1.addActionListener(this);
lbl = new JLabel("Swing Applet Example. ");
add(lbl);
setBackground(Color.yellow);
}
public void actionPerformed(ActionEvent ae ){
try {
num = Integer.parseInt(input.getText());
sum = sum+num;
input.setText("");
output.setText(Integer.toString(sum));
lbl.setForeground(Color.blue);
lbl.setText("Output of the second Text Box : " + output.getText());
} catch(NumberFormatException e) {
lbl.setForeground(Color.red);
lbl.setText("Invalid Entry!");
}
}
}
The above code sample will produce the following result in a java enabled web browser.
View in Browser.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2101,
"s": 2068,
"text": "How to use swing applet in JAVA?"
},
{
"code": null,
"e": 2221,
"s": 2101,
"text": "Following example demonstrates how to go use Swing Applet in JAVA by implementing ActionListener & by creating JLabels."
},
{
"code": null,
"e": 3581,
"s": 2221,
"text": "import javax.swing.*;\nimport java.applet.*;\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class SApplet extends Applet implements ActionListener {\n TextField input,output;\n Label label1,label2;\n Button b1;\n JLabel lbl;\n int num, sum = 0;\n \n public void init() {\n label1 = new Label(\"please enter number : \");\n add(label1);\n label1.setBackground(Color.yellow);\n label1.setForeground(Color.magenta);\n input = new TextField(5);\n \n add(input);\n label2 = new Label(\"Sum : \");\n \n add(label2);\n label2.setBackground(Color.yellow);\n label2.setForeground(Color.magenta);\n output = new TextField(20);\n \n add(output);\n b1 = new Button(\"Add\");\n \n add(b1);\n b1.addActionListener(this);\n lbl = new JLabel(\"Swing Applet Example. \");\n add(lbl);\n setBackground(Color.yellow);\n } \n public void actionPerformed(ActionEvent ae ){\n try {\n num = Integer.parseInt(input.getText());\n sum = sum+num;\n input.setText(\"\");\n output.setText(Integer.toString(sum));\n lbl.setForeground(Color.blue);\n lbl.setText(\"Output of the second Text Box : \" + output.getText());\n } catch(NumberFormatException e) {\n lbl.setForeground(Color.red);\n lbl.setText(\"Invalid Entry!\");\n }\n } \n}"
},
{
"code": null,
"e": 3668,
"s": 3581,
"text": "The above code sample will produce the following result in a java enabled web browser."
},
{
"code": null,
"e": 3687,
"s": 3668,
"text": "View in Browser. \n"
},
{
"code": null,
"e": 3694,
"s": 3687,
"text": " Print"
},
{
"code": null,
"e": 3705,
"s": 3694,
"text": " Add Notes"
}
] |
Difference between import and package in Java?
|
In Java classes and interfaces related to each other are grouped under a package. Package is nothing but a directory storing classes and interfaces of a particular concept. For example, all the classes and interfaces related to input and output operations are stored in java.io package.
You can group required classes and interfaces under one package just by declaring the package at the top of the Class/Interface (file) using the keyword package as −
package com.tutorialspoint.mypackage;
public class Sample{
public void demo(){
System.out.println("This is a method of the sample class");
}
public static void main(String args[]){
System.out.println("Hello how are you......");
}
}
Unlike other programs to compile a program with a package, you need to use the –d option of the javac command specifying the destination path where you need to create the package.
javac –d . Sample.java
If you haven’t mentioned the destination path the package will be created in the current directory.
To execute the byte code within a file you need to specify the absolute class name (name along with the package) as −
java com.tutorialspoint.mypackage.Sample
Hello how are you......
To access the classes/interfaces that are grouped under a package, you need to add the location of the package in the classpath variable (or make sure the package is in the current directory) and import the class/interface of it using the import keyword.
import com.tutorialspoint.mypackage.Sample;
public class Test{
public static void main(String args[]){
Sample obj = new Sample();
obj.demo();
}
}
This is a method of the sample class
As discussed above the package keyword is used to group certain classes and interface under one package and, the import keyword is used include/use the classes and interface from a package in the current program.
|
[
{
"code": null,
"e": 1349,
"s": 1062,
"text": "In Java classes and interfaces related to each other are grouped under a package. Package is nothing but a directory storing classes and interfaces of a particular concept. For example, all the classes and interfaces related to input and output operations are stored in java.io package."
},
{
"code": null,
"e": 1515,
"s": 1349,
"text": "You can group required classes and interfaces under one package just by declaring the package at the top of the Class/Interface (file) using the keyword package as −"
},
{
"code": null,
"e": 1771,
"s": 1515,
"text": "package com.tutorialspoint.mypackage;\npublic class Sample{\n public void demo(){\n System.out.println(\"This is a method of the sample class\");\n }\n public static void main(String args[]){\n System.out.println(\"Hello how are you......\");\n }\n}"
},
{
"code": null,
"e": 1951,
"s": 1771,
"text": "Unlike other programs to compile a program with a package, you need to use the –d option of the javac command specifying the destination path where you need to create the package."
},
{
"code": null,
"e": 1974,
"s": 1951,
"text": "javac –d . Sample.java"
},
{
"code": null,
"e": 2074,
"s": 1974,
"text": "If you haven’t mentioned the destination path the package will be created in the current directory."
},
{
"code": null,
"e": 2192,
"s": 2074,
"text": "To execute the byte code within a file you need to specify the absolute class name (name along with the package) as −"
},
{
"code": null,
"e": 2257,
"s": 2192,
"text": "java com.tutorialspoint.mypackage.Sample\nHello how are you......"
},
{
"code": null,
"e": 2512,
"s": 2257,
"text": "To access the classes/interfaces that are grouped under a package, you need to add the location of the package in the classpath variable (or make sure the package is in the current directory) and import the class/interface of it using the import keyword."
},
{
"code": null,
"e": 2676,
"s": 2512,
"text": "import com.tutorialspoint.mypackage.Sample;\npublic class Test{\n public static void main(String args[]){\n Sample obj = new Sample();\n obj.demo();\n }\n}"
},
{
"code": null,
"e": 2713,
"s": 2676,
"text": "This is a method of the sample class"
},
{
"code": null,
"e": 2926,
"s": 2713,
"text": "As discussed above the package keyword is used to group certain classes and interface under one package and, the import keyword is used include/use the classes and interface from a package in the current program."
}
] |
How to set multiple cookies in JavaScript?
|
With JavaScript, to set more than one cookie, set document.cookie more than once using the; separator.
You can try to run the following code to set multiple cookies −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script>
var num=1;
function addCookie() {
document.cookie=num+"="+num;
num++;
}
function listCookies() {
var result = document.cookie;
document.getElementById("list").innerHTML=result;
}
function removeCookies() {
var res = document.cookie;
var multiple = res.split(";");
for(var i=0;i<multiple.length;i++) {
var key = multiple[i].split("=");
document.cookie=key[0]+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
}
}
</script>
</head>
<body>
<button onclick='addCookie()'>ADD</button><br>
<button onclick='listCookies()'>LIST COOKIES</button><br>
<button onclick='removeCookies()'>REMOVE</button>
<h1>Cookies List</h1>
<p id="list"></p>
</body>
</html>
|
[
{
"code": null,
"e": 1165,
"s": 1062,
"text": "With JavaScript, to set more than one cookie, set document.cookie more than once using the; separator."
},
{
"code": null,
"e": 1229,
"s": 1165,
"text": "You can try to run the following code to set multiple cookies −"
},
{
"code": null,
"e": 1239,
"s": 1229,
"text": "Live Demo"
},
{
"code": null,
"e": 2112,
"s": 1239,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n var num=1;\n function addCookie() {\n document.cookie=num+\"=\"+num;\n num++;\n }\n function listCookies() {\n var result = document.cookie;\n document.getElementById(\"list\").innerHTML=result;\n }\n function removeCookies() {\n var res = document.cookie;\n var multiple = res.split(\";\");\n for(var i=0;i<multiple.length;i++) {\n var key = multiple[i].split(\"=\");\n document.cookie=key[0]+\"=; expires=Thu, 01 Jan 1970 00:00:00 UTC\";\n }\n }\n </script>\n </head>\n <body>\n <button onclick='addCookie()'>ADD</button><br>\n <button onclick='listCookies()'>LIST COOKIES</button><br>\n <button onclick='removeCookies()'>REMOVE</button>\n <h1>Cookies List</h1>\n <p id=\"list\"></p>\n </body>\n</html>"
}
] |
Download Anything to Google Drive using Google colab - GeeksforGeeks
|
30 Oct, 2019
When we download/upload something from a cloud server, it gives more transfer rate as compared to a normal server. We can use Google Drive for storage as well as fast speed download. The problem is how to upload something to G-Drive direct from Internet. So, Here we will see a solution to upload anything to Google drive directly from Internet.
All we need is google account and a few lines of code.
Google Colab:
Google Colab is a free cloud service with GPU support. It is like Jupyter Notebook and very simple to use. In this tutorial, we will be using Google Colab to download anything to our google drive.
Step #1 : Sign in to Google Colab and Create a new Python3 notebook. Step #2 : Importing google drive to colab
To import google drive, write this code in code section of colab and run it by Ctrl+Enter.
from google.colab import drivedrive.mount('/content/gdrive')
On running code, one blue link and a text box will appear we need to provide a permission text. So click the link and a new tab will open where you will be asked for permission to access google drive. After providing permissions a text will be displayed that we need to Copy and paste on colabs text box.
Paste text in box and press enter. That all to import gdrive. We can see google drive on Left side Panel. Step #3 : Download something to Google Drive
To download something all we need is URL to downloadable file.
import requests file_url = "http://1.droppdf.com/files/5iHzx/automate-the-boring-stuff-with-python-2015-.pdf" r = requests.get(file_url, stream = True) with open("/content/gdrive/My Drive/python.pdf", "wb") as file: for block in r.iter_content(chunk_size = 1024): if block: file.write(block)
Run this code to download the files in gdrive (Change the file_url with your file’s url).We can see on the left side panel that pdf file is downloaded.
Conclusion :We can use google colab to download any file on google drive. As you can see a folder parrot (parrot OS of 3.7 GB ), downloaded to gdrive using Colab.
nidhi_biet
GBlog
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Front End Developer Skills That You Need in 2022
DSA Sheet by Love Babbar
6 Best IDE's For Python in 2022
GET and POST requests using Python
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Read JSON file using Python
Python map() function
Python Dictionary
Taking input in Python
Read a file line by line in Python
|
[
{
"code": null,
"e": 24800,
"s": 24772,
"text": "\n30 Oct, 2019"
},
{
"code": null,
"e": 25146,
"s": 24800,
"text": "When we download/upload something from a cloud server, it gives more transfer rate as compared to a normal server. We can use Google Drive for storage as well as fast speed download. The problem is how to upload something to G-Drive direct from Internet. So, Here we will see a solution to upload anything to Google drive directly from Internet."
},
{
"code": null,
"e": 25201,
"s": 25146,
"text": "All we need is google account and a few lines of code."
},
{
"code": null,
"e": 25215,
"s": 25201,
"text": "Google Colab:"
},
{
"code": null,
"e": 25412,
"s": 25215,
"text": "Google Colab is a free cloud service with GPU support. It is like Jupyter Notebook and very simple to use. In this tutorial, we will be using Google Colab to download anything to our google drive."
},
{
"code": null,
"e": 25523,
"s": 25412,
"text": "Step #1 : Sign in to Google Colab and Create a new Python3 notebook. Step #2 : Importing google drive to colab"
},
{
"code": null,
"e": 25614,
"s": 25523,
"text": "To import google drive, write this code in code section of colab and run it by Ctrl+Enter."
},
{
"code": "from google.colab import drivedrive.mount('/content/gdrive')",
"e": 25675,
"s": 25614,
"text": null
},
{
"code": null,
"e": 25980,
"s": 25675,
"text": "On running code, one blue link and a text box will appear we need to provide a permission text. So click the link and a new tab will open where you will be asked for permission to access google drive. After providing permissions a text will be displayed that we need to Copy and paste on colabs text box."
},
{
"code": null,
"e": 26131,
"s": 25980,
"text": "Paste text in box and press enter. That all to import gdrive. We can see google drive on Left side Panel. Step #3 : Download something to Google Drive"
},
{
"code": null,
"e": 26194,
"s": 26131,
"text": "To download something all we need is URL to downloadable file."
},
{
"code": "import requests file_url = \"http://1.droppdf.com/files/5iHzx/automate-the-boring-stuff-with-python-2015-.pdf\" r = requests.get(file_url, stream = True) with open(\"/content/gdrive/My Drive/python.pdf\", \"wb\") as file: for block in r.iter_content(chunk_size = 1024): if block: file.write(block) ",
"e": 26517,
"s": 26194,
"text": null
},
{
"code": null,
"e": 26669,
"s": 26517,
"text": "Run this code to download the files in gdrive (Change the file_url with your file’s url).We can see on the left side panel that pdf file is downloaded."
},
{
"code": null,
"e": 26832,
"s": 26669,
"text": "Conclusion :We can use google colab to download any file on google drive. As you can see a folder parrot (parrot OS of 3.7 GB ), downloaded to gdrive using Colab."
},
{
"code": null,
"e": 26843,
"s": 26832,
"text": "nidhi_biet"
},
{
"code": null,
"e": 26849,
"s": 26843,
"text": "GBlog"
},
{
"code": null,
"e": 26856,
"s": 26849,
"text": "Python"
},
{
"code": null,
"e": 26872,
"s": 26856,
"text": "Python Programs"
},
{
"code": null,
"e": 26970,
"s": 26872,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26979,
"s": 26970,
"text": "Comments"
},
{
"code": null,
"e": 26992,
"s": 26979,
"text": "Old Comments"
},
{
"code": null,
"e": 27048,
"s": 26992,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 27073,
"s": 27048,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 27105,
"s": 27073,
"text": "6 Best IDE's For Python in 2022"
},
{
"code": null,
"e": 27140,
"s": 27105,
"text": "GET and POST requests using Python"
},
{
"code": null,
"e": 27202,
"s": 27140,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27230,
"s": 27202,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 27252,
"s": 27230,
"text": "Python map() function"
},
{
"code": null,
"e": 27270,
"s": 27252,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27293,
"s": 27270,
"text": "Taking input in Python"
}
] |
How to extract numbers from string in PHP ? - GeeksforGeeks
|
21 May, 2021
In this article, we will extract numbers from strings using PHP. There are various built-in methods to extract numbers from strings, some of them are discussed below.
Methods:
Using preg_match_all() Function.
Using filter_var() Function.
Using preg_replace() function.
Method 1: Using preg_match_all() Function.
Note: preg_match() function is used to extract numbers from a string. Usually, the search starts from the beginning of the subject string. The optional parameter offset is used to specify the position from where to start the search.
Syntax:
int preg_match( $pattern, $input, $matches, $flags, $offset )
Return value: It returns true if a pattern exists, otherwise false.
Example 1: The following example extracts Integer Numbers using the preg_match_all() function.
PHP
<?php// PHP program to illustrate// preg_match function// Declare a variable and initialize it$geeks = 'Welcome 2 Geeks 4 Geeks.'; // Use preg_match_all() function to check matchpreg_match_all('!\d+!', $geeks, $matches); // print output of functionprint_r($matches); ?>
Array
(
[0] => Array
(
[0] => 2
[1] => 4
)
)
Example 2: The following example extracts decimal numbers using the preg_match_all() function.
PHP
<?php// Declare a variable and initialize it$geeks = 'Welcome 2 Geeks 4.8 Geeks.'; // Use preg_match_all() function to check matchpreg_match_all('!\d+\.*\d*!', $geeks, $matches); // Display matches resultprint_r($matches); ?>
Array
(
[0] => Array
(
[0] => 2
[1] => 4.8
)
)
Method 2: Using filter_var() function.
Note: The filter_var() function filters a variable with the specified filter. This function is used to both validate and sanitize the data.
Syntax:
filter_var(var, filtername, options)
Return Value: It returns the filtered data on success, or FALSE on failure.
Example:
PHP
<?php// PHP program to illustrate filter_var Function// Declare a variable and initialize it$geeks = 'Welcome 2 Geeks 4 Geeks.'; // Filter the Numbers from String$int_var = (int)filter_var($geeks, FILTER_SANITIZE_NUMBER_INT); // print output of functionecho ("The numbers are: $int_var \n"); ?>
The numbers are: 24
Method 3: Using preg_replace() function.
Note: The preg_replace() function is an inbuilt function in PHP that is used to perform a regular expression for search and replace the content.
Syntax:
preg_replace( $pattern, $replacement, $subject, $limit, $count )
Return Value: This function returns an array if the subject parameter is an array, or a string otherwise.
Example:
PHP
<?php // PHP program to illustrate // preg_replace function // Declare a variable and initialize it $geeks = 'Welcome 2 Geeks 4 Geeks.'; // Filter the Numbers from String $int_var = preg_replace('/[^0-9]/', '', $geeks); // print output of function echo("The numbers are: $int_var \n"); ?>
The numbers are: 24
PHP-function
PHP-Questions
PHP
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Different ways for passing data to view in Laravel
Create a drop-down list that options fetched from a MySQL database in PHP
How to create admin login page using PHP?
How to generate PDF file using PHP ?
PHP Cookies
PHP | shell_exec() vs exec() Function
PHP str_replace() Function
How to pass form variables from one page to other page in PHP ?
PHP | Ternary Operator
|
[
{
"code": null,
"e": 24972,
"s": 24944,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 25139,
"s": 24972,
"text": "In this article, we will extract numbers from strings using PHP. There are various built-in methods to extract numbers from strings, some of them are discussed below."
},
{
"code": null,
"e": 25148,
"s": 25139,
"text": "Methods:"
},
{
"code": null,
"e": 25181,
"s": 25148,
"text": "Using preg_match_all() Function."
},
{
"code": null,
"e": 25211,
"s": 25181,
"text": "Using filter_var() Function."
},
{
"code": null,
"e": 25243,
"s": 25211,
"text": "Using preg_replace() function."
},
{
"code": null,
"e": 25286,
"s": 25243,
"text": "Method 1: Using preg_match_all() Function."
},
{
"code": null,
"e": 25520,
"s": 25286,
"text": "Note: preg_match() function is used to extract numbers from a string. Usually, the search starts from the beginning of the subject string. The optional parameter offset is used to specify the position from where to start the search."
},
{
"code": null,
"e": 25528,
"s": 25520,
"text": "Syntax:"
},
{
"code": null,
"e": 25590,
"s": 25528,
"text": "int preg_match( $pattern, $input, $matches, $flags, $offset )"
},
{
"code": null,
"e": 25658,
"s": 25590,
"text": "Return value: It returns true if a pattern exists, otherwise false."
},
{
"code": null,
"e": 25753,
"s": 25658,
"text": "Example 1: The following example extracts Integer Numbers using the preg_match_all() function."
},
{
"code": null,
"e": 25757,
"s": 25753,
"text": "PHP"
},
{
"code": "<?php// PHP program to illustrate// preg_match function// Declare a variable and initialize it$geeks = 'Welcome 2 Geeks 4 Geeks.'; // Use preg_match_all() function to check matchpreg_match_all('!\\d+!', $geeks, $matches); // print output of functionprint_r($matches); ?>",
"e": 26030,
"s": 25757,
"text": null
},
{
"code": null,
"e": 26120,
"s": 26030,
"text": "Array\n(\n [0] => Array\n (\n [0] => 2\n [1] => 4\n )\n\n)"
},
{
"code": null,
"e": 26215,
"s": 26120,
"text": "Example 2: The following example extracts decimal numbers using the preg_match_all() function."
},
{
"code": null,
"e": 26219,
"s": 26215,
"text": "PHP"
},
{
"code": "<?php// Declare a variable and initialize it$geeks = 'Welcome 2 Geeks 4.8 Geeks.'; // Use preg_match_all() function to check matchpreg_match_all('!\\d+\\.*\\d*!', $geeks, $matches); // Display matches resultprint_r($matches); ?>",
"e": 26448,
"s": 26219,
"text": null
},
{
"code": null,
"e": 26540,
"s": 26448,
"text": "Array\n(\n [0] => Array\n (\n [0] => 2\n [1] => 4.8\n )\n\n)"
},
{
"code": null,
"e": 26579,
"s": 26540,
"text": "Method 2: Using filter_var() function."
},
{
"code": null,
"e": 26719,
"s": 26579,
"text": "Note: The filter_var() function filters a variable with the specified filter. This function is used to both validate and sanitize the data."
},
{
"code": null,
"e": 26727,
"s": 26719,
"text": "Syntax:"
},
{
"code": null,
"e": 26764,
"s": 26727,
"text": "filter_var(var, filtername, options)"
},
{
"code": null,
"e": 26840,
"s": 26764,
"text": "Return Value: It returns the filtered data on success, or FALSE on failure."
},
{
"code": null,
"e": 26849,
"s": 26840,
"text": "Example:"
},
{
"code": null,
"e": 26853,
"s": 26849,
"text": "PHP"
},
{
"code": "<?php// PHP program to illustrate filter_var Function// Declare a variable and initialize it$geeks = 'Welcome 2 Geeks 4 Geeks.'; // Filter the Numbers from String$int_var = (int)filter_var($geeks, FILTER_SANITIZE_NUMBER_INT); // print output of functionecho (\"The numbers are: $int_var \\n\"); ?>",
"e": 27151,
"s": 26853,
"text": null
},
{
"code": null,
"e": 27172,
"s": 27151,
"text": "The numbers are: 24 "
},
{
"code": null,
"e": 27214,
"s": 27172,
"text": "Method 3: Using preg_replace() function."
},
{
"code": null,
"e": 27359,
"s": 27214,
"text": "Note: The preg_replace() function is an inbuilt function in PHP that is used to perform a regular expression for search and replace the content."
},
{
"code": null,
"e": 27367,
"s": 27359,
"text": "Syntax:"
},
{
"code": null,
"e": 27432,
"s": 27367,
"text": "preg_replace( $pattern, $replacement, $subject, $limit, $count )"
},
{
"code": null,
"e": 27538,
"s": 27432,
"text": "Return Value: This function returns an array if the subject parameter is an array, or a string otherwise."
},
{
"code": null,
"e": 27547,
"s": 27538,
"text": "Example:"
},
{
"code": null,
"e": 27551,
"s": 27547,
"text": "PHP"
},
{
"code": "<?php // PHP program to illustrate // preg_replace function // Declare a variable and initialize it $geeks = 'Welcome 2 Geeks 4 Geeks.'; // Filter the Numbers from String $int_var = preg_replace('/[^0-9]/', '', $geeks); // print output of function echo(\"The numbers are: $int_var \\n\"); ?>",
"e": 27869,
"s": 27551,
"text": null
},
{
"code": null,
"e": 27890,
"s": 27869,
"text": "The numbers are: 24 "
},
{
"code": null,
"e": 27903,
"s": 27890,
"text": "PHP-function"
},
{
"code": null,
"e": 27917,
"s": 27903,
"text": "PHP-Questions"
},
{
"code": null,
"e": 27921,
"s": 27917,
"text": "PHP"
},
{
"code": null,
"e": 27925,
"s": 27921,
"text": "PHP"
},
{
"code": null,
"e": 28023,
"s": 27925,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28105,
"s": 28023,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 28156,
"s": 28105,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 28230,
"s": 28156,
"text": "Create a drop-down list that options fetched from a MySQL database in PHP"
},
{
"code": null,
"e": 28272,
"s": 28230,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 28309,
"s": 28272,
"text": "How to generate PDF file using PHP ?"
},
{
"code": null,
"e": 28321,
"s": 28309,
"text": "PHP Cookies"
},
{
"code": null,
"e": 28359,
"s": 28321,
"text": "PHP | shell_exec() vs exec() Function"
},
{
"code": null,
"e": 28386,
"s": 28359,
"text": "PHP str_replace() Function"
},
{
"code": null,
"e": 28450,
"s": 28386,
"text": "How to pass form variables from one page to other page in PHP ?"
}
] |
Cat command in Linux with examples - GeeksforGeeks
|
06 Dec, 2021
Cat(concatenate) command is very frequently used in Linux. It reads data from the file and gives their content as output. It helps us to create, view, concatenate files. So let us see some frequently used cat commands.
1) To view a single file Command:
$cat filename
Output
It will show content of given filename
2) To view multiple files Command:
$cat file1 file2
Output
This will show the content of file1 and file2.
3) To view contents of a file preceding with line numbers. Command:
$cat -n filename
Output
It will show content with line number
example:-cat-n geeks.txt
1)This is geeks
2)A unique array
4) Create a file Command:
$ cat > newfile
Output
Will create a file named newfile
5) Copy the contents of one file to another file. Command:
$cat [filename-whose-contents-is-to-be-copied] > [destination-filename]
Output
The content will be copied in destination file
6) Cat command can suppress repeated empty lines in output Command:
$cat -s geeks.txt
Output
Will suppress repeated empty lines in output
7) Cat command can append the contents of one file to the end of another file. Command:
$cat file1 >> file2
Output
Will append the contents of one file to the end of another file
8) Cat command can display content in reverse order using tac command. Command:
$tac filename
Output
Will display content in reverse order
9) Cat command can highlight the end of line. Command:
$cat -E "filename"
Output
Will highlight the end of line
10) If you want to use the -v, -E and -T option together, then instead of writing -vET in the command, you can just use the -A command line option. Command
$cat -A "filename"
11) Cat command to open dashed files. Command:
$cat -- "-dashfile"
Output
Will display the content of -dashfile
12) Cat command if the file has a lot of content and can’t fit in the terminal. Command:
$cat "filename" | more
Output
Will show that much content, which could fit in terminal and will ask to show more.
13) Cat command to merge the contents of multiple files. Command:
$cat "filename1" "filename2" "filename3" > "merged_filename"
Output
Will merge the contents of file in respective order and will insert that content in "merged_filename".
14) Cat command to display the content of all text files in the folder. Command:
$cat *.txt
Output
Will show the content of all text files present in the folder.
15) Cat command to write in an already existing file.
Command :
$cat >> geeks.txt
The newly added text.
Output
Will append the text "The newly added text." to the end of the file.
YouTubeGeeksforGeeks500K subscribersLinux Tutorials | cat - A versatile command | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:22•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=exj5WMUJ11g" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
?list=PLqM7alHXFySFc4KtwEZTANgmyJm3NqS_L
This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
manav014
srishtiganguly1999
9bc75jeff
om_mishra
Linux-basic-commands
linux-command
Linux-file-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
UDP Server-Client implementation in C
Conditional Statements | Shell Script
echo command in Linux with Examples
Compiling with g++
Tail command in Linux with examples
Mutex lock for Linux Thread Synchronization
|
[
{
"code": null,
"e": 23705,
"s": 23677,
"text": "\n06 Dec, 2021"
},
{
"code": null,
"e": 23925,
"s": 23705,
"text": "Cat(concatenate) command is very frequently used in Linux. It reads data from the file and gives their content as output. It helps us to create, view, concatenate files. So let us see some frequently used cat commands. "
},
{
"code": null,
"e": 23961,
"s": 23925,
"text": "1) To view a single file Command: "
},
{
"code": null,
"e": 23975,
"s": 23961,
"text": "$cat filename"
},
{
"code": null,
"e": 23984,
"s": 23975,
"text": "Output "
},
{
"code": null,
"e": 24023,
"s": 23984,
"text": "It will show content of given filename"
},
{
"code": null,
"e": 24060,
"s": 24023,
"text": "2) To view multiple files Command: "
},
{
"code": null,
"e": 24077,
"s": 24060,
"text": "$cat file1 file2"
},
{
"code": null,
"e": 24086,
"s": 24077,
"text": "Output "
},
{
"code": null,
"e": 24133,
"s": 24086,
"text": "This will show the content of file1 and file2."
},
{
"code": null,
"e": 24203,
"s": 24133,
"text": "3) To view contents of a file preceding with line numbers. Command: "
},
{
"code": null,
"e": 24220,
"s": 24203,
"text": "$cat -n filename"
},
{
"code": null,
"e": 24229,
"s": 24220,
"text": "Output "
},
{
"code": null,
"e": 24326,
"s": 24229,
"text": "It will show content with line number\nexample:-cat-n geeks.txt\n1)This is geeks\n2)A unique array"
},
{
"code": null,
"e": 24354,
"s": 24326,
"text": "4) Create a file Command: "
},
{
"code": null,
"e": 24370,
"s": 24354,
"text": "$ cat > newfile"
},
{
"code": null,
"e": 24379,
"s": 24370,
"text": "Output "
},
{
"code": null,
"e": 24412,
"s": 24379,
"text": "Will create a file named newfile"
},
{
"code": null,
"e": 24473,
"s": 24412,
"text": "5) Copy the contents of one file to another file. Command: "
},
{
"code": null,
"e": 24545,
"s": 24473,
"text": "$cat [filename-whose-contents-is-to-be-copied] > [destination-filename]"
},
{
"code": null,
"e": 24554,
"s": 24545,
"text": "Output "
},
{
"code": null,
"e": 24601,
"s": 24554,
"text": "The content will be copied in destination file"
},
{
"code": null,
"e": 24671,
"s": 24601,
"text": "6) Cat command can suppress repeated empty lines in output Command: "
},
{
"code": null,
"e": 24689,
"s": 24671,
"text": "$cat -s geeks.txt"
},
{
"code": null,
"e": 24698,
"s": 24689,
"text": "Output "
},
{
"code": null,
"e": 24743,
"s": 24698,
"text": "Will suppress repeated empty lines in output"
},
{
"code": null,
"e": 24833,
"s": 24743,
"text": "7) Cat command can append the contents of one file to the end of another file. Command: "
},
{
"code": null,
"e": 24853,
"s": 24833,
"text": "$cat file1 >> file2"
},
{
"code": null,
"e": 24862,
"s": 24853,
"text": "Output "
},
{
"code": null,
"e": 24926,
"s": 24862,
"text": "Will append the contents of one file to the end of another file"
},
{
"code": null,
"e": 25008,
"s": 24926,
"text": "8) Cat command can display content in reverse order using tac command. Command: "
},
{
"code": null,
"e": 25023,
"s": 25008,
"text": " $tac filename"
},
{
"code": null,
"e": 25032,
"s": 25023,
"text": "Output "
},
{
"code": null,
"e": 25071,
"s": 25032,
"text": "Will display content in reverse order "
},
{
"code": null,
"e": 25128,
"s": 25071,
"text": "9) Cat command can highlight the end of line. Command: "
},
{
"code": null,
"e": 25147,
"s": 25128,
"text": "$cat -E \"filename\""
},
{
"code": null,
"e": 25156,
"s": 25147,
"text": "Output "
},
{
"code": null,
"e": 25187,
"s": 25156,
"text": "Will highlight the end of line"
},
{
"code": null,
"e": 25345,
"s": 25187,
"text": "10) If you want to use the -v, -E and -T option together, then instead of writing -vET in the command, you can just use the -A command line option. Command "
},
{
"code": null,
"e": 25365,
"s": 25345,
"text": "$cat -A \"filename\""
},
{
"code": null,
"e": 25414,
"s": 25365,
"text": "11) Cat command to open dashed files. Command: "
},
{
"code": null,
"e": 25434,
"s": 25414,
"text": "$cat -- \"-dashfile\""
},
{
"code": null,
"e": 25443,
"s": 25434,
"text": "Output "
},
{
"code": null,
"e": 25481,
"s": 25443,
"text": "Will display the content of -dashfile"
},
{
"code": null,
"e": 25572,
"s": 25481,
"text": "12) Cat command if the file has a lot of content and can’t fit in the terminal. Command: "
},
{
"code": null,
"e": 25595,
"s": 25572,
"text": "$cat \"filename\" | more"
},
{
"code": null,
"e": 25604,
"s": 25595,
"text": "Output "
},
{
"code": null,
"e": 25688,
"s": 25604,
"text": "Will show that much content, which could fit in terminal and will ask to show more."
},
{
"code": null,
"e": 25756,
"s": 25688,
"text": "13) Cat command to merge the contents of multiple files. Command: "
},
{
"code": null,
"e": 25817,
"s": 25756,
"text": "$cat \"filename1\" \"filename2\" \"filename3\" > \"merged_filename\""
},
{
"code": null,
"e": 25826,
"s": 25817,
"text": "Output "
},
{
"code": null,
"e": 25929,
"s": 25826,
"text": "Will merge the contents of file in respective order and will insert that content in \"merged_filename\"."
},
{
"code": null,
"e": 26012,
"s": 25929,
"text": "14) Cat command to display the content of all text files in the folder. Command: "
},
{
"code": null,
"e": 26023,
"s": 26012,
"text": "$cat *.txt"
},
{
"code": null,
"e": 26032,
"s": 26023,
"text": "Output "
},
{
"code": null,
"e": 26095,
"s": 26032,
"text": "Will show the content of all text files present in the folder."
},
{
"code": null,
"e": 26150,
"s": 26095,
"text": "15) Cat command to write in an already existing file. "
},
{
"code": null,
"e": 26160,
"s": 26150,
"text": "Command :"
},
{
"code": null,
"e": 26200,
"s": 26160,
"text": "$cat >> geeks.txt\nThe newly added text."
},
{
"code": null,
"e": 26207,
"s": 26200,
"text": "Output"
},
{
"code": null,
"e": 26276,
"s": 26207,
"text": "Will append the text \"The newly added text.\" to the end of the file."
},
{
"code": null,
"e": 27118,
"s": 26276,
"text": "YouTubeGeeksforGeeks500K subscribersLinux Tutorials | cat - A versatile command | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:22•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=exj5WMUJ11g\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 27160,
"s": 27118,
"text": "?list=PLqM7alHXFySFc4KtwEZTANgmyJm3NqS_L "
},
{
"code": null,
"e": 27453,
"s": 27162,
"text": "This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 27580,
"s": 27455,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27591,
"s": 27582,
"text": "manav014"
},
{
"code": null,
"e": 27610,
"s": 27591,
"text": "srishtiganguly1999"
},
{
"code": null,
"e": 27620,
"s": 27610,
"text": "9bc75jeff"
},
{
"code": null,
"e": 27630,
"s": 27620,
"text": "om_mishra"
},
{
"code": null,
"e": 27651,
"s": 27630,
"text": "Linux-basic-commands"
},
{
"code": null,
"e": 27665,
"s": 27651,
"text": "linux-command"
},
{
"code": null,
"e": 27685,
"s": 27665,
"text": "Linux-file-commands"
},
{
"code": null,
"e": 27696,
"s": 27685,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27794,
"s": 27696,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27803,
"s": 27794,
"text": "Comments"
},
{
"code": null,
"e": 27816,
"s": 27803,
"text": "Old Comments"
},
{
"code": null,
"e": 27854,
"s": 27816,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 27889,
"s": 27854,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 27924,
"s": 27889,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 27960,
"s": 27924,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 27998,
"s": 27960,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 28036,
"s": 27998,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 28072,
"s": 28036,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 28091,
"s": 28072,
"text": "Compiling with g++"
},
{
"code": null,
"e": 28127,
"s": 28091,
"text": "Tail command in Linux with examples"
}
] |
PCA and OLS in matrix form with R | by Serafim Petrov | Apr, 2021 | Towards Data Science | Towards Data Science
|
Principal Component Analysis (PCA) and Ordinary Least Squares (OLS) are two important statistical methods. They are even better when performed together. We will explore these methods using matrix operations in R and introduce a basic Principal Component Regression (PCR) technique.
We will generate a simple data set of four highly correlated exploratory variables from the Gaussian distribution, and a response variable which will be a linear combination of them with added random noise.
> library(‘MASS’)> mu=rep(3,4)> sigma=matrix(.9, nrow=4, ncol=4) + diag(4)*0.1> set.seed(2021)> data <- as.data.frame(mvrnorm(20, mu = mu, Sigma = sigma), + empirical = T)> y <- apply(data, 1, sum)+rnorm(20, 1, 1)
We may observe the correlation matrix and confirm that the exploratory variables are highly correlated. In this case, the regression coefficients might be biased.
> cor(data)
This statistical method helps us to deal with multicollinearity and high dimensionality. Using R, we might obtain PCs just in 4 steps.
First, we need to scale the data. In our example we know that the data are of the equivalent magnitude; therefore, we will only center it.
data.scaled <- scale(data, scale=F)
Second, we need to compute the covariance matrix:
data.cov <- cov(data.scaled)
Third, we need to compute eigenvalues to obtain eigenvectors. In R the function eigen() returns both results. The eigenvalue is a scale parameter; the eigenvector is a rotation parameter.
data.eigen <- eigen(data.cov)
Finally, we need to perform a matrix multiplication of our data and eigenvectors. The result would bring Principal Components: these are coordinates of original data on the new axis.
> data.custom.pca <- data.scaled%*%(data.eigen$vectors)
The components are orthogonal, and we may confirm this by observing the correlation matrix:
> round(cor(data.custom.pca),5)
We may also compute the proportion of explained variation captured by each component. The first component captures 93.88% of variation; the first + second components capture 97.06%, and so on.
> cumsum(data.eigen$values)/sum(data.eigen$values)
This function automates the four-step approach we performed earlier. From the results below, we may see, that the components are equivalent to the ones we have just obtained:
> data.pca <- prcomp(data)
Some components have opposite signs, but if we check the corresponding eigenvectors (named rotation in this package), we notice that their signs are opposite as well, and when we multiply them to obtain original data, everything would work well.
> data.pca$rotation
The eigenvalues could be obtained by squaring the standard deviation from this package.
> data.pca$sdev^2
Finally, the summary function would return the importance of components and the proportion of variance captured by each component. We may observe that the results are consistent with our previous estimations.
> summary(data.pca)
Without further details, the coefficients for the regression equation could be obtained using this formula:
To compute it, we need to know three operations in R: how to invert matrices, how to transpose matrices, and how to multiply matrices:
# Matrix multiplication: %*% # Transpose matrix: t(x)# Invert matrix: solve(x)
But before we finalize our equation, we need to keep in mind, that this formula assumes that x0 = 1, therefore we to add a unit column to our data. Then we run the equation in matrix form and obtain the coefficients:
> x <- as.matrix(cbind(1,data))> solve(t(x)%*%x) %*% t(x) %*% y
We may see, that this equation in R directly repeats the one we stated at the beginning of the topic. Let us compare it with the built-in function in R:
> model <- lm(y~x[,2:5])
The coefficients are identical for both methods because it is essentially the same method.
Now we know how the PCA’s and OLS methods are performed on simple data set. This completes our prerequisite for the following topic.
We will use the PCs we have obtained earlier and since they had different signs for some components, we will show, that when we transform the data to the original form, the coefficients would be equivalent.
# Adding components from both methods to the data setdata.new <- cbind(data, data.custom.pca, data.pca$x, y)colnames(data.new)[5:8] <- c('cust1', 'cust2', 'cust3', 'cust4')
For demonstration purpose, the models would be estimated using all four components, even though usually after PCA we reduce the number of predictors:
model.cust <- lm(y~cust1+cust2+cust3+cust4, data.new)model.pca <- lm(y~PC1+PC2+PC3+PC4, data.new)
Now we need to convert the coefficients from the component rotation to the original space. This could be done by multiplying them by corresponding eigenvectors:
beta.pca <- as.matrix(model.pca$coefficients[2:5])beta.original.pca <- as.matrix(data.pca$rotation) %*% beta.pcabeta.cust.pca <- as.matrix(model.cust$coefficients[2:5])beta.original.cust <- as.matrix(data.custom.eigenvector) %*% beta.cust.pca
This confirms that the opposite signs of PCs would be compensated by signs of eigenvectors when we transform the points to the original system.
The function pcr() has several parameters to tune, but we will construct the most basic version, and obtain the coefficients.
library(pls)fit <- pcr(y ~., data = as.data.frame(data.scaled), center=F)
The function computes all PCs, eigenvalues, and many more, as well as coefficients for the different number of components. Above we slice it for all four components, and we may see, that they are not even slightly different from the ones we have obtained earlier.
But how many components are needed? We may plot our estimated PCs or the PCR model for searching for ‘elbow’ on the graph or try to make a prediction of the test set/cross-validation or use some more formal approaches.
plot(fit, "validation", val.type = "MSEP")# orplot(data.pca, type='l')
From the plot, we may see, that one PC is sufficient enough to capture the variance in the data. We also know from the previous observations, that the first component captures ~ 93.88% of the variation. Therefore if we wanted to run a regression on the real data set and obtained similar results, we would have used only the first component to escape multicollinearity in the data set.
In this article, we explored a matrix form approach to compute PCs and OLS coefficients, compared this custom approach with the built-in functions in R, and summarized it by performing the PCR. We found no difference in both techniques. For practical purposes, it is convenient to use the PLS library, but for theoretical purposes, it is useful to know the math behind the scene.
The full code can be found on GitHub.
If you have any questions or spotted a mistake or typo, please leave a comment below.
Connect on LinkedIn
|
[
{
"code": null,
"e": 454,
"s": 172,
"text": "Principal Component Analysis (PCA) and Ordinary Least Squares (OLS) are two important statistical methods. They are even better when performed together. We will explore these methods using matrix operations in R and introduce a basic Principal Component Regression (PCR) technique."
},
{
"code": null,
"e": 661,
"s": 454,
"text": "We will generate a simple data set of four highly correlated exploratory variables from the Gaussian distribution, and a response variable which will be a linear combination of them with added random noise."
},
{
"code": null,
"e": 875,
"s": 661,
"text": "> library(‘MASS’)> mu=rep(3,4)> sigma=matrix(.9, nrow=4, ncol=4) + diag(4)*0.1> set.seed(2021)> data <- as.data.frame(mvrnorm(20, mu = mu, Sigma = sigma), + empirical = T)> y <- apply(data, 1, sum)+rnorm(20, 1, 1)"
},
{
"code": null,
"e": 1038,
"s": 875,
"text": "We may observe the correlation matrix and confirm that the exploratory variables are highly correlated. In this case, the regression coefficients might be biased."
},
{
"code": null,
"e": 1050,
"s": 1038,
"text": "> cor(data)"
},
{
"code": null,
"e": 1185,
"s": 1050,
"text": "This statistical method helps us to deal with multicollinearity and high dimensionality. Using R, we might obtain PCs just in 4 steps."
},
{
"code": null,
"e": 1324,
"s": 1185,
"text": "First, we need to scale the data. In our example we know that the data are of the equivalent magnitude; therefore, we will only center it."
},
{
"code": null,
"e": 1361,
"s": 1324,
"text": "data.scaled <- scale(data, scale=F)"
},
{
"code": null,
"e": 1411,
"s": 1361,
"text": "Second, we need to compute the covariance matrix:"
},
{
"code": null,
"e": 1440,
"s": 1411,
"text": "data.cov <- cov(data.scaled)"
},
{
"code": null,
"e": 1628,
"s": 1440,
"text": "Third, we need to compute eigenvalues to obtain eigenvectors. In R the function eigen() returns both results. The eigenvalue is a scale parameter; the eigenvector is a rotation parameter."
},
{
"code": null,
"e": 1658,
"s": 1628,
"text": "data.eigen <- eigen(data.cov)"
},
{
"code": null,
"e": 1841,
"s": 1658,
"text": "Finally, we need to perform a matrix multiplication of our data and eigenvectors. The result would bring Principal Components: these are coordinates of original data on the new axis."
},
{
"code": null,
"e": 1897,
"s": 1841,
"text": "> data.custom.pca <- data.scaled%*%(data.eigen$vectors)"
},
{
"code": null,
"e": 1989,
"s": 1897,
"text": "The components are orthogonal, and we may confirm this by observing the correlation matrix:"
},
{
"code": null,
"e": 2021,
"s": 1989,
"text": "> round(cor(data.custom.pca),5)"
},
{
"code": null,
"e": 2214,
"s": 2021,
"text": "We may also compute the proportion of explained variation captured by each component. The first component captures 93.88% of variation; the first + second components capture 97.06%, and so on."
},
{
"code": null,
"e": 2265,
"s": 2214,
"text": "> cumsum(data.eigen$values)/sum(data.eigen$values)"
},
{
"code": null,
"e": 2440,
"s": 2265,
"text": "This function automates the four-step approach we performed earlier. From the results below, we may see, that the components are equivalent to the ones we have just obtained:"
},
{
"code": null,
"e": 2467,
"s": 2440,
"text": "> data.pca <- prcomp(data)"
},
{
"code": null,
"e": 2713,
"s": 2467,
"text": "Some components have opposite signs, but if we check the corresponding eigenvectors (named rotation in this package), we notice that their signs are opposite as well, and when we multiply them to obtain original data, everything would work well."
},
{
"code": null,
"e": 2733,
"s": 2713,
"text": "> data.pca$rotation"
},
{
"code": null,
"e": 2821,
"s": 2733,
"text": "The eigenvalues could be obtained by squaring the standard deviation from this package."
},
{
"code": null,
"e": 2839,
"s": 2821,
"text": "> data.pca$sdev^2"
},
{
"code": null,
"e": 3048,
"s": 2839,
"text": "Finally, the summary function would return the importance of components and the proportion of variance captured by each component. We may observe that the results are consistent with our previous estimations."
},
{
"code": null,
"e": 3068,
"s": 3048,
"text": "> summary(data.pca)"
},
{
"code": null,
"e": 3176,
"s": 3068,
"text": "Without further details, the coefficients for the regression equation could be obtained using this formula:"
},
{
"code": null,
"e": 3311,
"s": 3176,
"text": "To compute it, we need to know three operations in R: how to invert matrices, how to transpose matrices, and how to multiply matrices:"
},
{
"code": null,
"e": 3406,
"s": 3311,
"text": "# Matrix multiplication: %*% # Transpose matrix: t(x)# Invert matrix: solve(x)"
},
{
"code": null,
"e": 3623,
"s": 3406,
"text": "But before we finalize our equation, we need to keep in mind, that this formula assumes that x0 = 1, therefore we to add a unit column to our data. Then we run the equation in matrix form and obtain the coefficients:"
},
{
"code": null,
"e": 3687,
"s": 3623,
"text": "> x <- as.matrix(cbind(1,data))> solve(t(x)%*%x) %*% t(x) %*% y"
},
{
"code": null,
"e": 3840,
"s": 3687,
"text": "We may see, that this equation in R directly repeats the one we stated at the beginning of the topic. Let us compare it with the built-in function in R:"
},
{
"code": null,
"e": 3865,
"s": 3840,
"text": "> model <- lm(y~x[,2:5])"
},
{
"code": null,
"e": 3956,
"s": 3865,
"text": "The coefficients are identical for both methods because it is essentially the same method."
},
{
"code": null,
"e": 4089,
"s": 3956,
"text": "Now we know how the PCA’s and OLS methods are performed on simple data set. This completes our prerequisite for the following topic."
},
{
"code": null,
"e": 4296,
"s": 4089,
"text": "We will use the PCs we have obtained earlier and since they had different signs for some components, we will show, that when we transform the data to the original form, the coefficients would be equivalent."
},
{
"code": null,
"e": 4470,
"s": 4296,
"text": "# Adding components from both methods to the data setdata.new <- cbind(data, data.custom.pca, data.pca$x, y)colnames(data.new)[5:8] <- c('cust1', 'cust2', 'cust3', 'cust4')"
},
{
"code": null,
"e": 4620,
"s": 4470,
"text": "For demonstration purpose, the models would be estimated using all four components, even though usually after PCA we reduce the number of predictors:"
},
{
"code": null,
"e": 4718,
"s": 4620,
"text": "model.cust <- lm(y~cust1+cust2+cust3+cust4, data.new)model.pca <- lm(y~PC1+PC2+PC3+PC4, data.new)"
},
{
"code": null,
"e": 4879,
"s": 4718,
"text": "Now we need to convert the coefficients from the component rotation to the original space. This could be done by multiplying them by corresponding eigenvectors:"
},
{
"code": null,
"e": 5122,
"s": 4879,
"text": "beta.pca <- as.matrix(model.pca$coefficients[2:5])beta.original.pca <- as.matrix(data.pca$rotation) %*% beta.pcabeta.cust.pca <- as.matrix(model.cust$coefficients[2:5])beta.original.cust <- as.matrix(data.custom.eigenvector) %*% beta.cust.pca"
},
{
"code": null,
"e": 5266,
"s": 5122,
"text": "This confirms that the opposite signs of PCs would be compensated by signs of eigenvectors when we transform the points to the original system."
},
{
"code": null,
"e": 5392,
"s": 5266,
"text": "The function pcr() has several parameters to tune, but we will construct the most basic version, and obtain the coefficients."
},
{
"code": null,
"e": 5467,
"s": 5392,
"text": "library(pls)fit <- pcr(y ~., data = as.data.frame(data.scaled), center=F)"
},
{
"code": null,
"e": 5731,
"s": 5467,
"text": "The function computes all PCs, eigenvalues, and many more, as well as coefficients for the different number of components. Above we slice it for all four components, and we may see, that they are not even slightly different from the ones we have obtained earlier."
},
{
"code": null,
"e": 5950,
"s": 5731,
"text": "But how many components are needed? We may plot our estimated PCs or the PCR model for searching for ‘elbow’ on the graph or try to make a prediction of the test set/cross-validation or use some more formal approaches."
},
{
"code": null,
"e": 6021,
"s": 5950,
"text": "plot(fit, \"validation\", val.type = \"MSEP\")# orplot(data.pca, type='l')"
},
{
"code": null,
"e": 6407,
"s": 6021,
"text": "From the plot, we may see, that one PC is sufficient enough to capture the variance in the data. We also know from the previous observations, that the first component captures ~ 93.88% of the variation. Therefore if we wanted to run a regression on the real data set and obtained similar results, we would have used only the first component to escape multicollinearity in the data set."
},
{
"code": null,
"e": 6787,
"s": 6407,
"text": "In this article, we explored a matrix form approach to compute PCs and OLS coefficients, compared this custom approach with the built-in functions in R, and summarized it by performing the PCR. We found no difference in both techniques. For practical purposes, it is convenient to use the PLS library, but for theoretical purposes, it is useful to know the math behind the scene."
},
{
"code": null,
"e": 6825,
"s": 6787,
"text": "The full code can be found on GitHub."
},
{
"code": null,
"e": 6911,
"s": 6825,
"text": "If you have any questions or spotted a mistake or typo, please leave a comment below."
}
] |
How to deallocate the Azure VM using Azure CLI in PowerShell?
|
To deallocate the Azure VM using Azure CLI, we need to use the VM deallocation command az vm deallocate and need to provide the name of the VM and the resource group of the VM.
Before running the deallocation command, make sure that you are connected to the proper azure subscription and the azure account.
PS C:\> az vm deallocate -n VMName -g RGName --verbose
Or you can use
PS C:\> az vm deallocate --name VMName --resource-group RGName --verbose
If you are working on the multiple VMs, you can also apply the --no-wait parameter to continue next operation without waiting for the VM to stop.
PS C:\> az vm deallocate -n VmName -g RGName --no-wait --verbose
|
[
{
"code": null,
"e": 1239,
"s": 1062,
"text": "To deallocate the Azure VM using Azure CLI, we need to use the VM deallocation command az vm deallocate and need to provide the name of the VM and the resource group of the VM."
},
{
"code": null,
"e": 1369,
"s": 1239,
"text": "Before running the deallocation command, make sure that you are connected to the proper azure subscription and the azure account."
},
{
"code": null,
"e": 1424,
"s": 1369,
"text": "PS C:\\> az vm deallocate -n VMName -g RGName --verbose"
},
{
"code": null,
"e": 1439,
"s": 1424,
"text": "Or you can use"
},
{
"code": null,
"e": 1512,
"s": 1439,
"text": "PS C:\\> az vm deallocate --name VMName --resource-group RGName --verbose"
},
{
"code": null,
"e": 1658,
"s": 1512,
"text": "If you are working on the multiple VMs, you can also apply the --no-wait parameter to continue next operation without waiting for the VM to stop."
},
{
"code": null,
"e": 1723,
"s": 1658,
"text": "PS C:\\> az vm deallocate -n VmName -g RGName --no-wait --verbose"
}
] |
Apache Spark - Core Programming
|
Spark Core is the base of the whole project. It provides distributed task dispatching, scheduling, and basic I/O functionalities. Spark uses a specialized fundamental data structure known as RDD (Resilient Distributed Datasets) that is a logical collection of data partitioned across machines. RDDs can be created in two ways; one is by referencing datasets in external storage systems and second is by applying transformations (e.g. map, filter, reducer, join) on existing RDDs.
The RDD abstraction is exposed through a language-integrated API. This simplifies programming complexity because the way applications manipulate RDDs is similar to manipulating local collections of data.
Spark provides an interactive shell − a powerful tool to analyze data interactively. It is available in either Scala or Python language. Spark’s primary abstraction is a distributed collection of items called a Resilient Distributed Dataset (RDD). RDDs can be created from Hadoop Input Formats (such as HDFS files) or by transforming other RDDs.
The following command is used to open Spark shell.
$ spark-shell
Let us create a simple RDD from the text file. Use the following command to create a simple RDD.
scala> val inputfile = sc.textFile(“input.txt”)
The output for the above command is
inputfile: org.apache.spark.rdd.RDD[String] = input.txt MappedRDD[1] at textFile at <console>:12
The Spark RDD API introduces few Transformations and few Actions to manipulate RDD.
RDD transformations returns pointer to new RDD and allows you to create dependencies between RDDs. Each RDD in dependency chain (String of Dependencies) has a function for calculating its data and has a pointer (dependency) to its parent RDD.
Spark is lazy, so nothing will be executed unless you call some transformation or action that will trigger job creation and execution. Look at the following snippet of the word-count example.
Therefore, RDD transformation is not a set of data but is a step in a program (might be the only step) telling Spark how to get data and what to do with it.
Given below is a list of RDD transformations.
map(func)
Returns a new distributed dataset, formed by passing each element of the source through a function func.
filter(func)
Returns a new dataset formed by selecting those elements of the source on which func returns true.
flatMap(func)
Similar to map, but each input item can be mapped to 0 or more output items (so func should return a Seq rather than a single item).
mapPartitions(func)
Similar to map, but runs separately on each partition (block) of the RDD, so func must be of type Iterator<T> ⇒ Iterator<U> when running on an RDD of type T.
mapPartitionsWithIndex(func)
Similar to map Partitions, but also provides func with an integer value representing the index of the partition, so func must be of type (Int, Iterator<T>) ⇒ Iterator<U> when running on an RDD of type T.
sample(withReplacement, fraction, seed)
Sample a fraction of the data, with or without replacement, using a given random number generator seed.
union(otherDataset)
Returns a new dataset that contains the union of the elements in the source dataset and the argument.
intersection(otherDataset)
Returns a new RDD that contains the intersection of elements in the source dataset and the argument.
distinct([numTasks])
Returns a new dataset that contains the distinct elements of the source dataset.
groupByKey([numTasks])
When called on a dataset of (K, V) pairs, returns a dataset of (K, Iterable<V>) pairs.
Note − If you are grouping in order to perform an aggregation (such as a sum or average) over each key, using reduceByKey or aggregateByKey will yield much better performance.
reduceByKey(func, [numTasks])
When called on a dataset of (K, V) pairs, returns a dataset of (K, V) pairs where the values for each key are aggregated using the given reduce function func, which must be of type (V, V) ⇒ V. Like in groupByKey, the number of reduce tasks is configurable through an optional second argument.
aggregateByKey(zeroValue)(seqOp, combOp, [numTasks])
When called on a dataset of (K, V) pairs, returns a dataset of (K, U) pairs where the values for each key are aggregated using the given combine functions and a neutral "zero" value. Allows an aggregated value type that is different from the input value type, while avoiding unnecessary allocations. Like in groupByKey, the number of reduce tasks is configurable through an optional second argument.
sortByKey([ascending], [numTasks])
When called on a dataset of (K, V) pairs where K implements Ordered, returns a dataset of (K, V) pairs sorted by keys in ascending or descending order, as specified in the Boolean ascending argument.
join(otherDataset, [numTasks])
When called on datasets of type (K, V) and (K, W), returns a dataset of (K, (V, W)) pairs with all pairs of elements for each key. Outer joins are supported through leftOuterJoin, rightOuterJoin, and fullOuterJoin.
cogroup(otherDataset, [numTasks])
When called on datasets of type (K, V) and (K, W), returns a dataset of (K, (Iterable<V>, Iterable<W>)) tuples. This operation is also called group With.
cartesian(otherDataset)
When called on datasets of types T and U, returns a dataset of (T, U) pairs (all pairs of elements).
pipe(command, [envVars])
Pipe each partition of the RDD through a shell command, e.g. a Perl or bash script. RDD elements are written to the process's stdin and lines output to its stdout are returned as an RDD of strings.
coalesce(numPartitions)
Decrease the number of partitions in the RDD to numPartitions. Useful for running operations more efficiently after filtering down a large dataset.
repartition(numPartitions)
Reshuffle the data in the RDD randomly to create either more or fewer partitions and balance it across them. This always shuffles all data over the network.
repartitionAndSortWithinPartitions(partitioner)
Repartition the RDD according to the given partitioner and, within each resulting partition, sort records by their keys. This is more efficient than calling repartition and then sorting within each partition because it can push the sorting down into the shuffle machinery.
The following table gives a list of Actions, which return values.
reduce(func)
Aggregate the elements of the dataset using a function func (which takes two arguments and returns one). The function should be commutative and associative so that it can be computed correctly in parallel.
collect()
Returns all the elements of the dataset as an array at the driver program. This is usually useful after a filter or other operation that returns a sufficiently small subset of the data.
count()
Returns the number of elements in the dataset.
first()
Returns the first element of the dataset (similar to take (1)).
take(n)
Returns an array with the first n elements of the dataset.
takeSample (withReplacement,num, [seed])
Returns an array with a random sample of num elements of the dataset, with or without replacement, optionally pre-specifying a random number generator seed.
takeOrdered(n, [ordering])
Returns the first n elements of the RDD using either their natural order or a custom comparator.
saveAsTextFile(path)
Writes the elements of the dataset as a text file (or set of text files) in a given directory in the local filesystem, HDFS or any other Hadoop-supported file system. Spark calls toString on each element to convert it to a line of text in the file.
saveAsSequenceFile(path) (Java and Scala)
Writes the elements of the dataset as a Hadoop SequenceFile in a given path in the local filesystem, HDFS or any other Hadoop-supported file system. This is available on RDDs of key-value pairs that implement Hadoop's Writable interface. In Scala, it is also available on types that are implicitly convertible to Writable (Spark includes conversions for basic types like Int, Double, String, etc).
saveAsObjectFile(path) (Java and Scala)
Writes the elements of the dataset in a simple format using Java serialization, which can then be loaded using SparkContext.objectFile().
countByKey()
Only available on RDDs of type (K, V). Returns a hashmap of (K, Int) pairs with the count of each key.
foreach(func)
Runs a function func on each element of the dataset. This is usually, done for side effects such as updating an Accumulator or interacting with external storage systems.
Note − modifying variables other than Accumulators outside of the foreach() may result in undefined behavior. See Understanding closures for more details.
Let us see the implementations of few RDD transformations and actions in RDD programming with the help of an example.
Consider a word count example − It counts each word appearing in a document. Consider the following text as an input and is saved as an input.txt file in a home directory.
input.txt − input file.
people are not as beautiful as they look,
as they walk or as they talk.
they are only as beautiful as they love,
as they care as they share.
Follow the procedure given below to execute the given example.
The following command is used to open spark shell. Generally, spark is built using Scala. Therefore, a Spark program runs on Scala environment.
$ spark-shell
If Spark shell opens successfully then you will find the following output. Look at the last line of the output “Spark context available as sc” means the Spark container is automatically created spark context object with the name sc. Before starting the first step of a program, the SparkContext object should be created.
Spark assembly has been built with Hive, including Datanucleus jars on classpath
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
15/06/04 15:25:22 INFO SecurityManager: Changing view acls to: hadoop
15/06/04 15:25:22 INFO SecurityManager: Changing modify acls to: hadoop
15/06/04 15:25:22 INFO SecurityManager: SecurityManager: authentication disabled;
ui acls disabled; users with view permissions: Set(hadoop); users with modify permissions: Set(hadoop)
15/06/04 15:25:22 INFO HttpServer: Starting HTTP Server
15/06/04 15:25:23 INFO Utils: Successfully started service 'HTTP class server' on port 43292.
Welcome to
____ __
/ __/__ ___ _____/ /__
_\ \/ _ \/ _ `/ __/ '_/
/___/ .__/\_,_/_/ /_/\_\ version 1.4.0
/_/
Using Scala version 2.10.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_71)
Type in expressions to have them evaluated.
Spark context available as sc
scala>
First, we have to read the input file using Spark-Scala API and create an RDD.
The following command is used for reading a file from given location. Here, new RDD is created with the name of inputfile. The String which is given as an argument in the textFile(“”) method is absolute path for the input file name. However, if only the file name is given, then it means that the input file is in the current location.
scala> val inputfile = sc.textFile("input.txt")
Our aim is to count the words in a file. Create a flat map for splitting each line into words (flatMap(line ⇒ line.split(“ ”)).
Next, read each word as a key with a value ‘1’ (<key, value> = <word,1>)using map function (map(word ⇒ (word, 1)).
Finally, reduce those keys by adding values of similar keys (reduceByKey(_+_)).
The following command is used for executing word count logic. After executing this, you will not find any output because this is not an action, this is a transformation; pointing a new RDD or tell spark to what to do with the given data)
scala> val counts = inputfile.flatMap(line => line.split(" ")).map(word => (word, 1)).reduceByKey(_+_);
While working with the RDD, if you want to know about current RDD, then use the following command. It will show you the description about current RDD and its dependencies for debugging.
scala> counts.toDebugString
You can mark an RDD to be persisted using the persist() or cache() methods on it. The first time it is computed in an action, it will be kept in memory on the nodes. Use the following command to store the intermediate transformations in memory.
scala> counts.cache()
Applying an action, like store all the transformations, results into a text file. The String argument for saveAsTextFile(“ ”) method is the absolute path of output folder. Try the following command to save the output in a text file. In the following example, ‘output’ folder is in current location.
scala> counts.saveAsTextFile("output")
Open another terminal to go to home directory (where spark is executed in the other terminal). Use the following commands for checking output directory.
[hadoop@localhost ~]$ cd output/
[hadoop@localhost output]$ ls -1
part-00000
part-00001
_SUCCESS
The following command is used to see output from Part-00000 files.
[hadoop@localhost output]$ cat part-00000
(people,1)
(are,2)
(not,1)
(as,8)
(beautiful,2)
(they, 7)
(look,1)
The following command is used to see output from Part-00001 files.
[hadoop@localhost output]$ cat part-00001
(walk, 1)
(or, 1)
(talk, 1)
(only, 1)
(love, 1)
(care, 1)
(share, 1)
Before UN-persisting, if you want to see the storage space that is used for this application, then use the following URL in your browser.
http://localhost:4040
You will see the following screen, which shows the storage space used for the application, which are running on the Spark shell.
If you want to UN-persist the storage space of particular RDD, then use the following command.
Scala> counts.unpersist()
You will see the output as follows −
15/06/27 00:57:33 INFO ShuffledRDD: Removing RDD 9 from persistence list
15/06/27 00:57:33 INFO BlockManager: Removing RDD 9
15/06/27 00:57:33 INFO BlockManager: Removing block rdd_9_1
15/06/27 00:57:33 INFO MemoryStore: Block rdd_9_1 of size 480 dropped from memory (free 280061810)
15/06/27 00:57:33 INFO BlockManager: Removing block rdd_9_0
15/06/27 00:57:33 INFO MemoryStore: Block rdd_9_0 of size 296 dropped from memory (free 280062106)
res7: cou.type = ShuffledRDD[9] at reduceByKey at <console>:14
For verifying the storage space in the browser, use the following URL.
http://localhost:4040/
You will see the following screen. It shows the storage space used for the application, which are running on the Spark shell.
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2251,
"s": 1771,
"text": "Spark Core is the base of the whole project. It provides distributed task dispatching, scheduling, and basic I/O functionalities. Spark uses a specialized fundamental data structure known as RDD (Resilient Distributed Datasets) that is a logical collection of data partitioned across machines. RDDs can be created in two ways; one is by referencing datasets in external storage systems and second is by applying transformations (e.g. map, filter, reducer, join) on existing RDDs."
},
{
"code": null,
"e": 2455,
"s": 2251,
"text": "The RDD abstraction is exposed through a language-integrated API. This simplifies programming complexity because the way applications manipulate RDDs is similar to manipulating local collections of data."
},
{
"code": null,
"e": 2801,
"s": 2455,
"text": "Spark provides an interactive shell − a powerful tool to analyze data interactively. It is available in either Scala or Python language. Spark’s primary abstraction is a distributed collection of items called a Resilient Distributed Dataset (RDD). RDDs can be created from Hadoop Input Formats (such as HDFS files) or by transforming other RDDs."
},
{
"code": null,
"e": 2852,
"s": 2801,
"text": "The following command is used to open Spark shell."
},
{
"code": null,
"e": 2867,
"s": 2852,
"text": "$ spark-shell\n"
},
{
"code": null,
"e": 2964,
"s": 2867,
"text": "Let us create a simple RDD from the text file. Use the following command to create a simple RDD."
},
{
"code": null,
"e": 3012,
"s": 2964,
"text": "scala> val inputfile = sc.textFile(“input.txt”)"
},
{
"code": null,
"e": 3048,
"s": 3012,
"text": "The output for the above command is"
},
{
"code": null,
"e": 3146,
"s": 3048,
"text": "inputfile: org.apache.spark.rdd.RDD[String] = input.txt MappedRDD[1] at textFile at <console>:12\n"
},
{
"code": null,
"e": 3230,
"s": 3146,
"text": "The Spark RDD API introduces few Transformations and few Actions to manipulate RDD."
},
{
"code": null,
"e": 3473,
"s": 3230,
"text": "RDD transformations returns pointer to new RDD and allows you to create dependencies between RDDs. Each RDD in dependency chain (String of Dependencies) has a function for calculating its data and has a pointer (dependency) to its parent RDD."
},
{
"code": null,
"e": 3665,
"s": 3473,
"text": "Spark is lazy, so nothing will be executed unless you call some transformation or action that will trigger job creation and execution. Look at the following snippet of the word-count example."
},
{
"code": null,
"e": 3822,
"s": 3665,
"text": "Therefore, RDD transformation is not a set of data but is a step in a program (might be the only step) telling Spark how to get data and what to do with it."
},
{
"code": null,
"e": 3869,
"s": 3822,
"text": "Given below is a list of RDD transformations.\n"
},
{
"code": null,
"e": 3879,
"s": 3869,
"text": "map(func)"
},
{
"code": null,
"e": 3984,
"s": 3879,
"text": "Returns a new distributed dataset, formed by passing each element of the source through a function func."
},
{
"code": null,
"e": 3997,
"s": 3984,
"text": "filter(func)"
},
{
"code": null,
"e": 4096,
"s": 3997,
"text": "Returns a new dataset formed by selecting those elements of the source on which func returns true."
},
{
"code": null,
"e": 4110,
"s": 4096,
"text": "flatMap(func)"
},
{
"code": null,
"e": 4243,
"s": 4110,
"text": "Similar to map, but each input item can be mapped to 0 or more output items (so func should return a Seq rather than a single item)."
},
{
"code": null,
"e": 4263,
"s": 4243,
"text": "mapPartitions(func)"
},
{
"code": null,
"e": 4421,
"s": 4263,
"text": "Similar to map, but runs separately on each partition (block) of the RDD, so func must be of type Iterator<T> ⇒ Iterator<U> when running on an RDD of type T."
},
{
"code": null,
"e": 4450,
"s": 4421,
"text": "mapPartitionsWithIndex(func)"
},
{
"code": null,
"e": 4654,
"s": 4450,
"text": "Similar to map Partitions, but also provides func with an integer value representing the index of the partition, so func must be of type (Int, Iterator<T>) ⇒ Iterator<U> when running on an RDD of type T."
},
{
"code": null,
"e": 4694,
"s": 4654,
"text": "sample(withReplacement, fraction, seed)"
},
{
"code": null,
"e": 4798,
"s": 4694,
"text": "Sample a fraction of the data, with or without replacement, using a given random number generator seed."
},
{
"code": null,
"e": 4818,
"s": 4798,
"text": "union(otherDataset)"
},
{
"code": null,
"e": 4920,
"s": 4818,
"text": "Returns a new dataset that contains the union of the elements in the source dataset and the argument."
},
{
"code": null,
"e": 4947,
"s": 4920,
"text": "intersection(otherDataset)"
},
{
"code": null,
"e": 5048,
"s": 4947,
"text": "Returns a new RDD that contains the intersection of elements in the source dataset and the argument."
},
{
"code": null,
"e": 5069,
"s": 5048,
"text": "distinct([numTasks])"
},
{
"code": null,
"e": 5150,
"s": 5069,
"text": "Returns a new dataset that contains the distinct elements of the source dataset."
},
{
"code": null,
"e": 5173,
"s": 5150,
"text": "groupByKey([numTasks])"
},
{
"code": null,
"e": 5260,
"s": 5173,
"text": "When called on a dataset of (K, V) pairs, returns a dataset of (K, Iterable<V>) pairs."
},
{
"code": null,
"e": 5436,
"s": 5260,
"text": "Note − If you are grouping in order to perform an aggregation (such as a sum or average) over each key, using reduceByKey or aggregateByKey will yield much better performance."
},
{
"code": null,
"e": 5466,
"s": 5436,
"text": "reduceByKey(func, [numTasks])"
},
{
"code": null,
"e": 5759,
"s": 5466,
"text": "When called on a dataset of (K, V) pairs, returns a dataset of (K, V) pairs where the values for each key are aggregated using the given reduce function func, which must be of type (V, V) ⇒ V. Like in groupByKey, the number of reduce tasks is configurable through an optional second argument."
},
{
"code": null,
"e": 5812,
"s": 5759,
"text": "aggregateByKey(zeroValue)(seqOp, combOp, [numTasks])"
},
{
"code": null,
"e": 6212,
"s": 5812,
"text": "When called on a dataset of (K, V) pairs, returns a dataset of (K, U) pairs where the values for each key are aggregated using the given combine functions and a neutral \"zero\" value. Allows an aggregated value type that is different from the input value type, while avoiding unnecessary allocations. Like in groupByKey, the number of reduce tasks is configurable through an optional second argument."
},
{
"code": null,
"e": 6247,
"s": 6212,
"text": "sortByKey([ascending], [numTasks])"
},
{
"code": null,
"e": 6447,
"s": 6247,
"text": "When called on a dataset of (K, V) pairs where K implements Ordered, returns a dataset of (K, V) pairs sorted by keys in ascending or descending order, as specified in the Boolean ascending argument."
},
{
"code": null,
"e": 6478,
"s": 6447,
"text": "join(otherDataset, [numTasks])"
},
{
"code": null,
"e": 6693,
"s": 6478,
"text": "When called on datasets of type (K, V) and (K, W), returns a dataset of (K, (V, W)) pairs with all pairs of elements for each key. Outer joins are supported through leftOuterJoin, rightOuterJoin, and fullOuterJoin."
},
{
"code": null,
"e": 6727,
"s": 6693,
"text": "cogroup(otherDataset, [numTasks])"
},
{
"code": null,
"e": 6881,
"s": 6727,
"text": "When called on datasets of type (K, V) and (K, W), returns a dataset of (K, (Iterable<V>, Iterable<W>)) tuples. This operation is also called group With."
},
{
"code": null,
"e": 6905,
"s": 6881,
"text": "cartesian(otherDataset)"
},
{
"code": null,
"e": 7006,
"s": 6905,
"text": "When called on datasets of types T and U, returns a dataset of (T, U) pairs (all pairs of elements)."
},
{
"code": null,
"e": 7031,
"s": 7006,
"text": "pipe(command, [envVars])"
},
{
"code": null,
"e": 7229,
"s": 7031,
"text": "Pipe each partition of the RDD through a shell command, e.g. a Perl or bash script. RDD elements are written to the process's stdin and lines output to its stdout are returned as an RDD of strings."
},
{
"code": null,
"e": 7253,
"s": 7229,
"text": "coalesce(numPartitions)"
},
{
"code": null,
"e": 7401,
"s": 7253,
"text": "Decrease the number of partitions in the RDD to numPartitions. Useful for running operations more efficiently after filtering down a large dataset."
},
{
"code": null,
"e": 7428,
"s": 7401,
"text": "repartition(numPartitions)"
},
{
"code": null,
"e": 7585,
"s": 7428,
"text": "Reshuffle the data in the RDD randomly to create either more or fewer partitions and balance it across them. This always shuffles all data over the network."
},
{
"code": null,
"e": 7633,
"s": 7585,
"text": "repartitionAndSortWithinPartitions(partitioner)"
},
{
"code": null,
"e": 7906,
"s": 7633,
"text": "Repartition the RDD according to the given partitioner and, within each resulting partition, sort records by their keys. This is more efficient than calling repartition and then sorting within each partition because it can push the sorting down into the shuffle machinery."
},
{
"code": null,
"e": 7972,
"s": 7906,
"text": "The following table gives a list of Actions, which return values."
},
{
"code": null,
"e": 7985,
"s": 7972,
"text": "reduce(func)"
},
{
"code": null,
"e": 8191,
"s": 7985,
"text": "Aggregate the elements of the dataset using a function func (which takes two arguments and returns one). The function should be commutative and associative so that it can be computed correctly in parallel."
},
{
"code": null,
"e": 8201,
"s": 8191,
"text": "collect()"
},
{
"code": null,
"e": 8387,
"s": 8201,
"text": "Returns all the elements of the dataset as an array at the driver program. This is usually useful after a filter or other operation that returns a sufficiently small subset of the data."
},
{
"code": null,
"e": 8395,
"s": 8387,
"text": "count()"
},
{
"code": null,
"e": 8442,
"s": 8395,
"text": "Returns the number of elements in the dataset."
},
{
"code": null,
"e": 8450,
"s": 8442,
"text": "first()"
},
{
"code": null,
"e": 8514,
"s": 8450,
"text": "Returns the first element of the dataset (similar to take (1))."
},
{
"code": null,
"e": 8522,
"s": 8514,
"text": "take(n)"
},
{
"code": null,
"e": 8581,
"s": 8522,
"text": "Returns an array with the first n elements of the dataset."
},
{
"code": null,
"e": 8622,
"s": 8581,
"text": "takeSample (withReplacement,num, [seed])"
},
{
"code": null,
"e": 8779,
"s": 8622,
"text": "Returns an array with a random sample of num elements of the dataset, with or without replacement, optionally pre-specifying a random number generator seed."
},
{
"code": null,
"e": 8806,
"s": 8779,
"text": "takeOrdered(n, [ordering])"
},
{
"code": null,
"e": 8903,
"s": 8806,
"text": "Returns the first n elements of the RDD using either their natural order or a custom comparator."
},
{
"code": null,
"e": 8924,
"s": 8903,
"text": "saveAsTextFile(path)"
},
{
"code": null,
"e": 9173,
"s": 8924,
"text": "Writes the elements of the dataset as a text file (or set of text files) in a given directory in the local filesystem, HDFS or any other Hadoop-supported file system. Spark calls toString on each element to convert it to a line of text in the file."
},
{
"code": null,
"e": 9215,
"s": 9173,
"text": "saveAsSequenceFile(path) (Java and Scala)"
},
{
"code": null,
"e": 9613,
"s": 9215,
"text": "Writes the elements of the dataset as a Hadoop SequenceFile in a given path in the local filesystem, HDFS or any other Hadoop-supported file system. This is available on RDDs of key-value pairs that implement Hadoop's Writable interface. In Scala, it is also available on types that are implicitly convertible to Writable (Spark includes conversions for basic types like Int, Double, String, etc)."
},
{
"code": null,
"e": 9653,
"s": 9613,
"text": "saveAsObjectFile(path) (Java and Scala)"
},
{
"code": null,
"e": 9791,
"s": 9653,
"text": "Writes the elements of the dataset in a simple format using Java serialization, which can then be loaded using SparkContext.objectFile()."
},
{
"code": null,
"e": 9804,
"s": 9791,
"text": "countByKey()"
},
{
"code": null,
"e": 9907,
"s": 9804,
"text": "Only available on RDDs of type (K, V). Returns a hashmap of (K, Int) pairs with the count of each key."
},
{
"code": null,
"e": 9921,
"s": 9907,
"text": "foreach(func)"
},
{
"code": null,
"e": 10091,
"s": 9921,
"text": "Runs a function func on each element of the dataset. This is usually, done for side effects such as updating an Accumulator or interacting with external storage systems."
},
{
"code": null,
"e": 10246,
"s": 10091,
"text": "Note − modifying variables other than Accumulators outside of the foreach() may result in undefined behavior. See Understanding closures for more details."
},
{
"code": null,
"e": 10364,
"s": 10246,
"text": "Let us see the implementations of few RDD transformations and actions in RDD programming with the help of an example."
},
{
"code": null,
"e": 10536,
"s": 10364,
"text": "Consider a word count example − It counts each word appearing in a document. Consider the following text as an input and is saved as an input.txt file in a home directory."
},
{
"code": null,
"e": 10560,
"s": 10536,
"text": "input.txt − input file."
},
{
"code": null,
"e": 10705,
"s": 10560,
"text": "people are not as beautiful as they look, \nas they walk or as they talk.\nthey are only as beautiful as they love, \nas they care as they share.\n"
},
{
"code": null,
"e": 10768,
"s": 10705,
"text": "Follow the procedure given below to execute the given example."
},
{
"code": null,
"e": 10912,
"s": 10768,
"text": "The following command is used to open spark shell. Generally, spark is built using Scala. Therefore, a Spark program runs on Scala environment."
},
{
"code": null,
"e": 10927,
"s": 10912,
"text": "$ spark-shell\n"
},
{
"code": null,
"e": 11248,
"s": 10927,
"text": "If Spark shell opens successfully then you will find the following output. Look at the last line of the output “Spark context available as sc” means the Spark container is automatically created spark context object with the name sc. Before starting the first step of a program, the SparkContext object should be created."
},
{
"code": null,
"e": 12219,
"s": 11248,
"text": "Spark assembly has been built with Hive, including Datanucleus jars on classpath \nUsing Spark's default log4j profile: org/apache/spark/log4j-defaults.properties \n15/06/04 15:25:22 INFO SecurityManager: Changing view acls to: hadoop \n15/06/04 15:25:22 INFO SecurityManager: Changing modify acls to: hadoop \n15/06/04 15:25:22 INFO SecurityManager: SecurityManager: authentication disabled;\n ui acls disabled; users with view permissions: Set(hadoop); users with modify permissions: Set(hadoop) \n15/06/04 15:25:22 INFO HttpServer: Starting HTTP Server \n15/06/04 15:25:23 INFO Utils: Successfully started service 'HTTP class server' on port 43292. \nWelcome to \n ____ __ \n / __/__ ___ _____/ /__ \n _\\ \\/ _ \\/ _ `/ __/ '_/ \n /___/ .__/\\_,_/_/ /_/\\_\\ version 1.4.0 \n /_/ \n\t\t\nUsing Scala version 2.10.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_71) \nType in expressions to have them evaluated. \nSpark context available as sc \nscala>\n"
},
{
"code": null,
"e": 12298,
"s": 12219,
"text": "First, we have to read the input file using Spark-Scala API and create an RDD."
},
{
"code": null,
"e": 12634,
"s": 12298,
"text": "The following command is used for reading a file from given location. Here, new RDD is created with the name of inputfile. The String which is given as an argument in the textFile(“”) method is absolute path for the input file name. However, if only the file name is given, then it means that the input file is in the current location."
},
{
"code": null,
"e": 12683,
"s": 12634,
"text": "scala> val inputfile = sc.textFile(\"input.txt\")\n"
},
{
"code": null,
"e": 12811,
"s": 12683,
"text": "Our aim is to count the words in a file. Create a flat map for splitting each line into words (flatMap(line ⇒ line.split(“ ”))."
},
{
"code": null,
"e": 12926,
"s": 12811,
"text": "Next, read each word as a key with a value ‘1’ (<key, value> = <word,1>)using map function (map(word ⇒ (word, 1))."
},
{
"code": null,
"e": 13006,
"s": 12926,
"text": "Finally, reduce those keys by adding values of similar keys (reduceByKey(_+_))."
},
{
"code": null,
"e": 13244,
"s": 13006,
"text": "The following command is used for executing word count logic. After executing this, you will not find any output because this is not an action, this is a transformation; pointing a new RDD or tell spark to what to do with the given data)"
},
{
"code": null,
"e": 13349,
"s": 13244,
"text": "scala> val counts = inputfile.flatMap(line => line.split(\" \")).map(word => (word, 1)).reduceByKey(_+_);\n"
},
{
"code": null,
"e": 13535,
"s": 13349,
"text": "While working with the RDD, if you want to know about current RDD, then use the following command. It will show you the description about current RDD and its dependencies for debugging."
},
{
"code": null,
"e": 13564,
"s": 13535,
"text": "scala> counts.toDebugString\n"
},
{
"code": null,
"e": 13809,
"s": 13564,
"text": "You can mark an RDD to be persisted using the persist() or cache() methods on it. The first time it is computed in an action, it will be kept in memory on the nodes. Use the following command to store the intermediate transformations in memory."
},
{
"code": null,
"e": 13832,
"s": 13809,
"text": "scala> counts.cache()\n"
},
{
"code": null,
"e": 14131,
"s": 13832,
"text": "Applying an action, like store all the transformations, results into a text file. The String argument for saveAsTextFile(“ ”) method is the absolute path of output folder. Try the following command to save the output in a text file. In the following example, ‘output’ folder is in current location."
},
{
"code": null,
"e": 14171,
"s": 14131,
"text": "scala> counts.saveAsTextFile(\"output\")\n"
},
{
"code": null,
"e": 14324,
"s": 14171,
"text": "Open another terminal to go to home directory (where spark is executed in the other terminal). Use the following commands for checking output directory."
},
{
"code": null,
"e": 14428,
"s": 14324,
"text": "[hadoop@localhost ~]$ cd output/ \n[hadoop@localhost output]$ ls -1 \n \npart-00000 \npart-00001 \n_SUCCESS\n"
},
{
"code": null,
"e": 14495,
"s": 14428,
"text": "The following command is used to see output from Part-00000 files."
},
{
"code": null,
"e": 14538,
"s": 14495,
"text": "[hadoop@localhost output]$ cat part-00000\n"
},
{
"code": null,
"e": 14613,
"s": 14538,
"text": "(people,1) \n(are,2) \n(not,1) \n(as,8) \n(beautiful,2) \n(they, 7) \n(look,1) \n"
},
{
"code": null,
"e": 14680,
"s": 14613,
"text": "The following command is used to see output from Part-00001 files."
},
{
"code": null,
"e": 14724,
"s": 14680,
"text": "[hadoop@localhost output]$ cat part-00001 \n"
},
{
"code": null,
"e": 14801,
"s": 14724,
"text": "(walk, 1) \n(or, 1) \n(talk, 1) \n(only, 1) \n(love, 1) \n(care, 1) \n(share, 1) \n"
},
{
"code": null,
"e": 14939,
"s": 14801,
"text": "Before UN-persisting, if you want to see the storage space that is used for this application, then use the following URL in your browser."
},
{
"code": null,
"e": 14962,
"s": 14939,
"text": "http://localhost:4040\n"
},
{
"code": null,
"e": 15091,
"s": 14962,
"text": "You will see the following screen, which shows the storage space used for the application, which are running on the Spark shell."
},
{
"code": null,
"e": 15186,
"s": 15091,
"text": "If you want to UN-persist the storage space of particular RDD, then use the following command."
},
{
"code": null,
"e": 15213,
"s": 15186,
"text": "Scala> counts.unpersist()\n"
},
{
"code": null,
"e": 15250,
"s": 15213,
"text": "You will see the output as follows −"
},
{
"code": null,
"e": 15763,
"s": 15250,
"text": "15/06/27 00:57:33 INFO ShuffledRDD: Removing RDD 9 from persistence list \n15/06/27 00:57:33 INFO BlockManager: Removing RDD 9 \n15/06/27 00:57:33 INFO BlockManager: Removing block rdd_9_1 \n15/06/27 00:57:33 INFO MemoryStore: Block rdd_9_1 of size 480 dropped from memory (free 280061810) \n15/06/27 00:57:33 INFO BlockManager: Removing block rdd_9_0 \n15/06/27 00:57:33 INFO MemoryStore: Block rdd_9_0 of size 296 dropped from memory (free 280062106) \nres7: cou.type = ShuffledRDD[9] at reduceByKey at <console>:14\n"
},
{
"code": null,
"e": 15834,
"s": 15763,
"text": "For verifying the storage space in the browser, use the following URL."
},
{
"code": null,
"e": 15858,
"s": 15834,
"text": "http://localhost:4040/\n"
},
{
"code": null,
"e": 15984,
"s": 15858,
"text": "You will see the following screen. It shows the storage space used for the application, which are running on the Spark shell."
},
{
"code": null,
"e": 16019,
"s": 15984,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 16038,
"s": 16019,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 16073,
"s": 16038,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 16094,
"s": 16073,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 16127,
"s": 16094,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 16140,
"s": 16127,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 16175,
"s": 16140,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 16193,
"s": 16175,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 16226,
"s": 16193,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 16244,
"s": 16226,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 16277,
"s": 16244,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 16295,
"s": 16277,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 16302,
"s": 16295,
"text": " Print"
},
{
"code": null,
"e": 16313,
"s": 16302,
"text": " Add Notes"
}
] |
How to remove style added with .css() function using JavaScript? - GeeksforGeeks
|
22 Apr, 2019
There are many cases, especially as the content gets more interactive, where the developer want styles to dynamically kick in based on user input, some code having run in the background, and more. In these sorts of scenarios, the CSS model involving style rules or inline styles doesn’t help.
The solution to overcome all of these problems is one that involves JavaScript/jQuery. It not only lets style the element users are interacting with, more importantly, but it also allows developers to style elements all over the page. This freedom is very powerful and goes well beyond CSS’s limited ability to style content inside itself.
JavaScript:removeAttribute():It remove an attribute with specified name from the element.setAttribute():It sets the value of an attribute on the specified element.Example-1: Below example illustrates how to set/remove styles in JavaScript.<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title>JavaScript example</title></head> <body> <div> <p id="gfg"> Welcome to geeks for geeks </p> </div> <button type="button" id="setstyle" onclick="setstyle()"> Set Style </button> <button type="button" id="removestyle" onclick="removestyle()" disabled> Remove Style </button> </body> <script type="text/javascript"> removestyle = () => { document.getElementById( "gfg").removeAttribute("style"); document.getElementById( "setstyle").removeAttribute("disabled"); document.getElementById( "removestyle").setAttribute("disabled", "true"); };</script> </html>Output:Before Styling:After clicking on Set Style:After clicking on Remove Style:
removeAttribute():It remove an attribute with specified name from the element.
setAttribute():It sets the value of an attribute on the specified element.
Example-1: Below example illustrates how to set/remove styles in JavaScript.
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title>JavaScript example</title></head> <body> <div> <p id="gfg"> Welcome to geeks for geeks </p> </div> <button type="button" id="setstyle" onclick="setstyle()"> Set Style </button> <button type="button" id="removestyle" onclick="removestyle()" disabled> Remove Style </button> </body> <script type="text/javascript"> removestyle = () => { document.getElementById( "gfg").removeAttribute("style"); document.getElementById( "setstyle").removeAttribute("disabled"); document.getElementById( "removestyle").setAttribute("disabled", "true"); };</script> </html>
Output:Before Styling:
After clicking on Set Style:
After clicking on Remove Style:
jQuery:css():It sets or returns one or more style properties for selected elements.attr():It is used to set or return attributes and values of the selected elements.removeAttr():It removes one or more attributes from the selected elements.Example-2: Below example illustrates how to set/remove styles in jQuery.<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title>Jquery example</title> <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"> </script></head> <body> <div> <p id="gfg"> Welcome to geeks for geeks </p> </div> <button type="button" id="setstyle" onclick="setstyle()"> Set Style </button> <button type="button" id="removestyle" onclick="removestyle()" disabled> Remove Style </button> </body> <script type="text/javascript"> $(document).ready(() => { setstyle = () => { $("#gfg").css({ "color": "white", "background-color": "green", "padding": "10px", }); $("#setstyle").attr("disabled", "true"); $("#removestyle").removeAttr("disabled"); } });</script> </html>Output:Before Styling:After clicking on Set Style:After clicking on Remove Style:
css():It sets or returns one or more style properties for selected elements.
attr():It is used to set or return attributes and values of the selected elements.
removeAttr():It removes one or more attributes from the selected elements.
Example-2: Below example illustrates how to set/remove styles in jQuery.
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title>Jquery example</title> <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"> </script></head> <body> <div> <p id="gfg"> Welcome to geeks for geeks </p> </div> <button type="button" id="setstyle" onclick="setstyle()"> Set Style </button> <button type="button" id="removestyle" onclick="removestyle()" disabled> Remove Style </button> </body> <script type="text/javascript"> $(document).ready(() => { setstyle = () => { $("#gfg").css({ "color": "white", "background-color": "green", "padding": "10px", }); $("#setstyle").attr("disabled", "true"); $("#removestyle").removeAttr("disabled"); } });</script> </html>
Output:Before Styling:
After clicking on Set Style:
After clicking on Remove Style:
JavaScript-Misc
Picked
JavaScript
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
How to Use the JavaScript Fetch API to Get Data?
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to add options to a select element using jQuery?
|
[
{
"code": null,
"e": 24640,
"s": 24612,
"text": "\n22 Apr, 2019"
},
{
"code": null,
"e": 24933,
"s": 24640,
"text": "There are many cases, especially as the content gets more interactive, where the developer want styles to dynamically kick in based on user input, some code having run in the background, and more. In these sorts of scenarios, the CSS model involving style rules or inline styles doesn’t help."
},
{
"code": null,
"e": 25273,
"s": 24933,
"text": "The solution to overcome all of these problems is one that involves JavaScript/jQuery. It not only lets style the element users are interacting with, more importantly, but it also allows developers to style elements all over the page. This freedom is very powerful and goes well beyond CSS’s limited ability to style content inside itself."
},
{
"code": null,
"e": 26397,
"s": 25273,
"text": "JavaScript:removeAttribute():It remove an attribute with specified name from the element.setAttribute():It sets the value of an attribute on the specified element.Example-1: Below example illustrates how to set/remove styles in JavaScript.<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>JavaScript example</title></head> <body> <div> <p id=\"gfg\"> Welcome to geeks for geeks </p> </div> <button type=\"button\" id=\"setstyle\" onclick=\"setstyle()\"> Set Style </button> <button type=\"button\" id=\"removestyle\" onclick=\"removestyle()\" disabled> Remove Style </button> </body> <script type=\"text/javascript\"> removestyle = () => { document.getElementById( \"gfg\").removeAttribute(\"style\"); document.getElementById( \"setstyle\").removeAttribute(\"disabled\"); document.getElementById( \"removestyle\").setAttribute(\"disabled\", \"true\"); };</script> </html>Output:Before Styling:After clicking on Set Style:After clicking on Remove Style:"
},
{
"code": null,
"e": 26476,
"s": 26397,
"text": "removeAttribute():It remove an attribute with specified name from the element."
},
{
"code": null,
"e": 26551,
"s": 26476,
"text": "setAttribute():It sets the value of an attribute on the specified element."
},
{
"code": null,
"e": 26628,
"s": 26551,
"text": "Example-1: Below example illustrates how to set/remove styles in JavaScript."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>JavaScript example</title></head> <body> <div> <p id=\"gfg\"> Welcome to geeks for geeks </p> </div> <button type=\"button\" id=\"setstyle\" onclick=\"setstyle()\"> Set Style </button> <button type=\"button\" id=\"removestyle\" onclick=\"removestyle()\" disabled> Remove Style </button> </body> <script type=\"text/javascript\"> removestyle = () => { document.getElementById( \"gfg\").removeAttribute(\"style\"); document.getElementById( \"setstyle\").removeAttribute(\"disabled\"); document.getElementById( \"removestyle\").setAttribute(\"disabled\", \"true\"); };</script> </html>",
"e": 27432,
"s": 26628,
"text": null
},
{
"code": null,
"e": 27455,
"s": 27432,
"text": "Output:Before Styling:"
},
{
"code": null,
"e": 27484,
"s": 27455,
"text": "After clicking on Set Style:"
},
{
"code": null,
"e": 27516,
"s": 27484,
"text": "After clicking on Remove Style:"
},
{
"code": null,
"e": 28927,
"s": 27516,
"text": "jQuery:css():It sets or returns one or more style properties for selected elements.attr():It is used to set or return attributes and values of the selected elements.removeAttr():It removes one or more attributes from the selected elements.Example-2: Below example illustrates how to set/remove styles in jQuery.<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>Jquery example</title> <script src=\"https://code.jquery.com/jquery-3.3.1.js\" integrity=\"sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=\" crossorigin=\"anonymous\"> </script></head> <body> <div> <p id=\"gfg\"> Welcome to geeks for geeks </p> </div> <button type=\"button\" id=\"setstyle\" onclick=\"setstyle()\"> Set Style </button> <button type=\"button\" id=\"removestyle\" onclick=\"removestyle()\" disabled> Remove Style </button> </body> <script type=\"text/javascript\"> $(document).ready(() => { setstyle = () => { $(\"#gfg\").css({ \"color\": \"white\", \"background-color\": \"green\", \"padding\": \"10px\", }); $(\"#setstyle\").attr(\"disabled\", \"true\"); $(\"#removestyle\").removeAttr(\"disabled\"); } });</script> </html>Output:Before Styling:After clicking on Set Style:After clicking on Remove Style:"
},
{
"code": null,
"e": 29004,
"s": 28927,
"text": "css():It sets or returns one or more style properties for selected elements."
},
{
"code": null,
"e": 29087,
"s": 29004,
"text": "attr():It is used to set or return attributes and values of the selected elements."
},
{
"code": null,
"e": 29162,
"s": 29087,
"text": "removeAttr():It removes one or more attributes from the selected elements."
},
{
"code": null,
"e": 29235,
"s": 29162,
"text": "Example-2: Below example illustrates how to set/remove styles in jQuery."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>Jquery example</title> <script src=\"https://code.jquery.com/jquery-3.3.1.js\" integrity=\"sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=\" crossorigin=\"anonymous\"> </script></head> <body> <div> <p id=\"gfg\"> Welcome to geeks for geeks </p> </div> <button type=\"button\" id=\"setstyle\" onclick=\"setstyle()\"> Set Style </button> <button type=\"button\" id=\"removestyle\" onclick=\"removestyle()\" disabled> Remove Style </button> </body> <script type=\"text/javascript\"> $(document).ready(() => { setstyle = () => { $(\"#gfg\").css({ \"color\": \"white\", \"background-color\": \"green\", \"padding\": \"10px\", }); $(\"#setstyle\").attr(\"disabled\", \"true\"); $(\"#removestyle\").removeAttr(\"disabled\"); } });</script> </html>",
"e": 30254,
"s": 29235,
"text": null
},
{
"code": null,
"e": 30277,
"s": 30254,
"text": "Output:Before Styling:"
},
{
"code": null,
"e": 30306,
"s": 30277,
"text": "After clicking on Set Style:"
},
{
"code": null,
"e": 30338,
"s": 30306,
"text": "After clicking on Remove Style:"
},
{
"code": null,
"e": 30354,
"s": 30338,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 30361,
"s": 30354,
"text": "Picked"
},
{
"code": null,
"e": 30372,
"s": 30361,
"text": "JavaScript"
},
{
"code": null,
"e": 30379,
"s": 30372,
"text": "JQuery"
},
{
"code": null,
"e": 30396,
"s": 30379,
"text": "Web Technologies"
},
{
"code": null,
"e": 30423,
"s": 30396,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 30521,
"s": 30423,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30530,
"s": 30521,
"text": "Comments"
},
{
"code": null,
"e": 30543,
"s": 30530,
"text": "Old Comments"
},
{
"code": null,
"e": 30604,
"s": 30543,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30649,
"s": 30604,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30721,
"s": 30649,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 30762,
"s": 30721,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 30811,
"s": 30762,
"text": "How to Use the JavaScript Fetch API to Get Data?"
},
{
"code": null,
"e": 30857,
"s": 30811,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 30886,
"s": 30857,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 30949,
"s": 30886,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 31026,
"s": 30949,
"text": "How to change the background color after clicking the button in JavaScript ?"
}
] |
Interface Zigbee with Arduino
|
Zigbee is a wireless communication protocol targeted for battery powered devices (it has both low power and low cost). It generally operates in the 2.4GHz range (although there are geographic variations), and supports data ranges from 20 to 250 kbits/s.
The transmission distance though, is small compared to the likes of LoRa. It is 10 to 100 m, whereas LoRa can transmit over a few kilometers. Another thing to note is that Zigbee communication doesn’t work very well if there is no line of sight between transmitter and receiver.
Even minor obstacles have been observed to significantly degrade the communication. Keep these limitations in mind when using Zigbee. You may want to look out for other options if your application can’t meet these constraints.
In order to make Zigbee work with Arduino, we will use the XBee module.
These work with UART and therefore, it is fairly easy to interface them with Arduino. It is important to look at the pinout of XBee though, to understand which are the UART pins −
The DOUT and DIN pins in the figure above are the UART pins (TX and RX). They can be connected to two digital pins of Arduino (if you plan to use SoftwareSerial), or else to pins 0 and 1 of Arduino respectively (if you plan to use HW Serial). Please note that you won’t be able to read print statements from the Arduino on the Serial Monitor if you use Hardware Serial for Zigbee interface.
The XBee modules (transmitter and receiver) need to be configured using the X-CTU Software. It can be downloaded from here. This software is provided by DigiKey, and they have given a detailed configuration guide. Therefore, there is no point of me reinventing the wheel here. You can find the guide here.
There’s another one by Sparkfun that is adapted to the newer version of the X-CTU software.
Here’s another brief one by Instructables.
Please note that the two XBee modules that intend to communicate with each other should belong to the same series.
Here are a few things to note about the configuration −
You will need a breakout board or an Explorer with a USB to UART converter for this configuration.
You will need a breakout board or an Explorer with a USB to UART converter for this configuration.
The PAN ID (Personal Area Network ID) has to be the same for the devices that want to communicate with each other.
The PAN ID (Personal Area Network ID) has to be the same for the devices that want to communicate with each other.
One module needs to be set as the transmitter and the other as the receiver (this is determined by the CE field).
One module needs to be set as the transmitter and the other as the receiver (this is determined by the CE field).
Note the baud rate that you set. This will be used in the Arduino code, when configuring the Serial communication with XBee.
Note the baud rate that you set. This will be used in the Arduino code, when configuring the Serial communication with XBee.
Once your XBee is configured, you can connect it to the Arduino via the breakout/Explorer board. In that case, the pinout will be slightly different depending on which board/ Explorer you are using. Here we will assume you are connecting the XBee directly to Arduino Uno, in which case, the connections will be −
As you can see, we have connected Vcc to 3.3V on Arduino, GND to GND, DOUT (TX) to pin 2, which will act as RX on the Arduino, and DIN (RX) to pin 3, which will act as TX on the Arduino.
The connections will be similar on the receiving side as well. If you have an on-board antenna, that’s good, else you’ll have to connect an antenna to the UFL connector.
The code is quite straightforward. If you are using a board other than Arduino Uno, all digital pins may not support SoftwareSerial. Read the limitations of SoftwareSerial here
On the transmitting side, the code will be −
#include <SoftwareSerial.h>
SoftwareSerial xbeeSerial(2,3); //RX, TX
void setup() {
Serial.begin(9600);
xbeeSerial.begin(9600);
}
void loop() {
if(Serial.available() > 0){
char input = Serial.read();
xbeeSerial.print(input);
}
}
As you can see, whatever is sent by the user on the Serial Monitor is sent to the XBee module,and it will be received on the receiving side. The code for the receiving side is −
#include <SoftwareSerial.h>
SoftwareSerial xbeeSerial(2,3); //RX, TX
void setup() {
Serial.begin(9600);
xbeeSerial.begin(9600);
}
void loop() {
if(xbeeSerial.available() > 0){
char input = xbeeSerial.read();
Serial.print(input);
}
}
Over here, whatever is received from XBee is forwarded to the Serial Monitor. Thus, when testing out the combined system, whatever you type on the Serial Monitor on the transmitter side should be printed on the Serial Monitor on the receiver side.
|
[
{
"code": null,
"e": 1316,
"s": 1062,
"text": "Zigbee is a wireless communication protocol targeted for battery powered devices (it has both low power and low cost). It generally operates in the 2.4GHz range (although there are geographic variations), and supports data ranges from 20 to 250 kbits/s."
},
{
"code": null,
"e": 1595,
"s": 1316,
"text": "The transmission distance though, is small compared to the likes of LoRa. It is 10 to 100 m, whereas LoRa can transmit over a few kilometers. Another thing to note is that Zigbee communication doesn’t work very well if there is no line of sight between transmitter and receiver."
},
{
"code": null,
"e": 1822,
"s": 1595,
"text": "Even minor obstacles have been observed to significantly degrade the communication. Keep these limitations in mind when using Zigbee. You may want to look out for other options if your application can’t meet these constraints."
},
{
"code": null,
"e": 1894,
"s": 1822,
"text": "In order to make Zigbee work with Arduino, we will use the XBee module."
},
{
"code": null,
"e": 2074,
"s": 1894,
"text": "These work with UART and therefore, it is fairly easy to interface them with Arduino. It is important to look at the pinout of XBee though, to understand which are the UART pins −"
},
{
"code": null,
"e": 2465,
"s": 2074,
"text": "The DOUT and DIN pins in the figure above are the UART pins (TX and RX). They can be connected to two digital pins of Arduino (if you plan to use SoftwareSerial), or else to pins 0 and 1 of Arduino respectively (if you plan to use HW Serial). Please note that you won’t be able to read print statements from the Arduino on the Serial Monitor if you use Hardware Serial for Zigbee interface."
},
{
"code": null,
"e": 2771,
"s": 2465,
"text": "The XBee modules (transmitter and receiver) need to be configured using the X-CTU Software. It can be downloaded from here. This software is provided by DigiKey, and they have given a detailed configuration guide. Therefore, there is no point of me reinventing the wheel here. You can find the guide here."
},
{
"code": null,
"e": 2863,
"s": 2771,
"text": "There’s another one by Sparkfun that is adapted to the newer version of the X-CTU software."
},
{
"code": null,
"e": 2906,
"s": 2863,
"text": "Here’s another brief one by Instructables."
},
{
"code": null,
"e": 3021,
"s": 2906,
"text": "Please note that the two XBee modules that intend to communicate with each other should belong to the same series."
},
{
"code": null,
"e": 3077,
"s": 3021,
"text": "Here are a few things to note about the configuration −"
},
{
"code": null,
"e": 3176,
"s": 3077,
"text": "You will need a breakout board or an Explorer with a USB to UART converter for this configuration."
},
{
"code": null,
"e": 3275,
"s": 3176,
"text": "You will need a breakout board or an Explorer with a USB to UART converter for this configuration."
},
{
"code": null,
"e": 3390,
"s": 3275,
"text": "The PAN ID (Personal Area Network ID) has to be the same for the devices that want to communicate with each other."
},
{
"code": null,
"e": 3505,
"s": 3390,
"text": "The PAN ID (Personal Area Network ID) has to be the same for the devices that want to communicate with each other."
},
{
"code": null,
"e": 3619,
"s": 3505,
"text": "One module needs to be set as the transmitter and the other as the receiver (this is determined by the CE field)."
},
{
"code": null,
"e": 3733,
"s": 3619,
"text": "One module needs to be set as the transmitter and the other as the receiver (this is determined by the CE field)."
},
{
"code": null,
"e": 3858,
"s": 3733,
"text": "Note the baud rate that you set. This will be used in the Arduino code, when configuring the Serial communication with XBee."
},
{
"code": null,
"e": 3983,
"s": 3858,
"text": "Note the baud rate that you set. This will be used in the Arduino code, when configuring the Serial communication with XBee."
},
{
"code": null,
"e": 4296,
"s": 3983,
"text": "Once your XBee is configured, you can connect it to the Arduino via the breakout/Explorer board. In that case, the pinout will be slightly different depending on which board/ Explorer you are using. Here we will assume you are connecting the XBee directly to Arduino Uno, in which case, the connections will be −"
},
{
"code": null,
"e": 4483,
"s": 4296,
"text": "As you can see, we have connected Vcc to 3.3V on Arduino, GND to GND, DOUT (TX) to pin 2, which will act as RX on the Arduino, and DIN (RX) to pin 3, which will act as TX on the Arduino."
},
{
"code": null,
"e": 4653,
"s": 4483,
"text": "The connections will be similar on the receiving side as well. If you have an on-board antenna, that’s good, else you’ll have to connect an antenna to the UFL connector."
},
{
"code": null,
"e": 4830,
"s": 4653,
"text": "The code is quite straightforward. If you are using a board other than Arduino Uno, all digital pins may not support SoftwareSerial. Read the limitations of SoftwareSerial here"
},
{
"code": null,
"e": 4875,
"s": 4830,
"text": "On the transmitting side, the code will be −"
},
{
"code": null,
"e": 5130,
"s": 4875,
"text": "#include <SoftwareSerial.h>\nSoftwareSerial xbeeSerial(2,3); //RX, TX\n\nvoid setup() {\n Serial.begin(9600);\n xbeeSerial.begin(9600);\n}\n\nvoid loop() {\n if(Serial.available() > 0){\n char input = Serial.read();\n xbeeSerial.print(input);\n }\n}"
},
{
"code": null,
"e": 5308,
"s": 5130,
"text": "As you can see, whatever is sent by the user on the Serial Monitor is sent to the XBee module,and it will be received on the receiving side. The code for the receiving side is −"
},
{
"code": null,
"e": 5567,
"s": 5308,
"text": "#include <SoftwareSerial.h>\nSoftwareSerial xbeeSerial(2,3); //RX, TX\n\nvoid setup() {\n Serial.begin(9600);\n xbeeSerial.begin(9600);\n}\n\nvoid loop() {\n if(xbeeSerial.available() > 0){\n char input = xbeeSerial.read();\n Serial.print(input);\n }\n}"
},
{
"code": null,
"e": 5815,
"s": 5567,
"text": "Over here, whatever is received from XBee is forwarded to the Serial Monitor. Thus, when testing out the combined system, whatever you type on the Serial Monitor on the transmitter side should be printed on the Serial Monitor on the receiver side."
}
] |
How do you make code reusable in C#?
|
To make code reusable in C#, use Interfaces. Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members. It often helps in providing a standard structure that the deriving classes would follow.
For example, Shape Interface −
public interface IShape {
void display();
}
Above we have declared an Interface Shape. You can notice that it begins with a capital “I”. It is a common convention that interfaces names begin with “I”.
We have not added an access specifier above since interface members are public by default.
In real applications, Polymorphism is key for code reuse. Interfaces are flexible because if you use interfaces, then with its help you can pass anything that implements that Interface.
|
[
{
"code": null,
"e": 1413,
"s": 1062,
"text": "To make code reusable in C#, use Interfaces. Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members. It often helps in providing a standard structure that the deriving classes would follow."
},
{
"code": null,
"e": 1444,
"s": 1413,
"text": "For example, Shape Interface −"
},
{
"code": null,
"e": 1491,
"s": 1444,
"text": "public interface IShape {\n void display();\n}"
},
{
"code": null,
"e": 1648,
"s": 1491,
"text": "Above we have declared an Interface Shape. You can notice that it begins with a capital “I”. It is a common convention that interfaces names begin with “I”."
},
{
"code": null,
"e": 1739,
"s": 1648,
"text": "We have not added an access specifier above since interface members are public by default."
},
{
"code": null,
"e": 1925,
"s": 1739,
"text": "In real applications, Polymorphism is key for code reuse. Interfaces are flexible because if you use interfaces, then with its help you can pass anything that implements that Interface."
}
] |
Stopwatch class in C#
|
Stopwatch is a class in C# to measure the elapsed time. Use it to calculate the time a function took to execute. It is found under System.Diagnostics.
To get the elapsed time, firstly begin the Stopwatch −
var sw = Stopwatch.StartNew();
For elapsed ticks −
long ticks = sw.ElapsedTicks;
Let us see an example −
Live Demo
using System;
using System.Linq;
using System.Diagnostics;
public class Demo {
public static void Main() {
var sw = Stopwatch.StartNew();
long ticks = sw.ElapsedTicks;
Console.WriteLine(ticks);
}
}
582
|
[
{
"code": null,
"e": 1213,
"s": 1062,
"text": "Stopwatch is a class in C# to measure the elapsed time. Use it to calculate the time a function took to execute. It is found under System.Diagnostics."
},
{
"code": null,
"e": 1268,
"s": 1213,
"text": "To get the elapsed time, firstly begin the Stopwatch −"
},
{
"code": null,
"e": 1299,
"s": 1268,
"text": "var sw = Stopwatch.StartNew();"
},
{
"code": null,
"e": 1319,
"s": 1299,
"text": "For elapsed ticks −"
},
{
"code": null,
"e": 1349,
"s": 1319,
"text": "long ticks = sw.ElapsedTicks;"
},
{
"code": null,
"e": 1373,
"s": 1349,
"text": "Let us see an example −"
},
{
"code": null,
"e": 1384,
"s": 1373,
"text": " Live Demo"
},
{
"code": null,
"e": 1606,
"s": 1384,
"text": "using System;\nusing System.Linq;\nusing System.Diagnostics;\npublic class Demo {\n public static void Main() {\n var sw = Stopwatch.StartNew();\n long ticks = sw.ElapsedTicks;\n Console.WriteLine(ticks);\n }\n}"
},
{
"code": null,
"e": 1610,
"s": 1606,
"text": "582"
}
] |
wxPython - ComboBox & Choice Class
|
A wx.ComboBox object presents a list of items to select from. It can be configured to be a dropdown list or with permanent display.
The selected item from the list is displayed in a text field, which by default is editable, but can be set to be read-only in the presence of wx.CB_READONLY style parameter.
wxPython API contains a wx.Choice class, whose object is also a dropdown list, which is permanently read-only.
The parameters used by wx.ComboBox class constructor are −
Wx.ComboBox(parent, id, value, pos, size, choices[], style)
The value parameter is the text to be displayed in the text box of combobox. It is populated from the items in choices[] collection.
The following style parameters are defined for wx.ComboBox −
wx.CB_SIMPLE
Combobox with permanently displayed list
wx.CB_DROPDOWN
Combobox with dropdown list
wx.CB_READONLY
Chosen item is not editable
wx.CB_SORT
List is displayed in alphabetical order
The following table shows commonly used methods of wx.ComboBox class −
GetCurrentSelection ()
Returns the item being selected
SetSelection()
Sets the item at the given index as selected
GetString()
Returns the string associated with the item at the given index
SetString()
Changes the text of item at the given index
SetValue()
Sets a string as the text displayed in the edit field of combobox
GetValue()
Returns the contents of the text field of combobox
FindString()
Searches for the given string in the list
GetStringSelection()
Gets the text of the currently selected item
Event binders for events generated by this class are as follows −
wx. COMBOBOX
When item from the list is selected
wx. EVT_TEXT
When combobox text changes
wx. EVT_COMBOBOX_DROPDOWN
When list drops down
wx. EVT_COMBOBOX_CLOSEUP
When list folds up
wx.Choice class constructor prototype is as follows −
wx.Choice(parent, id, pos, size, n, choices[], style)
Parameter ‘n’ stands for number of strings with which the choice list is to be initialized. Like comboBox, the list is populated with items in choices[] collection.
For Choice class, only one style parameter is defined. It is wx.CB_SORT. Only one event binder processes the event emitted by this class. It is wx.EVT_CHOICE.
This example displays the features of wx.ComboBox and wx.Choice. Both objects are put in a vertical box sizer. The lists are populated with items in languages[] List object.
languages = ['C', 'C++', 'Python', 'Java', 'Perl']
self.combo = wx.ComboBox(panel,choices = languages)
self.choice = wx.Choice(panel,choices = languages)
Event binders EVT_COMBOBOX and EVT_CHOICE process corresponding events on them.
self.combo.Bind(wx.EVT_COMBOBOX, self.OnCombo)
self.choice.Bind(wx.EVT_CHOICE, self.OnChoice)
The following handler functions display the selected item from the list on the label.
def OnCombo(self, event):
self.label.SetLabel("selected "+ self.combo.GetValue() +" from Combobox")
def OnChoice(self,event):
self.label.SetLabel("selected "+ self.choice.
GetString( self.choice.GetSelection() ) +" from Choice")
The complete code listing is as follows −
import wx
class Mywin(wx.Frame):
def __init__(self, parent, title):
super(Mywin, self).__init__(parent, title = title,size = (300,200))
panel = wx.Panel(self)
box = wx.BoxSizer(wx.VERTICAL)
self.label = wx.StaticText(panel,label = "Your choice:" ,style = wx.ALIGN_CENTRE)
box.Add(self.label, 0 , wx.EXPAND |wx.ALIGN_CENTER_HORIZONTAL |wx.ALL, 20)
cblbl = wx.StaticText(panel,label = "Combo box",style = wx.ALIGN_CENTRE)
box.Add(cblbl,0,wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALL,5)
languages = ['C', 'C++', 'Python', 'Java', 'Perl']
self.combo = wx.ComboBox(panel,choices = languages)
box.Add(self.combo,1,wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALL,5)
chlbl = wx.StaticText(panel,label = "Choice control",style = wx.ALIGN_CENTRE)
box.Add(chlbl,0,wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALL,5)
self.choice = wx.Choice(panel,choices = languages)
box.Add(self.choice,1,wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALL,5)
box.AddStretchSpacer()
self.combo.Bind(wx.EVT_COMBOBOX, self.OnCombo)
self.choice.Bind(wx.EVT_CHOICE, self.OnChoice)
panel.SetSizer(box)
self.Centre()
self.Show()
def OnCombo(self, event):
self.label.SetLabel("You selected"+self.combo.GetValue()+" from Combobox")
def OnChoice(self,event):
self.label.SetLabel("You selected "+ self.choice.GetString
(self.choice.GetSelection())+" from Choice")
app = wx.App()
Mywin(None, 'ComboBox and Choice demo')
app.MainLoop()
The above code produces the following output −
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2014,
"s": 1882,
"text": "A wx.ComboBox object presents a list of items to select from. It can be configured to be a dropdown list or with permanent display."
},
{
"code": null,
"e": 2188,
"s": 2014,
"text": "The selected item from the list is displayed in a text field, which by default is editable, but can be set to be read-only in the presence of wx.CB_READONLY style parameter."
},
{
"code": null,
"e": 2299,
"s": 2188,
"text": "wxPython API contains a wx.Choice class, whose object is also a dropdown list, which is permanently read-only."
},
{
"code": null,
"e": 2358,
"s": 2299,
"text": "The parameters used by wx.ComboBox class constructor are −"
},
{
"code": null,
"e": 2419,
"s": 2358,
"text": "Wx.ComboBox(parent, id, value, pos, size, choices[], style)\n"
},
{
"code": null,
"e": 2552,
"s": 2419,
"text": "The value parameter is the text to be displayed in the text box of combobox. It is populated from the items in choices[] collection."
},
{
"code": null,
"e": 2613,
"s": 2552,
"text": "The following style parameters are defined for wx.ComboBox −"
},
{
"code": null,
"e": 2626,
"s": 2613,
"text": "wx.CB_SIMPLE"
},
{
"code": null,
"e": 2667,
"s": 2626,
"text": "Combobox with permanently displayed list"
},
{
"code": null,
"e": 2682,
"s": 2667,
"text": "wx.CB_DROPDOWN"
},
{
"code": null,
"e": 2710,
"s": 2682,
"text": "Combobox with dropdown list"
},
{
"code": null,
"e": 2725,
"s": 2710,
"text": "wx.CB_READONLY"
},
{
"code": null,
"e": 2753,
"s": 2725,
"text": "Chosen item is not editable"
},
{
"code": null,
"e": 2764,
"s": 2753,
"text": "wx.CB_SORT"
},
{
"code": null,
"e": 2804,
"s": 2764,
"text": "List is displayed in alphabetical order"
},
{
"code": null,
"e": 2875,
"s": 2804,
"text": "The following table shows commonly used methods of wx.ComboBox class −"
},
{
"code": null,
"e": 2898,
"s": 2875,
"text": "GetCurrentSelection ()"
},
{
"code": null,
"e": 2930,
"s": 2898,
"text": "Returns the item being selected"
},
{
"code": null,
"e": 2945,
"s": 2930,
"text": "SetSelection()"
},
{
"code": null,
"e": 2990,
"s": 2945,
"text": "Sets the item at the given index as selected"
},
{
"code": null,
"e": 3002,
"s": 2990,
"text": "GetString()"
},
{
"code": null,
"e": 3065,
"s": 3002,
"text": "Returns the string associated with the item at the given index"
},
{
"code": null,
"e": 3077,
"s": 3065,
"text": "SetString()"
},
{
"code": null,
"e": 3121,
"s": 3077,
"text": "Changes the text of item at the given index"
},
{
"code": null,
"e": 3132,
"s": 3121,
"text": "SetValue()"
},
{
"code": null,
"e": 3198,
"s": 3132,
"text": "Sets a string as the text displayed in the edit field of combobox"
},
{
"code": null,
"e": 3209,
"s": 3198,
"text": "GetValue()"
},
{
"code": null,
"e": 3260,
"s": 3209,
"text": "Returns the contents of the text field of combobox"
},
{
"code": null,
"e": 3273,
"s": 3260,
"text": "FindString()"
},
{
"code": null,
"e": 3315,
"s": 3273,
"text": "Searches for the given string in the list"
},
{
"code": null,
"e": 3336,
"s": 3315,
"text": "GetStringSelection()"
},
{
"code": null,
"e": 3381,
"s": 3336,
"text": "Gets the text of the currently selected item"
},
{
"code": null,
"e": 3447,
"s": 3381,
"text": "Event binders for events generated by this class are as follows −"
},
{
"code": null,
"e": 3460,
"s": 3447,
"text": "wx. COMBOBOX"
},
{
"code": null,
"e": 3496,
"s": 3460,
"text": "When item from the list is selected"
},
{
"code": null,
"e": 3509,
"s": 3496,
"text": "wx. EVT_TEXT"
},
{
"code": null,
"e": 3536,
"s": 3509,
"text": "When combobox text changes"
},
{
"code": null,
"e": 3562,
"s": 3536,
"text": "wx. EVT_COMBOBOX_DROPDOWN"
},
{
"code": null,
"e": 3583,
"s": 3562,
"text": "When list drops down"
},
{
"code": null,
"e": 3608,
"s": 3583,
"text": "wx. EVT_COMBOBOX_CLOSEUP"
},
{
"code": null,
"e": 3627,
"s": 3608,
"text": "When list folds up"
},
{
"code": null,
"e": 3681,
"s": 3627,
"text": "wx.Choice class constructor prototype is as follows −"
},
{
"code": null,
"e": 3736,
"s": 3681,
"text": "wx.Choice(parent, id, pos, size, n, choices[], style)\n"
},
{
"code": null,
"e": 3901,
"s": 3736,
"text": "Parameter ‘n’ stands for number of strings with which the choice list is to be initialized. Like comboBox, the list is populated with items in choices[] collection."
},
{
"code": null,
"e": 4060,
"s": 3901,
"text": "For Choice class, only one style parameter is defined. It is wx.CB_SORT. Only one event binder processes the event emitted by this class. It is wx.EVT_CHOICE."
},
{
"code": null,
"e": 4234,
"s": 4060,
"text": "This example displays the features of wx.ComboBox and wx.Choice. Both objects are put in a vertical box sizer. The lists are populated with items in languages[] List object."
},
{
"code": null,
"e": 4390,
"s": 4234,
"text": "languages = ['C', 'C++', 'Python', 'Java', 'Perl'] \nself.combo = wx.ComboBox(panel,choices = languages) \nself.choice = wx.Choice(panel,choices = languages)"
},
{
"code": null,
"e": 4470,
"s": 4390,
"text": "Event binders EVT_COMBOBOX and EVT_CHOICE process corresponding events on them."
},
{
"code": null,
"e": 4566,
"s": 4470,
"text": "self.combo.Bind(wx.EVT_COMBOBOX, self.OnCombo) \nself.choice.Bind(wx.EVT_CHOICE, self.OnChoice)\n"
},
{
"code": null,
"e": 4652,
"s": 4566,
"text": "The following handler functions display the selected item from the list on the label."
},
{
"code": null,
"e": 4898,
"s": 4652,
"text": "def OnCombo(self, event): \n self.label.SetLabel(\"selected \"+ self.combo.GetValue() +\" from Combobox\") \n\t\ndef OnChoice(self,event): \n self.label.SetLabel(\"selected \"+ self.choice.\n GetString( self.choice.GetSelection() ) +\" from Choice\")"
},
{
"code": null,
"e": 4940,
"s": 4898,
"text": "The complete code listing is as follows −"
},
{
"code": null,
"e": 6562,
"s": 4940,
"text": "import wx \nclass Mywin(wx.Frame): \n def __init__(self, parent, title): \n super(Mywin, self).__init__(parent, title = title,size = (300,200)) \n\t\t\n panel = wx.Panel(self) \n box = wx.BoxSizer(wx.VERTICAL) \n self.label = wx.StaticText(panel,label = \"Your choice:\" ,style = wx.ALIGN_CENTRE) \n box.Add(self.label, 0 , wx.EXPAND |wx.ALIGN_CENTER_HORIZONTAL |wx.ALL, 20) \n cblbl = wx.StaticText(panel,label = \"Combo box\",style = wx.ALIGN_CENTRE) \n\t\t\n box.Add(cblbl,0,wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALL,5) \n languages = ['C', 'C++', 'Python', 'Java', 'Perl'] \n self.combo = wx.ComboBox(panel,choices = languages) \n\t\t\n box.Add(self.combo,1,wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALL,5) \n chlbl = wx.StaticText(panel,label = \"Choice control\",style = wx.ALIGN_CENTRE) \n\t\t\n box.Add(chlbl,0,wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALL,5) \n self.choice = wx.Choice(panel,choices = languages) \n box.Add(self.choice,1,wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALL,5) \n \n box.AddStretchSpacer() \n self.combo.Bind(wx.EVT_COMBOBOX, self.OnCombo) \n self.choice.Bind(wx.EVT_CHOICE, self.OnChoice)\n\t\t\n panel.SetSizer(box) \n self.Centre() \n self.Show() \n\t\t \n def OnCombo(self, event): \n self.label.SetLabel(\"You selected\"+self.combo.GetValue()+\" from Combobox\") \n\t\t\n def OnChoice(self,event): \n self.label.SetLabel(\"You selected \"+ self.choice.GetString\n (self.choice.GetSelection())+\" from Choice\") \n \napp = wx.App() \nMywin(None, 'ComboBox and Choice demo') \napp.MainLoop()"
},
{
"code": null,
"e": 6609,
"s": 6562,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 6616,
"s": 6609,
"text": " Print"
},
{
"code": null,
"e": 6627,
"s": 6616,
"text": " Add Notes"
}
] |
10 QuestionsTo Practice Before Your Databricks Apache Spark 3.0 Developer Exam | by AnBento | Towards Data Science
|
A note for my readers: This post includes affiliate links for which I may earn a small commission at no extra cost to you, should you make a purchase.
If you are in the process of studying for the Databricks Associate Developer for Apache Spark 3.0 certification you are probably facing the same problem I faced a few weeks ago: a lack of mock tests to assess your readiness.
By now, you should know that the exam consists of 60 MCQs and that you will be given 120 mins to answer correctly to at least 42 of them (70%).
Another particular I suppose you have noticed is that the exam will cost you $240 (including VAT) but you will be allowed a single attempt, such that if you fail, you will have to pay again to retake it. With these premises, I guess you really wish to nail the exam at the first shot.
But you might be wondering: “If I can’t find any examples of questions that are representative of the level of difficulty of the exam, how can I actually understand if I am ready or not?”.
This is the same dilemma I run into just before sitting the exam: I was not sure to be ready enough to get beyond the 70% threshold and probably I wasn’t, as I found real questions being more challenging than expected.
I found real questions being more challenging than expected.
Despite some struggles (also technical as my exam was paused by the proctor for 30 mins), I managed to clear the certification with a good mark after preparing for around 2 months.
There are at least a dozen of other articles on Medium on this topic (I read them all as part of my preparation) and I found 3–4 of them really insightful (links at the end of the article), but none of them included any mock multiple choice questions that helped me to test my knowledge.
In this article I share with you 10 MCQs for the PySpark version of the certification, that you can expect to find in the real exam.
For this reason, in this article, I share with you 10 MCQs for the PySpark version of the certification, that you can expect to find in the real exam. Please note that I am not allowed to disclose the exact questions, so I have rephrased them, by keeping the level of difficulty intact, so you can trust them being a valuable study resource.
Before jumping on the actual questions, let me give you 3 tips that you won’t probably find in other articles, but that I reckon could make a huge difference in terms of the final mark you could get.
medium.com
towardsdatascience.com
No, I won’t suggest you peruse Spark - The Definitive Guide or the 2d Edition of Learning Spark as...you already know about them...right? What I am going to give you are 3 tips that will disproportionally increase your chance to succeed - so read carefully!
This is probably the best suggestion I can give you to excel. In effect, during the exam, you will be allowed to refer to the pyspark.sql documentation on your right screen, but you won’t be able to use CTRL+F to search for keywords.
This means that unless you know where to find specific methods or specific functions, you could waste a lot of time scrolling back and forth and - trust me- this will make you nervous. Instead, I suggest you to focus on the content of the following three classes:
pyspark.sql.DataFrame: for instance, you should be able to locate the coalesce() and join() functions.
pyspark.sq.Column: for instance, you should know that when() , between() and otherwise are applied to columns of a DataFrame and not directly to the DataFrame.
pyspark.sql.functions: for instance, you should know that functions used to manipulate time fields like date_add() , date_sun() and from_unixtime() (yes I got a question on this function! Nowhere to be found in the books...) are described here.
I approached and studied the structure of the documentation only 2 days before the test, but I wish I did it much earlier as this knowledge helped me to answer correctly to at least 7–8 questions.
Hence, what I am trying to convey here is not to overestimate your knowledge on the PySpark syntax as your memory could betray you during the exam. Take full advantage of the documentation instead.
It turns out that actually 2 full mock tests for Python/Pyspark are available on Udemy and include 120 practice exam quiz for the Apache Spark 3.0 certification exam!
I purchased access to the tests 2 months before the exam, as I wanted to study the material based on real questions and review the topics for which I got wrong answers.
Like in the real exam, you have 2 hours to complete the test and the weight of each topic is also respected, that means:
Spark DataFrame API Applications (~72%)
Spark Architecture: Conceptual understanding (~17%)
Spark Architecture: Applied understanding (~11%)
In my case, at least 12–15 questions in the actual exam were very similar to questions I practiced in these tests (both in terms of phrasing and solutions), so I reckon it is an excellent investment while you are studying for the certification.
With hindsight, one thing I could have done better while preparing, was to experiment running many more functions and methods belonging to the Spark DataFrame API and carefully review their syntax in detail, instead of just focusing on the code snippets on the books.
Think about that: you will find at least 40–43 questions around the Spark DataFrame API, therefore it is fair to expect that a large variety of concepts will be tested (even concepts that you won’t find mentioned in the books — life sucks!).
Also, bear in mind that a good 30% of these 40–43 questions are going to be particularly tricky, with at least two very similar options, so that you will need to be extremely sure about the syntax. But remember: worst-case scenario you can always consult the documentation (that brings us back to point #1).
Now it’s time for some quizzes!
towardsdatascience.com
Given a dataframe df, select the code that returns its number of rows:A. df.take('all') B. df.collect()C. df.show()D. df.count() --> CORRECTE. df.numRows()
The correct answer is D as df.count() actually returns the number of rows in a DataFrame as you can see in the documentation. This was a warm-up questions, but don’t forget about it as you could find something similar.
Given a DataFrame df that includes a number of columns among which a column named quantity and a column named price, complete the code below such that it will create a DataFrame including all the original columns and a new column revenue defined as quantity*price:df._1_(_2_ , _3_)A. withColumnRenamed, "revenue", expr("quantity*price")B. withColumn, revenue, expr("quantity*price")C. withColumn, "revenue", expr("quantity*price") --> CORRECTD. withColumn, expr("quantity*price"), "revenue"E. withColumnRenamed, "revenue", col("quantity")*col("price")
The correct answer is C as the code should be:
df.withColumn("revenue", expr("quantity*price"))
You will be asked at least 2–3 questions that involve adding a new column to a DF or renaming an existing one, so learn the syntax of withColumn() and withColumnRenamed() very well.
# Given a DataFrame df that has some null values in the column created_date, complete the code below such that it will sort rows in ascending order based on the column creted_date with null values appearing last.df._1_(_2_)A. orderBy, asc_nulls_last("created_date")B. sort, asc_nulls_last("created_date")C. orderBy, col("created_date").asc_nulls_last() --> CORRECTD. orderBy, col("created_date"), ascending=True)E. orderBy, col("created_date").asc()
The correct answer is C as the code should be:
df.orderBy(col("created_date").asc_null_last())
but also df.orderBy(df.created_date.asc_null_last()) would work.
In effect, like for asc() in answer E, asc_null_last() does not take any argument, but is applied to column to return a sort expression based on ascending order of the column, and null values appear after non-null values.
Which one of the following commands does NOT trigger an eager evaluation?A. df.collect()B. df.take()C. df.show()D. df.saveAsTable()E. df.join() --> CORRECT
The correct answer is E as in Apache Spark all transformations are evaluated lazily and all the actions are evaluated eagerly. In this case, the only command that will be evaluated lazily is df.join() .
Below you find some additional transformations and actions that often appear in similar questions:
Transformations ActionsorderBy() show()groupBy() take()filter() count()select() collect()join() save()limit() foreach()map(), flatMap() first()sort() count(), countByValue()printSchema() reduce() cache()
Which of the following statements are NOT true for broadcast variables ?A. Broadcast variables are shared, immutable variables that are cached on every machine in the cluster instead of being serialized with every single task.B. A custom broadcast class can be defined by extending org.apache.spark.utilbroadcastV2 in Java or Scala or pyspark.Accumulatorparams in Python. --> CORRECTC. It is a way of updating a value inside a variety of transformations and propagating that value to the driver node in an efficient and fault-tolerant way.--> CORRECTD. It provides a mutable variable that Spark cluster can safely update on a per-row basis. --> CORRECTE. The canonical use case is to pass around a small table that does fit in memory on executors.
The correct options are B, C and D as these are characteristics of accumulators (the alternative type of distributed shared variable).
For the exam remember that broadcast variables are immutable and lazily replicated across all nodes in the cluster when an action is triggered. Broadcast variables are efficient at scale, as they avoid the cost of serializing data for every task. They can be used in the context of RDDs or Structured APIs.
The code below should return a new DataFrame with 50 percent of random records from DataFrame df without replacement. Choose the response that correctly fills in the numbered blanks within the code block to complete this task.df._1_(_2_,_3_,_4_)A. sample, False, 0.5, 5 --> CORRECTB. random, False, 0.5, 5C. sample, False, 5, 25D. sample, False, 50, 5E. sample, withoutReplacement, 0.5, 5
The correct answer is A as the code block should bedf.sample(False, 0.5, 5) in fact the correct syntax for sample() is:
df.sample(withReplacement, fraction, seed)
In this case the seed is a random number and not really relevant for the answer. You should just remember that it is the last in the order.
Which of the following DataFrame commands will NOT generate a shuffle of data from each executor across the cluster?A. df.map() --> CORRECTB. df.collect()C. df.orderBy()D. df.repartition()E. df.distinct()F. df.join()
The correct answer is A as map() is the only narrow transformation in the list.
In particular, transformations can be classified as having either narrow dependencies or wide dependencies. Any transformation where a single output partition can be computed from a single input partition is a narrow transformation. For example, filter(), contains() and map() represent narrow transformations because they can operate on a single partition and produce the resulting output partition without any exchange of data.
Below you find a list including a number of narrow and wide transformations, useful to revise just before the exam:
WIDE TRANSORM NARROW TRANSFORMorderBy() filter()repartition() contains()distinct() map()collect() flatMap()cartesian() MapPartition()intersection() sample()reduceByKey() union()groupByKey() coalesce() --> when numPartitions is reducedgroupBy() drop()join() cache()
When Spark runs in Cluster Mode, which of the following statements about nodes is correct ?A. There is one single worker node that contains the Spark driver and all the executors.B. The Spark Driver runs in a worker node inside the cluster. --> CORRECTC. There is always more than one worker node.D. There are less executors than total number of worker nodes.E. Each executor is a running JVM inside of a cluster manager node.
The correct answer is B as in Cluster Mode, the cluster manager launches the driver process on a worker node inside the cluster, in addition to the executor processes. This means that the cluster manager is responsible for maintaining all Spark worker nodes. Therefore, the cluster manager places the driver on a worker node and the executors on separate worker nodes.
The DataFrame df includes a time string column named timestamp_1. Which is the correct syntax that creates a new DataFrame df1 that is just made by the time string field converted to a unix timestamp?A. df1 = df.select(unix_timestamp(col("timestamp_1"),"MM-dd-yyyy HH:mm:ss").as("timestamp_1"))B. df1 = df.select(unix_timestamp(col("timestamp_1"),"MM-dd-yyyy HH:mm:ss", "America/Los Angeles").alias("timestamp_1"))C. df1 = df.select(unix_timestamp(col("timestamp_1"),"America/Los Angeles").alias("timestamp_1"))D. df1 = df.select(unixTimestamp(col("timestamp_1"),"America/Los Angeles").alias("timestamp_1"))E. df1 = df.select(unix_timestamp(col("timestamp_1"),"MM-dd-yyyy HH:mm:ss").alias("timestamp_1"))
The correct answer is E as the appropriate syntax for unix_timestamp() is:
unix_timestamp(timestamp, format)
This functions does not include a timezone argument as it is meant to use the default one. Also, in PySpark, the correct method in order to rename a column inside a function is alias() .
If you wanted to:1. Cache a df as SERIALIZED Java objects in the JVM and; 2. If the df does not fit in memory, store the partitions that don’t fit on disk, and read them from there when they’re needed; 3. Replicate each partition on two cluster nodes.which command would you choose ?A. df.persist(StorageLevel.MEMORY_ONLY)B. df.persist(StorageLevel.MEMORY_AND_DISK_SER)C. df.cache(StorageLevel.MEMORY_AND_DISK_2_SER)D. df.cache(StorageLevel.MEMORY_AND_DISK_2_SER)E. df.persist(StorageLevel.MEMORY_AND_DISK_2_SER) --> CORRECT
The correct answer is E as the right command should be:
df.persist(StorageLevel.MEMORY_AND_DISK_2_SER)
In fact for Spark DataFrames, the cache() command always places data in memory and disk by default ( MEMORY_AND_DISK). On the contrary, the persist() method can take a StorageLevel object to specify exactly where to cache data.
Bear in mind that data is always serialized when stored on disk, whereas you need to specify if you wish to serialize data in memory (example MEMORY_AND_DISK_2_SER).
In this article I shared 10 MCQs (multiple choice questions) you should use to prepare for the Databricks Apache Spark 3.0 Developer Certification. These questions are extremely similar to the ones you are going to bump into in the real exam, hence I hope this will be a valuable study resource for you.
If you found this material useful, feel free to let me know in the comments as I would be happy to write a PART 2 including 10 more quizzes.
For the time being, I will leave you with some other articles on Medium that touch base on more general topics related to the certification.
Study guide for clearing “Databricks Certified Associate Developer for Apache Spark 3.0” exam (Python) By Shruti BhawsarGuide and Tips for Apache Spark 3.0/2.4 Databricks Certification Preparation By Anoop MalayamkumarathCrack Databricks Certified Associate Developer for Apache Spark 3.0- Preparation Tips, Info & Clarifications By Sriram Narayanan
Study guide for clearing “Databricks Certified Associate Developer for Apache Spark 3.0” exam (Python) By Shruti Bhawsar
Guide and Tips for Apache Spark 3.0/2.4 Databricks Certification Preparation By Anoop Malayamkumarath
Crack Databricks Certified Associate Developer for Apache Spark 3.0- Preparation Tips, Info & Clarifications By Sriram Narayanan
|
[
{
"code": null,
"e": 323,
"s": 172,
"text": "A note for my readers: This post includes affiliate links for which I may earn a small commission at no extra cost to you, should you make a purchase."
},
{
"code": null,
"e": 548,
"s": 323,
"text": "If you are in the process of studying for the Databricks Associate Developer for Apache Spark 3.0 certification you are probably facing the same problem I faced a few weeks ago: a lack of mock tests to assess your readiness."
},
{
"code": null,
"e": 692,
"s": 548,
"text": "By now, you should know that the exam consists of 60 MCQs and that you will be given 120 mins to answer correctly to at least 42 of them (70%)."
},
{
"code": null,
"e": 977,
"s": 692,
"text": "Another particular I suppose you have noticed is that the exam will cost you $240 (including VAT) but you will be allowed a single attempt, such that if you fail, you will have to pay again to retake it. With these premises, I guess you really wish to nail the exam at the first shot."
},
{
"code": null,
"e": 1166,
"s": 977,
"text": "But you might be wondering: “If I can’t find any examples of questions that are representative of the level of difficulty of the exam, how can I actually understand if I am ready or not?”."
},
{
"code": null,
"e": 1385,
"s": 1166,
"text": "This is the same dilemma I run into just before sitting the exam: I was not sure to be ready enough to get beyond the 70% threshold and probably I wasn’t, as I found real questions being more challenging than expected."
},
{
"code": null,
"e": 1446,
"s": 1385,
"text": "I found real questions being more challenging than expected."
},
{
"code": null,
"e": 1627,
"s": 1446,
"text": "Despite some struggles (also technical as my exam was paused by the proctor for 30 mins), I managed to clear the certification with a good mark after preparing for around 2 months."
},
{
"code": null,
"e": 1915,
"s": 1627,
"text": "There are at least a dozen of other articles on Medium on this topic (I read them all as part of my preparation) and I found 3–4 of them really insightful (links at the end of the article), but none of them included any mock multiple choice questions that helped me to test my knowledge."
},
{
"code": null,
"e": 2048,
"s": 1915,
"text": "In this article I share with you 10 MCQs for the PySpark version of the certification, that you can expect to find in the real exam."
},
{
"code": null,
"e": 2390,
"s": 2048,
"text": "For this reason, in this article, I share with you 10 MCQs for the PySpark version of the certification, that you can expect to find in the real exam. Please note that I am not allowed to disclose the exact questions, so I have rephrased them, by keeping the level of difficulty intact, so you can trust them being a valuable study resource."
},
{
"code": null,
"e": 2590,
"s": 2390,
"text": "Before jumping on the actual questions, let me give you 3 tips that you won’t probably find in other articles, but that I reckon could make a huge difference in terms of the final mark you could get."
},
{
"code": null,
"e": 2601,
"s": 2590,
"text": "medium.com"
},
{
"code": null,
"e": 2624,
"s": 2601,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2882,
"s": 2624,
"text": "No, I won’t suggest you peruse Spark - The Definitive Guide or the 2d Edition of Learning Spark as...you already know about them...right? What I am going to give you are 3 tips that will disproportionally increase your chance to succeed - so read carefully!"
},
{
"code": null,
"e": 3116,
"s": 2882,
"text": "This is probably the best suggestion I can give you to excel. In effect, during the exam, you will be allowed to refer to the pyspark.sql documentation on your right screen, but you won’t be able to use CTRL+F to search for keywords."
},
{
"code": null,
"e": 3380,
"s": 3116,
"text": "This means that unless you know where to find specific methods or specific functions, you could waste a lot of time scrolling back and forth and - trust me- this will make you nervous. Instead, I suggest you to focus on the content of the following three classes:"
},
{
"code": null,
"e": 3483,
"s": 3380,
"text": "pyspark.sql.DataFrame: for instance, you should be able to locate the coalesce() and join() functions."
},
{
"code": null,
"e": 3643,
"s": 3483,
"text": "pyspark.sq.Column: for instance, you should know that when() , between() and otherwise are applied to columns of a DataFrame and not directly to the DataFrame."
},
{
"code": null,
"e": 3888,
"s": 3643,
"text": "pyspark.sql.functions: for instance, you should know that functions used to manipulate time fields like date_add() , date_sun() and from_unixtime() (yes I got a question on this function! Nowhere to be found in the books...) are described here."
},
{
"code": null,
"e": 4085,
"s": 3888,
"text": "I approached and studied the structure of the documentation only 2 days before the test, but I wish I did it much earlier as this knowledge helped me to answer correctly to at least 7–8 questions."
},
{
"code": null,
"e": 4283,
"s": 4085,
"text": "Hence, what I am trying to convey here is not to overestimate your knowledge on the PySpark syntax as your memory could betray you during the exam. Take full advantage of the documentation instead."
},
{
"code": null,
"e": 4450,
"s": 4283,
"text": "It turns out that actually 2 full mock tests for Python/Pyspark are available on Udemy and include 120 practice exam quiz for the Apache Spark 3.0 certification exam!"
},
{
"code": null,
"e": 4619,
"s": 4450,
"text": "I purchased access to the tests 2 months before the exam, as I wanted to study the material based on real questions and review the topics for which I got wrong answers."
},
{
"code": null,
"e": 4740,
"s": 4619,
"text": "Like in the real exam, you have 2 hours to complete the test and the weight of each topic is also respected, that means:"
},
{
"code": null,
"e": 4780,
"s": 4740,
"text": "Spark DataFrame API Applications (~72%)"
},
{
"code": null,
"e": 4832,
"s": 4780,
"text": "Spark Architecture: Conceptual understanding (~17%)"
},
{
"code": null,
"e": 4881,
"s": 4832,
"text": "Spark Architecture: Applied understanding (~11%)"
},
{
"code": null,
"e": 5126,
"s": 4881,
"text": "In my case, at least 12–15 questions in the actual exam were very similar to questions I practiced in these tests (both in terms of phrasing and solutions), so I reckon it is an excellent investment while you are studying for the certification."
},
{
"code": null,
"e": 5394,
"s": 5126,
"text": "With hindsight, one thing I could have done better while preparing, was to experiment running many more functions and methods belonging to the Spark DataFrame API and carefully review their syntax in detail, instead of just focusing on the code snippets on the books."
},
{
"code": null,
"e": 5636,
"s": 5394,
"text": "Think about that: you will find at least 40–43 questions around the Spark DataFrame API, therefore it is fair to expect that a large variety of concepts will be tested (even concepts that you won’t find mentioned in the books — life sucks!)."
},
{
"code": null,
"e": 5944,
"s": 5636,
"text": "Also, bear in mind that a good 30% of these 40–43 questions are going to be particularly tricky, with at least two very similar options, so that you will need to be extremely sure about the syntax. But remember: worst-case scenario you can always consult the documentation (that brings us back to point #1)."
},
{
"code": null,
"e": 5976,
"s": 5944,
"text": "Now it’s time for some quizzes!"
},
{
"code": null,
"e": 5999,
"s": 5976,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6155,
"s": 5999,
"text": "Given a dataframe df, select the code that returns its number of rows:A. df.take('all') B. df.collect()C. df.show()D. df.count() --> CORRECTE. df.numRows()"
},
{
"code": null,
"e": 6374,
"s": 6155,
"text": "The correct answer is D as df.count() actually returns the number of rows in a DataFrame as you can see in the documentation. This was a warm-up questions, but don’t forget about it as you could find something similar."
},
{
"code": null,
"e": 6926,
"s": 6374,
"text": "Given a DataFrame df that includes a number of columns among which a column named quantity and a column named price, complete the code below such that it will create a DataFrame including all the original columns and a new column revenue defined as quantity*price:df._1_(_2_ , _3_)A. withColumnRenamed, \"revenue\", expr(\"quantity*price\")B. withColumn, revenue, expr(\"quantity*price\")C. withColumn, \"revenue\", expr(\"quantity*price\") --> CORRECTD. withColumn, expr(\"quantity*price\"), \"revenue\"E. withColumnRenamed, \"revenue\", col(\"quantity\")*col(\"price\")"
},
{
"code": null,
"e": 6973,
"s": 6926,
"text": "The correct answer is C as the code should be:"
},
{
"code": null,
"e": 7022,
"s": 6973,
"text": "df.withColumn(\"revenue\", expr(\"quantity*price\"))"
},
{
"code": null,
"e": 7204,
"s": 7022,
"text": "You will be asked at least 2–3 questions that involve adding a new column to a DF or renaming an existing one, so learn the syntax of withColumn() and withColumnRenamed() very well."
},
{
"code": null,
"e": 7654,
"s": 7204,
"text": "# Given a DataFrame df that has some null values in the column created_date, complete the code below such that it will sort rows in ascending order based on the column creted_date with null values appearing last.df._1_(_2_)A. orderBy, asc_nulls_last(\"created_date\")B. sort, asc_nulls_last(\"created_date\")C. orderBy, col(\"created_date\").asc_nulls_last() --> CORRECTD. orderBy, col(\"created_date\"), ascending=True)E. orderBy, col(\"created_date\").asc()"
},
{
"code": null,
"e": 7701,
"s": 7654,
"text": "The correct answer is C as the code should be:"
},
{
"code": null,
"e": 7749,
"s": 7701,
"text": "df.orderBy(col(\"created_date\").asc_null_last())"
},
{
"code": null,
"e": 7814,
"s": 7749,
"text": "but also df.orderBy(df.created_date.asc_null_last()) would work."
},
{
"code": null,
"e": 8036,
"s": 7814,
"text": "In effect, like for asc() in answer E, asc_null_last() does not take any argument, but is applied to column to return a sort expression based on ascending order of the column, and null values appear after non-null values."
},
{
"code": null,
"e": 8192,
"s": 8036,
"text": "Which one of the following commands does NOT trigger an eager evaluation?A. df.collect()B. df.take()C. df.show()D. df.saveAsTable()E. df.join() --> CORRECT"
},
{
"code": null,
"e": 8395,
"s": 8192,
"text": "The correct answer is E as in Apache Spark all transformations are evaluated lazily and all the actions are evaluated eagerly. In this case, the only command that will be evaluated lazily is df.join() ."
},
{
"code": null,
"e": 8494,
"s": 8395,
"text": "Below you find some additional transformations and actions that often appear in similar questions:"
},
{
"code": null,
"e": 8781,
"s": 8494,
"text": "Transformations ActionsorderBy() show()groupBy() take()filter() count()select() collect()join() save()limit() foreach()map(), flatMap() first()sort() count(), countByValue()printSchema() reduce() cache()"
},
{
"code": null,
"e": 9529,
"s": 8781,
"text": "Which of the following statements are NOT true for broadcast variables ?A. Broadcast variables are shared, immutable variables that are cached on every machine in the cluster instead of being serialized with every single task.B. A custom broadcast class can be defined by extending org.apache.spark.utilbroadcastV2 in Java or Scala or pyspark.Accumulatorparams in Python. --> CORRECTC. It is a way of updating a value inside a variety of transformations and propagating that value to the driver node in an efficient and fault-tolerant way.--> CORRECTD. It provides a mutable variable that Spark cluster can safely update on a per-row basis. --> CORRECTE. The canonical use case is to pass around a small table that does fit in memory on executors."
},
{
"code": null,
"e": 9664,
"s": 9529,
"text": "The correct options are B, C and D as these are characteristics of accumulators (the alternative type of distributed shared variable)."
},
{
"code": null,
"e": 9971,
"s": 9664,
"text": "For the exam remember that broadcast variables are immutable and lazily replicated across all nodes in the cluster when an action is triggered. Broadcast variables are efficient at scale, as they avoid the cost of serializing data for every task. They can be used in the context of RDDs or Structured APIs."
},
{
"code": null,
"e": 10360,
"s": 9971,
"text": "The code below should return a new DataFrame with 50 percent of random records from DataFrame df without replacement. Choose the response that correctly fills in the numbered blanks within the code block to complete this task.df._1_(_2_,_3_,_4_)A. sample, False, 0.5, 5 --> CORRECTB. random, False, 0.5, 5C. sample, False, 5, 25D. sample, False, 50, 5E. sample, withoutReplacement, 0.5, 5"
},
{
"code": null,
"e": 10480,
"s": 10360,
"text": "The correct answer is A as the code block should bedf.sample(False, 0.5, 5) in fact the correct syntax for sample() is:"
},
{
"code": null,
"e": 10523,
"s": 10480,
"text": "df.sample(withReplacement, fraction, seed)"
},
{
"code": null,
"e": 10663,
"s": 10523,
"text": "In this case the seed is a random number and not really relevant for the answer. You should just remember that it is the last in the order."
},
{
"code": null,
"e": 10880,
"s": 10663,
"text": "Which of the following DataFrame commands will NOT generate a shuffle of data from each executor across the cluster?A. df.map() --> CORRECTB. df.collect()C. df.orderBy()D. df.repartition()E. df.distinct()F. df.join()"
},
{
"code": null,
"e": 10960,
"s": 10880,
"text": "The correct answer is A as map() is the only narrow transformation in the list."
},
{
"code": null,
"e": 11390,
"s": 10960,
"text": "In particular, transformations can be classified as having either narrow dependencies or wide dependencies. Any transformation where a single output partition can be computed from a single input partition is a narrow transformation. For example, filter(), contains() and map() represent narrow transformations because they can operate on a single partition and produce the resulting output partition without any exchange of data."
},
{
"code": null,
"e": 11506,
"s": 11390,
"text": "Below you find a list including a number of narrow and wide transformations, useful to revise just before the exam:"
},
{
"code": null,
"e": 11860,
"s": 11506,
"text": "WIDE TRANSORM NARROW TRANSFORMorderBy() filter()repartition() contains()distinct() map()collect() flatMap()cartesian() MapPartition()intersection() sample()reduceByKey() union()groupByKey() coalesce() --> when numPartitions is reducedgroupBy() drop()join() cache()"
},
{
"code": null,
"e": 12287,
"s": 11860,
"text": "When Spark runs in Cluster Mode, which of the following statements about nodes is correct ?A. There is one single worker node that contains the Spark driver and all the executors.B. The Spark Driver runs in a worker node inside the cluster. --> CORRECTC. There is always more than one worker node.D. There are less executors than total number of worker nodes.E. Each executor is a running JVM inside of a cluster manager node."
},
{
"code": null,
"e": 12656,
"s": 12287,
"text": "The correct answer is B as in Cluster Mode, the cluster manager launches the driver process on a worker node inside the cluster, in addition to the executor processes. This means that the cluster manager is responsible for maintaining all Spark worker nodes. Therefore, the cluster manager places the driver on a worker node and the executors on separate worker nodes."
},
{
"code": null,
"e": 13361,
"s": 12656,
"text": "The DataFrame df includes a time string column named timestamp_1. Which is the correct syntax that creates a new DataFrame df1 that is just made by the time string field converted to a unix timestamp?A. df1 = df.select(unix_timestamp(col(\"timestamp_1\"),\"MM-dd-yyyy HH:mm:ss\").as(\"timestamp_1\"))B. df1 = df.select(unix_timestamp(col(\"timestamp_1\"),\"MM-dd-yyyy HH:mm:ss\", \"America/Los Angeles\").alias(\"timestamp_1\"))C. df1 = df.select(unix_timestamp(col(\"timestamp_1\"),\"America/Los Angeles\").alias(\"timestamp_1\"))D. df1 = df.select(unixTimestamp(col(\"timestamp_1\"),\"America/Los Angeles\").alias(\"timestamp_1\"))E. df1 = df.select(unix_timestamp(col(\"timestamp_1\"),\"MM-dd-yyyy HH:mm:ss\").alias(\"timestamp_1\"))"
},
{
"code": null,
"e": 13436,
"s": 13361,
"text": "The correct answer is E as the appropriate syntax for unix_timestamp() is:"
},
{
"code": null,
"e": 13470,
"s": 13436,
"text": "unix_timestamp(timestamp, format)"
},
{
"code": null,
"e": 13657,
"s": 13470,
"text": "This functions does not include a timezone argument as it is meant to use the default one. Also, in PySpark, the correct method in order to rename a column inside a function is alias() ."
},
{
"code": null,
"e": 14182,
"s": 13657,
"text": "If you wanted to:1. Cache a df as SERIALIZED Java objects in the JVM and; 2. If the df does not fit in memory, store the partitions that don’t fit on disk, and read them from there when they’re needed; 3. Replicate each partition on two cluster nodes.which command would you choose ?A. df.persist(StorageLevel.MEMORY_ONLY)B. df.persist(StorageLevel.MEMORY_AND_DISK_SER)C. df.cache(StorageLevel.MEMORY_AND_DISK_2_SER)D. df.cache(StorageLevel.MEMORY_AND_DISK_2_SER)E. df.persist(StorageLevel.MEMORY_AND_DISK_2_SER) --> CORRECT"
},
{
"code": null,
"e": 14238,
"s": 14182,
"text": "The correct answer is E as the right command should be:"
},
{
"code": null,
"e": 14285,
"s": 14238,
"text": "df.persist(StorageLevel.MEMORY_AND_DISK_2_SER)"
},
{
"code": null,
"e": 14513,
"s": 14285,
"text": "In fact for Spark DataFrames, the cache() command always places data in memory and disk by default ( MEMORY_AND_DISK). On the contrary, the persist() method can take a StorageLevel object to specify exactly where to cache data."
},
{
"code": null,
"e": 14679,
"s": 14513,
"text": "Bear in mind that data is always serialized when stored on disk, whereas you need to specify if you wish to serialize data in memory (example MEMORY_AND_DISK_2_SER)."
},
{
"code": null,
"e": 14983,
"s": 14679,
"text": "In this article I shared 10 MCQs (multiple choice questions) you should use to prepare for the Databricks Apache Spark 3.0 Developer Certification. These questions are extremely similar to the ones you are going to bump into in the real exam, hence I hope this will be a valuable study resource for you."
},
{
"code": null,
"e": 15124,
"s": 14983,
"text": "If you found this material useful, feel free to let me know in the comments as I would be happy to write a PART 2 including 10 more quizzes."
},
{
"code": null,
"e": 15265,
"s": 15124,
"text": "For the time being, I will leave you with some other articles on Medium that touch base on more general topics related to the certification."
},
{
"code": null,
"e": 15615,
"s": 15265,
"text": "Study guide for clearing “Databricks Certified Associate Developer for Apache Spark 3.0” exam (Python) By Shruti BhawsarGuide and Tips for Apache Spark 3.0/2.4 Databricks Certification Preparation By Anoop MalayamkumarathCrack Databricks Certified Associate Developer for Apache Spark 3.0- Preparation Tips, Info & Clarifications By Sriram Narayanan"
},
{
"code": null,
"e": 15736,
"s": 15615,
"text": "Study guide for clearing “Databricks Certified Associate Developer for Apache Spark 3.0” exam (Python) By Shruti Bhawsar"
},
{
"code": null,
"e": 15838,
"s": 15736,
"text": "Guide and Tips for Apache Spark 3.0/2.4 Databricks Certification Preparation By Anoop Malayamkumarath"
}
] |
Entity Framework - Native SQL
|
In Entity Framework you can query with your entity classes using LINQ. You can also run queries using raw SQL directly against the database using DbCOntext. The techniques can be applied equally to models created with Code First and EF Designer.
The SqlQuery method on DbSet allows a raw SQL query to be written that will return entity instances. The returned objects will be tracked by the context just as they would be if they were returned by a LINQ query. For example −
class Program {
static void Main(string[] args) {
using (var context = new UniContextEntities()) {
var students = context.Students.SqlQuery("SELECT * FROM dbo.Student").ToList();
foreach (var student in students) {
string name = student.FirstMidName + " " + student.LastName;
Console.WriteLine("ID: {0}, Name: {1}, \tEnrollment Date {2} ",
student.ID, name, student.EnrollmentDate.ToString());
}
Console.ReadKey();
}
}
}
The above code will retrieve all the students from the database.
A SQL query returning instances of any type, including primitive types, can be created using the SqlQuery method on the Database class. For example −
class Program {
static void Main(string[] args) {
using (var context = new UniContextEntities()) {
var studentNames = context.Database.SqlQuery
<string>("SELECT FirstMidName FROM dbo.Student").ToList();
foreach (var student in studentNames) {
Console.WriteLine("Name: {0}", student);
}
Console.ReadKey();
}
}
}
ExecuteSqlCommnad method is used in sending non-query commands to the database, such as the Insert, Update or Delete command. Let’s take a look at the following code in which student’s first name is updated as ID = 1
class Program {
static void Main(string[] args) {
using (var context = new UniContextEntities()) {
//Update command
int noOfRowUpdated = context.Database.ExecuteSqlCommand("Update
student set FirstMidName = 'Ali' where ID = 1");
context.SaveChanges();
var student = context.Students.SqlQuery("SELECT * FROM
dbo.Student where ID = 1").Single();
string name = student.FirstMidName + " " + student.LastName;
Console.WriteLine("ID: {0}, Name: {1}, \tEnrollment Date {2} ",
student.ID, name, student.EnrollmentDate.ToString());
Console.ReadKey();
}
}
}
The above code will retrieve all the students’ first name from the database.
19 Lectures
5 hours
Trevoir Williams
33 Lectures
3.5 hours
Nilay Mehta
21 Lectures
2.5 hours
TELCOMA Global
89 Lectures
7.5 hours
Mustafa Radaideh
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3278,
"s": 3032,
"text": "In Entity Framework you can query with your entity classes using LINQ. You can also run queries using raw SQL directly against the database using DbCOntext. The techniques can be applied equally to models created with Code First and EF Designer."
},
{
"code": null,
"e": 3506,
"s": 3278,
"text": "The SqlQuery method on DbSet allows a raw SQL query to be written that will return entity instances. The returned objects will be tracked by the context just as they would be if they were returned by a LINQ query. For example −"
},
{
"code": null,
"e": 4025,
"s": 3506,
"text": "class Program {\n\n static void Main(string[] args) {\n\n using (var context = new UniContextEntities()) {\n\n var students = context.Students.SqlQuery(\"SELECT * FROM dbo.Student\").ToList();\n\n foreach (var student in students) {\n string name = student.FirstMidName + \" \" + student.LastName;\n Console.WriteLine(\"ID: {0}, Name: {1}, \\tEnrollment Date {2} \",\n student.ID, name, student.EnrollmentDate.ToString());\n }\n\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 4090,
"s": 4025,
"text": "The above code will retrieve all the students from the database."
},
{
"code": null,
"e": 4240,
"s": 4090,
"text": "A SQL query returning instances of any type, including primitive types, can be created using the SqlQuery method on the Database class. For example −"
},
{
"code": null,
"e": 4634,
"s": 4240,
"text": "class Program {\n\n static void Main(string[] args) {\n\n using (var context = new UniContextEntities()) {\n\n var studentNames = context.Database.SqlQuery\n <string>(\"SELECT FirstMidName FROM dbo.Student\").ToList();\n\n foreach (var student in studentNames) {\n Console.WriteLine(\"Name: {0}\", student);\n }\n\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 4851,
"s": 4634,
"text": "ExecuteSqlCommnad method is used in sending non-query commands to the database, such as the Insert, Update or Delete command. Let’s take a look at the following code in which student’s first name is updated as ID = 1"
},
{
"code": null,
"e": 5527,
"s": 4851,
"text": "class Program {\n\n static void Main(string[] args) {\n\n using (var context = new UniContextEntities()) {\n\n //Update command\n\n int noOfRowUpdated = context.Database.ExecuteSqlCommand(\"Update \n student set FirstMidName = 'Ali' where ID = 1\");\n\n context.SaveChanges();\n\n var student = context.Students.SqlQuery(\"SELECT * FROM\n dbo.Student where ID = 1\").Single();\n\n string name = student.FirstMidName + \" \" + student.LastName;\n\n Console.WriteLine(\"ID: {0}, Name: {1}, \\tEnrollment Date {2} \", \n student.ID, name, student.EnrollmentDate.ToString());\n\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 5604,
"s": 5527,
"text": "The above code will retrieve all the students’ first name from the database."
},
{
"code": null,
"e": 5637,
"s": 5604,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5655,
"s": 5637,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 5690,
"s": 5655,
"text": "\n 33 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5703,
"s": 5690,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 5738,
"s": 5703,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5754,
"s": 5738,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 5789,
"s": 5754,
"text": "\n 89 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5807,
"s": 5789,
"text": " Mustafa Radaideh"
},
{
"code": null,
"e": 5814,
"s": 5807,
"text": " Print"
},
{
"code": null,
"e": 5825,
"s": 5814,
"text": " Add Notes"
}
] |
The ResultSet updateRow() method with example
|
When we execute certain SQL queries (SELECT query in general) they return tabular data.
The java.sql.ResultSet interface represents such tabular data returned by the SQL statements.
i.e. the ResultSet object holds the tabular data returned by the methods that execute the statements which quires the database (executeQuery() method of the Statement interface in general).
The ResultSet object has a cursor/pointer which points to the current row. Initially this cursor is positioned before first row.
The updateRow() method of the ResultSet interface updates the contents of the current row to the database. For example if we have updated the values of a particular record using the updateXXX() methods of the ResultSet interface (updateNClob(), updateNCharacterStream(), updateString(), updateInt(), updateNString(), updateBinaryStream())
You need to invoke this method to reflect the changes you have made to the row in the database.
Note: To update the contents of a ResultSet using the updateRow() method. The ResultSet should be of type CONCUR_UPDATABLE and, the table should contain a primary key constraint.
Let us create a table with name customers in MySQL database using CREATE statement as shown below:
CREATE TABLE customers (
ID INT,
Name VARCHAR(20),
AGE INT,
SALARY INT,
ADDERSS VARCHAR(255),
PRIMARY KEY (ID)
);
Now, we will insert 12 records in customers table using INSERT statements -
insert into customers values(1, 'Amit', 25, 3000, 'Hyderabad');
insert into customers values(2, 'Kalyan', 27, 4000, 'Vishakhapatnam');
insert into customers values(3, 'Renuka', 30, 5000, 'Delhi');
insert into customers values(4, 'Archana', 24, 1500, 'Mumbai');
insert into customers values(5, 'Kaushik', 30, 9000, 'Kota');
insert into customers values(6, 'Hardik', 45, 6400, 'Bhopal');
insert into customers values(7, 'Trupthi', 33, 4360, 'Ahmedabad');
insert into customers values(8, 'Mithili', 26, 4100, 'Vijayawada');
insert into customers values(9, 'Maneesh', 39, 4000, 'Hyderabad');
insert into customers values(10, 'Rajaneesh', 30, 6400, 'Delhi');
insert into customers values(11, 'Komal', 29, 8000, 'Ahmedabad');
insert into customers values(12, 'Manyata', 25, 5000, 'Vijayawada');
Following JDBC program establishes connection with the database, retrieves the contents of the customers table into a ResultSet object, updates the contents of the row with id value 5 using the updateXXX() methods and updates the entire row to the database using the updateRow() method.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ResultSet_updateRow {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating the Statement
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
//Query to retrieve records
String query = "Select * from Customers";
//Executing the query
ResultSet rs = stmt.executeQuery(query);
//Updating the contents of the record with id value 5
while(rs.next()) {
if(rs.getInt("ID")==5) {
//Updating the salary
rs.updateInt("Salary", 11000);
//Updating the address
rs.updateString("ADDRESS","Narsipatnam");
//Updating the row
rs.updateRow();
}
}
rs.beforeFirst();
System.out.println("Contents of the Customers table after the update: ");
//Printing the contents of the table
while(rs.next()) {
System.out.print("ID: "+rs.getInt("ID")+", ");
System.out.print("Name: "+rs.getString("Name")+", ");
System.out.print("Age: "+rs.getInt("Age")+", ");
System.out.print("Salary: "+rs.getInt("Salary")+", ");
System.out.print("Address: "+rs.getString("Address"));
System.out.println();
}
}
}
Connection established......
Contents of the table Customers:
ID: 1, Name: Amit, Age: 25, Salary: 3000, Address: Hyderabad
ID: 2, Name: Kalyan, Age: 27, Salary: 4000, Address: Vishakhapatnam
ID: 3, Name: Renuka, Age: 30, Salary: 5000, Address: Delhi
ID: 4, Name: Archana, Age: 24, Salary: 1500, Address: Mumbai
ID: 5, Name: Koushik, Age: 30, Salary: 11000, Address: Narsipatnam
ID: 6, Name: Hardik, Age: 45, Salary: 6400, Address: Bhopal
ID: 7, Name: Trupthi, Age: 33, Salary: 4360, Address: Ahmedabad
ID: 8, Name: Mithili, Age: 26, Salary: 4100, Address: Vijayawada
ID: 9, Name: Maneesh, Age: 39, Salary: 4000, Address: Hyderabad
ID: 10, Name: Rajaneesh, Age: 30, Salary: 6400, Address: Delhi
ID: 11, Name: Komal, Age: 29, Salary: 8000, Address: Ahmedabad
ID: 12, Name: Manyata, Age: 25, Salary: 5000, Address: Vijayawada
|
[
{
"code": null,
"e": 1150,
"s": 1062,
"text": "When we execute certain SQL queries (SELECT query in general) they return tabular data."
},
{
"code": null,
"e": 1244,
"s": 1150,
"text": "The java.sql.ResultSet interface represents such tabular data returned by the SQL statements."
},
{
"code": null,
"e": 1434,
"s": 1244,
"text": "i.e. the ResultSet object holds the tabular data returned by the methods that execute the statements which quires the database (executeQuery() method of the Statement interface in general)."
},
{
"code": null,
"e": 1563,
"s": 1434,
"text": "The ResultSet object has a cursor/pointer which points to the current row. Initially this cursor is positioned before first row."
},
{
"code": null,
"e": 1902,
"s": 1563,
"text": "The updateRow() method of the ResultSet interface updates the contents of the current row to the database. For example if we have updated the values of a particular record using the updateXXX() methods of the ResultSet interface (updateNClob(), updateNCharacterStream(), updateString(), updateInt(), updateNString(), updateBinaryStream())"
},
{
"code": null,
"e": 1998,
"s": 1902,
"text": "You need to invoke this method to reflect the changes you have made to the row in the database."
},
{
"code": null,
"e": 2177,
"s": 1998,
"text": "Note: To update the contents of a ResultSet using the updateRow() method. The ResultSet should be of type CONCUR_UPDATABLE and, the table should contain a primary key constraint."
},
{
"code": null,
"e": 2277,
"s": 2177,
"text": "Let us create a table with name customers in MySQL database using CREATE statement as shown below: "
},
{
"code": null,
"e": 2409,
"s": 2277,
"text": "CREATE TABLE customers (\n ID INT,\n Name VARCHAR(20),\n AGE INT,\n SALARY INT,\n ADDERSS VARCHAR(255),\n PRIMARY KEY (ID)\n);"
},
{
"code": null,
"e": 2485,
"s": 2409,
"text": "Now, we will insert 12 records in customers table using INSERT statements -"
},
{
"code": null,
"e": 3274,
"s": 2485,
"text": "insert into customers values(1, 'Amit', 25, 3000, 'Hyderabad');\ninsert into customers values(2, 'Kalyan', 27, 4000, 'Vishakhapatnam');\ninsert into customers values(3, 'Renuka', 30, 5000, 'Delhi');\ninsert into customers values(4, 'Archana', 24, 1500, 'Mumbai');\ninsert into customers values(5, 'Kaushik', 30, 9000, 'Kota');\ninsert into customers values(6, 'Hardik', 45, 6400, 'Bhopal');\ninsert into customers values(7, 'Trupthi', 33, 4360, 'Ahmedabad');\ninsert into customers values(8, 'Mithili', 26, 4100, 'Vijayawada');\ninsert into customers values(9, 'Maneesh', 39, 4000, 'Hyderabad');\ninsert into customers values(10, 'Rajaneesh', 30, 6400, 'Delhi');\ninsert into customers values(11, 'Komal', 29, 8000, 'Ahmedabad');\ninsert into customers values(12, 'Manyata', 25, 5000, 'Vijayawada');"
},
{
"code": null,
"e": 3561,
"s": 3274,
"text": "Following JDBC program establishes connection with the database, retrieves the contents of the customers table into a ResultSet object, updates the contents of the row with id value 5 using the updateXXX() methods and updates the entire row to the database using the updateRow() method."
},
{
"code": null,
"e": 5312,
"s": 3561,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class ResultSet_updateRow {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating the Statement\n Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);\n //Query to retrieve records\n String query = \"Select * from Customers\";\n //Executing the query\n ResultSet rs = stmt.executeQuery(query);\n //Updating the contents of the record with id value 5\n while(rs.next()) {\n if(rs.getInt(\"ID\")==5) {\n //Updating the salary\n rs.updateInt(\"Salary\", 11000);\n //Updating the address\n rs.updateString(\"ADDRESS\",\"Narsipatnam\");\n //Updating the row\n rs.updateRow();\n }\n }\n rs.beforeFirst();\n System.out.println(\"Contents of the Customers table after the update: \");\n //Printing the contents of the table\n while(rs.next()) {\n System.out.print(\"ID: \"+rs.getInt(\"ID\")+\", \");\n System.out.print(\"Name: \"+rs.getString(\"Name\")+\", \");\n System.out.print(\"Age: \"+rs.getInt(\"Age\")+\", \");\n System.out.print(\"Salary: \"+rs.getInt(\"Salary\")+\", \");\n System.out.print(\"Address: \"+rs.getString(\"Address\"));\n System.out.println();\n }\n }\n}"
},
{
"code": null,
"e": 6135,
"s": 5312,
"text": "Connection established......\nContents of the table Customers:\nID: 1, Name: Amit, Age: 25, Salary: 3000, Address: Hyderabad\nID: 2, Name: Kalyan, Age: 27, Salary: 4000, Address: Vishakhapatnam\nID: 3, Name: Renuka, Age: 30, Salary: 5000, Address: Delhi\nID: 4, Name: Archana, Age: 24, Salary: 1500, Address: Mumbai\nID: 5, Name: Koushik, Age: 30, Salary: 11000, Address: Narsipatnam\nID: 6, Name: Hardik, Age: 45, Salary: 6400, Address: Bhopal\nID: 7, Name: Trupthi, Age: 33, Salary: 4360, Address: Ahmedabad\nID: 8, Name: Mithili, Age: 26, Salary: 4100, Address: Vijayawada\nID: 9, Name: Maneesh, Age: 39, Salary: 4000, Address: Hyderabad\nID: 10, Name: Rajaneesh, Age: 30, Salary: 6400, Address: Delhi\nID: 11, Name: Komal, Age: 29, Salary: 8000, Address: Ahmedabad\nID: 12, Name: Manyata, Age: 25, Salary: 5000, Address: Vijayawada"
}
] |
N-th number which is both a square and a cube - GeeksforGeeks
|
31 Mar, 2021
Given a number n, find the n-th number which is both a square and a cube. First few such numbers are 1, 64, 729, ...
Examples :
Input : 3
Output :729
729 is square of 27 and cube of 3.
Input :5
Output :15625
The idea is simple, n-th such number is n6
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find n-th number which is both// square and cube.#include <bits/stdc++.h>using namespace std; int nthSquareCube(int n){ return n*n*n*n*n*n;} // Driver codeint main(){ int n = 5; cout << nthSquareCube(n); return 0;}
// Java program to find n-th number// which is both square and cube.class GFG { static int nthSquareCube(int n) { return n * n * n * n * n * n; } // Driver code public static void main(String[] args) { int n = 5; System.out.println(nthSquareCube(n)); }} // This code is contributed by// Smitha Dinesh Semwal
# program to find n-th number# which is both square and cube. def nthSquareCube(n): return n * n * n * n * n * n # Driver coden = 5print(nthSquareCube(n))# This code is contributed by# Smitha Dinesh Semwal
// C# program to find n-th number// which is both square and cube.using System; class GFG{ static int nthSquareCube(int n) { return n * n * n * n * n * n; } // Driver code static public void Main () { int n = 5; Console.WriteLine(nthSquareCube(n)); }} // This code is contributed by Ajit.
<?php// PHP program to find n-th// number which is both// square and cube. function nthSquareCube($n){ return $n * $n * $n * $n * $n * $n;} // Driver code$n = 5;echo(nthSquareCube($n)); // This code is contributed by Ajit.?>
<script> // JavaScript program to find n-th number// which is bothsquare and cube.function nthSquareCube(n){ return n * n * n * n * n * n;} // Driver codelet n = 5; document.write(nthSquareCube(n)); // This code is contributed by Surbhi Tyagi. </script>
15625
Smitha Dinesh Semwal
jit_t
surbhityagi15
maths-cube
series
Mathematical
School Programming
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Program to find GCD or HCF of two numbers
Prime Numbers
Modulo Operator (%) in C/C++ with Examples
Sieve of Eratosthenes
Python Dictionary
Arrays in C/C++
Reverse a string in Java
Inheritance in C++
C++ Classes and Objects
|
[
{
"code": null,
"e": 24854,
"s": 24826,
"text": "\n31 Mar, 2021"
},
{
"code": null,
"e": 24971,
"s": 24854,
"text": "Given a number n, find the n-th number which is both a square and a cube. First few such numbers are 1, 64, 729, ..."
},
{
"code": null,
"e": 24983,
"s": 24971,
"text": "Examples : "
},
{
"code": null,
"e": 25071,
"s": 24983,
"text": "Input : 3\nOutput :729\n 729 is square of 27 and cube of 3.\nInput :5\nOutput :15625"
},
{
"code": null,
"e": 25116,
"s": 25071,
"text": "The idea is simple, n-th such number is n6 "
},
{
"code": null,
"e": 25120,
"s": 25116,
"text": "C++"
},
{
"code": null,
"e": 25125,
"s": 25120,
"text": "Java"
},
{
"code": null,
"e": 25133,
"s": 25125,
"text": "Python3"
},
{
"code": null,
"e": 25136,
"s": 25133,
"text": "C#"
},
{
"code": null,
"e": 25140,
"s": 25136,
"text": "PHP"
},
{
"code": null,
"e": 25151,
"s": 25140,
"text": "Javascript"
},
{
"code": "// C++ program to find n-th number which is both// square and cube.#include <bits/stdc++.h>using namespace std; int nthSquareCube(int n){ return n*n*n*n*n*n;} // Driver codeint main(){ int n = 5; cout << nthSquareCube(n); return 0;}",
"e": 25395,
"s": 25151,
"text": null
},
{
"code": "// Java program to find n-th number// which is both square and cube.class GFG { static int nthSquareCube(int n) { return n * n * n * n * n * n; } // Driver code public static void main(String[] args) { int n = 5; System.out.println(nthSquareCube(n)); }} // This code is contributed by// Smitha Dinesh Semwal",
"e": 25764,
"s": 25395,
"text": null
},
{
"code": "# program to find n-th number# which is both square and cube. def nthSquareCube(n): return n * n * n * n * n * n # Driver coden = 5print(nthSquareCube(n))# This code is contributed by# Smitha Dinesh Semwal",
"e": 25975,
"s": 25764,
"text": null
},
{
"code": "// C# program to find n-th number// which is both square and cube.using System; class GFG{ static int nthSquareCube(int n) { return n * n * n * n * n * n; } // Driver code static public void Main () { int n = 5; Console.WriteLine(nthSquareCube(n)); }} // This code is contributed by Ajit.",
"e": 26325,
"s": 25975,
"text": null
},
{
"code": "<?php// PHP program to find n-th// number which is both// square and cube. function nthSquareCube($n){ return $n * $n * $n * $n * $n * $n;} // Driver code$n = 5;echo(nthSquareCube($n)); // This code is contributed by Ajit.?>",
"e": 26563,
"s": 26325,
"text": null
},
{
"code": "<script> // JavaScript program to find n-th number// which is bothsquare and cube.function nthSquareCube(n){ return n * n * n * n * n * n;} // Driver codelet n = 5; document.write(nthSquareCube(n)); // This code is contributed by Surbhi Tyagi. </script>",
"e": 26820,
"s": 26563,
"text": null
},
{
"code": null,
"e": 26826,
"s": 26820,
"text": "15625"
},
{
"code": null,
"e": 26849,
"s": 26828,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 26855,
"s": 26849,
"text": "jit_t"
},
{
"code": null,
"e": 26869,
"s": 26855,
"text": "surbhityagi15"
},
{
"code": null,
"e": 26880,
"s": 26869,
"text": "maths-cube"
},
{
"code": null,
"e": 26887,
"s": 26880,
"text": "series"
},
{
"code": null,
"e": 26900,
"s": 26887,
"text": "Mathematical"
},
{
"code": null,
"e": 26919,
"s": 26900,
"text": "School Programming"
},
{
"code": null,
"e": 26932,
"s": 26919,
"text": "Mathematical"
},
{
"code": null,
"e": 26939,
"s": 26932,
"text": "series"
},
{
"code": null,
"e": 27037,
"s": 26939,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27046,
"s": 27037,
"text": "Comments"
},
{
"code": null,
"e": 27059,
"s": 27046,
"text": "Old Comments"
},
{
"code": null,
"e": 27083,
"s": 27059,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 27125,
"s": 27083,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 27139,
"s": 27125,
"text": "Prime Numbers"
},
{
"code": null,
"e": 27182,
"s": 27139,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 27204,
"s": 27182,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 27222,
"s": 27204,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27238,
"s": 27222,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 27263,
"s": 27238,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 27282,
"s": 27263,
"text": "Inheritance in C++"
}
] |
Python - Plot a Pie Chart for Pandas Dataframe with Matplotlib?
|
To plot a Pie Chart, use the plot.pie(). The pie plot is a proportional representation of the numerical data in a column.
Import the required libraries −
import pandas as pd
import matplotlib.pyplot as plt
Create a DataFrame −
dataFrame = pd.DataFrame({
"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000]
})
Plot a Pie Chart for Registration Price column with label Car column −
plt.pie(dataFrame["Reg_Price"], labels = dataFrame["Car"])
Following is the code −
import pandas as pd
import matplotlib.pyplot as plt
# creating dataframe
dataFrame = pd.DataFrame({
"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000]
})
# plot a Pie Chart for Registration Price column with label Car column
plt.pie(dataFrame["Reg_Price"], labels = dataFrame["Car"])
plt.show()
This will produce the following output −
|
[
{
"code": null,
"e": 1184,
"s": 1062,
"text": "To plot a Pie Chart, use the plot.pie(). The pie plot is a proportional representation of the numerical data in a column."
},
{
"code": null,
"e": 1216,
"s": 1184,
"text": "Import the required libraries −"
},
{
"code": null,
"e": 1268,
"s": 1216,
"text": "import pandas as pd\nimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 1289,
"s": 1268,
"text": "Create a DataFrame −"
},
{
"code": null,
"e": 1438,
"s": 1289,
"text": "dataFrame = pd.DataFrame({\n \"Car\": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],\"Reg_Price\": [7000, 1500, 5000, 8000, 9000, 6000]\n})"
},
{
"code": null,
"e": 1509,
"s": 1438,
"text": "Plot a Pie Chart for Registration Price column with label Car column −"
},
{
"code": null,
"e": 1569,
"s": 1509,
"text": "plt.pie(dataFrame[\"Reg_Price\"], labels = dataFrame[\"Car\"])\n"
},
{
"code": null,
"e": 1593,
"s": 1569,
"text": "Following is the code −"
},
{
"code": null,
"e": 1958,
"s": 1593,
"text": "import pandas as pd\nimport matplotlib.pyplot as plt\n\n# creating dataframe\ndataFrame = pd.DataFrame({\n \"Car\": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],\"Reg_Price\": [7000, 1500, 5000, 8000, 9000, 6000]\n})\n\n# plot a Pie Chart for Registration Price column with label Car column\nplt.pie(dataFrame[\"Reg_Price\"], labels = dataFrame[\"Car\"])\nplt.show()"
},
{
"code": null,
"e": 1999,
"s": 1958,
"text": "This will produce the following output −"
}
] |
JavaScript - Variables
|
One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language.
JavaScript allows you to work with three primitive data types −
Numbers, eg. 123, 120.50 etc.
Numbers, eg. 123, 120.50 etc.
Strings of text e.g. "This text string" etc.
Strings of text e.g. "This text string" etc.
Boolean e.g. true or false.
Boolean e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which defines only a single value. In addition to these primitive data types, JavaScript supports a composite data type known as object. We will cover objects in detail in a separate chapter.
Note − JavaScript does not make a distinction between integer values and floating-point values. All numbers in JavaScript are represented as floating-point values. JavaScript represents numbers using the 64-bit floating-point format defined by the IEEE 754 standard.
Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows.
<script type = "text/javascript">
<!--
var money;
var name;
//-->
</script>
You can also declare multiple variables with the same var keyword as follows −
<script type = "text/javascript">
<!--
var money, name;
//-->
</script>
Storing a value in a variable is called variable initialization. You can do variable initialization at the time of variable creation or at a later point in time when you need that variable.
For instance, you might create a variable named money and assign the value 2000.50 to it later. For another variable, you can assign a value at the time of initialization as follows.
<script type = "text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
Note − Use the var keyword only for declaration or initialization, once for the life of any variable name in a document. You should not re-declare same variable twice.
JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type. Unlike many other languages, you don't have to tell JavaScript during variable declaration what type of value the variable will hold. The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically.
The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes.
Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code.
Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code.
Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. Take a look into the following example.
<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
</body>
</html>
This produces the following result −
local
While naming your variables in JavaScript, keep the following rules in mind.
You should not use any of the JavaScript reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid.
You should not use any of the JavaScript reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid.
JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one.
JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one.
JavaScript variable names are case-sensitive. For example, Name and name are two different variables.
JavaScript variable names are case-sensitive. For example, Name and name are two different variables.
A list of all the reserved words in JavaScript are given in the following table. They cannot be used as JavaScript variables, functions, methods, loop labels, or any object names.
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2670,
"s": 2466,
"text": "One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language."
},
{
"code": null,
"e": 2734,
"s": 2670,
"text": "JavaScript allows you to work with three primitive data types −"
},
{
"code": null,
"e": 2764,
"s": 2734,
"text": "Numbers, eg. 123, 120.50 etc."
},
{
"code": null,
"e": 2794,
"s": 2764,
"text": "Numbers, eg. 123, 120.50 etc."
},
{
"code": null,
"e": 2840,
"s": 2794,
"text": "Strings of text e.g. \"This text string\" etc."
},
{
"code": null,
"e": 2886,
"s": 2840,
"text": "Strings of text e.g. \"This text string\" etc."
},
{
"code": null,
"e": 2914,
"s": 2886,
"text": "Boolean e.g. true or false."
},
{
"code": null,
"e": 2942,
"s": 2914,
"text": "Boolean e.g. true or false."
},
{
"code": null,
"e": 3210,
"s": 2942,
"text": "JavaScript also defines two trivial data types, null and undefined, each of which defines only a single value. In addition to these primitive data types, JavaScript supports a composite data type known as object. We will cover objects in detail in a separate chapter."
},
{
"code": null,
"e": 3477,
"s": 3210,
"text": "Note − JavaScript does not make a distinction between integer values and floating-point values. All numbers in JavaScript are represented as floating-point values. JavaScript represents numbers using the 64-bit floating-point format defined by the IEEE 754 standard."
},
{
"code": null,
"e": 3691,
"s": 3477,
"text": "Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container."
},
{
"code": null,
"e": 3819,
"s": 3691,
"text": "Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows."
},
{
"code": null,
"e": 3913,
"s": 3819,
"text": "<script type = \"text/javascript\">\n <!--\n var money;\n var name;\n //-->\n</script>"
},
{
"code": null,
"e": 3992,
"s": 3913,
"text": "You can also declare multiple variables with the same var keyword as follows −"
},
{
"code": null,
"e": 4076,
"s": 3992,
"text": "<script type = \"text/javascript\">\n <!--\n var money, name;\n //-->\n</script>"
},
{
"code": null,
"e": 4266,
"s": 4076,
"text": "Storing a value in a variable is called variable initialization. You can do variable initialization at the time of variable creation or at a later point in time when you need that variable."
},
{
"code": null,
"e": 4449,
"s": 4266,
"text": "For instance, you might create a variable named money and assign the value 2000.50 to it later. For another variable, you can assign a value at the time of initialization as follows."
},
{
"code": null,
"e": 4574,
"s": 4449,
"text": "<script type = \"text/javascript\">\n <!--\n var name = \"Ali\";\n var money;\n money = 2000.50;\n //-->\n</script>"
},
{
"code": null,
"e": 4742,
"s": 4574,
"text": "Note − Use the var keyword only for declaration or initialization, once for the life of any variable name in a document. You should not re-declare same variable twice."
},
{
"code": null,
"e": 5102,
"s": 4742,
"text": "JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type. Unlike many other languages, you don't have to tell JavaScript during variable declaration what type of value the variable will hold. The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically."
},
{
"code": null,
"e": 5223,
"s": 5102,
"text": "The scope of a variable is the region of your program in which it is defined. JavaScript variables have only two scopes."
},
{
"code": null,
"e": 5341,
"s": 5223,
"text": "Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code."
},
{
"code": null,
"e": 5459,
"s": 5341,
"text": "Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code."
},
{
"code": null,
"e": 5609,
"s": 5459,
"text": "Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function."
},
{
"code": null,
"e": 5759,
"s": 5609,
"text": "Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function."
},
{
"code": null,
"e": 6044,
"s": 5759,
"text": "Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. Take a look into the following example."
},
{
"code": null,
"e": 6420,
"s": 6044,
"text": "<html>\n <body onload = checkscope();> \n <script type = \"text/javascript\">\n <!--\n var myVar = \"global\"; // Declare a global variable\n function checkscope( ) {\n var myVar = \"local\"; // Declare a local variable\n document.write(myVar);\n }\n //-->\n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 6457,
"s": 6420,
"text": "This produces the following result −"
},
{
"code": null,
"e": 6464,
"s": 6457,
"text": "local\n"
},
{
"code": null,
"e": 6541,
"s": 6464,
"text": "While naming your variables in JavaScript, keep the following rules in mind."
},
{
"code": null,
"e": 6730,
"s": 6541,
"text": "You should not use any of the JavaScript reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid."
},
{
"code": null,
"e": 6919,
"s": 6730,
"text": "You should not use any of the JavaScript reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid."
},
{
"code": null,
"e": 7120,
"s": 6919,
"text": "JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one."
},
{
"code": null,
"e": 7321,
"s": 7120,
"text": "JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one."
},
{
"code": null,
"e": 7423,
"s": 7321,
"text": "JavaScript variable names are case-sensitive. For example, Name and name are two different variables."
},
{
"code": null,
"e": 7525,
"s": 7423,
"text": "JavaScript variable names are case-sensitive. For example, Name and name are two different variables."
},
{
"code": null,
"e": 7705,
"s": 7525,
"text": "A list of all the reserved words in JavaScript are given in the following table. They cannot be used as JavaScript variables, functions, methods, loop labels, or any object names."
},
{
"code": null,
"e": 7740,
"s": 7705,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7754,
"s": 7740,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7788,
"s": 7754,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 7802,
"s": 7788,
"text": " Lets Kode It"
},
{
"code": null,
"e": 7837,
"s": 7802,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 7854,
"s": 7837,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7889,
"s": 7854,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 7906,
"s": 7889,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7939,
"s": 7906,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 7967,
"s": 7939,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 8001,
"s": 7967,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 8029,
"s": 8001,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 8036,
"s": 8029,
"text": " Print"
},
{
"code": null,
"e": 8047,
"s": 8036,
"text": " Add Notes"
}
] |
Forecasting Multiple Time-Series Using Neural Network | by Sarit Maitra | Towards Data Science
| ERROR: type should be string, got "https://sarit-maitra.medium.com/membership\nStock prediction is a difficult task because the data generated is enormous and is highly non-linear. Modeling such dynamical data require effective modeling technique which can analyze the hidden patterns and underlying dynamics. Neural network which is deep learning algorithms are capable of identifying and exploiting the interactions and patterns existing in a data through a self learning process.\nWe shall focus on a simple prediction model using long-short term memory architecture involving multiple time-series. We shall keep the whole exercise a simple process for illustration purpose and better understanding.\nLet us consider four different series S&P 500 (^GSPC), Dow Jones Industrial Average (^DJI), NASDAQ Composite (^IXIC) and Russell 2000 (^RUT) which is Chicago options. Our data set if from 1990 to till date. The data retrieved from yahoo finance and formatted into a Pandas DataFrame object.\nstock = ['^RUT', '^GSPC', '^DJI', '^IXIC' ]start = pd.to_datetime('1990-01-03')df = web.DataReader(stock, data_source = 'yahoo', start = start )print(df.head())\nLet us fit all the closing prices of the series in a neural network architecture and shall predict one series from there.\nX = data.copy()X = X.drop(columns = [‘Date’])print(X.shape)print(X.tail())\nIf we see the correlation analysis, we will know as why these 4 series are chosen.\nThe time series was split into a training set (80%) and a test set (20%) as shown below.\nsplit_ratio = 0.2X = X.values # Convert to NumPy arraysplit = int(len(X) * (1-split_ratio))train_set = X[: split]test_set = X[split:]print(train_set.shape, test_set.shape)\nLet us format the in such a way that, supervised learning can be applied for ML model. Here, both the training set and test set will undergo the same transformation. We will achieve the objective with the below function.\ndef supvervisedSeries(data, n, h): x, y = list (), list () for i in range (len(data)-n-h+1): x.append(data[i:(i+n)]) y.append(data[i+h+n-1]) return np.array(x), np.array(y)h = 1n = 4trainX, trainY = supvervisedSeries(training_set, n, h)testX, testY = supvervisedSeries(test_set, n, h)print(\"trainX: \", trainX.shape)print(\"trainY: \", trainY.shape)print(\"testX: \", testX.shape)print(\"testY: \", testY.shape)\nh = time horizon & n = number of features; these parameters are chosen prior to transformation.\nNow, trainY and testY must be modified as per required feature prediction because by default it contains all 4 features.\ntestY = np.reshape(testY[:, 0], (testY [:, 0].shape[0], 1))trainY = np.reshape(trainY[:, 0], (trainY[:, 0].shape[0], 1))print(“trainY: “, trainY.shape)print(“testY: “, testY.shape)\nHere, we have selected index[0] which is ^RUT daily Adj Close price.\nML model require the data to lie within the range (0, 1). We have used MinMaxScaler which rescales the data set such that all feature values are in the range [0, 1]. It normally preserve the shape of the data set.\nscalers = {}for i in range (trainX.shape[2]): scalers[i] = MinMaxScaler() trainX[:, :, i] = scalers[i].fit_transform(trainX[:, :, i])for i in range(testX.shape[2]): testX[:, :, i] = scalers[i].transform(testX[:, :, i])# The target values are 2D arrays, which is easy to scalescalerY = MinMaxScaler()trainY = scalerY.fit_transform(trainY)testY = scalerY.transform(testY)\nIn below, only 100 neurons in each layer was used to deal with our small data set. Also, dropout as a regularization technique was used to reduce overfitting. The class Dense represents a fully connected layer.\n# Flatten input (to support multivariate input)n_input = trainX.shape[1] * trainX.shape[2]trainX = trainX.reshape((trainX.shape[0], n_input))n_input = testX.shape[1] * testX.shape[2]testX = testX.reshape((testX.shape[0], n_input))# Create multilayered FFNN modelmodel = Sequential()model.add(Dense(100, activation='relu', input_dim=trainX.shape[1]))model.add(Dropout(0.2))model.add(Dense(100, activation='relu'))model.add(Dropout(0.2))model.add(Dense(100, activation='relu'))model.add(Dense(trainY.shape[1]))model.compile(loss='mean_squared_error', optimizer='adam')model.summary()# Fit modelhistory = model.fit(trainX, trainY, epochs =60, verbose =1)# Predict the test setpredictions = model.predict(testX)\nWe have to descale the data to bring back to original values using the same scaler that was originally used to scale the data.\n# Descalepredictions = scalerY.inverse_transform(predictions)testY = scalerY.inverse_transform(testY)# Mean absolute errormae = mean_absolute_error(testY, predictions)print(\"Test MAE: %.6f\" % mae)\nplt.figure(figsize=(15,6))plt.plot(predictions, label=\"Test set predictions\" )plt.plot(testY, label=\"Real data\")plt.legend()plt.ylabel('Price Index')plt.xlabel('time step' )plt.title (\"Russell 2000 Adj close Price prediction- with MAE {:10.4f}\".format(mae))plt.show()\nHere, it can be seen that out network architecture is able to pick-up the hidden trend in the data; similarly, other series can also be predicted selecting the right scale for chosen the series.\nWe can see that, deep neural network architecture is capable of capturing hidden dynamics and are able to make predictions. To keep it simple, we have just fitted a simple LSTM network and not optimized any parameter of our network. in order to built a robust network we have to work on the right parameters such as number of epochs, batch size, number of neurons, number of hidden layers etc.\nConnect me here." |
[
{
"code": null,
"e": 215,
"s": 172,
"text": "https://sarit-maitra.medium.com/membership"
},
{
"code": null,
"e": 619,
"s": 215,
"text": "Stock prediction is a difficult task because the data generated is enormous and is highly non-linear. Modeling such dynamical data require effective modeling technique which can analyze the hidden patterns and underlying dynamics. Neural network which is deep learning algorithms are capable of identifying and exploiting the interactions and patterns existing in a data through a self learning process."
},
{
"code": null,
"e": 838,
"s": 619,
"text": "We shall focus on a simple prediction model using long-short term memory architecture involving multiple time-series. We shall keep the whole exercise a simple process for illustration purpose and better understanding."
},
{
"code": null,
"e": 1129,
"s": 838,
"text": "Let us consider four different series S&P 500 (^GSPC), Dow Jones Industrial Average (^DJI), NASDAQ Composite (^IXIC) and Russell 2000 (^RUT) which is Chicago options. Our data set if from 1990 to till date. The data retrieved from yahoo finance and formatted into a Pandas DataFrame object."
},
{
"code": null,
"e": 1290,
"s": 1129,
"text": "stock = ['^RUT', '^GSPC', '^DJI', '^IXIC' ]start = pd.to_datetime('1990-01-03')df = web.DataReader(stock, data_source = 'yahoo', start = start )print(df.head())"
},
{
"code": null,
"e": 1412,
"s": 1290,
"text": "Let us fit all the closing prices of the series in a neural network architecture and shall predict one series from there."
},
{
"code": null,
"e": 1487,
"s": 1412,
"text": "X = data.copy()X = X.drop(columns = [‘Date’])print(X.shape)print(X.tail())"
},
{
"code": null,
"e": 1570,
"s": 1487,
"text": "If we see the correlation analysis, we will know as why these 4 series are chosen."
},
{
"code": null,
"e": 1659,
"s": 1570,
"text": "The time series was split into a training set (80%) and a test set (20%) as shown below."
},
{
"code": null,
"e": 1831,
"s": 1659,
"text": "split_ratio = 0.2X = X.values # Convert to NumPy arraysplit = int(len(X) * (1-split_ratio))train_set = X[: split]test_set = X[split:]print(train_set.shape, test_set.shape)"
},
{
"code": null,
"e": 2052,
"s": 1831,
"text": "Let us format the in such a way that, supervised learning can be applied for ML model. Here, both the training set and test set will undergo the same transformation. We will achieve the objective with the below function."
},
{
"code": null,
"e": 2466,
"s": 2052,
"text": "def supvervisedSeries(data, n, h): x, y = list (), list () for i in range (len(data)-n-h+1): x.append(data[i:(i+n)]) y.append(data[i+h+n-1]) return np.array(x), np.array(y)h = 1n = 4trainX, trainY = supvervisedSeries(training_set, n, h)testX, testY = supvervisedSeries(test_set, n, h)print(\"trainX: \", trainX.shape)print(\"trainY: \", trainY.shape)print(\"testX: \", testX.shape)print(\"testY: \", testY.shape)"
},
{
"code": null,
"e": 2562,
"s": 2466,
"text": "h = time horizon & n = number of features; these parameters are chosen prior to transformation."
},
{
"code": null,
"e": 2683,
"s": 2562,
"text": "Now, trainY and testY must be modified as per required feature prediction because by default it contains all 4 features."
},
{
"code": null,
"e": 2864,
"s": 2683,
"text": "testY = np.reshape(testY[:, 0], (testY [:, 0].shape[0], 1))trainY = np.reshape(trainY[:, 0], (trainY[:, 0].shape[0], 1))print(“trainY: “, trainY.shape)print(“testY: “, testY.shape)"
},
{
"code": null,
"e": 2933,
"s": 2864,
"text": "Here, we have selected index[0] which is ^RUT daily Adj Close price."
},
{
"code": null,
"e": 3147,
"s": 2933,
"text": "ML model require the data to lie within the range (0, 1). We have used MinMaxScaler which rescales the data set such that all feature values are in the range [0, 1]. It normally preserve the shape of the data set."
},
{
"code": null,
"e": 3520,
"s": 3147,
"text": "scalers = {}for i in range (trainX.shape[2]): scalers[i] = MinMaxScaler() trainX[:, :, i] = scalers[i].fit_transform(trainX[:, :, i])for i in range(testX.shape[2]): testX[:, :, i] = scalers[i].transform(testX[:, :, i])# The target values are 2D arrays, which is easy to scalescalerY = MinMaxScaler()trainY = scalerY.fit_transform(trainY)testY = scalerY.transform(testY)"
},
{
"code": null,
"e": 3731,
"s": 3520,
"text": "In below, only 100 neurons in each layer was used to deal with our small data set. Also, dropout as a regularization technique was used to reduce overfitting. The class Dense represents a fully connected layer."
},
{
"code": null,
"e": 4439,
"s": 3731,
"text": "# Flatten input (to support multivariate input)n_input = trainX.shape[1] * trainX.shape[2]trainX = trainX.reshape((trainX.shape[0], n_input))n_input = testX.shape[1] * testX.shape[2]testX = testX.reshape((testX.shape[0], n_input))# Create multilayered FFNN modelmodel = Sequential()model.add(Dense(100, activation='relu', input_dim=trainX.shape[1]))model.add(Dropout(0.2))model.add(Dense(100, activation='relu'))model.add(Dropout(0.2))model.add(Dense(100, activation='relu'))model.add(Dense(trainY.shape[1]))model.compile(loss='mean_squared_error', optimizer='adam')model.summary()# Fit modelhistory = model.fit(trainX, trainY, epochs =60, verbose =1)# Predict the test setpredictions = model.predict(testX)"
},
{
"code": null,
"e": 4566,
"s": 4439,
"text": "We have to descale the data to bring back to original values using the same scaler that was originally used to scale the data."
},
{
"code": null,
"e": 4763,
"s": 4566,
"text": "# Descalepredictions = scalerY.inverse_transform(predictions)testY = scalerY.inverse_transform(testY)# Mean absolute errormae = mean_absolute_error(testY, predictions)print(\"Test MAE: %.6f\" % mae)"
},
{
"code": null,
"e": 5031,
"s": 4763,
"text": "plt.figure(figsize=(15,6))plt.plot(predictions, label=\"Test set predictions\" )plt.plot(testY, label=\"Real data\")plt.legend()plt.ylabel('Price Index')plt.xlabel('time step' )plt.title (\"Russell 2000 Adj close Price prediction- with MAE {:10.4f}\".format(mae))plt.show()"
},
{
"code": null,
"e": 5226,
"s": 5031,
"text": "Here, it can be seen that out network architecture is able to pick-up the hidden trend in the data; similarly, other series can also be predicted selecting the right scale for chosen the series."
},
{
"code": null,
"e": 5620,
"s": 5226,
"text": "We can see that, deep neural network architecture is capable of capturing hidden dynamics and are able to make predictions. To keep it simple, we have just fitted a simple LSTM network and not optimized any parameter of our network. in order to built a robust network we have to work on the right parameters such as number of epochs, batch size, number of neurons, number of hidden layers etc."
}
] |
React Native - Running IOS
|
If you want to test your app in the IOS simulator, all you need is to open the root folder of your app in terminal and run −
react-native run-ios
The above command will start the simulator and run the app.
We can also specify the device we want to use.
react-native run-ios --simulator "iPhone 5s
After you open the app in simulator, you can press command + D on IOS to open the developers menu. You can check more about this in our debugging chapter.
You can also reload the IOS simulator by pressing command + R.
20 Lectures
1.5 hours
Anadi Sharma
61 Lectures
6.5 hours
A To Z Mentor
40 Lectures
4.5 hours
Eduonix Learning Solutions
56 Lectures
12.5 hours
Eduonix Learning Solutions
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2469,
"s": 2344,
"text": "If you want to test your app in the IOS simulator, all you need is to open the root folder of your app in terminal and run −"
},
{
"code": null,
"e": 2491,
"s": 2469,
"text": "react-native run-ios\n"
},
{
"code": null,
"e": 2551,
"s": 2491,
"text": "The above command will start the simulator and run the app."
},
{
"code": null,
"e": 2598,
"s": 2551,
"text": "We can also specify the device we want to use."
},
{
"code": null,
"e": 2643,
"s": 2598,
"text": "react-native run-ios --simulator \"iPhone 5s\n"
},
{
"code": null,
"e": 2798,
"s": 2643,
"text": "After you open the app in simulator, you can press command + D on IOS to open the developers menu. You can check more about this in our debugging chapter."
},
{
"code": null,
"e": 2861,
"s": 2798,
"text": "You can also reload the IOS simulator by pressing command + R."
},
{
"code": null,
"e": 2896,
"s": 2861,
"text": "\n 20 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 2910,
"s": 2896,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 2945,
"s": 2910,
"text": "\n 61 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 2960,
"s": 2945,
"text": " A To Z Mentor"
},
{
"code": null,
"e": 2995,
"s": 2960,
"text": "\n 40 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3023,
"s": 2995,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3059,
"s": 3023,
"text": "\n 56 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 3087,
"s": 3059,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3122,
"s": 3087,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3134,
"s": 3122,
"text": " Senol Atac"
},
{
"code": null,
"e": 3169,
"s": 3134,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3181,
"s": 3169,
"text": " Senol Atac"
},
{
"code": null,
"e": 3188,
"s": 3181,
"text": " Print"
},
{
"code": null,
"e": 3199,
"s": 3188,
"text": " Add Notes"
}
] |
MySQL - CREATE FUNCTION Statement
|
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.
MySQL provides a set of built-in function which performs particular tasks for example the CURDATE() function returns the current date.
You can create a stored function using the CREATE FUNCTION statement.
Following is the syntax the CREATE FUNCTION statement −
CREATE FUNCTION function_Name(input_arguments) RETURNS output_parameter
Where, function_name is the name of the function you need to create, input_arguments are the input values of the function and output_parameter is the return value of the function.
Suppose we have created a table named Emp in the database using the CREATE statement as shown below −
mysql> CREATE TABLE Emp(Name VARCHAR(255), DOB DATE, Location VARCHAR(255));
Query OK, 0 rows affected (2.03 sec)
And we have inserted three records in the Emp table as −
mysql> INSERT INTO Emp VALUES ('Amit', DATE('1970-01-08'), 'Hyderabad');
mysql> INSERT INTO Emp VALUES ('Sumith', DATE('1990-11-02'), 'Vishakhapatnam');
mysql> INSERT INTO Emp VALUES ('Sudha', DATE('1980-11-06'), 'Vijayawada');
Following query creates a function named getDob() which accepts the name of the employee, retrieves and returns the value of DOB column.
mysql> DELIMITER //
mysql> CREATE FUNCTION test.getDob(emp_name VARCHAR(50))
RETURNS DATE
DETERMINISTIC
BEGIN
declare dateOfBirth DATE;
select DOB into dateOfBirth from test.emp where Name = emp_name; MySQL CREATE FUNCTION Statement
return dateOfBirth;
END//
Query OK, 0 rows affected (0.31 sec)
mysql> DELIMITER ;
If you call the function you can get date of birth of an employee as shown below −
mysql> SELECT getDob('Amit');
+----------------+
| getDob('Amit') |
+----------------+
| 1970-01-08 |
+----------------+
1 row in set (0.15 sec)
Assume we have created another table as shown below −
CREATE TABLE student (Name VARCHAR(100), Math INT, English INT, Science INT, History INT);
INSERT INTO student values('Raman', 95, 89, 85, 81);
INSERT INTO student values('Rahul' , 90, 87, 86, 81);
INSERT INTO student values('Mohit', 90, 85, 86, 81);
INSERT INTO student values('Saurabh', NULL, NULL, NULL, NULL );
Following query creates a function with name tbl_Update −
mysql> DELIMITER //
Create Function tbl_Update(S_name Varchar(50), M1 INT, M2 INT, M3 INT, M4 INT)
RETURNS INT
DETERMINISTIC
BEGIN
UPDATE student SET Math = M1, English = M2, Science = M3, History = M4 WHERE Name = S_name;
RETURN 1;
END //
mysql> DELIMITER ;
You can call the above created function as shown below −
mysql> Select tbl_update('Saurabh',85,69,75,82);
+-----------------------------------+
| tbl_update('Saurabh',85,69,75,82) |
+-----------------------------------+
| 1 |
+-----------------------------------+
1 row in set (0.28 sec)
If you get the records of the table student using the select statement you can observe the modified record −
mysql> SELECT * from student;
+---------+------+---------+---------+---------+
| Name | Math | English | Science | History |
+---------+------+---------+---------+---------+
| Raman | 95 | 89 | 85 | 81 |
| Rahul | 90 | 87 | 86 | 81 |
| Mohit | 90 | 85 | 86 | 81 |
| Saurabh | 85 | 69 | 75 | 82 |
+---------+------+---------+---------+---------+
4 rows in set (0.00 sec)
31 Lectures
6 hours
Eduonix Learning Solutions
84 Lectures
5.5 hours
Frahaan Hussain
6 Lectures
3.5 hours
DATAhill Solutions Srinivas Reddy
60 Lectures
10 hours
Vijay Kumar Parvatha Reddy
10 Lectures
1 hours
Harshit Srivastava
25 Lectures
4 hours
Trevoir Williams
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2525,
"s": 2333,
"text": "A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing."
},
{
"code": null,
"e": 2660,
"s": 2525,
"text": "MySQL provides a set of built-in function which performs particular tasks for example the CURDATE() function returns the current date."
},
{
"code": null,
"e": 2730,
"s": 2660,
"text": "You can create a stored function using the CREATE FUNCTION statement."
},
{
"code": null,
"e": 2786,
"s": 2730,
"text": "Following is the syntax the CREATE FUNCTION statement −"
},
{
"code": null,
"e": 2859,
"s": 2786,
"text": "CREATE FUNCTION function_Name(input_arguments) RETURNS output_parameter\n"
},
{
"code": null,
"e": 3039,
"s": 2859,
"text": "Where, function_name is the name of the function you need to create, input_arguments are the input values of the function and output_parameter is the return value of the function."
},
{
"code": null,
"e": 3141,
"s": 3039,
"text": "Suppose we have created a table named Emp in the database using the CREATE statement as shown below −"
},
{
"code": null,
"e": 3256,
"s": 3141,
"text": "mysql> CREATE TABLE Emp(Name VARCHAR(255), DOB DATE, Location VARCHAR(255));\nQuery OK, 0 rows affected (2.03 sec)\n"
},
{
"code": null,
"e": 3313,
"s": 3256,
"text": "And we have inserted three records in the Emp table as −"
},
{
"code": null,
"e": 3542,
"s": 3313,
"text": "mysql> INSERT INTO Emp VALUES ('Amit', DATE('1970-01-08'), 'Hyderabad');\nmysql> INSERT INTO Emp VALUES ('Sumith', DATE('1990-11-02'), 'Vishakhapatnam');\nmysql> INSERT INTO Emp VALUES ('Sudha', DATE('1980-11-06'), 'Vijayawada');\n"
},
{
"code": null,
"e": 3679,
"s": 3542,
"text": "Following query creates a function named getDob() which accepts the name of the employee, retrieves and returns the value of DOB column."
},
{
"code": null,
"e": 4027,
"s": 3679,
"text": "mysql> DELIMITER //\nmysql> CREATE FUNCTION test.getDob(emp_name VARCHAR(50))\n RETURNS DATE\n DETERMINISTIC\n BEGIN\n declare dateOfBirth DATE;\n select DOB into dateOfBirth from test.emp where Name = emp_name; MySQL CREATE FUNCTION Statement\n return dateOfBirth;\n END//\nQuery OK, 0 rows affected (0.31 sec)\nmysql> DELIMITER ;"
},
{
"code": null,
"e": 4110,
"s": 4027,
"text": "If you call the function you can get date of birth of an employee as shown below −"
},
{
"code": null,
"e": 4260,
"s": 4110,
"text": "mysql> SELECT getDob('Amit');\n+----------------+\n| getDob('Amit') |\n+----------------+\n| 1970-01-08 |\n+----------------+\n1 row in set (0.15 sec)\n"
},
{
"code": null,
"e": 4314,
"s": 4260,
"text": "Assume we have created another table as shown below −"
},
{
"code": null,
"e": 4630,
"s": 4314,
"text": "CREATE TABLE student (Name VARCHAR(100), Math INT, English INT, Science INT, History INT);\nINSERT INTO student values('Raman', 95, 89, 85, 81);\nINSERT INTO student values('Rahul' , 90, 87, 86, 81);\nINSERT INTO student values('Mohit', 90, 85, 86, 81);\nINSERT INTO student values('Saurabh', NULL, NULL, NULL, NULL );\n"
},
{
"code": null,
"e": 4688,
"s": 4630,
"text": "Following query creates a function with name tbl_Update −"
},
{
"code": null,
"e": 4965,
"s": 4688,
"text": "mysql> DELIMITER //\nCreate Function tbl_Update(S_name Varchar(50), M1 INT, M2 INT, M3 INT, M4 INT)\n RETURNS INT\n DETERMINISTIC\n BEGIN\n UPDATE student SET Math = M1, English = M2, Science = M3, History = M4 WHERE Name = S_name;\n RETURN 1;\n END //\nmysql> DELIMITER ;"
},
{
"code": null,
"e": 5022,
"s": 4965,
"text": "You can call the above created function as shown below −"
},
{
"code": null,
"e": 5285,
"s": 5022,
"text": "mysql> Select tbl_update('Saurabh',85,69,75,82);\n+-----------------------------------+\n| tbl_update('Saurabh',85,69,75,82) |\n+-----------------------------------+\n| 1 |\n+-----------------------------------+\n1 row in set (0.28 sec)"
},
{
"code": null,
"e": 5394,
"s": 5285,
"text": "If you get the records of the table student using the select statement you can observe the modified record −"
},
{
"code": null,
"e": 5841,
"s": 5394,
"text": "mysql> SELECT * from student;\n+---------+------+---------+---------+---------+\n| Name | Math | English | Science | History |\n+---------+------+---------+---------+---------+\n| Raman | 95 | 89 | 85 | 81 |\n| Rahul | 90 | 87 | 86 | 81 |\n| Mohit | 90 | 85 | 86 | 81 |\n| Saurabh | 85 | 69 | 75 | 82 |\n+---------+------+---------+---------+---------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 5874,
"s": 5841,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5902,
"s": 5874,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5937,
"s": 5902,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5954,
"s": 5937,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5988,
"s": 5954,
"text": "\n 6 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6023,
"s": 5988,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 6057,
"s": 6023,
"text": "\n 60 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 6085,
"s": 6057,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 6118,
"s": 6085,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6138,
"s": 6118,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 6171,
"s": 6138,
"text": "\n 25 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6189,
"s": 6171,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 6196,
"s": 6189,
"text": " Print"
},
{
"code": null,
"e": 6207,
"s": 6196,
"text": " Add Notes"
}
] |
How to find the sum of diagonal elements in a table in R?
|
The sum of diagonal elements could be required in matrix analysis therefore, we can convert the matrix into a table and find the sum of diagonal elements. This can be easily done by using sun function by extracting diagonal elements of the table using diag function. For example, if we have a table T then the sum of diagonal elements of T can be found as sum(diag(T)).
Live Demo
Table1<-as.table(matrix(1:25,ncol=5))
Table1
A B C D E
A 1 6 11 16 21
B 2 7 12 17 22
C 3 8 13 18 23
D 4 9 14 19 24
E 5 10 15 20 25
sum(diag(Table1))
[1] 65
Live Demo
Table2<-as.table(matrix(1:100,ncol=10))
Table2
A B C D E F G H I J
A 1 11 21 31 41 51 61 71 81 91
B 2 12 22 32 42 52 62 72 82 92
C 3 13 23 33 43 53 63 73 83 93
D 4 14 24 34 44 54 64 74 84 94
E 5 15 25 35 45 55 65 75 85 95
F 6 16 26 36 46 56 66 76 86 96
G 7 17 27 37 47 57 67 77 87 97
H 8 18 28 38 48 58 68 78 88 98
I 9 19 29 39 49 59 69 79 89 99
J 10 20 30 40 50 60 70 80 90 100
sum(diag(Table2))
[1] 505
Live Demo
Table3<-as.table(matrix(rnorm(36),nrow=6)) Table3
A B C D E F
A -0.02015819 -2.14686269 -0.79392704 -0.55050284 0.23070052 0.13070019
B -0.39663252 -0.12698078 -0.09832510 -1.41939702 -0.49657164 -0.45341576
C 0.23753427 0.78309823 2.11059813 -0.41943086 -0.33058117 0.63018308
D -2.03889403 1.33432969 1.65307088 1.67585600 -1.49239102 -0.67350890
E -0.61901214 -0.89328172 1.03601932 -0.16994050 0.73360113 0.42438789
F -1.09296499 -1.10922272 0.04226664 2.58299950 0.51644977 0.41344741
sum(diag(Table3))
[1] -1.493482
Live Demo
Table4<-as.table(matrix(rnorm(36,100,5),nrow=6))
Table4
A B C D E F
A 105.44635 93.14600 97.80468 100.68027 95.28400 100.82330
B 95.16300 98.87825 98.75319 96.53916 108.81398 99.40972
C 94.99926 105.25513 100.37713 100.96798 93.41062 101.70070
D 99.21070 99.82776 88.46770 97.40873 102.29429 95.97573
E 98.70941 95.46398 101.49608 102.96491 101.35786 105.05309
F 102.20267 101.30244 100.53210 91.06927 87.33858 102.15255
sum(diag(Table4))
[1] 608.7968
Live Demo
Table5<-as.table(matrix(rnorm(25,500,50),nrow=5))
Table5
A B C D E
A 505.2863 493.6967 542.0539 577.7998 504.0781
B 500.1169 518.8777 403.9920 569.6609 506.1925
C 410.2091 404.1374 521.1845 547.0921 489.7272
D 520.4017 491.4741 502.0402 453.0907 490.6733
E 499.4468 520.5062 449.8988 541.2709 562.4680
sum(diag(Table5))
[1] 2422.402
Live Demo
Table6<-as.table(matrix(runif(25,5,10),nrow=5))
Table6
A B C D E
A 9.957061 8.584646 6.731691 6.645764 6.343259
B 7.157706 5.733703 5.630403 9.290109 5.232770
C 8.244165 5.308932 5.100177 6.389525 7.758126
D 6.445069 8.942210 5.995070 6.302655 8.955960
E 8.200180 7.202910 9.770459 6.822972 6.435597
sum(diag(Table6))
[1] 31.74213
Live Demo
Table7<-as.table(matrix(rexp(25,3.5),nrow=5)) Table7
A B C D E
A 0.29068590 0.27290414 0.55115684 0.23493220 0.51366603
B 0.69828775 0.39694271 0.08617531 0.01405418 0.29315770
C 0.07375495 0.14626855 0.36778766 0.58536517 0.38151674
D 0.02949406 0.01493486 0.23719988 0.01521633 0.03468193
E 0.08120215 0.42675242 0.33896103 0.34181323 0.06136357
sum(diag(Table7))
[1] 0.310424
Live Demo
Table10<-as.table(matrix(rpois(100,15),ncol=10))
Table10
A B C D E F G H I J
A 22 21 16 13 10 17 10 6 11 13
B 9 13 17 15 18 8 12 17 12 12
C 22 24 17 14 15 17 12 19 18 18
D 15 15 20 19 12 17 13 14 7 16
E 18 10 15 15 6 15 13 27 22 11
F 9 14 11 8 15 10 19 12 17 14
G 17 14 13 12 11 12 14 16 12 18
H 15 18 13 18 18 20 13 15 6 20
I 16 16 15 14 12 15 9 17 14 14
J 13 20 21 13 18 17 11 16 15 15
sum(diag(Table10))
[1] 156
|
[
{
"code": null,
"e": 1432,
"s": 1062,
"text": "The sum of diagonal elements could be required in matrix analysis therefore, we can convert the matrix into a table and find the sum of diagonal elements. This can be easily done by using sun function by extracting diagonal elements of the table using diag function. For example, if we have a table T then the sum of diagonal elements of T can be found as sum(diag(T))."
},
{
"code": null,
"e": 1443,
"s": 1432,
"text": " Live Demo"
},
{
"code": null,
"e": 1488,
"s": 1443,
"text": "Table1<-as.table(matrix(1:25,ncol=5))\nTable1"
},
{
"code": null,
"e": 1579,
"s": 1488,
"text": " A B C D E\nA 1 6 11 16 21\nB 2 7 12 17 22\nC 3 8 13 18 23\nD 4 9 14 19 24\nE 5 10 15 20 25"
},
{
"code": null,
"e": 1597,
"s": 1579,
"text": "sum(diag(Table1))"
},
{
"code": null,
"e": 1604,
"s": 1597,
"text": "[1] 65"
},
{
"code": null,
"e": 1615,
"s": 1604,
"text": " Live Demo"
},
{
"code": null,
"e": 1662,
"s": 1615,
"text": "Table2<-as.table(matrix(1:100,ncol=10))\nTable2"
},
{
"code": null,
"e": 2005,
"s": 1662,
"text": " A B C D E F G H I J\nA 1 11 21 31 41 51 61 71 81 91\nB 2 12 22 32 42 52 62 72 82 92\nC 3 13 23 33 43 53 63 73 83 93\nD 4 14 24 34 44 54 64 74 84 94\nE 5 15 25 35 45 55 65 75 85 95\nF 6 16 26 36 46 56 66 76 86 96\nG 7 17 27 37 47 57 67 77 87 97\nH 8 18 28 38 48 58 68 78 88 98\nI 9 19 29 39 49 59 69 79 89 99\nJ 10 20 30 40 50 60 70 80 90 100"
},
{
"code": null,
"e": 2023,
"s": 2005,
"text": "sum(diag(Table2))"
},
{
"code": null,
"e": 2031,
"s": 2023,
"text": "[1] 505"
},
{
"code": null,
"e": 2042,
"s": 2031,
"text": " Live Demo"
},
{
"code": null,
"e": 2092,
"s": 2042,
"text": "Table3<-as.table(matrix(rnorm(36),nrow=6)) Table3"
},
{
"code": null,
"e": 2604,
"s": 2092,
"text": " A B C D E F\nA -0.02015819 -2.14686269 -0.79392704 -0.55050284 0.23070052 0.13070019\nB -0.39663252 -0.12698078 -0.09832510 -1.41939702 -0.49657164 -0.45341576\nC 0.23753427 0.78309823 2.11059813 -0.41943086 -0.33058117 0.63018308\nD -2.03889403 1.33432969 1.65307088 1.67585600 -1.49239102 -0.67350890\nE -0.61901214 -0.89328172 1.03601932 -0.16994050 0.73360113 0.42438789\nF -1.09296499 -1.10922272 0.04226664 2.58299950 0.51644977 0.41344741"
},
{
"code": null,
"e": 2622,
"s": 2604,
"text": "sum(diag(Table3))"
},
{
"code": null,
"e": 2636,
"s": 2622,
"text": "[1] -1.493482"
},
{
"code": null,
"e": 2647,
"s": 2636,
"text": " Live Demo"
},
{
"code": null,
"e": 2703,
"s": 2647,
"text": "Table4<-as.table(matrix(rnorm(36,100,5),nrow=6))\nTable4"
},
{
"code": null,
"e": 3129,
"s": 2703,
"text": " A B C D E F\nA 105.44635 93.14600 97.80468 100.68027 95.28400 100.82330\nB 95.16300 98.87825 98.75319 96.53916 108.81398 99.40972\nC 94.99926 105.25513 100.37713 100.96798 93.41062 101.70070\nD 99.21070 99.82776 88.46770 97.40873 102.29429 95.97573\nE 98.70941 95.46398 101.49608 102.96491 101.35786 105.05309\nF 102.20267 101.30244 100.53210 91.06927 87.33858 102.15255"
},
{
"code": null,
"e": 3147,
"s": 3129,
"text": "sum(diag(Table4))"
},
{
"code": null,
"e": 3160,
"s": 3147,
"text": "[1] 608.7968"
},
{
"code": null,
"e": 3171,
"s": 3160,
"text": " Live Demo"
},
{
"code": null,
"e": 3228,
"s": 3171,
"text": "Table5<-as.table(matrix(rnorm(25,500,50),nrow=5))\nTable5"
},
{
"code": null,
"e": 3505,
"s": 3228,
"text": " A B C D E\nA 505.2863 493.6967 542.0539 577.7998 504.0781\nB 500.1169 518.8777 403.9920 569.6609 506.1925\nC 410.2091 404.1374 521.1845 547.0921 489.7272\nD 520.4017 491.4741 502.0402 453.0907 490.6733\nE 499.4468 520.5062 449.8988 541.2709 562.4680"
},
{
"code": null,
"e": 3523,
"s": 3505,
"text": "sum(diag(Table5))"
},
{
"code": null,
"e": 3536,
"s": 3523,
"text": "[1] 2422.402"
},
{
"code": null,
"e": 3547,
"s": 3536,
"text": " Live Demo"
},
{
"code": null,
"e": 3602,
"s": 3547,
"text": "Table6<-as.table(matrix(runif(25,5,10),nrow=5))\nTable6"
},
{
"code": null,
"e": 3880,
"s": 3602,
"text": " A B C D E\nA 9.957061 8.584646 6.731691 6.645764 6.343259\nB 7.157706 5.733703 5.630403 9.290109 5.232770\nC 8.244165 5.308932 5.100177 6.389525 7.758126\nD 6.445069 8.942210 5.995070 6.302655 8.955960\nE 8.200180 7.202910 9.770459 6.822972 6.435597"
},
{
"code": null,
"e": 3898,
"s": 3880,
"text": "sum(diag(Table6))"
},
{
"code": null,
"e": 3911,
"s": 3898,
"text": "[1] 31.74213"
},
{
"code": null,
"e": 3922,
"s": 3911,
"text": " Live Demo"
},
{
"code": null,
"e": 3975,
"s": 3922,
"text": "Table7<-as.table(matrix(rexp(25,3.5),nrow=5)) Table7"
},
{
"code": null,
"e": 4312,
"s": 3975,
"text": " A B C D E \nA 0.29068590 0.27290414 0.55115684 0.23493220 0.51366603\nB 0.69828775 0.39694271 0.08617531 0.01405418 0.29315770\nC 0.07375495 0.14626855 0.36778766 0.58536517 0.38151674\nD 0.02949406 0.01493486 0.23719988 0.01521633 0.03468193\nE 0.08120215 0.42675242 0.33896103 0.34181323 0.06136357"
},
{
"code": null,
"e": 4330,
"s": 4312,
"text": "sum(diag(Table7))"
},
{
"code": null,
"e": 4343,
"s": 4330,
"text": "[1] 0.310424"
},
{
"code": null,
"e": 4354,
"s": 4343,
"text": " Live Demo"
},
{
"code": null,
"e": 4411,
"s": 4354,
"text": "Table10<-as.table(matrix(rpois(100,15),ncol=10))\nTable10"
},
{
"code": null,
"e": 4837,
"s": 4411,
"text": " A B C D E F G H I J\nA 22 21 16 13 10 17 10 6 11 13\nB 9 13 17 15 18 8 12 17 12 12\nC 22 24 17 14 15 17 12 19 18 18\nD 15 15 20 19 12 17 13 14 7 16\nE 18 10 15 15 6 15 13 27 22 11\nF 9 14 11 8 15 10 19 12 17 14\nG 17 14 13 12 11 12 14 16 12 18\nH 15 18 13 18 18 20 13 15 6 20\nI 16 16 15 14 12 15 9 17 14 14\nJ 13 20 21 13 18 17 11 16 15 15"
},
{
"code": null,
"e": 4856,
"s": 4837,
"text": "sum(diag(Table10))"
},
{
"code": null,
"e": 4864,
"s": 4856,
"text": "[1] 156"
}
] |
How do I drop a MongoDB database from the command line?
|
To drop a MongoDB database from the command line, use the following syntax:
mongo yourDatabaseName --eval "db.dropDatabase()"
To understand the above syntax, let us display all the database from MongoDB. The query is as follows −
> show dbs;
The following is the output −
StudentTracker 0.000GB
admin 0.000GB
config 0.000GB
local 0.000GB
sample 0.000GB
test 0.003GB
Drop the database with the name ‘StudentTracker’. The query is as follows to drop a database from command line −
C:\Program Files\MongoDB\Server\4.0\bin>mongo StudentTracker --eval "db.dropDatabase()"
The following is the output −
MongoDB shell version v4.0.5
connecting to: mongodb://127.0.0.1:27017/StudentTracker?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("afc34e93-b4c0-46f0-85bd-b80ed17b8c11") }
MongoDB server version: 4.0.5
{ "dropped" : "StudentTracker", "ok" : 1 }
Now check the database has been dropped or not. The query is as follows −
> show dbs
The following is the output −
admin 0.000GB
config 0.000GB
local 0.000GB
sample 0.000GB
test 0.003GB
Look at the sample output, the database ‘StudentTracker’ has been dropped.
|
[
{
"code": null,
"e": 1138,
"s": 1062,
"text": "To drop a MongoDB database from the command line, use the following syntax:"
},
{
"code": null,
"e": 1188,
"s": 1138,
"text": "mongo yourDatabaseName --eval \"db.dropDatabase()\""
},
{
"code": null,
"e": 1292,
"s": 1188,
"text": "To understand the above syntax, let us display all the database from MongoDB. The query is as follows −"
},
{
"code": null,
"e": 1304,
"s": 1292,
"text": "> show dbs;"
},
{
"code": null,
"e": 1334,
"s": 1304,
"text": "The following is the output −"
},
{
"code": null,
"e": 1428,
"s": 1334,
"text": "StudentTracker 0.000GB\nadmin 0.000GB\nconfig 0.000GB\nlocal 0.000GB\nsample 0.000GB\ntest 0.003GB"
},
{
"code": null,
"e": 1541,
"s": 1428,
"text": "Drop the database with the name ‘StudentTracker’. The query is as follows to drop a database from command line −"
},
{
"code": null,
"e": 1629,
"s": 1541,
"text": "C:\\Program Files\\MongoDB\\Server\\4.0\\bin>mongo StudentTracker --eval \"db.dropDatabase()\""
},
{
"code": null,
"e": 1659,
"s": 1629,
"text": "The following is the output −"
},
{
"code": null,
"e": 1925,
"s": 1659,
"text": "MongoDB shell version v4.0.5\nconnecting to: mongodb://127.0.0.1:27017/StudentTracker?gssapiServiceName=mongodb\nImplicit session: session { \"id\" : UUID(\"afc34e93-b4c0-46f0-85bd-b80ed17b8c11\") }\nMongoDB server version: 4.0.5\n{ \"dropped\" : \"StudentTracker\", \"ok\" : 1 }"
},
{
"code": null,
"e": 1999,
"s": 1925,
"text": "Now check the database has been dropped or not. The query is as follows −"
},
{
"code": null,
"e": 2010,
"s": 1999,
"text": "> show dbs"
},
{
"code": null,
"e": 2040,
"s": 2010,
"text": "The following is the output −"
},
{
"code": null,
"e": 2111,
"s": 2040,
"text": "admin 0.000GB\nconfig 0.000GB\nlocal 0.000GB\nsample 0.000GB\ntest 0.003GB"
},
{
"code": null,
"e": 2186,
"s": 2111,
"text": "Look at the sample output, the database ‘StudentTracker’ has been dropped."
}
] |
Difference between file_get_contents and cURL in PHP
|
13 Sep, 2021
file_get_contents() Function: This PHP function is used to retrieve the contents of a file. The contents can be stored as a string variable. Alternatively, it also simulates HTTP transactions, involving requests via GET method and responses using POST method respectively. Primarily, it is best-suited for simple HTTP manipulations and to get single-line JSON responses.
Example:
PHP
<?php // Reading contents from the// GeeksforGeeks homepage$homepage = file_get_contents( "https://www.geeksforgeeks.org/"); echo $homepage; ?>
Output: It will redirect to GeeksforGeeks home page.
cURL: It is a third party library that simulates HTTP requests and responses in a much more efficient way. It can handle asynchronous HTTP requests and complex communications like callback functions or break point continual transferring. It is also suitable for carrying out cross-domain based FTP request. Also, it can be used in different applications like proxy setup and Website Scraping etc.
Example:
PHP
<?php // From URL to get webpage contents$url = "https://www.geeksforgeeks.org/"; // Initialize a CURL session.$ch = curl_init(); // Return Page contents.curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Grab URL and pass it to the variablecurl_setopt($ch, CURLOPT_URL, $url); $result = curl_exec($ch); echo $result; ?>
Output: It will redirect to GeeksforGeeks home page.
akshaysingh98088
PHP-function
PHP-Misc
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to receive JSON POST with PHP ?
How to get parameters from a URL string in PHP?
Split a comma delimited string into an array in PHP
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to get parameters from a URL string in PHP?
Split a comma delimited string into an array in PHP
How to pass JavaScript variables to PHP ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Sep, 2021"
},
{
"code": null,
"e": 400,
"s": 28,
"text": "file_get_contents() Function: This PHP function is used to retrieve the contents of a file. The contents can be stored as a string variable. Alternatively, it also simulates HTTP transactions, involving requests via GET method and responses using POST method respectively. Primarily, it is best-suited for simple HTTP manipulations and to get single-line JSON responses. "
},
{
"code": null,
"e": 409,
"s": 400,
"text": "Example:"
},
{
"code": null,
"e": 413,
"s": 409,
"text": "PHP"
},
{
"code": "<?php // Reading contents from the// GeeksforGeeks homepage$homepage = file_get_contents( \"https://www.geeksforgeeks.org/\"); echo $homepage; ?>",
"e": 558,
"s": 413,
"text": null
},
{
"code": null,
"e": 611,
"s": 558,
"text": "Output: It will redirect to GeeksforGeeks home page."
},
{
"code": null,
"e": 1009,
"s": 611,
"text": "cURL: It is a third party library that simulates HTTP requests and responses in a much more efficient way. It can handle asynchronous HTTP requests and complex communications like callback functions or break point continual transferring. It is also suitable for carrying out cross-domain based FTP request. Also, it can be used in different applications like proxy setup and Website Scraping etc. "
},
{
"code": null,
"e": 1018,
"s": 1009,
"text": "Example:"
},
{
"code": null,
"e": 1022,
"s": 1018,
"text": "PHP"
},
{
"code": "<?php // From URL to get webpage contents$url = \"https://www.geeksforgeeks.org/\"; // Initialize a CURL session.$ch = curl_init(); // Return Page contents.curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Grab URL and pass it to the variablecurl_setopt($ch, CURLOPT_URL, $url); $result = curl_exec($ch); echo $result; ?>",
"e": 1340,
"s": 1022,
"text": null
},
{
"code": null,
"e": 1393,
"s": 1340,
"text": "Output: It will redirect to GeeksforGeeks home page."
},
{
"code": null,
"e": 1410,
"s": 1393,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 1423,
"s": 1410,
"text": "PHP-function"
},
{
"code": null,
"e": 1432,
"s": 1423,
"text": "PHP-Misc"
},
{
"code": null,
"e": 1439,
"s": 1432,
"text": "Picked"
},
{
"code": null,
"e": 1443,
"s": 1439,
"text": "PHP"
},
{
"code": null,
"e": 1456,
"s": 1443,
"text": "PHP Programs"
},
{
"code": null,
"e": 1473,
"s": 1456,
"text": "Web Technologies"
},
{
"code": null,
"e": 1500,
"s": 1473,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1504,
"s": 1500,
"text": "PHP"
},
{
"code": null,
"e": 1602,
"s": 1504,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1642,
"s": 1602,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 1687,
"s": 1642,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 1723,
"s": 1687,
"text": "How to receive JSON POST with PHP ?"
},
{
"code": null,
"e": 1771,
"s": 1723,
"text": "How to get parameters from a URL string in PHP?"
},
{
"code": null,
"e": 1823,
"s": 1771,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 1863,
"s": 1823,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 1915,
"s": 1863,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 1963,
"s": 1915,
"text": "How to get parameters from a URL string in PHP?"
},
{
"code": null,
"e": 2015,
"s": 1963,
"text": "Split a comma delimited string into an array in PHP"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.