title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Pascal - Pointers
|
Pointers in Pascal are easy and fun to learn. Some Pascal programming tasks are performed more easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a perfect Pascal programmer. Let's start learning them in simple and easy steps.
As you know, every variable is a memory location and every memory location has its address defined which can be accessed using the name of the pointer variable, which denotes an address in memory.
A pointer is a dynamic variable, whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address. The general form of a pointer variable declaration is −
type
ptr-identifier = ^base-variable-type;
The pointer type is defined by prefixing the up-arrow of caret symbol (^) with the base type. The base-type defines the types of the data items. Once a pointer variable is defined to be of certain type, it can point data items of that type only. Once a pointer type has been defined, we can use the var declaration to declare pointer variables.
var
p1, p2, ... : ptr-identifier;
Following are some valid pointer declarations −
type
Rptr = ^real;
Cptr = ^char;
Bptr = ^ Boolean;
Aptr = ^array[1..5] of real;
date-ptr = ^ date;
Date = record
Day: 1..31;
Month: 1..12;
Year: 1900..3000;
End;
var
a, b : Rptr;
d: date-ptr;
The pointer variables are dereferenced by using the same caret symbol (^). For example, the associated variable referred by a pointer rptr, is rptr^. It can be accessed as −
rptr^ := 234.56;
The following example will illustrate this concept −
program exPointers;
var
number: integer;
iptr: ^integer;
begin
number := 100;
writeln('Number is: ', number);
iptr := @number;
writeln('iptr points to a value: ', iptr^);
iptr^ := 200;
writeln('Number is: ', number);
writeln('iptr points to a value: ', iptr^);
end.
When the above code is compiled and executed, it produces the following result −
Number is: 100
iptr points to a value: 100
Number is: 200
iptr points to a value: 200
In Pascal, we can assign the address of a variable to a pointer variable using the address operator (@). We use this pointer to manipulate and access the data item. However, if for some reason, we need to work with the memory address itself, we need to store it in a word type variable.
Let us extend the above example to print the memory address stored in the pointer iptr −
program exPointers;
var
number: integer;
iptr: ^integer;
y: ^word;
begin
number := 100;
writeln('Number is: ', number);
iptr := @number;
writeln('iptr points to a value: ', iptr^);
iptr^ := 200;
writeln('Number is: ', number);
writeln('iptr points to a value: ', iptr^);
y := addr(iptr);
writeln(y^);
end.
When the above code is compiled and executed, it produces the following result −
Number is: 100
iptr points to a value: 100
Number is: 200
iptr points to a value: 200
45504
It is always a good practice to assign a NIL value to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NIL points to nowhere. Consider the following program −
program exPointers;
var
number: integer;
iptr: ^integer;
y: ^word;
begin
iptr := nil;
y := addr(iptr);
writeln('the vaule of iptr is ', y^);
end.
When the above code is compiled and executed, it produces the following result −
The value of ptr is 0
To check for a nil pointer you can use an if statement as follows −
if(ptr <> nill )then (* succeeds if p is not null *)
if(ptr = nill)then (* succeeds if p is null *)
Pointers have many but easy concepts and they are very important to Pascal programming. There are following few important pointer concepts, which should be clear to a Pascal programmer −
There are four arithmetic operators that can be used on pointers: increment,decrement, +, -
You can define arrays to hold a number of pointers.
Pascal allows you to have pointer on a pointer and so on.
Passing an argument by reference or by address both enable the passed argument to be changed in the calling subprogram by the called subprogram.
Pascal allows a subprogram to return a pointer.
94 Lectures
8.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2430,
"s": 2083,
"text": "Pointers in Pascal are easy and fun to learn. Some Pascal programming tasks are performed more easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a perfect Pascal programmer. Let's start learning them in simple and easy steps."
},
{
"code": null,
"e": 2627,
"s": 2430,
"text": "As you know, every variable is a memory location and every memory location has its address defined which can be accessed using the name of the pointer variable, which denotes an address in memory."
},
{
"code": null,
"e": 2921,
"s": 2627,
"text": "A pointer is a dynamic variable, whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address. The general form of a pointer variable declaration is −"
},
{
"code": null,
"e": 2967,
"s": 2921,
"text": "type\n ptr-identifier = ^base-variable-type;"
},
{
"code": null,
"e": 3313,
"s": 2967,
"text": "The pointer type is defined by prefixing the up-arrow of caret symbol (^) with the base type. The base-type defines the types of the data items. Once a pointer variable is defined to be of certain type, it can point data items of that type only. Once a pointer type has been defined, we can use the var declaration to declare pointer variables."
},
{
"code": null,
"e": 3350,
"s": 3313,
"text": "var\n p1, p2, ... : ptr-identifier;"
},
{
"code": null,
"e": 3398,
"s": 3350,
"text": "Following are some valid pointer declarations −"
},
{
"code": null,
"e": 3650,
"s": 3398,
"text": "type\n Rptr = ^real;\n Cptr = ^char;\n Bptr = ^ Boolean;\n Aptr = ^array[1..5] of real;\n date-ptr = ^ date;\n Date = record\n Day: 1..31;\n Month: 1..12;\n Year: 1900..3000;\n End;\nvar\n a, b : Rptr;\n d: date-ptr;"
},
{
"code": null,
"e": 3824,
"s": 3650,
"text": "The pointer variables are dereferenced by using the same caret symbol (^). For example, the associated variable referred by a pointer rptr, is rptr^. It can be accessed as −"
},
{
"code": null,
"e": 3841,
"s": 3824,
"text": "rptr^ := 234.56;"
},
{
"code": null,
"e": 3894,
"s": 3841,
"text": "The following example will illustrate this concept −"
},
{
"code": null,
"e": 4196,
"s": 3894,
"text": "program exPointers;\nvar\n number: integer;\n iptr: ^integer;\n\nbegin\n number := 100;\n writeln('Number is: ', number);\n \n iptr := @number;\n writeln('iptr points to a value: ', iptr^);\n \n iptr^ := 200;\n writeln('Number is: ', number);\n writeln('iptr points to a value: ', iptr^);\nend."
},
{
"code": null,
"e": 4277,
"s": 4196,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4364,
"s": 4277,
"text": "Number is: 100\niptr points to a value: 100\nNumber is: 200\niptr points to a value: 200\n"
},
{
"code": null,
"e": 4651,
"s": 4364,
"text": "In Pascal, we can assign the address of a variable to a pointer variable using the address operator (@). We use this pointer to manipulate and access the data item. However, if for some reason, we need to work with the memory address itself, we need to store it in a word type variable."
},
{
"code": null,
"e": 4740,
"s": 4651,
"text": "Let us extend the above example to print the memory address stored in the pointer iptr −"
},
{
"code": null,
"e": 5088,
"s": 4740,
"text": "program exPointers;\nvar\n number: integer;\n iptr: ^integer;\n y: ^word;\n\nbegin\n number := 100;\n writeln('Number is: ', number);\n iptr := @number;\n writeln('iptr points to a value: ', iptr^);\n \n iptr^ := 200;\n writeln('Number is: ', number);\n writeln('iptr points to a value: ', iptr^);\n y := addr(iptr);\n writeln(y^); \nend."
},
{
"code": null,
"e": 5169,
"s": 5088,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5262,
"s": 5169,
"text": "Number is: 100\niptr points to a value: 100\nNumber is: 200\niptr points to a value: 200\n45504\n"
},
{
"code": null,
"e": 5522,
"s": 5262,
"text": "It is always a good practice to assign a NIL value to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NIL points to nowhere. Consider the following program −"
},
{
"code": null,
"e": 5691,
"s": 5522,
"text": "program exPointers;\nvar\n number: integer;\n iptr: ^integer;\n y: ^word;\n\nbegin\n iptr := nil;\n y := addr(iptr);\n \n writeln('the vaule of iptr is ', y^);\nend."
},
{
"code": null,
"e": 5772,
"s": 5691,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5795,
"s": 5772,
"text": "The value of ptr is 0\n"
},
{
"code": null,
"e": 5863,
"s": 5795,
"text": "To check for a nil pointer you can use an if statement as follows −"
},
{
"code": null,
"e": 5970,
"s": 5863,
"text": "if(ptr <> nill )then (* succeeds if p is not null *)\nif(ptr = nill)then (* succeeds if p is null *)"
},
{
"code": null,
"e": 6157,
"s": 5970,
"text": "Pointers have many but easy concepts and they are very important to Pascal programming. There are following few important pointer concepts, which should be clear to a Pascal programmer −"
},
{
"code": null,
"e": 6249,
"s": 6157,
"text": "There are four arithmetic operators that can be used on pointers: increment,decrement, +, -"
},
{
"code": null,
"e": 6301,
"s": 6249,
"text": "You can define arrays to hold a number of pointers."
},
{
"code": null,
"e": 6359,
"s": 6301,
"text": "Pascal allows you to have pointer on a pointer and so on."
},
{
"code": null,
"e": 6504,
"s": 6359,
"text": "Passing an argument by reference or by address both enable the passed argument to be changed in the calling subprogram by the called subprogram."
},
{
"code": null,
"e": 6552,
"s": 6504,
"text": "Pascal allows a subprogram to return a pointer."
},
{
"code": null,
"e": 6587,
"s": 6552,
"text": "\n 94 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 6610,
"s": 6587,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 6617,
"s": 6610,
"text": " Print"
},
{
"code": null,
"e": 6628,
"s": 6617,
"text": " Add Notes"
}
] |
PHP - Function preg_grep()
|
array preg_grep ( string $pattern, array $input [, int $flags] );
Returns the array consisting of the elements of the input array that match the given pattern.
If flag is set to PREG_GREP_INVERT, this function returns the elements of the input array that do not match the given pattern.
Returns an array indexed using the keys from the input array.
Returns an array indexed using the keys from the input array.
Following is the piece of code, copy and paste this code into a file and verify the result.
<?php
$foods = array("pasta", "steak", "fish", "potatoes");
// find elements beginning with "p", followed by one or more letters.
$p_foods = preg_grep("/p(\w+)/", $foods);
print "Found food is " . $p_foods[0];
print "Found food is " . $p_foods[1];
?>
This will produce the following result −
Found food is pastaFound food is
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2824,
"s": 2757,
"text": "array preg_grep ( string $pattern, array $input [, int $flags] );\n"
},
{
"code": null,
"e": 2918,
"s": 2824,
"text": "Returns the array consisting of the elements of the input array that match the given pattern."
},
{
"code": null,
"e": 3045,
"s": 2918,
"text": "If flag is set to PREG_GREP_INVERT, this function returns the elements of the input array that do not match the given pattern."
},
{
"code": null,
"e": 3107,
"s": 3045,
"text": "Returns an array indexed using the keys from the input array."
},
{
"code": null,
"e": 3169,
"s": 3107,
"text": "Returns an array indexed using the keys from the input array."
},
{
"code": null,
"e": 3261,
"s": 3169,
"text": "Following is the piece of code, copy and paste this code into a file and verify the result."
},
{
"code": null,
"e": 3535,
"s": 3261,
"text": "<?php\n $foods = array(\"pasta\", \"steak\", \"fish\", \"potatoes\");\n \n // find elements beginning with \"p\", followed by one or more letters.\n $p_foods = preg_grep(\"/p(\\w+)/\", $foods);\n \n print \"Found food is \" . $p_foods[0];\n print \"Found food is \" . $p_foods[1];\n?>"
},
{
"code": null,
"e": 3576,
"s": 3535,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3610,
"s": 3576,
"text": "Found food is pastaFound food is\n"
},
{
"code": null,
"e": 3643,
"s": 3610,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 3659,
"s": 3643,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3692,
"s": 3659,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3703,
"s": 3692,
"text": " Syed Raza"
},
{
"code": null,
"e": 3738,
"s": 3703,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3755,
"s": 3738,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3788,
"s": 3755,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3803,
"s": 3788,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 3838,
"s": 3803,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 3850,
"s": 3838,
"text": " Azaz Patel"
},
{
"code": null,
"e": 3885,
"s": 3850,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3913,
"s": 3885,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 3920,
"s": 3913,
"text": " Print"
},
{
"code": null,
"e": 3931,
"s": 3920,
"text": " Add Notes"
}
] |
Python - API.statuses_lookup() in Tweepy - GeeksforGeeks
|
05 Jun, 2020
Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication.
The statuses_lookup() method of the API class in Tweepy module is used to get the statuses specified by the status IDs, up to 100.
Syntax : API.statuses_lookup(parameters)
Parameters :
id_ : A list of Tweet IDs to fetch, up to 100
trim_user : A boolean indicating if user IDs should be provided, instead of complete user objects, the default value is False.
Returns : a list of objects of the class Status
Example 1 :
# import the moduleimport tweepy # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = "" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # list of status IDs to be fetched id_ = [1266978261701210112, 1266735261012111360, 1266342841648898049] # fetching the statusesstatuses = api.statuses_lookup(id_) # printing the statusesfor status in statuses: print("The status " + str(status.id) + " is posted by " + status.user.screen_name) print("This status says : \n\n" + status.text, end = "\n\n")
Output :
The status 1266978261701210112 is posted by geeksforgeeks
This status says :
Avoid errors, not client calls
.
Geeks, Keep this going...
.
#sundayvibes #programming #programmingmemes #coding https://t.co/JkA5iStofZ
The status 1266735261012111360 is posted by geeksforgeeks
This status says :
With the access to our Job Portal, find the jobs that are best for you & experience happy placement journey....
.
L... https://t.co/mzMMFVzjMv
The status 1266342841648898049 is posted by geeksforgeeks
This status says :
My reaction to this Lockdown :
"Der Lagi Lekin... Maine Ab Hai Jeena Seekh Liya"
What's your reaction to it?
.... https://t.co/nH9L0eewSr
Example 2: Using the statuses_lookup() method with the trim_user parameter.
# list of status IDs to be fetched id_ = [1266978261701210112, 1266735261012111360, 1266342841648898049] # fetching the statusesstatuses = api.statuses_lookup(id_, trim_user = True) # printing the statusesfor status in statuses: print(status.user.id)
Output :
57741058
57741058
57741058
Python-Tweepy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
sum() function in Python
*args and **kwargs in Python
|
[
{
"code": null,
"e": 24454,
"s": 24426,
"text": "\n05 Jun, 2020"
},
{
"code": null,
"e": 24854,
"s": 24454,
"text": "Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication."
},
{
"code": null,
"e": 24985,
"s": 24854,
"text": "The statuses_lookup() method of the API class in Tweepy module is used to get the statuses specified by the status IDs, up to 100."
},
{
"code": null,
"e": 25026,
"s": 24985,
"text": "Syntax : API.statuses_lookup(parameters)"
},
{
"code": null,
"e": 25039,
"s": 25026,
"text": "Parameters :"
},
{
"code": null,
"e": 25085,
"s": 25039,
"text": "id_ : A list of Tweet IDs to fetch, up to 100"
},
{
"code": null,
"e": 25212,
"s": 25085,
"text": "trim_user : A boolean indicating if user IDs should be provided, instead of complete user objects, the default value is False."
},
{
"code": null,
"e": 25260,
"s": 25212,
"text": "Returns : a list of objects of the class Status"
},
{
"code": null,
"e": 25272,
"s": 25260,
"text": "Example 1 :"
},
{
"code": "# import the moduleimport tweepy # assign the values accordinglyconsumer_key = \"\"consumer_secret = \"\"access_token = \"\"access_token_secret = \"\" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # list of status IDs to be fetched id_ = [1266978261701210112, 1266735261012111360, 1266342841648898049] # fetching the statusesstatuses = api.statuses_lookup(id_) # printing the statusesfor status in statuses: print(\"The status \" + str(status.id) + \" is posted by \" + status.user.screen_name) print(\"This status says : \\n\\n\" + status.text, end = \"\\n\\n\")",
"e": 26042,
"s": 25272,
"text": null
},
{
"code": null,
"e": 26051,
"s": 26042,
"text": "Output :"
},
{
"code": null,
"e": 26713,
"s": 26051,
"text": "The status 1266978261701210112 is posted by geeksforgeeks\nThis status says : \n\nAvoid errors, not client calls\n.\nGeeks, Keep this going...\n.\n#sundayvibes #programming #programmingmemes #coding https://t.co/JkA5iStofZ\n\nThe status 1266735261012111360 is posted by geeksforgeeks\nThis status says : \n\nWith the access to our Job Portal, find the jobs that are best for you & experience happy placement journey....\n.\nL... https://t.co/mzMMFVzjMv\n\nThe status 1266342841648898049 is posted by geeksforgeeks\nThis status says : \n\nMy reaction to this Lockdown : \n\n\"Der Lagi Lekin... Maine Ab Hai Jeena Seekh Liya\" \n\nWhat's your reaction to it?\n.... https://t.co/nH9L0eewSr\n"
},
{
"code": null,
"e": 26789,
"s": 26713,
"text": "Example 2: Using the statuses_lookup() method with the trim_user parameter."
},
{
"code": "# list of status IDs to be fetched id_ = [1266978261701210112, 1266735261012111360, 1266342841648898049] # fetching the statusesstatuses = api.statuses_lookup(id_, trim_user = True) # printing the statusesfor status in statuses: print(status.user.id)",
"e": 27045,
"s": 26789,
"text": null
},
{
"code": null,
"e": 27054,
"s": 27045,
"text": "Output :"
},
{
"code": null,
"e": 27082,
"s": 27054,
"text": "57741058\n57741058\n57741058\n"
},
{
"code": null,
"e": 27096,
"s": 27082,
"text": "Python-Tweepy"
},
{
"code": null,
"e": 27103,
"s": 27096,
"text": "Python"
},
{
"code": null,
"e": 27201,
"s": 27103,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27210,
"s": 27201,
"text": "Comments"
},
{
"code": null,
"e": 27223,
"s": 27210,
"text": "Old Comments"
},
{
"code": null,
"e": 27241,
"s": 27223,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27276,
"s": 27241,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27298,
"s": 27276,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27330,
"s": 27298,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27372,
"s": 27330,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27398,
"s": 27372,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27435,
"s": 27398,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27479,
"s": 27435,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27504,
"s": 27479,
"text": "sum() function in Python"
}
] |
Spark Join Strategies — How & What? | by Jyoti Dhiman | Towards Data Science
|
While dealing with data, we have all dealt with different kinds of joins, be it inner, outer, left or (maybe)left-semi. This article covers the different join strategies employed by Spark to perform the join operation. Knowing spark join internals comes in handy to optimize tricky join operations, in finding root cause of some out of memory errors, and for improved performance of spark jobs(we all want that, don’t we?). Please read on to find out.
Before beginning the Broadcast Hash join spark, let’s first understand Hash Join, in general:
As the name suggests, Hash Join is performed by first creating a Hash Table based on join_key of smaller relation and then looping over larger relation to match the hashed join_key values. Also, this is only supported for ‘=’ join.
In spark, Hash Join plays a role at per node level and the strategy is used to join partitions available on the node.
Now, coming to Broadcast Hash Join.
In broadcast hash join, copy of one of the join relations are being sent to all the worker nodes and it saves shuffling cost. This is useful when you are joining a large relation with a smaller one. It is also known as map-side join(associating worker nodes with mappers).
Spark deploys this join strategy when the size of one of the join relations is less than the threshold values(default 10 M). The spark property which defines this threshold is spark.sql.autoBroadcastJoinThreshold(configurable).
Broadcast relations are shared among executors using the BitTorrent protocol(read more here). It is a peer to peer protocol in which block of files can be shared by peers amongst each other. Hence, they don’t need to rely on a single node. This is how peer to peer protocol works:
Things to Note:
The broadcasted relation should fit completely into the memory of each executor as well as the driver. In Driver, because driver will start the data transfer.
Only supported for ‘=’ join.
Supported for all join types(inner, left, right) except full outer joins.
When the broadcast size is small, it is usually faster than other join strategies.
Copy of relation is broadcasted over the network. Therefore, being a network-intensive operation could cause out of memory errors or performance issues when broadcast size is big(for instance, when explicitly specified to use broadcast join/changes in the default threshold).
You can’t make changes to the broadcasted relation, after broadcast. Even if you do, they won’t be available to the worker nodes(because the copy is already shipped).
Shuffle Hash Join involves moving data with the same value of join key in the same executor node followed by Hash Join(explained above). Using the join condition as output key, data is shuffled amongst executor nodes and in the last step, data is combined using Hash Join, as we know data of the same key will be present in the same executor.
Things to Note:
Only supported for ‘=’ join.
The join keys don’t need to be sortable(this will make sense below).
Supported for all join types except full outer joins.
In my opinion, it’s an expensive join in a way that involves both shuffling and hashing(Hash Join as explained above). Maintaining a hash table requires memory and computation.
Let’s first understand Sort-Merge Join
Sort join involves, first sorting the relations based on join keys and then merging both the datasets(think of merge step of merge sort).
Now, let’s understand shuffle sort-merge join strategy in spark:
Shuffle sort-merge join involves, shuffling of data to get the same join_key with the same worker, and then performing sort-merge join operation at the partition level in the worker nodes.
Things to Note:
Since spark 2.3, this is the default join strategy in spark and can be disabled with spark.sql.join.preferSortMergeJoin.
Only supported for ‘=’ join.
The join keys need to be sortable(obviously).
Supported for all join types.
In this strategy, the cartesian product(similar to SQL) of the two relations is calculated to evaluate join.
Think of this as a nested loop comparison of both the relations:
for record_1 in relation_1: for record_2 in relation_2: # join condition is executed
As you can see, this can be a very slow strategy. This is generally, a fallback option when no other join type can be applied. Spark handles this using BroadcastNestedLoopJoinExec operator that broadcasts the appropriate side of the query, so you can think that at least some chunk of results will be broadcasted to improve performance.
Things to note:
Supports both ‘=’ and non-equi-joins(‘≤=’, ‘<’ etc.).
Supports all the join types
Taken directly from spark code, let’s see how spark decides on join strategy.
If it is an ‘=’ join:
Look at the join hints, in the following order:1. Broadcast Hint: Pick broadcast hash join if the join type is supported.2. Sort merge hint: Pick sort-merge join if join keys are sortable.3. shuffle hash hint: Pick shuffle hash join if the join type is supported.4. shuffle replicate NL hint: pick cartesian product if join type is inner like.
If there is no hint or the hints are not applicable1. Pick broadcast hash join if one side is small enough to broadcast, and the join type is supported. 2. Pick shuffle hash join if one side is small enough to build the local hash map, and is much smaller than the other side, and spark.sql.join.preferSortMergeJoin is false.3. Pick sort-merge join if join keys are sortable.4. Pick cartesian product if join type is inner . 5. Pick broadcast nested loop join as the final solution. It may OOM but there is no other choice.
If it’s not ‘=’ join:
Look at the join hints, in the following order:1. broadcast hint: pick broadcast nested loop join. 2. shuffle replicate NL hint: pick cartesian product if join type is inner like.
If there is no hint or the hints are not applicable1. Pick broadcast nested loop join if one side is small enough to broadcast. 2. Pick cartesian product if join type is inner like. 3. Pick broadcast nested loop join as the final solution. It may OOM but we don’t have any other choice.
|
[
{
"code": null,
"e": 624,
"s": 172,
"text": "While dealing with data, we have all dealt with different kinds of joins, be it inner, outer, left or (maybe)left-semi. This article covers the different join strategies employed by Spark to perform the join operation. Knowing spark join internals comes in handy to optimize tricky join operations, in finding root cause of some out of memory errors, and for improved performance of spark jobs(we all want that, don’t we?). Please read on to find out."
},
{
"code": null,
"e": 718,
"s": 624,
"text": "Before beginning the Broadcast Hash join spark, let’s first understand Hash Join, in general:"
},
{
"code": null,
"e": 950,
"s": 718,
"text": "As the name suggests, Hash Join is performed by first creating a Hash Table based on join_key of smaller relation and then looping over larger relation to match the hashed join_key values. Also, this is only supported for ‘=’ join."
},
{
"code": null,
"e": 1068,
"s": 950,
"text": "In spark, Hash Join plays a role at per node level and the strategy is used to join partitions available on the node."
},
{
"code": null,
"e": 1104,
"s": 1068,
"text": "Now, coming to Broadcast Hash Join."
},
{
"code": null,
"e": 1377,
"s": 1104,
"text": "In broadcast hash join, copy of one of the join relations are being sent to all the worker nodes and it saves shuffling cost. This is useful when you are joining a large relation with a smaller one. It is also known as map-side join(associating worker nodes with mappers)."
},
{
"code": null,
"e": 1605,
"s": 1377,
"text": "Spark deploys this join strategy when the size of one of the join relations is less than the threshold values(default 10 M). The spark property which defines this threshold is spark.sql.autoBroadcastJoinThreshold(configurable)."
},
{
"code": null,
"e": 1886,
"s": 1605,
"text": "Broadcast relations are shared among executors using the BitTorrent protocol(read more here). It is a peer to peer protocol in which block of files can be shared by peers amongst each other. Hence, they don’t need to rely on a single node. This is how peer to peer protocol works:"
},
{
"code": null,
"e": 1902,
"s": 1886,
"text": "Things to Note:"
},
{
"code": null,
"e": 2061,
"s": 1902,
"text": "The broadcasted relation should fit completely into the memory of each executor as well as the driver. In Driver, because driver will start the data transfer."
},
{
"code": null,
"e": 2090,
"s": 2061,
"text": "Only supported for ‘=’ join."
},
{
"code": null,
"e": 2164,
"s": 2090,
"text": "Supported for all join types(inner, left, right) except full outer joins."
},
{
"code": null,
"e": 2247,
"s": 2164,
"text": "When the broadcast size is small, it is usually faster than other join strategies."
},
{
"code": null,
"e": 2523,
"s": 2247,
"text": "Copy of relation is broadcasted over the network. Therefore, being a network-intensive operation could cause out of memory errors or performance issues when broadcast size is big(for instance, when explicitly specified to use broadcast join/changes in the default threshold)."
},
{
"code": null,
"e": 2690,
"s": 2523,
"text": "You can’t make changes to the broadcasted relation, after broadcast. Even if you do, they won’t be available to the worker nodes(because the copy is already shipped)."
},
{
"code": null,
"e": 3033,
"s": 2690,
"text": "Shuffle Hash Join involves moving data with the same value of join key in the same executor node followed by Hash Join(explained above). Using the join condition as output key, data is shuffled amongst executor nodes and in the last step, data is combined using Hash Join, as we know data of the same key will be present in the same executor."
},
{
"code": null,
"e": 3049,
"s": 3033,
"text": "Things to Note:"
},
{
"code": null,
"e": 3078,
"s": 3049,
"text": "Only supported for ‘=’ join."
},
{
"code": null,
"e": 3147,
"s": 3078,
"text": "The join keys don’t need to be sortable(this will make sense below)."
},
{
"code": null,
"e": 3201,
"s": 3147,
"text": "Supported for all join types except full outer joins."
},
{
"code": null,
"e": 3378,
"s": 3201,
"text": "In my opinion, it’s an expensive join in a way that involves both shuffling and hashing(Hash Join as explained above). Maintaining a hash table requires memory and computation."
},
{
"code": null,
"e": 3417,
"s": 3378,
"text": "Let’s first understand Sort-Merge Join"
},
{
"code": null,
"e": 3555,
"s": 3417,
"text": "Sort join involves, first sorting the relations based on join keys and then merging both the datasets(think of merge step of merge sort)."
},
{
"code": null,
"e": 3620,
"s": 3555,
"text": "Now, let’s understand shuffle sort-merge join strategy in spark:"
},
{
"code": null,
"e": 3809,
"s": 3620,
"text": "Shuffle sort-merge join involves, shuffling of data to get the same join_key with the same worker, and then performing sort-merge join operation at the partition level in the worker nodes."
},
{
"code": null,
"e": 3825,
"s": 3809,
"text": "Things to Note:"
},
{
"code": null,
"e": 3946,
"s": 3825,
"text": "Since spark 2.3, this is the default join strategy in spark and can be disabled with spark.sql.join.preferSortMergeJoin."
},
{
"code": null,
"e": 3975,
"s": 3946,
"text": "Only supported for ‘=’ join."
},
{
"code": null,
"e": 4021,
"s": 3975,
"text": "The join keys need to be sortable(obviously)."
},
{
"code": null,
"e": 4051,
"s": 4021,
"text": "Supported for all join types."
},
{
"code": null,
"e": 4160,
"s": 4051,
"text": "In this strategy, the cartesian product(similar to SQL) of the two relations is calculated to evaluate join."
},
{
"code": null,
"e": 4225,
"s": 4160,
"text": "Think of this as a nested loop comparison of both the relations:"
},
{
"code": null,
"e": 4314,
"s": 4225,
"text": "for record_1 in relation_1: for record_2 in relation_2: # join condition is executed"
},
{
"code": null,
"e": 4651,
"s": 4314,
"text": "As you can see, this can be a very slow strategy. This is generally, a fallback option when no other join type can be applied. Spark handles this using BroadcastNestedLoopJoinExec operator that broadcasts the appropriate side of the query, so you can think that at least some chunk of results will be broadcasted to improve performance."
},
{
"code": null,
"e": 4667,
"s": 4651,
"text": "Things to note:"
},
{
"code": null,
"e": 4721,
"s": 4667,
"text": "Supports both ‘=’ and non-equi-joins(‘≤=’, ‘<’ etc.)."
},
{
"code": null,
"e": 4749,
"s": 4721,
"text": "Supports all the join types"
},
{
"code": null,
"e": 4827,
"s": 4749,
"text": "Taken directly from spark code, let’s see how spark decides on join strategy."
},
{
"code": null,
"e": 4849,
"s": 4827,
"text": "If it is an ‘=’ join:"
},
{
"code": null,
"e": 5193,
"s": 4849,
"text": "Look at the join hints, in the following order:1. Broadcast Hint: Pick broadcast hash join if the join type is supported.2. Sort merge hint: Pick sort-merge join if join keys are sortable.3. shuffle hash hint: Pick shuffle hash join if the join type is supported.4. shuffle replicate NL hint: pick cartesian product if join type is inner like."
},
{
"code": null,
"e": 5717,
"s": 5193,
"text": "If there is no hint or the hints are not applicable1. Pick broadcast hash join if one side is small enough to broadcast, and the join type is supported. 2. Pick shuffle hash join if one side is small enough to build the local hash map, and is much smaller than the other side, and spark.sql.join.preferSortMergeJoin is false.3. Pick sort-merge join if join keys are sortable.4. Pick cartesian product if join type is inner . 5. Pick broadcast nested loop join as the final solution. It may OOM but there is no other choice."
},
{
"code": null,
"e": 5739,
"s": 5717,
"text": "If it’s not ‘=’ join:"
},
{
"code": null,
"e": 5919,
"s": 5739,
"text": "Look at the join hints, in the following order:1. broadcast hint: pick broadcast nested loop join. 2. shuffle replicate NL hint: pick cartesian product if join type is inner like."
}
] |
BeautifulSoup - Find all <li> in <ul> - GeeksforGeeks
|
15 Mar, 2021
Prerequisites: Beautifulsoup
Beautifulsoup is a Python module used for web scraping. In this article, we will discuss how contents of <li> tags can be retrieved from <ul> using Beautifulsoup.
bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files.
requests: Requests allow you to send HTTP/1.1 requests extremely easily. This module also does not comes built-in with Python.
Import the modules
Provide an URL that has ul and li tags
Make the requests
Create the beautifulsoup object
Find the required tags
Retrieve the contents under li
Below the code, the HTML snippet contains a body with ul and li tags that have been obtained by the beautifulsoup object.
In this method, we use the descendants attribute present in beautifulsoup which basically returns a list iterator object having all the descendants/children of the parent tag, here parent is <ul> tag.
First, import the required modules, then provide the URL and create its requests object that will be parsed by the beautifulsoup object. Now with the help of find() function in beautifulsoup we will find the <body> and its corresponding <ul> tags. After this, the descendants attribute will give us the list iterator object which is needed to convert back into list. This list has a next line item, the tags with text, and finally the only text. So, we will print every second successive element of the list.
Example:
Python3
# importing the modulesimport requestsfrom bs4 import BeautifulSoup # providing urlurl = "https://auth.geeksforgeeks.org/user/adityaprasad1308/articles" # creating requests objecthtml = requests.get(url).content # creating soup objectdata = BeautifulSoup(html, 'html.parser') # finding parent <ul> tagparent = data.find("body").find("ul") # finding all <li> tagstext = list(parent.descendants) # printing the content in <li> tagprint(text)for i in range(2, len(text), 2): print(text[i], end=" ")
Output:
Approach is same as the above example, but instead of finding the body we will find ul tags and then find all the li tags with the help of find_all() function which takes the tag name as an argument and returns all the li tags. After this we will simply iterate over all the <li> tags and with the help of text attribute we will print the text present in the <li> tag.
Example:
Python3
# importing the modulesimport requestsfrom bs4 import BeautifulSoup # providing urlurl = 'https://auth.geeksforgeeks.org/user/adityaprasad1308/articles' # creating request objectreq = requests.get(url) # creating soup objectdata = BeautifulSoup(req.text, 'html') # finding all li tags in ul and printing the text within itdata1 = data.find('ul')for li in data1.find_all("li"): print(li.text, end=" ")
Output:
Picked
Python BeautifulSoup
Python bs4-Exercises
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24886,
"s": 24858,
"text": "\n15 Mar, 2021"
},
{
"code": null,
"e": 24915,
"s": 24886,
"text": "Prerequisites: Beautifulsoup"
},
{
"code": null,
"e": 25079,
"s": 24915,
"text": "Beautifulsoup is a Python module used for web scraping. In this article, we will discuss how contents of <li> tags can be retrieved from <ul> using Beautifulsoup. "
},
{
"code": null,
"e": 25169,
"s": 25079,
"text": "bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files."
},
{
"code": null,
"e": 25296,
"s": 25169,
"text": "requests: Requests allow you to send HTTP/1.1 requests extremely easily. This module also does not comes built-in with Python."
},
{
"code": null,
"e": 25315,
"s": 25296,
"text": "Import the modules"
},
{
"code": null,
"e": 25354,
"s": 25315,
"text": "Provide an URL that has ul and li tags"
},
{
"code": null,
"e": 25372,
"s": 25354,
"text": "Make the requests"
},
{
"code": null,
"e": 25404,
"s": 25372,
"text": "Create the beautifulsoup object"
},
{
"code": null,
"e": 25427,
"s": 25404,
"text": "Find the required tags"
},
{
"code": null,
"e": 25458,
"s": 25427,
"text": "Retrieve the contents under li"
},
{
"code": null,
"e": 25580,
"s": 25458,
"text": "Below the code, the HTML snippet contains a body with ul and li tags that have been obtained by the beautifulsoup object."
},
{
"code": null,
"e": 25781,
"s": 25580,
"text": "In this method, we use the descendants attribute present in beautifulsoup which basically returns a list iterator object having all the descendants/children of the parent tag, here parent is <ul> tag."
},
{
"code": null,
"e": 26290,
"s": 25781,
"text": "First, import the required modules, then provide the URL and create its requests object that will be parsed by the beautifulsoup object. Now with the help of find() function in beautifulsoup we will find the <body> and its corresponding <ul> tags. After this, the descendants attribute will give us the list iterator object which is needed to convert back into list. This list has a next line item, the tags with text, and finally the only text. So, we will print every second successive element of the list."
},
{
"code": null,
"e": 26299,
"s": 26290,
"text": "Example:"
},
{
"code": null,
"e": 26307,
"s": 26299,
"text": "Python3"
},
{
"code": "# importing the modulesimport requestsfrom bs4 import BeautifulSoup # providing urlurl = \"https://auth.geeksforgeeks.org/user/adityaprasad1308/articles\" # creating requests objecthtml = requests.get(url).content # creating soup objectdata = BeautifulSoup(html, 'html.parser') # finding parent <ul> tagparent = data.find(\"body\").find(\"ul\") # finding all <li> tagstext = list(parent.descendants) # printing the content in <li> tagprint(text)for i in range(2, len(text), 2): print(text[i], end=\" \")",
"e": 26812,
"s": 26307,
"text": null
},
{
"code": null,
"e": 26820,
"s": 26812,
"text": "Output:"
},
{
"code": null,
"e": 27189,
"s": 26820,
"text": "Approach is same as the above example, but instead of finding the body we will find ul tags and then find all the li tags with the help of find_all() function which takes the tag name as an argument and returns all the li tags. After this we will simply iterate over all the <li> tags and with the help of text attribute we will print the text present in the <li> tag."
},
{
"code": null,
"e": 27198,
"s": 27189,
"text": "Example:"
},
{
"code": null,
"e": 27206,
"s": 27198,
"text": "Python3"
},
{
"code": "# importing the modulesimport requestsfrom bs4 import BeautifulSoup # providing urlurl = 'https://auth.geeksforgeeks.org/user/adityaprasad1308/articles' # creating request objectreq = requests.get(url) # creating soup objectdata = BeautifulSoup(req.text, 'html') # finding all li tags in ul and printing the text within itdata1 = data.find('ul')for li in data1.find_all(\"li\"): print(li.text, end=\" \")",
"e": 27614,
"s": 27206,
"text": null
},
{
"code": null,
"e": 27622,
"s": 27614,
"text": "Output:"
},
{
"code": null,
"e": 27629,
"s": 27622,
"text": "Picked"
},
{
"code": null,
"e": 27650,
"s": 27629,
"text": "Python BeautifulSoup"
},
{
"code": null,
"e": 27671,
"s": 27650,
"text": "Python bs4-Exercises"
},
{
"code": null,
"e": 27678,
"s": 27671,
"text": "Python"
},
{
"code": null,
"e": 27776,
"s": 27678,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27785,
"s": 27776,
"text": "Comments"
},
{
"code": null,
"e": 27798,
"s": 27785,
"text": "Old Comments"
},
{
"code": null,
"e": 27816,
"s": 27798,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27851,
"s": 27816,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27883,
"s": 27851,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27905,
"s": 27883,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27935,
"s": 27905,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27977,
"s": 27935,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28003,
"s": 27977,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28046,
"s": 28003,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28083,
"s": 28046,
"text": "Create a Pandas DataFrame from Lists"
}
] |
How to draw circle in HTML page?
|
To draw a circle in HTML page, use SVG or canvas. You can also draw it using CSS, with the border-radius property.
You can try to run the following code to learn how to draw a circle in HTML
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
#circle {
width: 50px;
height: 50px;
-webkit-border-radius: 25px;
-moz-border-radius: 25px;
border-radius: 25px;
background: blue;
}
</style>
<head>
<body>
<div id="circle"></div>
</body>
</html>
|
[
{
"code": null,
"e": 1177,
"s": 1062,
"text": "To draw a circle in HTML page, use SVG or canvas. You can also draw it using CSS, with the border-radius property."
},
{
"code": null,
"e": 1253,
"s": 1177,
"text": "You can try to run the following code to learn how to draw a circle in HTML"
},
{
"code": null,
"e": 1263,
"s": 1253,
"text": "Live Demo"
},
{
"code": null,
"e": 1617,
"s": 1263,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n #circle {\n width: 50px;\n height: 50px;\n -webkit-border-radius: 25px;\n -moz-border-radius: 25px;\n border-radius: 25px;\n background: blue;\n }\n </style>\n <head>\n <body>\n <div id=\"circle\"></div>\n </body>\n</html>"
}
] |
Creating COVID-19 Folium map | Towards Data Science
|
All of the code shown in this article are available in my GitHub repo here.
There are many ways to create an interactive map, but my favorite way to creating it is via Folium; a map visualization library based on the Python language.
In this article, I want to show how to create a nice interactive map and with current condition right now (4 April 2020); the best data to represent the condition would be the number of COVID-19 confirmed cases in the world. Let’s get into it.
For you who did not know what Folium is; it basically a map visualization library that has many built-in specific just for creating an interactive map. We could install the Folium library by using the command below.
#Installation via pippip install folium#or, installation via condaconda install folium -c conda-forge
Just like that we already have our library installed. Now, let’s try to show a simple interactive map (or base map).
import folium#Creating a base mapm = folium.Map()m
Now we already have our base map. In this case, I want to create a world map which shown a colored country section (this is basically what we called a choropleth map) of the COVID-19 confirmed case as of today (3 April 2020).
To do that, we need to actually have the data first. Luckily, there are many existing API now that provide this data. In my case, I would use the API from thevirustracker.com. Let’s try to pull some data from the API. Here are the steps to pull data from the API.
#We would use the requests module to pull the data from APIimport requests#Pulling the Worldwide COVID-19 data, we use the get function from requests module with API endpoint(Basically a URL address to request your data) as the function parameter. To know available endpoint, check the API documentationres = requests.get('https://api.thevirustracker.com/free-api?countryTotals=ALL')#We turn the data into json. It would become dictionary in the Python.covid_current = res.json()
In the data above, we could see that there are much data available but in this case, I would only take the data for the Country (‘title’) and the Total case (‘total_cases’).
#Creating the COVID-19 DataFramedf = []for j in range(1,len(covid_current['countryitems'][0])): df.append([covid_current['countryitems'][0]['{}'.format(j)] ['title'], covid_current['countryitems'][0]['{}'.format(j)]['total_cases']])df_covid = pd.DataFrame(df, columns = ['Country', 'Total Case'])
For the last data, we also need a GeoJSON data of the countries in the world. GeoJSON data is a data format representing the geographical feature, such as the country border. For our case, Folium already possessing this GeoJSON data that we could use.
#Setting up the world countries data URLurl = 'https://raw.githubusercontent.com/python-visualization/folium/master/examples/data'country_shapes = f'{url}/world-countries.json'
I would clean the COVID-19 data as well because, in my next step, I would use this world country data provided by Folium on the map. In that case, I need my country name in the COVID-19 dataset to following the country name provided by Folium.
#Replacing the country namedf_covid.replace('USA', "United States of America", inplace = True)df_covid.replace('Tanzania', "United Republic of Tanzania", inplace = True)df_covid.replace('Democratic Republic of Congo', "Democratic Republic of the Congo", inplace = True)df_covid.replace('Congo', "Republic of the Congo", inplace = True)df_covid.replace('Lao', "Laos", inplace = True)df_covid.replace('Syrian Arab Republic', "Syria", inplace = True)df_covid.replace('Serbia', "Republic of Serbia", inplace = True)df_covid.replace('Czechia', "Czech Republic", inplace = True)df_covid.replace('UAE', "United Arab Emirates", inplace = True)
Now we have the data to create the COVID-19 confirmed case choropleth map using the Folium. In the next step, we just need to add the choropleth layer into our base map.
#Adding the Choropleth layer onto our base mapfolium.Choropleth( #The GeoJSON data to represent the world country geo_data=country_shapes, name='choropleth COVID-19', data=df_covid, #The column aceppting list with 2 value; The country name and the numerical value columns=['Country', 'Total Case'], key_on='feature.properties.name', fill_color='PuRd', nan_fill_color='white').add_to(m)m
Just like that, we already have a simple map representing the confirmed case of COVID-19 in the world. As we can see, the United State of America as per 3 April 2020 are colored the darkest. This is because of the number of cases there are the highest right now. Some countries like Italia, China, Spain, Italy are also colored slightly darker than the other because they have the highest number of confirmed cases after the USA.
As an addition, I would add a clickable marker to show the country name. In this case, we would need the latitude and longitude of each country which is available in this csv file.
for lat, lon, name in zip(country['latitude'],country['longitude'],country['name']): #Creating the marker folium.Marker( #Coordinate of the country location=[lat, lon], #The popup that show up if click the marker popup=name ).add_to(m)m
Here we are. We just create a simple interactive map from the COVID-19 confirmed case. There are still many things we could visualize such as the recovered cases, death cases, percentage, and many more.
Creating a simple interactive map is made easy by the Folium library, what we need is just the data which right now could be pulled via API. Choropleth is one of the maps that suitable to visualize the COVID-19 confirmed case in the world.
I hope it helps!
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.
If you are not subscribed as a Medium Member, please consider subscribing through my referral.
|
[
{
"code": null,
"e": 247,
"s": 171,
"text": "All of the code shown in this article are available in my GitHub repo here."
},
{
"code": null,
"e": 405,
"s": 247,
"text": "There are many ways to create an interactive map, but my favorite way to creating it is via Folium; a map visualization library based on the Python language."
},
{
"code": null,
"e": 649,
"s": 405,
"text": "In this article, I want to show how to create a nice interactive map and with current condition right now (4 April 2020); the best data to represent the condition would be the number of COVID-19 confirmed cases in the world. Let’s get into it."
},
{
"code": null,
"e": 865,
"s": 649,
"text": "For you who did not know what Folium is; it basically a map visualization library that has many built-in specific just for creating an interactive map. We could install the Folium library by using the command below."
},
{
"code": null,
"e": 967,
"s": 865,
"text": "#Installation via pippip install folium#or, installation via condaconda install folium -c conda-forge"
},
{
"code": null,
"e": 1084,
"s": 967,
"text": "Just like that we already have our library installed. Now, let’s try to show a simple interactive map (or base map)."
},
{
"code": null,
"e": 1135,
"s": 1084,
"text": "import folium#Creating a base mapm = folium.Map()m"
},
{
"code": null,
"e": 1361,
"s": 1135,
"text": "Now we already have our base map. In this case, I want to create a world map which shown a colored country section (this is basically what we called a choropleth map) of the COVID-19 confirmed case as of today (3 April 2020)."
},
{
"code": null,
"e": 1625,
"s": 1361,
"text": "To do that, we need to actually have the data first. Luckily, there are many existing API now that provide this data. In my case, I would use the API from thevirustracker.com. Let’s try to pull some data from the API. Here are the steps to pull data from the API."
},
{
"code": null,
"e": 2105,
"s": 1625,
"text": "#We would use the requests module to pull the data from APIimport requests#Pulling the Worldwide COVID-19 data, we use the get function from requests module with API endpoint(Basically a URL address to request your data) as the function parameter. To know available endpoint, check the API documentationres = requests.get('https://api.thevirustracker.com/free-api?countryTotals=ALL')#We turn the data into json. It would become dictionary in the Python.covid_current = res.json()"
},
{
"code": null,
"e": 2279,
"s": 2105,
"text": "In the data above, we could see that there are much data available but in this case, I would only take the data for the Country (‘title’) and the Total case (‘total_cases’)."
},
{
"code": null,
"e": 2588,
"s": 2279,
"text": "#Creating the COVID-19 DataFramedf = []for j in range(1,len(covid_current['countryitems'][0])): df.append([covid_current['countryitems'][0]['{}'.format(j)] ['title'], covid_current['countryitems'][0]['{}'.format(j)]['total_cases']])df_covid = pd.DataFrame(df, columns = ['Country', 'Total Case'])"
},
{
"code": null,
"e": 2840,
"s": 2588,
"text": "For the last data, we also need a GeoJSON data of the countries in the world. GeoJSON data is a data format representing the geographical feature, such as the country border. For our case, Folium already possessing this GeoJSON data that we could use."
},
{
"code": null,
"e": 3017,
"s": 2840,
"text": "#Setting up the world countries data URLurl = 'https://raw.githubusercontent.com/python-visualization/folium/master/examples/data'country_shapes = f'{url}/world-countries.json'"
},
{
"code": null,
"e": 3261,
"s": 3017,
"text": "I would clean the COVID-19 data as well because, in my next step, I would use this world country data provided by Folium on the map. In that case, I need my country name in the COVID-19 dataset to following the country name provided by Folium."
},
{
"code": null,
"e": 3897,
"s": 3261,
"text": "#Replacing the country namedf_covid.replace('USA', \"United States of America\", inplace = True)df_covid.replace('Tanzania', \"United Republic of Tanzania\", inplace = True)df_covid.replace('Democratic Republic of Congo', \"Democratic Republic of the Congo\", inplace = True)df_covid.replace('Congo', \"Republic of the Congo\", inplace = True)df_covid.replace('Lao', \"Laos\", inplace = True)df_covid.replace('Syrian Arab Republic', \"Syria\", inplace = True)df_covid.replace('Serbia', \"Republic of Serbia\", inplace = True)df_covid.replace('Czechia', \"Czech Republic\", inplace = True)df_covid.replace('UAE', \"United Arab Emirates\", inplace = True)"
},
{
"code": null,
"e": 4067,
"s": 3897,
"text": "Now we have the data to create the COVID-19 confirmed case choropleth map using the Folium. In the next step, we just need to add the choropleth layer into our base map."
},
{
"code": null,
"e": 4482,
"s": 4067,
"text": "#Adding the Choropleth layer onto our base mapfolium.Choropleth( #The GeoJSON data to represent the world country geo_data=country_shapes, name='choropleth COVID-19', data=df_covid, #The column aceppting list with 2 value; The country name and the numerical value columns=['Country', 'Total Case'], key_on='feature.properties.name', fill_color='PuRd', nan_fill_color='white').add_to(m)m"
},
{
"code": null,
"e": 4912,
"s": 4482,
"text": "Just like that, we already have a simple map representing the confirmed case of COVID-19 in the world. As we can see, the United State of America as per 3 April 2020 are colored the darkest. This is because of the number of cases there are the highest right now. Some countries like Italia, China, Spain, Italy are also colored slightly darker than the other because they have the highest number of confirmed cases after the USA."
},
{
"code": null,
"e": 5093,
"s": 4912,
"text": "As an addition, I would add a clickable marker to show the country name. In this case, we would need the latitude and longitude of each country which is available in this csv file."
},
{
"code": null,
"e": 5353,
"s": 5093,
"text": "for lat, lon, name in zip(country['latitude'],country['longitude'],country['name']): #Creating the marker folium.Marker( #Coordinate of the country location=[lat, lon], #The popup that show up if click the marker popup=name ).add_to(m)m"
},
{
"code": null,
"e": 5556,
"s": 5353,
"text": "Here we are. We just create a simple interactive map from the COVID-19 confirmed case. There are still many things we could visualize such as the recovered cases, death cases, percentage, and many more."
},
{
"code": null,
"e": 5796,
"s": 5556,
"text": "Creating a simple interactive map is made easy by the Folium library, what we need is just the data which right now could be pulled via API. Choropleth is one of the maps that suitable to visualize the COVID-19 confirmed case in the world."
},
{
"code": null,
"e": 5813,
"s": 5796,
"text": "I hope it helps!"
},
{
"code": null,
"e": 6149,
"s": 5813,
"text": "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."
}
] |
queue::push() and queue::pop() in C++ STL
|
In this article we will be discussing the working, syntax and examples of queue::push() and queue::pop() functions in C++ STL.
Queue is a simple sequence or data structure defined in the C++ STL which does insertion and deletion of the data in FIFO(First In First Out) fashion. The data in a queue is stored in continuous manner. The elements are inserted at the end and removed from the starting of the queue. In C++ STL there is already a predefined template of queue, which inserts and removes the data in the similar fashion of a queue.
queue::push() is an inbuilt function in C++ STL which is declared in header file. queue::push() is used to push or insert a new element at the end or at the back of the queue container. push() accepts one parameter, that is the element which we want to push/insert in the associated queue container, also this function increases the size of container by 1.
This function further calls push_back() which helps in easy insertion of the element at the back of the queue.
myqueue.push(type_t& value);
This function accepts one parameter the value which is of type_t that is the type of elements in the queue container.
This function returns nothing.
Input: queue<int> myqueue = {10, 20 30, 40};
myqueue.push(23);
Output:
Elements in the queue are= 10 20 30 40 23
Live Demo
#include <iostream>
#include <queue>
using namespace std;
int main(){
queue<int> Queue;
for(int i=0 ;i<=5 ;i++){
Queue.push(i);
}
cout<<"Elements in queue are : ";
while (!Queue.empty()){
cout << ' ' << Queue.front();
Queue.pop();
}
}
If we run the above code it will generate the following output −
Elements in queue are : 0 1 2 3 4 5
queue::pop() is an inbuilt function in C++ STL which is declared in header file. queue::pop() is used to push or delete an existing element from the beginning or start of the queue container. pop() accepts no parameter, and deletes the element from the beginning of the queue associated with the function and reduces the size of the queue container by 1.
myqueue.pop();
This function accepts no parameters
This function returns nothing.
Input: queue myqueue = {10, 20, 30, 40};
myqueue.pop();
Output:
Elements in the queue are= 20 30 40
Live Demo
#include <iostream>
#include <queue>
using namespace std;
int main(){
queue<int> Queue;
for(int i=0 ;i<=5 ;i++){
Queue.push(i);
}
for(int i=0 ;i<5 ;i++){
Queue.pop();
}
cout<<"Element left in queue is : ";
while (!Queue.empty()){
cout << ' ' << Queue.front();
Queue.pop();
}
}
If we run the above code it will generate the following output −
Element left in queue is : 5
|
[
{
"code": null,
"e": 1189,
"s": 1062,
"text": "In this article we will be discussing the working, syntax and examples of queue::push() and queue::pop() functions in C++ STL."
},
{
"code": null,
"e": 1603,
"s": 1189,
"text": "Queue is a simple sequence or data structure defined in the C++ STL which does insertion and deletion of the data in FIFO(First In First Out) fashion. The data in a queue is stored in continuous manner. The elements are inserted at the end and removed from the starting of the queue. In C++ STL there is already a predefined template of queue, which inserts and removes the data in the similar fashion of a queue."
},
{
"code": null,
"e": 1961,
"s": 1603,
"text": "queue::push() is an inbuilt function in C++ STL which is declared in header file. queue::push() is used to push or insert a new element at the end or at the back of the queue container. push() accepts one parameter, that is the element which we want to push/insert in the associated queue container, also this function increases the size of container by 1."
},
{
"code": null,
"e": 2072,
"s": 1961,
"text": "This function further calls push_back() which helps in easy insertion of the element at the back of the queue."
},
{
"code": null,
"e": 2101,
"s": 2072,
"text": "myqueue.push(type_t& value);"
},
{
"code": null,
"e": 2219,
"s": 2101,
"text": "This function accepts one parameter the value which is of type_t that is the type of elements in the queue container."
},
{
"code": null,
"e": 2250,
"s": 2219,
"text": "This function returns nothing."
},
{
"code": null,
"e": 2375,
"s": 2250,
"text": "Input: queue<int> myqueue = {10, 20 30, 40};\n myqueue.push(23);\nOutput:\n Elements in the queue are= 10 20 30 40 23"
},
{
"code": null,
"e": 2386,
"s": 2375,
"text": " Live Demo"
},
{
"code": null,
"e": 2660,
"s": 2386,
"text": "#include <iostream>\n#include <queue>\nusing namespace std;\nint main(){\n queue<int> Queue;\n for(int i=0 ;i<=5 ;i++){\n Queue.push(i);\n }\n cout<<\"Elements in queue are : \";\n while (!Queue.empty()){\n cout << ' ' << Queue.front();\n Queue.pop();\n }\n}"
},
{
"code": null,
"e": 2725,
"s": 2660,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 2761,
"s": 2725,
"text": "Elements in queue are : 0 1 2 3 4 5"
},
{
"code": null,
"e": 3117,
"s": 2761,
"text": "queue::pop() is an inbuilt function in C++ STL which is declared in header file. queue::pop() is used to push or delete an existing element from the beginning or start of the queue container. pop() accepts no parameter, and deletes the element from the beginning of the queue associated with the function and reduces the size of the queue container by 1."
},
{
"code": null,
"e": 3132,
"s": 3117,
"text": "myqueue.pop();"
},
{
"code": null,
"e": 3168,
"s": 3132,
"text": "This function accepts no parameters"
},
{
"code": null,
"e": 3199,
"s": 3168,
"text": "This function returns nothing."
},
{
"code": null,
"e": 3311,
"s": 3199,
"text": "Input: queue myqueue = {10, 20, 30, 40};\n myqueue.pop();\nOutput:\n Elements in the queue are= 20 30 40"
},
{
"code": null,
"e": 3322,
"s": 3311,
"text": " Live Demo"
},
{
"code": null,
"e": 3647,
"s": 3322,
"text": "#include <iostream>\n#include <queue>\nusing namespace std;\nint main(){\n queue<int> Queue;\n for(int i=0 ;i<=5 ;i++){\n Queue.push(i);\n }\n for(int i=0 ;i<5 ;i++){\n Queue.pop();\n }\n cout<<\"Element left in queue is : \";\n while (!Queue.empty()){\n cout << ' ' << Queue.front();\n Queue.pop();\n }\n}"
},
{
"code": null,
"e": 3712,
"s": 3647,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 3741,
"s": 3712,
"text": "Element left in queue is : 5"
}
] |
R - Statistics - GeeksforGeeks
|
16 Dec, 2021
Statistics is a form of mathematical analysis that concerns the collection, organization, analysis, interpretation, and presentation of data. The statistical analysis helps to make the best usage of the vast data available and improves the efficiency of solutions.
R is a programming language and is used for environment statistical computing and graphics. The following is an introduction to basic statistical concepts like plotting graphs such as bar charts, pie charts, Histograms, and boxplots.
In this post, we will be learning about plotting charts for a single variable. The following software is required to learn and implement statistics in R:
R software
RStudio IDE
Following is a list of functions that are required to plot graphs for the representation of Statistical data:
plot() Function: This function is used to Draw a scatter plot with axes and titles.
Syntax:
plot(x, y = NULL, ylim = NULL, xlim = NULL, type = “b”....)
data() function: This function is used to load specified data sets.
Syntax:
data(list = character(), lib.loc = NULL, package = NULL.....)
table() Function: The table function is used to build a contingency table of the counts at each combination of factor levels.
table(x, row.names = NULL, ...)
barplot() Function: It creates a bar plot with vertical/horizontal bars.
Syntax:
barplot(height, width = 1, names.arg = NULL, space = NULL...)
pie() Function: This function is used to create a pie chart.
Syntax:
pie(x, labels = names(x), radius = 0.6, edges = 100, clockwise = TRUE ...)
hist() Function: The function hist() creates a histogram of the given data values.
Syntax:
hist(x, breaks = “Sturges”, probability = !freq, freq = NULL,...)
Note: You can find the information about each function using the “?” symbol before the beginning of each function.
R built-in datasets are very useful to start with and develop skills, So we will be using a few Built-in datasets. Let’s start by creating a simple bar chart by using chickwts dataset and learn how to use datasets and few functions of RStudio.
A Bar chart represents categorical data with rectangular bars where the bars can be plotted vertically or horizontally.
R
# ? is used before a function# to get help on that function?plot ?chickwts data(chickwts) #loading data into workspaceplot(chickwts$feed) # plot feed from chickwts
In the above code ‘?’ in front of a particular function means that it gives information about that function with its syntax. In R ‘#’ is used for commenting single line and there is no multiline comment in R. Here we are using chickwts as the dataset and feed is the attribute in the dataset.
Output:
R
feeds=table(chickwts$feed) # plots graph in decreasing orderbarplot(feeds[order(feeds, decreasing=TRUE)])
Output:
R
feeds = table(chickwts$feed) # outside margins bottom, left, top, right.par(oma=c(1, 1, 1, 1)) par(mar=c(4, 5, 2, 1)) # las is used orientation of axis labels barplot(feeds[order(feeds, decreasing=TRUE)] # horiz is used for bars to be shown as horizontal.barplot(feeds[order(feeds)], horiz=TRUE, # col is used for colouring bars. # xlab is used to label x-axis.xlab="Number of chicks", las=1 col="yellow")
Output:
A pie chart is a circular statistical graph that is divided into slices to show the different sizes of the data.
R
data("chickwts") # main is used to create# an heading for the chartd = table(chickwts$feed) pie(d[order(d, decreasing=TRUE)], clockwise=TRUE, main="Pie Chart of feeds from chichwits", )
Output:
Histograms are the representation of the distribution of data(numerical or categorical). It is similar to a bar chart but it groups data in terms of ranges.
R
# break is used for number of bins.data(lynx) # lynx is a built-in dataset.lynx # hist function is used to plot histogram.hist(lynx)hist(lynx, break=7, col="green", main="Histogram of Annual Canadian Lynx Trappings")
Output :
R
data(lynx) # if freq=FALSE this will draw normal distributionlynx hist(lynx)hist(lynx, break=7, col="green", freq=FALSE main="Histogram of Annual Canadian Lynx Trappings") curve(dnorm(x, mean=mean(lynx), sd=sd(lynx)), col="red", lwd=2, add=TRUE)
Output:
Box Plot is a function for graphically depicting groups of numerical data using quartiles. It represents the distribution of data and understanding mean, median, and variance.
R
# USJudgeRatings is Built-in Dataset.?USJudgeRatings # ylim is used to specify the range.boxplot(USJudgeRatings$RTEN, horizontal=TRUE, xlab="Lawyers Rating", notch=TRUE, ylim=c(0, 10), col="pink")
USJudgeRating is a Build-in dataset with 6 attributes and RTEN is one of the attribute among it which is rating between 0 to 10 inclusive. We used it to for plotting a boxplot with different attributes of boxplot function.
Output:
kumar_satyam
R-Charts
R-Graphs
R-plots
R-Statistics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change column name of a given DataFrame in R
How to Replace specific values in column in R DataFrame ?
Adding elements in a vector in R programming - append() method
Loops in R (for, while, repeat)
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Convert Factor to Numeric and Numeric to Factor in R Programming
Remove rows with NA in one column of R DataFrame
How to Change Axis Scales in R Plots?
|
[
{
"code": null,
"e": 29044,
"s": 29016,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 29309,
"s": 29044,
"text": "Statistics is a form of mathematical analysis that concerns the collection, organization, analysis, interpretation, and presentation of data. The statistical analysis helps to make the best usage of the vast data available and improves the efficiency of solutions."
},
{
"code": null,
"e": 29543,
"s": 29309,
"text": "R is a programming language and is used for environment statistical computing and graphics. The following is an introduction to basic statistical concepts like plotting graphs such as bar charts, pie charts, Histograms, and boxplots."
},
{
"code": null,
"e": 29698,
"s": 29543,
"text": "In this post, we will be learning about plotting charts for a single variable. The following software is required to learn and implement statistics in R: "
},
{
"code": null,
"e": 29709,
"s": 29698,
"text": "R software"
},
{
"code": null,
"e": 29721,
"s": 29709,
"text": "RStudio IDE"
},
{
"code": null,
"e": 29832,
"s": 29721,
"text": "Following is a list of functions that are required to plot graphs for the representation of Statistical data: "
},
{
"code": null,
"e": 29916,
"s": 29832,
"text": "plot() Function: This function is used to Draw a scatter plot with axes and titles."
},
{
"code": null,
"e": 29924,
"s": 29916,
"text": "Syntax:"
},
{
"code": null,
"e": 29984,
"s": 29924,
"text": "plot(x, y = NULL, ylim = NULL, xlim = NULL, type = “b”....)"
},
{
"code": null,
"e": 30052,
"s": 29984,
"text": "data() function: This function is used to load specified data sets."
},
{
"code": null,
"e": 30060,
"s": 30052,
"text": "Syntax:"
},
{
"code": null,
"e": 30122,
"s": 30060,
"text": "data(list = character(), lib.loc = NULL, package = NULL.....)"
},
{
"code": null,
"e": 30248,
"s": 30122,
"text": "table() Function: The table function is used to build a contingency table of the counts at each combination of factor levels."
},
{
"code": null,
"e": 30280,
"s": 30248,
"text": "table(x, row.names = NULL, ...)"
},
{
"code": null,
"e": 30353,
"s": 30280,
"text": "barplot() Function: It creates a bar plot with vertical/horizontal bars."
},
{
"code": null,
"e": 30361,
"s": 30353,
"text": "Syntax:"
},
{
"code": null,
"e": 30423,
"s": 30361,
"text": "barplot(height, width = 1, names.arg = NULL, space = NULL...)"
},
{
"code": null,
"e": 30484,
"s": 30423,
"text": "pie() Function: This function is used to create a pie chart."
},
{
"code": null,
"e": 30492,
"s": 30484,
"text": "Syntax:"
},
{
"code": null,
"e": 30567,
"s": 30492,
"text": "pie(x, labels = names(x), radius = 0.6, edges = 100, clockwise = TRUE ...)"
},
{
"code": null,
"e": 30651,
"s": 30567,
"text": "hist() Function: The function hist() creates a histogram of the given data values. "
},
{
"code": null,
"e": 30659,
"s": 30651,
"text": "Syntax:"
},
{
"code": null,
"e": 30725,
"s": 30659,
"text": "hist(x, breaks = “Sturges”, probability = !freq, freq = NULL,...)"
},
{
"code": null,
"e": 30840,
"s": 30725,
"text": "Note: You can find the information about each function using the “?” symbol before the beginning of each function."
},
{
"code": null,
"e": 31084,
"s": 30840,
"text": "R built-in datasets are very useful to start with and develop skills, So we will be using a few Built-in datasets. Let’s start by creating a simple bar chart by using chickwts dataset and learn how to use datasets and few functions of RStudio."
},
{
"code": null,
"e": 31205,
"s": 31084,
"text": "A Bar chart represents categorical data with rectangular bars where the bars can be plotted vertically or horizontally. "
},
{
"code": null,
"e": 31207,
"s": 31205,
"text": "R"
},
{
"code": "# ? is used before a function# to get help on that function?plot ?chickwts data(chickwts) #loading data into workspaceplot(chickwts$feed) # plot feed from chickwts",
"e": 31379,
"s": 31207,
"text": null
},
{
"code": null,
"e": 31672,
"s": 31379,
"text": "In the above code ‘?’ in front of a particular function means that it gives information about that function with its syntax. In R ‘#’ is used for commenting single line and there is no multiline comment in R. Here we are using chickwts as the dataset and feed is the attribute in the dataset."
},
{
"code": null,
"e": 31681,
"s": 31672,
"text": "Output: "
},
{
"code": null,
"e": 31683,
"s": 31681,
"text": "R"
},
{
"code": "feeds=table(chickwts$feed) # plots graph in decreasing orderbarplot(feeds[order(feeds, decreasing=TRUE)])",
"e": 31789,
"s": 31683,
"text": null
},
{
"code": null,
"e": 31798,
"s": 31789,
"text": "Output: "
},
{
"code": null,
"e": 31800,
"s": 31798,
"text": "R"
},
{
"code": "feeds = table(chickwts$feed) # outside margins bottom, left, top, right.par(oma=c(1, 1, 1, 1)) par(mar=c(4, 5, 2, 1)) # las is used orientation of axis labels barplot(feeds[order(feeds, decreasing=TRUE)] # horiz is used for bars to be shown as horizontal.barplot(feeds[order(feeds)], horiz=TRUE, # col is used for colouring bars. # xlab is used to label x-axis.xlab=\"Number of chicks\", las=1 col=\"yellow\") ",
"e": 32270,
"s": 31800,
"text": null
},
{
"code": null,
"e": 32279,
"s": 32270,
"text": "Output: "
},
{
"code": null,
"e": 32392,
"s": 32279,
"text": "A pie chart is a circular statistical graph that is divided into slices to show the different sizes of the data."
},
{
"code": null,
"e": 32394,
"s": 32392,
"text": "R"
},
{
"code": "data(\"chickwts\") # main is used to create# an heading for the chartd = table(chickwts$feed) pie(d[order(d, decreasing=TRUE)], clockwise=TRUE, main=\"Pie Chart of feeds from chichwits\", )",
"e": 32597,
"s": 32394,
"text": null
},
{
"code": null,
"e": 32606,
"s": 32597,
"text": "Output: "
},
{
"code": null,
"e": 32764,
"s": 32606,
"text": "Histograms are the representation of the distribution of data(numerical or categorical). It is similar to a bar chart but it groups data in terms of ranges. "
},
{
"code": null,
"e": 32766,
"s": 32764,
"text": "R"
},
{
"code": "# break is used for number of bins.data(lynx) # lynx is a built-in dataset.lynx # hist function is used to plot histogram.hist(lynx)hist(lynx, break=7, col=\"green\", main=\"Histogram of Annual Canadian Lynx Trappings\")",
"e": 32993,
"s": 32766,
"text": null
},
{
"code": null,
"e": 33002,
"s": 32993,
"text": "Output :"
},
{
"code": null,
"e": 33004,
"s": 33002,
"text": "R"
},
{
"code": "data(lynx) # if freq=FALSE this will draw normal distributionlynx hist(lynx)hist(lynx, break=7, col=\"green\", freq=FALSE main=\"Histogram of Annual Canadian Lynx Trappings\") curve(dnorm(x, mean=mean(lynx), sd=sd(lynx)), col=\"red\", lwd=2, add=TRUE)",
"e": 33289,
"s": 33004,
"text": null
},
{
"code": null,
"e": 33297,
"s": 33289,
"text": "Output:"
},
{
"code": null,
"e": 33473,
"s": 33297,
"text": "Box Plot is a function for graphically depicting groups of numerical data using quartiles. It represents the distribution of data and understanding mean, median, and variance."
},
{
"code": null,
"e": 33475,
"s": 33473,
"text": "R"
},
{
"code": "# USJudgeRatings is Built-in Dataset.?USJudgeRatings # ylim is used to specify the range.boxplot(USJudgeRatings$RTEN, horizontal=TRUE, xlab=\"Lawyers Rating\", notch=TRUE, ylim=c(0, 10), col=\"pink\")",
"e": 33709,
"s": 33475,
"text": null
},
{
"code": null,
"e": 33933,
"s": 33709,
"text": "USJudgeRating is a Build-in dataset with 6 attributes and RTEN is one of the attribute among it which is rating between 0 to 10 inclusive. We used it to for plotting a boxplot with different attributes of boxplot function. "
},
{
"code": null,
"e": 33942,
"s": 33933,
"text": "Output: "
},
{
"code": null,
"e": 33955,
"s": 33942,
"text": "kumar_satyam"
},
{
"code": null,
"e": 33964,
"s": 33955,
"text": "R-Charts"
},
{
"code": null,
"e": 33973,
"s": 33964,
"text": "R-Graphs"
},
{
"code": null,
"e": 33981,
"s": 33973,
"text": "R-plots"
},
{
"code": null,
"e": 33994,
"s": 33981,
"text": "R-Statistics"
},
{
"code": null,
"e": 34005,
"s": 33994,
"text": "R Language"
},
{
"code": null,
"e": 34103,
"s": 34005,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34112,
"s": 34103,
"text": "Comments"
},
{
"code": null,
"e": 34125,
"s": 34112,
"text": "Old Comments"
},
{
"code": null,
"e": 34170,
"s": 34125,
"text": "Change column name of a given DataFrame in R"
},
{
"code": null,
"e": 34228,
"s": 34170,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 34291,
"s": 34228,
"text": "Adding elements in a vector in R programming - append() method"
},
{
"code": null,
"e": 34323,
"s": 34291,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 34375,
"s": 34323,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 34427,
"s": 34375,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 34471,
"s": 34427,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 34536,
"s": 34471,
"text": "Convert Factor to Numeric and Numeric to Factor in R Programming"
},
{
"code": null,
"e": 34585,
"s": 34536,
"text": "Remove rows with NA in one column of R DataFrame"
}
] |
How to add a column in MongoDB collection?
|
To add a column, you need to update the collection. The syntax is as follows −
db.getCollection(yourCollectionName).update({}, {$set: {"yourColumnName": "yourValue"}},false,true);
To understand the above syntax, let us create a collection with documents −
> db.addColumnDemo.insertOne({"StudentId":101,"StudentName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e04d66af5e889d7a519950f")
}
> db.addColumnDemo.insertOne({"StudentId":102,"StudentName":"Robert"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e04d673f5e889d7a5199510")
}
> db.addColumnDemo.insertOne({"StudentId":103,"StudentName":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e04d67bf5e889d7a5199511")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.addColumnDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e04d66af5e889d7a519950f"),
"StudentId" : 101,
"StudentName" : "Chris"
}
{
"_id" : ObjectId("5e04d673f5e889d7a5199510"),
"StudentId" : 102,
"StudentName" : "Robert"
}
{
"_id" : ObjectId("5e04d67bf5e889d7a5199511"),
"StudentId" : 103,
"StudentName" : "David"
}
Here is the query to add a column in MongoDB −
> db.getCollection('addColumnDemo').update({}, {$set: {"StudentCityName": "New York"}},false,true);
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })
Following is the query to display all documents from a collection with the help of find() method −
> db.addColumnDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e04d66af5e889d7a519950f"),
"StudentId" : 101,
"StudentName" : "Chris",
"StudentCityName" : "New York"
}
{
"_id" : ObjectId("5e04d673f5e889d7a5199510"),
"StudentId" : 102,
"StudentName" : "Robert",
"StudentCityName" : "New York"
}
{
"_id" : ObjectId("5e04d67bf5e889d7a5199511"),
"StudentId" : 103,
"StudentName" : "David",
"StudentCityName" : "New York"
}
|
[
{
"code": null,
"e": 1141,
"s": 1062,
"text": "To add a column, you need to update the collection. The syntax is as follows −"
},
{
"code": null,
"e": 1242,
"s": 1141,
"text": "db.getCollection(yourCollectionName).update({}, {$set: {\"yourColumnName\": \"yourValue\"}},false,true);"
},
{
"code": null,
"e": 1318,
"s": 1242,
"text": "To understand the above syntax, let us create a collection with documents −"
},
{
"code": null,
"e": 1787,
"s": 1318,
"text": "> db.addColumnDemo.insertOne({\"StudentId\":101,\"StudentName\":\"Chris\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e04d66af5e889d7a519950f\")\n}\n> db.addColumnDemo.insertOne({\"StudentId\":102,\"StudentName\":\"Robert\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e04d673f5e889d7a5199510\")\n}\n> db.addColumnDemo.insertOne({\"StudentId\":103,\"StudentName\":\"David\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e04d67bf5e889d7a5199511\")\n}"
},
{
"code": null,
"e": 1886,
"s": 1787,
"text": "Following is the query to display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1922,
"s": 1886,
"text": "> db.addColumnDemo.find().pretty();"
},
{
"code": null,
"e": 1963,
"s": 1922,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2270,
"s": 1963,
"text": "{\n \"_id\" : ObjectId(\"5e04d66af5e889d7a519950f\"),\n \"StudentId\" : 101,\n \"StudentName\" : \"Chris\"\n}\n{\n \"_id\" : ObjectId(\"5e04d673f5e889d7a5199510\"),\n \"StudentId\" : 102,\n \"StudentName\" : \"Robert\"\n}\n{\n \"_id\" : ObjectId(\"5e04d67bf5e889d7a5199511\"),\n \"StudentId\" : 103,\n \"StudentName\" : \"David\"\n}"
},
{
"code": null,
"e": 2317,
"s": 2270,
"text": "Here is the query to add a column in MongoDB −"
},
{
"code": null,
"e": 2483,
"s": 2317,
"text": "> db.getCollection('addColumnDemo').update({}, {$set: {\"StudentCityName\": \"New York\"}},false,true);\nWriteResult({ \"nMatched\" : 3, \"nUpserted\" : 0, \"nModified\" : 3 })"
},
{
"code": null,
"e": 2582,
"s": 2483,
"text": "Following is the query to display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 2618,
"s": 2582,
"text": "> db.addColumnDemo.find().pretty();"
},
{
"code": null,
"e": 2659,
"s": 2618,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3071,
"s": 2659,
"text": "{\n \"_id\" : ObjectId(\"5e04d66af5e889d7a519950f\"),\n \"StudentId\" : 101,\n \"StudentName\" : \"Chris\",\n \"StudentCityName\" : \"New York\"\n}\n{\n \"_id\" : ObjectId(\"5e04d673f5e889d7a5199510\"),\n \"StudentId\" : 102,\n \"StudentName\" : \"Robert\",\n \"StudentCityName\" : \"New York\"\n}\n{\n \"_id\" : ObjectId(\"5e04d67bf5e889d7a5199511\"),\n \"StudentId\" : 103,\n \"StudentName\" : \"David\",\n \"StudentCityName\" : \"New York\"\n}"
}
] |
How to code The Transformer in Pytorch | by Samuel Lynn-Evans | Towards Data Science
|
Could The Transformer be another nail in the coffin for RNNs?
Doing away with the clunky for loops, it finds a way to allow whole sentences to simultaneously enter the network in batches. The miracle; NLP now reclaims the advantage of python’s highly efficient linear algebra libraries. This time-saving can then spent deploying more layers into the model.
So far it seems the result is faster convergence and better results. What’s not to love?
My personal experience of it has been highly promising. It trained on 2 million French-English sentence pairs to create a sophisticated translator in only three days.
You can play with the model yourself on language translating tasks if you go to my implementation on Github here. Also check out my next post, where I share my journey building the translator and the results.
Or finally, you could build one yourself. Here’s the guide on how to do it, and how it works.
This guide only explains how to code the model and run it, for information on how to obtain data and process it for seq2seq see my guide here.
The diagram above shows the overview of the Transformer model. The inputs to the encoder will be the English sentence, and the ‘Outputs‘ entering the decoder will be the French sentence.
In effect, there are five processes we need to understand to implement this model:
Embedding the inputs
The Positional Encodings
Creating Masks
The Multi-Head Attention layer
The Feed-Forward layer
Embedding words has become standard practice in NMT, feeding the network with far more information about words than a one hot encoding would. For more information on this see my post here.
Embedding is handled simply in pytorch:
class Embedder(nn.Module): def __init__(self, vocab_size, d_model): super().__init__() self.embed = nn.Embedding(vocab_size, d_model) def forward(self, x): return self.embed(x)
When each word is fed into the network, this code will perform a look-up and retrieve its embedding vector. These vectors will then be learnt as a parameters by the model, adjusted with each iteration of gradient descent.
In order for the model to make sense of a sentence, it needs to know two things about each word: what does the word mean? And what is its position in the sentence?
The embedding vector for each word will learn the meaning, so now we need to input something that tells the network about the word’s position.
Vasmari et al answered this problem by using these functions to create a constant of position-specific values:
This constant is a 2d matrix. Pos refers to the order in the sentence, and i refers to the position along the embedding vector dimension. Each value in the pos/i matrix is then worked out using the equations above.
An intuitive way of coding our Positional Encoder looks like this:
class PositionalEncoder(nn.Module): def __init__(self, d_model, max_seq_len = 80): super().__init__() self.d_model = d_model # create constant 'pe' matrix with values dependant on # pos and i pe = torch.zeros(max_seq_len, d_model) for pos in range(max_seq_len): for i in range(0, d_model, 2): pe[pos, i] = \ math.sin(pos / (10000 ** ((2 * i)/d_model))) pe[pos, i + 1] = \ math.cos(pos / (10000 ** ((2 * (i + 1))/d_model))) pe = pe.unsqueeze(0) self.register_buffer('pe', pe) def forward(self, x): # make embeddings relatively larger x = x * math.sqrt(self.d_model) #add constant to embedding seq_len = x.size(1) x = x + Variable(self.pe[:,:seq_len], \ requires_grad=False).cuda() return x
The above module lets us add the positional encoding to the embedding vector, providing information about structure to the model.
The reason we increase the embedding values before addition is to make the positional encoding relatively smaller. This means the original meaning in the embedding vector won’t be lost when we add them together.
Masking plays an important role in the transformer. It serves two purposes:
In the encoder and decoder: To zero attention outputs wherever there is just padding in the input sentences.
In the decoder: To prevent the decoder ‘peaking’ ahead at the rest of the translated sentence when predicting the next word.
Creating the mask for the input is simple:
batch = next(iter(train_iter))input_seq = batch.English.transpose(0,1)input_pad = EN_TEXT.vocab.stoi['<pad>']# creates mask with 0s wherever there is padding in the inputinput_msk = (input_seq != input_pad).unsqueeze(1)
For the target_seq we do the same, but then create an additional step:
# create mask as beforetarget_seq = batch.French.transpose(0,1)target_pad = FR_TEXT.vocab.stoi['<pad>']target_msk = (target_seq != target_pad).unsqueeze(1)size = target_seq.size(1) # get seq_len for matrixnopeak_mask = np.triu(np.ones(1, size, size),k=1).astype('uint8')nopeak_mask = Variable(torch.from_numpy(nopeak_mask) == 0)target_msk = target_msk & nopeak_mask
The initial input into the decoder will be the target sequence (the French translation). The way the decoder predicts each output word is by making use of all the encoder outputs and the French sentence only up until the point of each word its predicting.
Therefore we need to prevent the first output predictions from being able to see later into the sentence. For this we use the nopeak_mask:
If we later apply this mask to the attention scores, the values wherever the input is ahead will not be able to contribute when calculating the outputs.
Once we have our embedded values (with positional encodings) and our masks, we can start building the layers of our model.
Here is an overview of the multi-headed attention layer:
V, K and Q stand for ‘key’, ‘value’ and ‘query’. These are terms used in attention functions, but honestly, I don’t think explaining this terminology is particularly important for understanding the model.
In the case of the Encoder, V, K and G will simply be identical copies of the embedding vector (plus positional encoding). They will have the dimensions Batch_size * seq_len * d_model.
In multi-head attention we split the embedding vector into N heads, so they will then have the dimensions batch_size * N * seq_len * (d_model / N).
This final dimension (d_model / N ) we will refer to as d_k.
Let’s see the code for the decoder module:
class MultiHeadAttention(nn.Module): def __init__(self, heads, d_model, dropout = 0.1): super().__init__() self.d_model = d_model self.d_k = d_model // heads self.h = heads self.q_linear = nn.Linear(d_model, d_model) self.v_linear = nn.Linear(d_model, d_model) self.k_linear = nn.Linear(d_model, d_model) self.dropout = nn.Dropout(dropout) self.out = nn.Linear(d_model, d_model) def forward(self, q, k, v, mask=None): bs = q.size(0) # perform linear operation and split into h heads k = self.k_linear(k).view(bs, -1, self.h, self.d_k) q = self.q_linear(q).view(bs, -1, self.h, self.d_k) v = self.v_linear(v).view(bs, -1, self.h, self.d_k) # transpose to get dimensions bs * h * sl * d_model k = k.transpose(1,2) q = q.transpose(1,2) v = v.transpose(1,2)# calculate attention using function we will define next scores = attention(q, k, v, self.d_k, mask, self.dropout) # concatenate heads and put through final linear layer concat = scores.transpose(1,2).contiguous()\ .view(bs, -1, self.d_model) output = self.out(concat) return output
This is the only other equation we will be considering today, and this diagram from the paper does a god job at explaining each step.
Each arrow in the diagram reflects a part of the equation.
Initially we must multiply Q by the transpose of K. This is then ‘scaled’ by dividing the output by the square root of d_k.
A step that’s not shown in the equation is the masking operation. Before we perform Softmax, we apply our mask and hence reduce values where the input is padding (or in the decoder, also where the input is ahead of the current word).
Another step not shown is dropout, which we will apply after Softmax.
Finally, the last step is doing a dot product between the result so far and V.
Here is the code for the attention function:
def attention(q, k, v, d_k, mask=None, dropout=None): scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(d_k)if mask is not None: mask = mask.unsqueeze(1) scores = scores.masked_fill(mask == 0, -1e9)scores = F.softmax(scores, dim=-1) if dropout is not None: scores = dropout(scores) output = torch.matmul(scores, v) return output
Ok if you’ve understood so far, give yourself a big pat on the back as we’ve made it to the final layer and it’s all pretty simple from here!
This layer just consists of two linear operations, with a relu and dropout operation in between them.
class FeedForward(nn.Module): def __init__(self, d_model, d_ff=2048, dropout = 0.1): super().__init__() # We set d_ff as a default to 2048 self.linear_1 = nn.Linear(d_model, d_ff) self.dropout = nn.Dropout(dropout) self.linear_2 = nn.Linear(d_ff, d_model) def forward(self, x): x = self.dropout(F.relu(self.linear_1(x))) x = self.linear_2(x) return x
The feed-forward layer simply deepens our network, employing linear layers to analyse patterns in the attention layers output.
Normalisation is highly important in deep neural networks. It prevents the range of values in the layers changing too much, meaning the model trains faster and has better ability to generalise.
We will be normalising our results between each layer in the encoder/decoder, so before building our model let’s define that function:
class Norm(nn.Module): def __init__(self, d_model, eps = 1e-6): super().__init__() self.size = d_model # create two learnable parameters to calibrate normalisation self.alpha = nn.Parameter(torch.ones(self.size)) self.bias = nn.Parameter(torch.zeros(self.size)) self.eps = eps def forward(self, x): norm = self.alpha * (x - x.mean(dim=-1, keepdim=True)) \ / (x.std(dim=-1, keepdim=True) + self.eps) + self.bias return norm
If you understand the details above, you now understand the model. The rest is simply putting everything into place.
Let’s have another look at the over-all architecture and start building:
One last Variable: If you look at the diagram closely you can see a ‘Nx’ next to the encoder and decoder architectures. In reality, the encoder and decoder in the diagram above represent one layer of an encoder and one of the decoder. N is the variable for the number of layers there will be. Eg. if N=6, the data goes through six encoder layers (with the architecture seen above), then these outputs are passed to the decoder which also consists of six repeating decoder layers.
We will now build EncoderLayer and DecoderLayer modules with the architecture shown in the model above. Then when we build the encoder and decoder we can define how many of these layers to have.
# build an encoder layer with one multi-head attention layer and one # feed-forward layerclass EncoderLayer(nn.Module): def __init__(self, d_model, heads, dropout = 0.1): super().__init__() self.norm_1 = Norm(d_model) self.norm_2 = Norm(d_model) self.attn = MultiHeadAttention(heads, d_model) self.ff = FeedForward(d_model) self.dropout_1 = nn.Dropout(dropout) self.dropout_2 = nn.Dropout(dropout) def forward(self, x, mask): x2 = self.norm_1(x) x = x + self.dropout_1(self.attn(x2,x2,x2,mask)) x2 = self.norm_2(x) x = x + self.dropout_2(self.ff(x2)) return x # build a decoder layer with two multi-head attention layers and# one feed-forward layerclass DecoderLayer(nn.Module): def __init__(self, d_model, heads, dropout=0.1): super().__init__() self.norm_1 = Norm(d_model) self.norm_2 = Norm(d_model) self.norm_3 = Norm(d_model) self.dropout_1 = nn.Dropout(dropout) self.dropout_2 = nn.Dropout(dropout) self.dropout_3 = nn.Dropout(dropout) self.attn_1 = MultiHeadAttention(heads, d_model) self.attn_2 = MultiHeadAttention(heads, d_model) self.ff = FeedForward(d_model).cuda()def forward(self, x, e_outputs, src_mask, trg_mask): x2 = self.norm_1(x) x = x + self.dropout_1(self.attn_1(x2, x2, x2, trg_mask)) x2 = self.norm_2(x) x = x + self.dropout_2(self.attn_2(x2, e_outputs, e_outputs, src_mask)) x2 = self.norm_3(x) x = x + self.dropout_3(self.ff(x2)) return x# We can then build a convenient cloning function that can generate multiple layers:def get_clones(module, N): return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
We’re now ready to build the encoder and decoder:
class Encoder(nn.Module): def __init__(self, vocab_size, d_model, N, heads): super().__init__() self.N = N self.embed = Embedder(vocab_size, d_model) self.pe = PositionalEncoder(d_model) self.layers = get_clones(EncoderLayer(d_model, heads), N) self.norm = Norm(d_model) def forward(self, src, mask): x = self.embed(src) x = self.pe(x) for i in range(N): x = self.layers[i](x, mask) return self.norm(x) class Decoder(nn.Module): def __init__(self, vocab_size, d_model, N, heads): super().__init__() self.N = N self.embed = Embedder(vocab_size, d_model) self.pe = PositionalEncoder(d_model) self.layers = get_clones(DecoderLayer(d_model, heads), N) self.norm = Norm(d_model) def forward(self, trg, e_outputs, src_mask, trg_mask): x = self.embed(trg) x = self.pe(x) for i in range(self.N): x = self.layers[i](x, e_outputs, src_mask, trg_mask) return self.norm(x)
And finally... The transformer!
class Transformer(nn.Module): def __init__(self, src_vocab, trg_vocab, d_model, N, heads): super().__init__() self.encoder = Encoder(src_vocab, d_model, N, heads) self.decoder = Decoder(trg_vocab, d_model, N, heads) self.out = nn.Linear(d_model, trg_vocab) def forward(self, src, trg, src_mask, trg_mask): e_outputs = self.encoder(src, src_mask) d_output = self.decoder(trg, e_outputs, src_mask, trg_mask) output = self.out(d_output) return output# we don't perform softmax on the output as this will be handled # automatically by our loss function
With the transformer built, all that remains is to train that sucker on the EuroParl dataset. The coding part is pretty painless, but be prepared to wait for about 2 days for this model to start converging!
Let’s define some parameters first:
d_model = 512heads = 8N = 6src_vocab = len(EN_TEXT.vocab)trg_vocab = len(FR_TEXT.vocab)model = Transformer(src_vocab, trg_vocab, d_model, N, heads)for p in model.parameters(): if p.dim() > 1: nn.init.xavier_uniform_(p)# this code is very important! It initialises the parameters with a# range of values that stops the signal fading or getting too big.# See this blog for a mathematical explanation.optim = torch.optim.Adam(model.parameters(), lr=0.0001, betas=(0.9, 0.98), eps=1e-9)
And now we’re good to train:
def train_model(epochs, print_every=100): model.train() start = time.time() temp = start total_loss = 0 for epoch in range(epochs): for i, batch in enumerate(train_iter): src = batch.English.transpose(0,1) trg = batch.French.transpose(0,1) # the French sentence we input has all words except # the last, as it is using each word to predict the next trg_input = trg[:, :-1] # the words we are trying to predict targets = trg[:, 1:].contiguous().view(-1) # create function to make masks using mask code above src_mask, trg_mask = create_masks(src, trg_input) preds = model(src, trg_input, src_mask, trg_mask) optim.zero_grad() loss = F.cross_entropy(preds.view(-1, preds.size(-1)), results, ignore_index=target_pad) loss.backward() optim.step() total_loss += loss.data[0] if (i + 1) % print_every == 0: loss_avg = total_loss / print_every print("time = %dm, epoch %d, iter = %d, loss = %.3f, %ds per %d iters" % ((time.time() - start) // 60, epoch + 1, i + 1, loss_avg, time.time() - temp, print_every)) total_loss = 0 temp = time.time()
We can use the below function to translate sentences. We can feed it sentences directly from our batches, or input custom strings.
The translator works by running a loop. We start off by encoding the English sentence. We then feed the decoder the <sos> token index and the encoder outputs. The decoder makes a prediction for the first word, and we add this to our decoder input with the sos token. We rerun the loop, getting the next prediction and adding this to the decoder input, until we reach the <eos> token letting us know it has finished translating.
def translate(model, src, max_len = 80, custom_string=False): model.eval()if custom_sentence == True: src = tokenize_en(src) sentence=\ Variable(torch.LongTensor([[EN_TEXT.vocab.stoi[tok] for tok in sentence]])).cuda()src_mask = (src != input_pad).unsqueeze(-2) e_outputs = model.encoder(src, src_mask) outputs = torch.zeros(max_len).type_as(src.data) outputs[0] = torch.LongTensor([FR_TEXT.vocab.stoi['<sos>']])for i in range(1, max_len): trg_mask = np.triu(np.ones((1, i, i), k=1).astype('uint8') trg_mask= Variable(torch.from_numpy(trg_mask) == 0).cuda() out = model.out(model.decoder(outputs[:i].unsqueeze(0), e_outputs, src_mask, trg_mask)) out = F.softmax(out, dim=-1) val, ix = out[:, -1].data.topk(1) outputs[i] = ix[0][0] if ix[0][0] == FR_TEXT.vocab.stoi['<eos>']: breakreturn ' '.join( [FR_TEXT.vocab.itos[ix] for ix in outputs[:i]] )
And that’s it. See my Github here where I’ve written this code up as a program that will take in two parallel texts as parameters and train this model on them. Or practise the knowledge and implement it yourself!
|
[
{
"code": null,
"e": 234,
"s": 172,
"text": "Could The Transformer be another nail in the coffin for RNNs?"
},
{
"code": null,
"e": 529,
"s": 234,
"text": "Doing away with the clunky for loops, it finds a way to allow whole sentences to simultaneously enter the network in batches. The miracle; NLP now reclaims the advantage of python’s highly efficient linear algebra libraries. This time-saving can then spent deploying more layers into the model."
},
{
"code": null,
"e": 618,
"s": 529,
"text": "So far it seems the result is faster convergence and better results. What’s not to love?"
},
{
"code": null,
"e": 785,
"s": 618,
"text": "My personal experience of it has been highly promising. It trained on 2 million French-English sentence pairs to create a sophisticated translator in only three days."
},
{
"code": null,
"e": 994,
"s": 785,
"text": "You can play with the model yourself on language translating tasks if you go to my implementation on Github here. Also check out my next post, where I share my journey building the translator and the results."
},
{
"code": null,
"e": 1088,
"s": 994,
"text": "Or finally, you could build one yourself. Here’s the guide on how to do it, and how it works."
},
{
"code": null,
"e": 1231,
"s": 1088,
"text": "This guide only explains how to code the model and run it, for information on how to obtain data and process it for seq2seq see my guide here."
},
{
"code": null,
"e": 1418,
"s": 1231,
"text": "The diagram above shows the overview of the Transformer model. The inputs to the encoder will be the English sentence, and the ‘Outputs‘ entering the decoder will be the French sentence."
},
{
"code": null,
"e": 1501,
"s": 1418,
"text": "In effect, there are five processes we need to understand to implement this model:"
},
{
"code": null,
"e": 1522,
"s": 1501,
"text": "Embedding the inputs"
},
{
"code": null,
"e": 1547,
"s": 1522,
"text": "The Positional Encodings"
},
{
"code": null,
"e": 1562,
"s": 1547,
"text": "Creating Masks"
},
{
"code": null,
"e": 1593,
"s": 1562,
"text": "The Multi-Head Attention layer"
},
{
"code": null,
"e": 1616,
"s": 1593,
"text": "The Feed-Forward layer"
},
{
"code": null,
"e": 1805,
"s": 1616,
"text": "Embedding words has become standard practice in NMT, feeding the network with far more information about words than a one hot encoding would. For more information on this see my post here."
},
{
"code": null,
"e": 1845,
"s": 1805,
"text": "Embedding is handled simply in pytorch:"
},
{
"code": null,
"e": 2049,
"s": 1845,
"text": "class Embedder(nn.Module): def __init__(self, vocab_size, d_model): super().__init__() self.embed = nn.Embedding(vocab_size, d_model) def forward(self, x): return self.embed(x)"
},
{
"code": null,
"e": 2271,
"s": 2049,
"text": "When each word is fed into the network, this code will perform a look-up and retrieve its embedding vector. These vectors will then be learnt as a parameters by the model, adjusted with each iteration of gradient descent."
},
{
"code": null,
"e": 2435,
"s": 2271,
"text": "In order for the model to make sense of a sentence, it needs to know two things about each word: what does the word mean? And what is its position in the sentence?"
},
{
"code": null,
"e": 2578,
"s": 2435,
"text": "The embedding vector for each word will learn the meaning, so now we need to input something that tells the network about the word’s position."
},
{
"code": null,
"e": 2689,
"s": 2578,
"text": "Vasmari et al answered this problem by using these functions to create a constant of position-specific values:"
},
{
"code": null,
"e": 2904,
"s": 2689,
"text": "This constant is a 2d matrix. Pos refers to the order in the sentence, and i refers to the position along the embedding vector dimension. Each value in the pos/i matrix is then worked out using the equations above."
},
{
"code": null,
"e": 2971,
"s": 2904,
"text": "An intuitive way of coding our Positional Encoder looks like this:"
},
{
"code": null,
"e": 3872,
"s": 2971,
"text": "class PositionalEncoder(nn.Module): def __init__(self, d_model, max_seq_len = 80): super().__init__() self.d_model = d_model # create constant 'pe' matrix with values dependant on # pos and i pe = torch.zeros(max_seq_len, d_model) for pos in range(max_seq_len): for i in range(0, d_model, 2): pe[pos, i] = \\ math.sin(pos / (10000 ** ((2 * i)/d_model))) pe[pos, i + 1] = \\ math.cos(pos / (10000 ** ((2 * (i + 1))/d_model))) pe = pe.unsqueeze(0) self.register_buffer('pe', pe) def forward(self, x): # make embeddings relatively larger x = x * math.sqrt(self.d_model) #add constant to embedding seq_len = x.size(1) x = x + Variable(self.pe[:,:seq_len], \\ requires_grad=False).cuda() return x"
},
{
"code": null,
"e": 4002,
"s": 3872,
"text": "The above module lets us add the positional encoding to the embedding vector, providing information about structure to the model."
},
{
"code": null,
"e": 4214,
"s": 4002,
"text": "The reason we increase the embedding values before addition is to make the positional encoding relatively smaller. This means the original meaning in the embedding vector won’t be lost when we add them together."
},
{
"code": null,
"e": 4290,
"s": 4214,
"text": "Masking plays an important role in the transformer. It serves two purposes:"
},
{
"code": null,
"e": 4399,
"s": 4290,
"text": "In the encoder and decoder: To zero attention outputs wherever there is just padding in the input sentences."
},
{
"code": null,
"e": 4524,
"s": 4399,
"text": "In the decoder: To prevent the decoder ‘peaking’ ahead at the rest of the translated sentence when predicting the next word."
},
{
"code": null,
"e": 4567,
"s": 4524,
"text": "Creating the mask for the input is simple:"
},
{
"code": null,
"e": 4787,
"s": 4567,
"text": "batch = next(iter(train_iter))input_seq = batch.English.transpose(0,1)input_pad = EN_TEXT.vocab.stoi['<pad>']# creates mask with 0s wherever there is padding in the inputinput_msk = (input_seq != input_pad).unsqueeze(1)"
},
{
"code": null,
"e": 4858,
"s": 4787,
"text": "For the target_seq we do the same, but then create an additional step:"
},
{
"code": null,
"e": 5224,
"s": 4858,
"text": "# create mask as beforetarget_seq = batch.French.transpose(0,1)target_pad = FR_TEXT.vocab.stoi['<pad>']target_msk = (target_seq != target_pad).unsqueeze(1)size = target_seq.size(1) # get seq_len for matrixnopeak_mask = np.triu(np.ones(1, size, size),k=1).astype('uint8')nopeak_mask = Variable(torch.from_numpy(nopeak_mask) == 0)target_msk = target_msk & nopeak_mask"
},
{
"code": null,
"e": 5480,
"s": 5224,
"text": "The initial input into the decoder will be the target sequence (the French translation). The way the decoder predicts each output word is by making use of all the encoder outputs and the French sentence only up until the point of each word its predicting."
},
{
"code": null,
"e": 5619,
"s": 5480,
"text": "Therefore we need to prevent the first output predictions from being able to see later into the sentence. For this we use the nopeak_mask:"
},
{
"code": null,
"e": 5772,
"s": 5619,
"text": "If we later apply this mask to the attention scores, the values wherever the input is ahead will not be able to contribute when calculating the outputs."
},
{
"code": null,
"e": 5895,
"s": 5772,
"text": "Once we have our embedded values (with positional encodings) and our masks, we can start building the layers of our model."
},
{
"code": null,
"e": 5952,
"s": 5895,
"text": "Here is an overview of the multi-headed attention layer:"
},
{
"code": null,
"e": 6157,
"s": 5952,
"text": "V, K and Q stand for ‘key’, ‘value’ and ‘query’. These are terms used in attention functions, but honestly, I don’t think explaining this terminology is particularly important for understanding the model."
},
{
"code": null,
"e": 6342,
"s": 6157,
"text": "In the case of the Encoder, V, K and G will simply be identical copies of the embedding vector (plus positional encoding). They will have the dimensions Batch_size * seq_len * d_model."
},
{
"code": null,
"e": 6490,
"s": 6342,
"text": "In multi-head attention we split the embedding vector into N heads, so they will then have the dimensions batch_size * N * seq_len * (d_model / N)."
},
{
"code": null,
"e": 6551,
"s": 6490,
"text": "This final dimension (d_model / N ) we will refer to as d_k."
},
{
"code": null,
"e": 6594,
"s": 6551,
"text": "Let’s see the code for the decoder module:"
},
{
"code": null,
"e": 7883,
"s": 6594,
"text": "class MultiHeadAttention(nn.Module): def __init__(self, heads, d_model, dropout = 0.1): super().__init__() self.d_model = d_model self.d_k = d_model // heads self.h = heads self.q_linear = nn.Linear(d_model, d_model) self.v_linear = nn.Linear(d_model, d_model) self.k_linear = nn.Linear(d_model, d_model) self.dropout = nn.Dropout(dropout) self.out = nn.Linear(d_model, d_model) def forward(self, q, k, v, mask=None): bs = q.size(0) # perform linear operation and split into h heads k = self.k_linear(k).view(bs, -1, self.h, self.d_k) q = self.q_linear(q).view(bs, -1, self.h, self.d_k) v = self.v_linear(v).view(bs, -1, self.h, self.d_k) # transpose to get dimensions bs * h * sl * d_model k = k.transpose(1,2) q = q.transpose(1,2) v = v.transpose(1,2)# calculate attention using function we will define next scores = attention(q, k, v, self.d_k, mask, self.dropout) # concatenate heads and put through final linear layer concat = scores.transpose(1,2).contiguous()\\ .view(bs, -1, self.d_model) output = self.out(concat) return output"
},
{
"code": null,
"e": 8017,
"s": 7883,
"text": "This is the only other equation we will be considering today, and this diagram from the paper does a god job at explaining each step."
},
{
"code": null,
"e": 8076,
"s": 8017,
"text": "Each arrow in the diagram reflects a part of the equation."
},
{
"code": null,
"e": 8200,
"s": 8076,
"text": "Initially we must multiply Q by the transpose of K. This is then ‘scaled’ by dividing the output by the square root of d_k."
},
{
"code": null,
"e": 8434,
"s": 8200,
"text": "A step that’s not shown in the equation is the masking operation. Before we perform Softmax, we apply our mask and hence reduce values where the input is padding (or in the decoder, also where the input is ahead of the current word)."
},
{
"code": null,
"e": 8504,
"s": 8434,
"text": "Another step not shown is dropout, which we will apply after Softmax."
},
{
"code": null,
"e": 8583,
"s": 8504,
"text": "Finally, the last step is doing a dot product between the result so far and V."
},
{
"code": null,
"e": 8628,
"s": 8583,
"text": "Here is the code for the attention function:"
},
{
"code": null,
"e": 9015,
"s": 8628,
"text": "def attention(q, k, v, d_k, mask=None, dropout=None): scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(d_k)if mask is not None: mask = mask.unsqueeze(1) scores = scores.masked_fill(mask == 0, -1e9)scores = F.softmax(scores, dim=-1) if dropout is not None: scores = dropout(scores) output = torch.matmul(scores, v) return output"
},
{
"code": null,
"e": 9157,
"s": 9015,
"text": "Ok if you’ve understood so far, give yourself a big pat on the back as we’ve made it to the final layer and it’s all pretty simple from here!"
},
{
"code": null,
"e": 9259,
"s": 9157,
"text": "This layer just consists of two linear operations, with a relu and dropout operation in between them."
},
{
"code": null,
"e": 9673,
"s": 9259,
"text": "class FeedForward(nn.Module): def __init__(self, d_model, d_ff=2048, dropout = 0.1): super().__init__() # We set d_ff as a default to 2048 self.linear_1 = nn.Linear(d_model, d_ff) self.dropout = nn.Dropout(dropout) self.linear_2 = nn.Linear(d_ff, d_model) def forward(self, x): x = self.dropout(F.relu(self.linear_1(x))) x = self.linear_2(x) return x"
},
{
"code": null,
"e": 9800,
"s": 9673,
"text": "The feed-forward layer simply deepens our network, employing linear layers to analyse patterns in the attention layers output."
},
{
"code": null,
"e": 9994,
"s": 9800,
"text": "Normalisation is highly important in deep neural networks. It prevents the range of values in the layers changing too much, meaning the model trains faster and has better ability to generalise."
},
{
"code": null,
"e": 10129,
"s": 9994,
"text": "We will be normalising our results between each layer in the encoder/decoder, so before building our model let’s define that function:"
},
{
"code": null,
"e": 10625,
"s": 10129,
"text": "class Norm(nn.Module): def __init__(self, d_model, eps = 1e-6): super().__init__() self.size = d_model # create two learnable parameters to calibrate normalisation self.alpha = nn.Parameter(torch.ones(self.size)) self.bias = nn.Parameter(torch.zeros(self.size)) self.eps = eps def forward(self, x): norm = self.alpha * (x - x.mean(dim=-1, keepdim=True)) \\ / (x.std(dim=-1, keepdim=True) + self.eps) + self.bias return norm"
},
{
"code": null,
"e": 10742,
"s": 10625,
"text": "If you understand the details above, you now understand the model. The rest is simply putting everything into place."
},
{
"code": null,
"e": 10815,
"s": 10742,
"text": "Let’s have another look at the over-all architecture and start building:"
},
{
"code": null,
"e": 11295,
"s": 10815,
"text": "One last Variable: If you look at the diagram closely you can see a ‘Nx’ next to the encoder and decoder architectures. In reality, the encoder and decoder in the diagram above represent one layer of an encoder and one of the decoder. N is the variable for the number of layers there will be. Eg. if N=6, the data goes through six encoder layers (with the architecture seen above), then these outputs are passed to the decoder which also consists of six repeating decoder layers."
},
{
"code": null,
"e": 11490,
"s": 11295,
"text": "We will now build EncoderLayer and DecoderLayer modules with the architecture shown in the model above. Then when we build the encoder and decoder we can define how many of these layers to have."
},
{
"code": null,
"e": 13278,
"s": 11490,
"text": "# build an encoder layer with one multi-head attention layer and one # feed-forward layerclass EncoderLayer(nn.Module): def __init__(self, d_model, heads, dropout = 0.1): super().__init__() self.norm_1 = Norm(d_model) self.norm_2 = Norm(d_model) self.attn = MultiHeadAttention(heads, d_model) self.ff = FeedForward(d_model) self.dropout_1 = nn.Dropout(dropout) self.dropout_2 = nn.Dropout(dropout) def forward(self, x, mask): x2 = self.norm_1(x) x = x + self.dropout_1(self.attn(x2,x2,x2,mask)) x2 = self.norm_2(x) x = x + self.dropout_2(self.ff(x2)) return x # build a decoder layer with two multi-head attention layers and# one feed-forward layerclass DecoderLayer(nn.Module): def __init__(self, d_model, heads, dropout=0.1): super().__init__() self.norm_1 = Norm(d_model) self.norm_2 = Norm(d_model) self.norm_3 = Norm(d_model) self.dropout_1 = nn.Dropout(dropout) self.dropout_2 = nn.Dropout(dropout) self.dropout_3 = nn.Dropout(dropout) self.attn_1 = MultiHeadAttention(heads, d_model) self.attn_2 = MultiHeadAttention(heads, d_model) self.ff = FeedForward(d_model).cuda()def forward(self, x, e_outputs, src_mask, trg_mask): x2 = self.norm_1(x) x = x + self.dropout_1(self.attn_1(x2, x2, x2, trg_mask)) x2 = self.norm_2(x) x = x + self.dropout_2(self.attn_2(x2, e_outputs, e_outputs, src_mask)) x2 = self.norm_3(x) x = x + self.dropout_3(self.ff(x2)) return x# We can then build a convenient cloning function that can generate multiple layers:def get_clones(module, N): return nn.ModuleList([copy.deepcopy(module) for i in range(N)])"
},
{
"code": null,
"e": 13328,
"s": 13278,
"text": "We’re now ready to build the encoder and decoder:"
},
{
"code": null,
"e": 14366,
"s": 13328,
"text": "class Encoder(nn.Module): def __init__(self, vocab_size, d_model, N, heads): super().__init__() self.N = N self.embed = Embedder(vocab_size, d_model) self.pe = PositionalEncoder(d_model) self.layers = get_clones(EncoderLayer(d_model, heads), N) self.norm = Norm(d_model) def forward(self, src, mask): x = self.embed(src) x = self.pe(x) for i in range(N): x = self.layers[i](x, mask) return self.norm(x) class Decoder(nn.Module): def __init__(self, vocab_size, d_model, N, heads): super().__init__() self.N = N self.embed = Embedder(vocab_size, d_model) self.pe = PositionalEncoder(d_model) self.layers = get_clones(DecoderLayer(d_model, heads), N) self.norm = Norm(d_model) def forward(self, trg, e_outputs, src_mask, trg_mask): x = self.embed(trg) x = self.pe(x) for i in range(self.N): x = self.layers[i](x, e_outputs, src_mask, trg_mask) return self.norm(x)"
},
{
"code": null,
"e": 14398,
"s": 14366,
"text": "And finally... The transformer!"
},
{
"code": null,
"e": 15009,
"s": 14398,
"text": "class Transformer(nn.Module): def __init__(self, src_vocab, trg_vocab, d_model, N, heads): super().__init__() self.encoder = Encoder(src_vocab, d_model, N, heads) self.decoder = Decoder(trg_vocab, d_model, N, heads) self.out = nn.Linear(d_model, trg_vocab) def forward(self, src, trg, src_mask, trg_mask): e_outputs = self.encoder(src, src_mask) d_output = self.decoder(trg, e_outputs, src_mask, trg_mask) output = self.out(d_output) return output# we don't perform softmax on the output as this will be handled # automatically by our loss function"
},
{
"code": null,
"e": 15216,
"s": 15009,
"text": "With the transformer built, all that remains is to train that sucker on the EuroParl dataset. The coding part is pretty painless, but be prepared to wait for about 2 days for this model to start converging!"
},
{
"code": null,
"e": 15252,
"s": 15216,
"text": "Let’s define some parameters first:"
},
{
"code": null,
"e": 15745,
"s": 15252,
"text": "d_model = 512heads = 8N = 6src_vocab = len(EN_TEXT.vocab)trg_vocab = len(FR_TEXT.vocab)model = Transformer(src_vocab, trg_vocab, d_model, N, heads)for p in model.parameters(): if p.dim() > 1: nn.init.xavier_uniform_(p)# this code is very important! It initialises the parameters with a# range of values that stops the signal fading or getting too big.# See this blog for a mathematical explanation.optim = torch.optim.Adam(model.parameters(), lr=0.0001, betas=(0.9, 0.98), eps=1e-9)"
},
{
"code": null,
"e": 15774,
"s": 15745,
"text": "And now we’re good to train:"
},
{
"code": null,
"e": 17255,
"s": 15774,
"text": "def train_model(epochs, print_every=100): model.train() start = time.time() temp = start total_loss = 0 for epoch in range(epochs): for i, batch in enumerate(train_iter): src = batch.English.transpose(0,1) trg = batch.French.transpose(0,1) # the French sentence we input has all words except # the last, as it is using each word to predict the next trg_input = trg[:, :-1] # the words we are trying to predict targets = trg[:, 1:].contiguous().view(-1) # create function to make masks using mask code above src_mask, trg_mask = create_masks(src, trg_input) preds = model(src, trg_input, src_mask, trg_mask) optim.zero_grad() loss = F.cross_entropy(preds.view(-1, preds.size(-1)), results, ignore_index=target_pad) loss.backward() optim.step() total_loss += loss.data[0] if (i + 1) % print_every == 0: loss_avg = total_loss / print_every print(\"time = %dm, epoch %d, iter = %d, loss = %.3f, %ds per %d iters\" % ((time.time() - start) // 60, epoch + 1, i + 1, loss_avg, time.time() - temp, print_every)) total_loss = 0 temp = time.time()"
},
{
"code": null,
"e": 17386,
"s": 17255,
"text": "We can use the below function to translate sentences. We can feed it sentences directly from our batches, or input custom strings."
},
{
"code": null,
"e": 17814,
"s": 17386,
"text": "The translator works by running a loop. We start off by encoding the English sentence. We then feed the decoder the <sos> token index and the encoder outputs. The decoder makes a prediction for the first word, and we add this to our decoder input with the sos token. We rerun the loop, getting the next prediction and adding this to the decoder input, until we reach the <eos> token letting us know it has finished translating."
},
{
"code": null,
"e": 18820,
"s": 17814,
"text": "def translate(model, src, max_len = 80, custom_string=False): model.eval()if custom_sentence == True: src = tokenize_en(src) sentence=\\ Variable(torch.LongTensor([[EN_TEXT.vocab.stoi[tok] for tok in sentence]])).cuda()src_mask = (src != input_pad).unsqueeze(-2) e_outputs = model.encoder(src, src_mask) outputs = torch.zeros(max_len).type_as(src.data) outputs[0] = torch.LongTensor([FR_TEXT.vocab.stoi['<sos>']])for i in range(1, max_len): trg_mask = np.triu(np.ones((1, i, i), k=1).astype('uint8') trg_mask= Variable(torch.from_numpy(trg_mask) == 0).cuda() out = model.out(model.decoder(outputs[:i].unsqueeze(0), e_outputs, src_mask, trg_mask)) out = F.softmax(out, dim=-1) val, ix = out[:, -1].data.topk(1) outputs[i] = ix[0][0] if ix[0][0] == FR_TEXT.vocab.stoi['<eos>']: breakreturn ' '.join( [FR_TEXT.vocab.itos[ix] for ix in outputs[:i]] )"
}
] |
Display tooltip text while hovering a textbox in jQuery
|
For this, use jQuery(selector).toolTip().
Following is the code: −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
<label>Write Your Favourite Subject Name:</label>
<input id="demoTooltip" title="Your Favourite Subject may be JavaScript...">
</body>
<script>
jQuery(".demoTooltip").toolTip()
</script>
</html>
To run the above program, save the file name anyName.html (index.html). Right click on the file and select the option “Open with Live Server” in VS Code editor.
The output is as follows −
When you will hover the mouse inside the text box, you will get your tooltip −
Your Favourite Subject may be JavaScript...
Displayed in the below screenshot as well −
|
[
{
"code": null,
"e": 1104,
"s": 1062,
"text": "For this, use jQuery(selector).toolTip()."
},
{
"code": null,
"e": 1129,
"s": 1104,
"text": "Following is the code: −"
},
{
"code": null,
"e": 1140,
"s": 1129,
"text": " Live Demo"
},
{
"code": null,
"e": 1747,
"s": 1140,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n</head>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<body>\n <label>Write Your Favourite Subject Name:</label>\n <input id=\"demoTooltip\" title=\"Your Favourite Subject may be JavaScript...\">\n</body>\n<script>\n jQuery(\".demoTooltip\").toolTip()\n</script>\n</html>"
},
{
"code": null,
"e": 1908,
"s": 1747,
"text": "To run the above program, save the file name anyName.html (index.html). Right click on the file and select the option “Open with Live Server” in VS Code editor."
},
{
"code": null,
"e": 1935,
"s": 1908,
"text": "The output is as follows −"
},
{
"code": null,
"e": 2014,
"s": 1935,
"text": "When you will hover the mouse inside the text box, you will get your tooltip −"
},
{
"code": null,
"e": 2058,
"s": 2014,
"text": "Your Favourite Subject may be JavaScript..."
},
{
"code": null,
"e": 2102,
"s": 2058,
"text": "Displayed in the below screenshot as well −"
}
] |
Performance Metrics for Classification Machine Learning Problems | by Ramya Vidiyala | Towards Data Science
|
Many learning algorithms have been proposed. It is often valuable to assess the efficacy of an algorithm. In many cases, such assessment is relative, that is, evaluating which of several alternative algorithms is best suited to a specific application.
People even end up creating metrics that suit the application. In this article, we will see some of the most common metrics in a classification setting of a problem.
The most commonly used Performance metrics for classification problem are as follows,
Accuracy
Confusion Matrix
Precision, Recall, and F1 score
ROC AUC
Log-loss
Accuracy is the simple ratio between the number of correctly classified points to the total number of points.
To calculate accuracy, scikit-learn provides a utility function.
from sklearn.metrics import accuracy_score#predicted y valuesy_pred = [0, 2, 1, 3]#actual y valuesy_true = [0, 1, 2, 3]accuracy_score(y_true, y_pred)0.5
Accuracy is simple to calculate but has its own disadvantages.
If the data set is highly imbalanced, and the model classifies all the data points as the majority class data points, the accuracy will be high. This makes accuracy not a reliable performance metric for imbalanced data.
From accuracy, the probability of the predictions of the model can be derived. So from accuracy, we can not measure how good the predictions of the model are.
Confusion Matrix is a summary of predicted results in specific table layout that allows visualization of the performance measure of the machine learning model for a binary classification problem (2 classes) or multi-class classification problem (more than 2 classes)
TP means True Positive. It can be interpreted as the model predicted positive class and it is True.
FP means False Positive. It can be interpreted as the model predicted positive class but it is False.
FN means False Negative. It can be interpreted as the model predicted negative class but it is False.
TN means True Negative. It can be interpreted as the model predicted negative class and it is True.
For a sensible model, the principal diagonal element values will be high and the off-diagonal element values will be below i.e., TP, TN will be high.
To get an appropriate example in a real-world problem, consider a diagnostic test that seeks to determine whether a person has a certain disease. A false positive in this case occurs when the person tests positive but does not actually have the disease. A false negative, on the other hand, occurs when the person tests negative, suggesting they are healthy when they actually do have the disease.
For a multi-class classification problem, with ‘c’ class labels, the confusion matrix will be a (c*c) matrix.
To calculate confusion matrix, sklearn provides a utility function
from sklearn.metrics import confusion_matrixy_true = [2, 0, 2, 2, 0, 1]y_pred = [0, 0, 2, 2, 0, 2]confusion_matrix(y_true, y_pred)array([[2, 0, 0], [0, 0, 1], [1, 0, 2]])
The confusion matrix provides detailed results of the classification.
Derivates of the confusion matrix are widely used.
Visual inspection of results can be enhanced by using a heat map.
Precision is the fraction of the correctly classified instances from the total classified instances. Recall is the fraction of the correctly classified instances from the total classified instances. Precision and recall are given as follows,
For example, consider that a search query results in 30 pages, out of which 20 are relevant. And the results fail to display 40 other relevant results. So the precision is 20/30 and recall is 20/60.
Precision helps us understand how useful the results are. Recall helps us understand how complete the results are.
But to reduce the checking of pockets twice, the F1 score is used. F1 score is the harmonic mean of precision and recall. It is given as,
The F-score is often used in the field of information retrieval for measuring search, document classification, and query classification performance.
The F-score has been widely used in the natural language processing literature, such as the evaluation of named entity recognition and word segmentation.
Logarithmic loss (or log loss) measures the performance of a classification model where the prediction is a probability value between 0 and 1. Log loss increases as the predicted probability diverge from the actual label. Log loss is a widely used metric for Kaggle competitions.
Here ’N’ is the total number of data points in the data set, yi is the actual value of y and pi is the probability of y belonging to the positive class.
Lower the log-loss value, better are the predictions of the model.
To calculate log-loss, scikit-learn provides a utility function.
from sklearn.metrics import log_losslog_loss(y_true, y_pred)
A Receiver Operating Characteristic curve or ROC curve is created by plotting the True Positive (TP) against the False Positive (FP) at various threshold settings. The ROC curve is generated by plotting the cumulative distribution function of the True Positive in the y-axis versus the cumulative distribution function of the False Positive on the x-axis.
The area under the ROC curve (ROC AUC) is the single-valued metric used for evaluating the performance.
The higher the AUC, the better the performance of the model at distinguishing between the classes.
In general, an AUC of 0.5 suggests no discrimination, a value between 0.5–0.7 is acceptable and anything above 0.7 is good-to-go-model. However, medical diagnosis models, usually AUC of 0.95 or more is considered to be good-to-go-model.
ROC curves are widely used to compare and evaluate different classification algorithms.
ROC curve is widely used when the dataset is imbalanced.
ROC curves are also used in verification of forecasts in meteorology
Thanks for the read. I am going to write more beginner-friendly posts in the future. Follow me up on Medium to be informed about them. I welcome feedback and can be reached out on Twitter ramya_vidiyala and LinkedIn RamyaVidiyala. Happy learning!
|
[
{
"code": null,
"e": 424,
"s": 172,
"text": "Many learning algorithms have been proposed. It is often valuable to assess the efficacy of an algorithm. In many cases, such assessment is relative, that is, evaluating which of several alternative algorithms is best suited to a specific application."
},
{
"code": null,
"e": 590,
"s": 424,
"text": "People even end up creating metrics that suit the application. In this article, we will see some of the most common metrics in a classification setting of a problem."
},
{
"code": null,
"e": 676,
"s": 590,
"text": "The most commonly used Performance metrics for classification problem are as follows,"
},
{
"code": null,
"e": 685,
"s": 676,
"text": "Accuracy"
},
{
"code": null,
"e": 702,
"s": 685,
"text": "Confusion Matrix"
},
{
"code": null,
"e": 734,
"s": 702,
"text": "Precision, Recall, and F1 score"
},
{
"code": null,
"e": 742,
"s": 734,
"text": "ROC AUC"
},
{
"code": null,
"e": 751,
"s": 742,
"text": "Log-loss"
},
{
"code": null,
"e": 861,
"s": 751,
"text": "Accuracy is the simple ratio between the number of correctly classified points to the total number of points."
},
{
"code": null,
"e": 926,
"s": 861,
"text": "To calculate accuracy, scikit-learn provides a utility function."
},
{
"code": null,
"e": 1079,
"s": 926,
"text": "from sklearn.metrics import accuracy_score#predicted y valuesy_pred = [0, 2, 1, 3]#actual y valuesy_true = [0, 1, 2, 3]accuracy_score(y_true, y_pred)0.5"
},
{
"code": null,
"e": 1142,
"s": 1079,
"text": "Accuracy is simple to calculate but has its own disadvantages."
},
{
"code": null,
"e": 1362,
"s": 1142,
"text": "If the data set is highly imbalanced, and the model classifies all the data points as the majority class data points, the accuracy will be high. This makes accuracy not a reliable performance metric for imbalanced data."
},
{
"code": null,
"e": 1521,
"s": 1362,
"text": "From accuracy, the probability of the predictions of the model can be derived. So from accuracy, we can not measure how good the predictions of the model are."
},
{
"code": null,
"e": 1788,
"s": 1521,
"text": "Confusion Matrix is a summary of predicted results in specific table layout that allows visualization of the performance measure of the machine learning model for a binary classification problem (2 classes) or multi-class classification problem (more than 2 classes)"
},
{
"code": null,
"e": 1888,
"s": 1788,
"text": "TP means True Positive. It can be interpreted as the model predicted positive class and it is True."
},
{
"code": null,
"e": 1990,
"s": 1888,
"text": "FP means False Positive. It can be interpreted as the model predicted positive class but it is False."
},
{
"code": null,
"e": 2092,
"s": 1990,
"text": "FN means False Negative. It can be interpreted as the model predicted negative class but it is False."
},
{
"code": null,
"e": 2192,
"s": 2092,
"text": "TN means True Negative. It can be interpreted as the model predicted negative class and it is True."
},
{
"code": null,
"e": 2342,
"s": 2192,
"text": "For a sensible model, the principal diagonal element values will be high and the off-diagonal element values will be below i.e., TP, TN will be high."
},
{
"code": null,
"e": 2740,
"s": 2342,
"text": "To get an appropriate example in a real-world problem, consider a diagnostic test that seeks to determine whether a person has a certain disease. A false positive in this case occurs when the person tests positive but does not actually have the disease. A false negative, on the other hand, occurs when the person tests negative, suggesting they are healthy when they actually do have the disease."
},
{
"code": null,
"e": 2850,
"s": 2740,
"text": "For a multi-class classification problem, with ‘c’ class labels, the confusion matrix will be a (c*c) matrix."
},
{
"code": null,
"e": 2917,
"s": 2850,
"text": "To calculate confusion matrix, sklearn provides a utility function"
},
{
"code": null,
"e": 3100,
"s": 2917,
"text": "from sklearn.metrics import confusion_matrixy_true = [2, 0, 2, 2, 0, 1]y_pred = [0, 0, 2, 2, 0, 2]confusion_matrix(y_true, y_pred)array([[2, 0, 0], [0, 0, 1], [1, 0, 2]])"
},
{
"code": null,
"e": 3170,
"s": 3100,
"text": "The confusion matrix provides detailed results of the classification."
},
{
"code": null,
"e": 3221,
"s": 3170,
"text": "Derivates of the confusion matrix are widely used."
},
{
"code": null,
"e": 3287,
"s": 3221,
"text": "Visual inspection of results can be enhanced by using a heat map."
},
{
"code": null,
"e": 3529,
"s": 3287,
"text": "Precision is the fraction of the correctly classified instances from the total classified instances. Recall is the fraction of the correctly classified instances from the total classified instances. Precision and recall are given as follows,"
},
{
"code": null,
"e": 3728,
"s": 3529,
"text": "For example, consider that a search query results in 30 pages, out of which 20 are relevant. And the results fail to display 40 other relevant results. So the precision is 20/30 and recall is 20/60."
},
{
"code": null,
"e": 3843,
"s": 3728,
"text": "Precision helps us understand how useful the results are. Recall helps us understand how complete the results are."
},
{
"code": null,
"e": 3981,
"s": 3843,
"text": "But to reduce the checking of pockets twice, the F1 score is used. F1 score is the harmonic mean of precision and recall. It is given as,"
},
{
"code": null,
"e": 4130,
"s": 3981,
"text": "The F-score is often used in the field of information retrieval for measuring search, document classification, and query classification performance."
},
{
"code": null,
"e": 4284,
"s": 4130,
"text": "The F-score has been widely used in the natural language processing literature, such as the evaluation of named entity recognition and word segmentation."
},
{
"code": null,
"e": 4564,
"s": 4284,
"text": "Logarithmic loss (or log loss) measures the performance of a classification model where the prediction is a probability value between 0 and 1. Log loss increases as the predicted probability diverge from the actual label. Log loss is a widely used metric for Kaggle competitions."
},
{
"code": null,
"e": 4717,
"s": 4564,
"text": "Here ’N’ is the total number of data points in the data set, yi is the actual value of y and pi is the probability of y belonging to the positive class."
},
{
"code": null,
"e": 4784,
"s": 4717,
"text": "Lower the log-loss value, better are the predictions of the model."
},
{
"code": null,
"e": 4849,
"s": 4784,
"text": "To calculate log-loss, scikit-learn provides a utility function."
},
{
"code": null,
"e": 4910,
"s": 4849,
"text": "from sklearn.metrics import log_losslog_loss(y_true, y_pred)"
},
{
"code": null,
"e": 5266,
"s": 4910,
"text": "A Receiver Operating Characteristic curve or ROC curve is created by plotting the True Positive (TP) against the False Positive (FP) at various threshold settings. The ROC curve is generated by plotting the cumulative distribution function of the True Positive in the y-axis versus the cumulative distribution function of the False Positive on the x-axis."
},
{
"code": null,
"e": 5370,
"s": 5266,
"text": "The area under the ROC curve (ROC AUC) is the single-valued metric used for evaluating the performance."
},
{
"code": null,
"e": 5469,
"s": 5370,
"text": "The higher the AUC, the better the performance of the model at distinguishing between the classes."
},
{
"code": null,
"e": 5706,
"s": 5469,
"text": "In general, an AUC of 0.5 suggests no discrimination, a value between 0.5–0.7 is acceptable and anything above 0.7 is good-to-go-model. However, medical diagnosis models, usually AUC of 0.95 or more is considered to be good-to-go-model."
},
{
"code": null,
"e": 5794,
"s": 5706,
"text": "ROC curves are widely used to compare and evaluate different classification algorithms."
},
{
"code": null,
"e": 5851,
"s": 5794,
"text": "ROC curve is widely used when the dataset is imbalanced."
},
{
"code": null,
"e": 5920,
"s": 5851,
"text": "ROC curves are also used in verification of forecasts in meteorology"
}
] |
Switching among OpenCV, Tensorflow and Pillow? Wait!!! | by Saksham Sinha | Towards Data Science
|
Modern Computer Vision (CV) is currently a hot field of research which involves largely working with images. For this, one needs to use a framework to open those images to do some processing on them.
In today’s rapid development of frameworks, every framework has its own way of handling images, each with its own specifications. Therefore, CV solutions developed in one framework may not work as expected in the other framework. The blog “How Tensorflow’s tf.image.resize stole 60 days of my life” (https://hackernoon.com/how-tensorflows-tf-image-resize-stole-60-days-of-my-life-aba5eb093f35) is a perfect example of this type of situation. It can take up multiple days to figure out what went wrong and could delay the project extensively.
This blog will discuss one such use case in detail where OpenCV and Tensorflow show the differences in reading and resizing a JPEG image. It will also show a way to make them work consistently. Also, thanks to Tejas Pandey for the help in achieving consistency between OpenCV and Tensorflow.
We’ll start with opening a simple JPEG image of a dog with two frameworks Tensorflow 1.x and OpenCV.
Let’s get started. We’ll import a few essential libraries in python.
%tensorflow_version 1.ximport cv2import matplotlib.pyplot as pltimport numpy as npfrom skimage import ioimport tensorflow as tf
Let’s open an image using OpenCV.
image_path = 'dog2.JPG'def plt_display(image, title): fig = plt.figure() a = fig.add_subplot(1, 1, 1) imgplot = plt.imshow(image) a.set_title(title)image = cv2.imread(image_path)plt_display(image, 'cv2-BGR')
Something’s strange about this figure above. It doesn’t look like the original. Well, yes, that’s true. Before diving into this, first let’s learn how colors in images are represented. Generally, images have three colors channels Red, Green, and Blue (RGB) which produces the colors in the pixel. The order of these channels changes the color of the pixels, as pixels will always interpret first channel as Red, second channel as Green and third channel as Blue.
Now that we have an understanding of how color channels work in an image, let’s look into why we saw a different color image above. When we open an image using OpenCV, by default OpenCV opens the image in Blue, Green and Red channel (BGR). This is fine but when we display the image, the pixels misinterpret the channels (i.e. pixels get confused and interpret Blue as Red and vice-versa). That’s why we get the above wrong colors in the image.
So how to fix this? After opening the image, we convert the image from BGR to RGB. We do this by using the OpenCV flag COLOR_BGR2RGB. The code below shows how to open an image with OpenCV correctly.
image_cv = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)print(image_cv.dtype)print(np.max(image_cv))plt_display(image_cv, 'cv2-RGB')
Let’s open an image with Tensorflow now and see if we get the same results. It’s a two-step process to open a JPEG image in Tensorflow. The first step is to open the image, and the second step is to perform JPEG decoding as JPEG is a compressed image.
print("Tensorflow version: ", tf.__version__)image_tf = tf.io.read_file(image_path)image_tf = tf.image.decode_jpeg(image_tf, channels=3)with tf.Session() as sess: image_tf = image_tf.eval()print(image_tf.dtype)plt_display(image_tf, 'TF')
On visual inspection, the image read from OpenCV and Tensorflow look the same. But are they? To see what are the differences, let’s subtract the two. If the two are same, we should see a completely black image. If not, then we will see some pixels with different colors.
image_diff = np.abs(image_cv- image_tf)plt_display(image_diff, 'OpenCV-TF')
Woah! That’s a huge difference. What went wrong? Well, this difference is arising from the fact that OpenCV, by default, uses integer accurate decompression of the JPEG image. In contrast, TensorFlow uses Discrete Cosine Transform as default. This type of decoding is inaccurate and so to make it the same as OpenCV, we need to decode it by using integer accurate decompression. This can be done by setting the parameter dct_method=’INTEGER_ACCURATE’ as shown below.
image_tf = tf.io.read_file(image_path)image_tf = tf.image.decode_jpeg(image_tf, channels=3, dct_method='INTEGER_ACCURATE')with tf.Session() as sess: image_tf = image_tf.eval()plt_display(image_tf,'TF_INT_ACC')
And now subtracting with the OpenCV image we get a black image. This means both our TF and OpenCV are now consistent in reading the image. This is an essential step because a small change in how you read the image will give rise to significant differences in the processing of the image later.
image_diff = np.abs(image_cv- image_tf)plt_display(image_diff, 'OpenCV-TF')
Now, since we have read the image consistently with OpenCV and TensorFlow, let’s try the resizing of the images with these frameworks. We’ll begin with OpenCV resize first.
# resizing the image with OpenCVprint("image shape before resize:", image_cv.shape)image_cv_resized = cv2.resize(image_cv,(300,300))print("image shape after resize:", image_cv_resized.shape)print("image dtype: ", image_cv_resized.dtype)
We have the OpenCV resize done. Now let’s do the TensorFlow resize. Tensorflow work with tensors. It’s resizing method expects a 4D tensor and returns a 4D tensor output. Hence, we will have to first expand the image from three to four. Then resize the image and squeeze the dimensions back to three. Since our image is still a tensor, we will create and run a Tensorflow session to get back our resized image in NumPy format. Once we have the NumPy image, we convert it to uint8 type as by default, session converts the NumPy to float32 type. This makes the types inconsistent with OpenCV. This is shown below-
# resizing the image with tensorflow 1.xprint("image shape before resize:", image_tf.shape)print("image dtype: ", image_tf.dtype)#This function takes in a 4D input. Hence we will have to expand the image and then squeeze back to three dimensions before we can use it as an image.image_tf_4D= tf.expand_dims(image_tf,0)# doing bilinear resizeimage_tf_resized_4D = tf.image.resize_bilinear( image_tf_4D, (300,300))#squeezing back the image to 3Dimage_tf_resized = tf.squeeze(image_tf_resized_4D)#Above is still a tensor. So we need to convert it to numpy. We do this by using tf session.with tf.Session() as sess: image_tf_resized = image_tf_resized.eval()print("image shape after resize:", image_tf_resized.shape)print("image dtype: ", image_tf_resized.dtype)#Since it is in float32 format, we need to convert it back to uint8.image_tf_resized = image_tf_resized.astype(np.uint8)print("image dtype after conversion uint8: ", image_tf_resized.dtype)
Now let’s see the difference between the resized images from OpenCV and TF.
image_resized_diff = np.abs(image_cv_resized- image_tf_resized)plt_display(image_resized_diff, 'Resized OpenCV2 - Resized TF')
We again see a big difference in the resize method of the two frameworks. Even when we opened the images consistently across both frameworks, the resize method gave different results. OpenCV resize method, by default, uses bilinear transformation. We used the same bilinear method with Tensorflow. Still, we ended up with different results.
This happened because OpenCV adds half-pixel corrections to the image while resizing. Whereas Tensorflow by default doesn’t. This adds up the difference in the resizing method outputs.
In order to fix this problem, there is a parameter in the TensorFlow bilinear resize that will do the half-pixel correction. This is shown below-
image_tf_4D= tf.expand_dims(image_tf,0)# doing bilinear resize with half pixel correctionimage_tf_resized_hpc_4D = tf.image.resize_bilinear( image_tf_4D, (300,300), half_pixel_centers=True)image_tf_resized_hpc = tf.squeeze(image_tf_resized_hpc_4D)with tf.Session() as sess: image_tf_resized_hpc = image_tf_resized_hpc.eval()image_tf_resized_hpc = image_tf_resized_hpc.astype(np.uint8)image_resized_diff = np.abs(image_cv_resized- image_tf_resized_hpc)plt_display(image_resized_diff, 'Resized OpenCV2 - Resized TF')
And now we have the expected result. Finally, we have Tensorflow and OpenCV working consistently with reading and resizing images.
A new person in the Computer Vision field trying out these functions will more likely make these mistakes and will be off to a bad start. Tutorials across the internet do not discuss this in detail. I created this blog to show people that from one framework to another, small minor things like what I discussed need to be checked and kept consistent. Otherwise, they will have different results in different frameworks and will adversely affect their work.
Another framework widely used is Pillow (PIL). Let’s see the differences with PIL and OpenCV. We’ll first read the image using PIL.
from PIL import Imageorig_image_pil = Image.open(image_path)image_pil = np.asarray(orig_image_pil)print(image_pil.dtype)plt_display(image_pil, 'PIL')
Now we will see if there is any difference between JPEG image opened by PIL and OpenCV.
image_cv_pil_diff = np.abs(image_cv - image_pil)plt_display(image_cv_pil_diff, 'CV-PIL-DIFF')
As expected from our experience from TF and OpenCV, these two frameworks again open the images differently. PIL, by default, doesn’t provide any way to use integer accurate decompression. However, one can write their own decoder to decode images. But in this blog, I am only showing the differences and if possible, to make them consistent if the library provides the support for it.
Since the images are read differently between these frameworks, this difference will propagate when we do resize. This is shown below-
image_pil_resized = orig_image_pil.resize((300,300), resample=Image.BILINEAR)image_pil_resized = np.asarray(image_pil_resized)#making sure we have the same dtype as OpenCV image.print(image_pil_resized.dtype)
image_cv_pil_resize_diff = np.abs(image_cv_resized - image_pil_resized)plt_display(image_cv_pil_resize_diff, 'Resized CV- Resized PIL')
Hence, we get the expected difference in resizing. PIL library doesn’t provide any support for half-pixel correction, and so there is no by default support for this. Since we know TF and OpenCV are consistent, we can expect the same results when considering the difference between PIL and TF as well.
Hence, when using PIL framework, one must keep this in mind that one cannot switch directly to another framework if the work is dependent on the pre-processing of the images such as above. This will lead to unexpected results.
I hope that this blog was useful to you and was able to make you aware of the framework dependent processing.
|
[
{
"code": null,
"e": 372,
"s": 172,
"text": "Modern Computer Vision (CV) is currently a hot field of research which involves largely working with images. For this, one needs to use a framework to open those images to do some processing on them."
},
{
"code": null,
"e": 914,
"s": 372,
"text": "In today’s rapid development of frameworks, every framework has its own way of handling images, each with its own specifications. Therefore, CV solutions developed in one framework may not work as expected in the other framework. The blog “How Tensorflow’s tf.image.resize stole 60 days of my life” (https://hackernoon.com/how-tensorflows-tf-image-resize-stole-60-days-of-my-life-aba5eb093f35) is a perfect example of this type of situation. It can take up multiple days to figure out what went wrong and could delay the project extensively."
},
{
"code": null,
"e": 1206,
"s": 914,
"text": "This blog will discuss one such use case in detail where OpenCV and Tensorflow show the differences in reading and resizing a JPEG image. It will also show a way to make them work consistently. Also, thanks to Tejas Pandey for the help in achieving consistency between OpenCV and Tensorflow."
},
{
"code": null,
"e": 1307,
"s": 1206,
"text": "We’ll start with opening a simple JPEG image of a dog with two frameworks Tensorflow 1.x and OpenCV."
},
{
"code": null,
"e": 1376,
"s": 1307,
"text": "Let’s get started. We’ll import a few essential libraries in python."
},
{
"code": null,
"e": 1504,
"s": 1376,
"text": "%tensorflow_version 1.ximport cv2import matplotlib.pyplot as pltimport numpy as npfrom skimage import ioimport tensorflow as tf"
},
{
"code": null,
"e": 1538,
"s": 1504,
"text": "Let’s open an image using OpenCV."
},
{
"code": null,
"e": 1750,
"s": 1538,
"text": "image_path = 'dog2.JPG'def plt_display(image, title): fig = plt.figure() a = fig.add_subplot(1, 1, 1) imgplot = plt.imshow(image) a.set_title(title)image = cv2.imread(image_path)plt_display(image, 'cv2-BGR')"
},
{
"code": null,
"e": 2213,
"s": 1750,
"text": "Something’s strange about this figure above. It doesn’t look like the original. Well, yes, that’s true. Before diving into this, first let’s learn how colors in images are represented. Generally, images have three colors channels Red, Green, and Blue (RGB) which produces the colors in the pixel. The order of these channels changes the color of the pixels, as pixels will always interpret first channel as Red, second channel as Green and third channel as Blue."
},
{
"code": null,
"e": 2658,
"s": 2213,
"text": "Now that we have an understanding of how color channels work in an image, let’s look into why we saw a different color image above. When we open an image using OpenCV, by default OpenCV opens the image in Blue, Green and Red channel (BGR). This is fine but when we display the image, the pixels misinterpret the channels (i.e. pixels get confused and interpret Blue as Red and vice-versa). That’s why we get the above wrong colors in the image."
},
{
"code": null,
"e": 2857,
"s": 2658,
"text": "So how to fix this? After opening the image, we convert the image from BGR to RGB. We do this by using the OpenCV flag COLOR_BGR2RGB. The code below shows how to open an image with OpenCV correctly."
},
{
"code": null,
"e": 2983,
"s": 2857,
"text": "image_cv = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)print(image_cv.dtype)print(np.max(image_cv))plt_display(image_cv, 'cv2-RGB')"
},
{
"code": null,
"e": 3235,
"s": 2983,
"text": "Let’s open an image with Tensorflow now and see if we get the same results. It’s a two-step process to open a JPEG image in Tensorflow. The first step is to open the image, and the second step is to perform JPEG decoding as JPEG is a compressed image."
},
{
"code": null,
"e": 3476,
"s": 3235,
"text": "print(\"Tensorflow version: \", tf.__version__)image_tf = tf.io.read_file(image_path)image_tf = tf.image.decode_jpeg(image_tf, channels=3)with tf.Session() as sess: image_tf = image_tf.eval()print(image_tf.dtype)plt_display(image_tf, 'TF')"
},
{
"code": null,
"e": 3747,
"s": 3476,
"text": "On visual inspection, the image read from OpenCV and Tensorflow look the same. But are they? To see what are the differences, let’s subtract the two. If the two are same, we should see a completely black image. If not, then we will see some pixels with different colors."
},
{
"code": null,
"e": 3823,
"s": 3747,
"text": "image_diff = np.abs(image_cv- image_tf)plt_display(image_diff, 'OpenCV-TF')"
},
{
"code": null,
"e": 4290,
"s": 3823,
"text": "Woah! That’s a huge difference. What went wrong? Well, this difference is arising from the fact that OpenCV, by default, uses integer accurate decompression of the JPEG image. In contrast, TensorFlow uses Discrete Cosine Transform as default. This type of decoding is inaccurate and so to make it the same as OpenCV, we need to decode it by using integer accurate decompression. This can be done by setting the parameter dct_method=’INTEGER_ACCURATE’ as shown below."
},
{
"code": null,
"e": 4503,
"s": 4290,
"text": "image_tf = tf.io.read_file(image_path)image_tf = tf.image.decode_jpeg(image_tf, channels=3, dct_method='INTEGER_ACCURATE')with tf.Session() as sess: image_tf = image_tf.eval()plt_display(image_tf,'TF_INT_ACC')"
},
{
"code": null,
"e": 4797,
"s": 4503,
"text": "And now subtracting with the OpenCV image we get a black image. This means both our TF and OpenCV are now consistent in reading the image. This is an essential step because a small change in how you read the image will give rise to significant differences in the processing of the image later."
},
{
"code": null,
"e": 4873,
"s": 4797,
"text": "image_diff = np.abs(image_cv- image_tf)plt_display(image_diff, 'OpenCV-TF')"
},
{
"code": null,
"e": 5046,
"s": 4873,
"text": "Now, since we have read the image consistently with OpenCV and TensorFlow, let’s try the resizing of the images with these frameworks. We’ll begin with OpenCV resize first."
},
{
"code": null,
"e": 5283,
"s": 5046,
"text": "# resizing the image with OpenCVprint(\"image shape before resize:\", image_cv.shape)image_cv_resized = cv2.resize(image_cv,(300,300))print(\"image shape after resize:\", image_cv_resized.shape)print(\"image dtype: \", image_cv_resized.dtype)"
},
{
"code": null,
"e": 5895,
"s": 5283,
"text": "We have the OpenCV resize done. Now let’s do the TensorFlow resize. Tensorflow work with tensors. It’s resizing method expects a 4D tensor and returns a 4D tensor output. Hence, we will have to first expand the image from three to four. Then resize the image and squeeze the dimensions back to three. Since our image is still a tensor, we will create and run a Tensorflow session to get back our resized image in NumPy format. Once we have the NumPy image, we convert it to uint8 type as by default, session converts the NumPy to float32 type. This makes the types inconsistent with OpenCV. This is shown below-"
},
{
"code": null,
"e": 6850,
"s": 5895,
"text": "# resizing the image with tensorflow 1.xprint(\"image shape before resize:\", image_tf.shape)print(\"image dtype: \", image_tf.dtype)#This function takes in a 4D input. Hence we will have to expand the image and then squeeze back to three dimensions before we can use it as an image.image_tf_4D= tf.expand_dims(image_tf,0)# doing bilinear resizeimage_tf_resized_4D = tf.image.resize_bilinear( image_tf_4D, (300,300))#squeezing back the image to 3Dimage_tf_resized = tf.squeeze(image_tf_resized_4D)#Above is still a tensor. So we need to convert it to numpy. We do this by using tf session.with tf.Session() as sess: image_tf_resized = image_tf_resized.eval()print(\"image shape after resize:\", image_tf_resized.shape)print(\"image dtype: \", image_tf_resized.dtype)#Since it is in float32 format, we need to convert it back to uint8.image_tf_resized = image_tf_resized.astype(np.uint8)print(\"image dtype after conversion uint8: \", image_tf_resized.dtype)"
},
{
"code": null,
"e": 6926,
"s": 6850,
"text": "Now let’s see the difference between the resized images from OpenCV and TF."
},
{
"code": null,
"e": 7053,
"s": 6926,
"text": "image_resized_diff = np.abs(image_cv_resized- image_tf_resized)plt_display(image_resized_diff, 'Resized OpenCV2 - Resized TF')"
},
{
"code": null,
"e": 7394,
"s": 7053,
"text": "We again see a big difference in the resize method of the two frameworks. Even when we opened the images consistently across both frameworks, the resize method gave different results. OpenCV resize method, by default, uses bilinear transformation. We used the same bilinear method with Tensorflow. Still, we ended up with different results."
},
{
"code": null,
"e": 7579,
"s": 7394,
"text": "This happened because OpenCV adds half-pixel corrections to the image while resizing. Whereas Tensorflow by default doesn’t. This adds up the difference in the resizing method outputs."
},
{
"code": null,
"e": 7725,
"s": 7579,
"text": "In order to fix this problem, there is a parameter in the TensorFlow bilinear resize that will do the half-pixel correction. This is shown below-"
},
{
"code": null,
"e": 8250,
"s": 7725,
"text": "image_tf_4D= tf.expand_dims(image_tf,0)# doing bilinear resize with half pixel correctionimage_tf_resized_hpc_4D = tf.image.resize_bilinear( image_tf_4D, (300,300), half_pixel_centers=True)image_tf_resized_hpc = tf.squeeze(image_tf_resized_hpc_4D)with tf.Session() as sess: image_tf_resized_hpc = image_tf_resized_hpc.eval()image_tf_resized_hpc = image_tf_resized_hpc.astype(np.uint8)image_resized_diff = np.abs(image_cv_resized- image_tf_resized_hpc)plt_display(image_resized_diff, 'Resized OpenCV2 - Resized TF')"
},
{
"code": null,
"e": 8381,
"s": 8250,
"text": "And now we have the expected result. Finally, we have Tensorflow and OpenCV working consistently with reading and resizing images."
},
{
"code": null,
"e": 8838,
"s": 8381,
"text": "A new person in the Computer Vision field trying out these functions will more likely make these mistakes and will be off to a bad start. Tutorials across the internet do not discuss this in detail. I created this blog to show people that from one framework to another, small minor things like what I discussed need to be checked and kept consistent. Otherwise, they will have different results in different frameworks and will adversely affect their work."
},
{
"code": null,
"e": 8970,
"s": 8838,
"text": "Another framework widely used is Pillow (PIL). Let’s see the differences with PIL and OpenCV. We’ll first read the image using PIL."
},
{
"code": null,
"e": 9120,
"s": 8970,
"text": "from PIL import Imageorig_image_pil = Image.open(image_path)image_pil = np.asarray(orig_image_pil)print(image_pil.dtype)plt_display(image_pil, 'PIL')"
},
{
"code": null,
"e": 9208,
"s": 9120,
"text": "Now we will see if there is any difference between JPEG image opened by PIL and OpenCV."
},
{
"code": null,
"e": 9302,
"s": 9208,
"text": "image_cv_pil_diff = np.abs(image_cv - image_pil)plt_display(image_cv_pil_diff, 'CV-PIL-DIFF')"
},
{
"code": null,
"e": 9686,
"s": 9302,
"text": "As expected from our experience from TF and OpenCV, these two frameworks again open the images differently. PIL, by default, doesn’t provide any way to use integer accurate decompression. However, one can write their own decoder to decode images. But in this blog, I am only showing the differences and if possible, to make them consistent if the library provides the support for it."
},
{
"code": null,
"e": 9821,
"s": 9686,
"text": "Since the images are read differently between these frameworks, this difference will propagate when we do resize. This is shown below-"
},
{
"code": null,
"e": 10036,
"s": 9821,
"text": "image_pil_resized = orig_image_pil.resize((300,300), resample=Image.BILINEAR)image_pil_resized = np.asarray(image_pil_resized)#making sure we have the same dtype as OpenCV image.print(image_pil_resized.dtype)"
},
{
"code": null,
"e": 10172,
"s": 10036,
"text": "image_cv_pil_resize_diff = np.abs(image_cv_resized - image_pil_resized)plt_display(image_cv_pil_resize_diff, 'Resized CV- Resized PIL')"
},
{
"code": null,
"e": 10473,
"s": 10172,
"text": "Hence, we get the expected difference in resizing. PIL library doesn’t provide any support for half-pixel correction, and so there is no by default support for this. Since we know TF and OpenCV are consistent, we can expect the same results when considering the difference between PIL and TF as well."
},
{
"code": null,
"e": 10700,
"s": 10473,
"text": "Hence, when using PIL framework, one must keep this in mind that one cannot switch directly to another framework if the work is dependent on the pre-processing of the images such as above. This will lead to unexpected results."
}
] |
Mirror Tree | Practice | GeeksforGeeks
|
Given a Binary Tree, convert it into its mirror.
Example 1:
Input:
1
/ \
2 3
Output: 3 1 2
Explanation: The tree is
1 (mirror) 1
/ \ => / \
2 3 3 2
The inorder of mirror is 3 1 2
Example 2:
Input:
10
/ \
20 30
/ \
40 60
Output: 30 10 60 20 40
Explanation: The tree is
10 10
/ \ (mirror) / \
20 30 => 30 20
/ \ / \
40 60 60 40
The inroder traversal of mirror is
30 10 60 20 40.
Your Task:
Just complete the function mirror() that takes node as paramter and convert it into its mirror. The printing is done by the driver code only.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the Tree).
Constraints:
1 ≤ Number of nodes ≤ 105
1 ≤ Data of a node ≤ 105
0
amarrajsmart1972 weeks ago
C++ Solution.
if(node==NULL) return ; mirror(node->left); mirror(node->right); swap(node->left,node->right);
0
hharshit81182 weeks ago
void mirror(Node* node) { if(node == NULL){ return; }
mirror(node->left); mirror(node->right); Node* temp = node->left; node->left = node->right; node->right = temp; }
+1
harshsinghreal3 weeks ago
C++ 4LINES OF CODE
void mirror(Node* node) {
if(node==NULL) return;
swap(node->left,node->right);
mirror(node->left);
mirror(node->right);
}
0
joyrockok3 weeks ago
class Solution { // Function to convert a binary tree into its mirror tree. void mirror(Node node) { // Your code here if(node == null) return; Node temp = node.left; node.left = node.right; node.right = temp; mirror(node.left); mirror(node.right); }}
0
adityagagtiwari3 weeks ago
Just swap the links of left and right nodes.
Recursively do this for all the nodes. And voila.
class Solution {
// Function to convert a binary tree into its mirror tree.
void mirror(Node node) {
// Your code here
if(node==null)
return;
Node temp = node.left;
node.left = node.right;
node.right = temp;
mirror(node.left);
mirror(node.right);
}
}
0
soumyadeepdatta344 weeks ago
class Solution {
// Function to convert a binary tree into its mirror tree.
void mirror(Node node) {
// Your code here
if (node == null || (node.left == null && node.right == null)) {
return;
}
mirror(node.left);
mirror(node.right);
Node tmp;
tmp = node.left;
node.left = node.right;
node.right = tmp;
}
}
0
harvey20014 weeks ago
void mirror(Node* root) { if(root==NULL) return; if(root->left) mirror(root->left); if(root->right) mirror(root->right); swap(root->left,root->right); }
0
vainalavinayvvk0981 month ago
class Solution: def mirrortraversal(self,root,res): if root: root.left,root.right = root.right,root.left self.mirrortraversal(root.left,res) res.append(root.data) self.mirrortraversal(root.right,res)
return res #Function to convert a binary tree into its mirror tree. def mirror(self,root): # Code here res = [] val = self.mirrortraversal(root,res) return val
0
sharmaaditya130641 month ago
void mirror(Node* root) {
if(!root)return;
swap(root->left,root->right);
mirror(root->left);
mirror(root->right);
}
0
crawler1 month ago
void swap(Node *node){
Node *left = node->left;
node->left = node->right;
node->right = left;
}
void mirror(Node* node) {
if(!node){
return;
}
mirror(node->left);
mirror(node->right);
swap(node);
}
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": 301,
"s": 238,
"text": "Given a Binary Tree, convert it into its mirror.\n "
},
{
"code": null,
"e": 312,
"s": 301,
"text": "Example 1:"
},
{
"code": null,
"e": 482,
"s": 312,
"text": "Input:\n 1\n / \\\n 2 3\nOutput: 3 1 2\nExplanation: The tree is\n 1 (mirror) 1\n / \\ => / \\\n2 3 3 2\nThe inorder of mirror is 3 1 2\n"
},
{
"code": null,
"e": 493,
"s": 482,
"text": "Example 2:"
},
{
"code": null,
"e": 793,
"s": 493,
"text": "Input:\n 10\n / \\\n 20 30\n / \\\n 40 60\nOutput: 30 10 60 20 40\nExplanation: The tree is\n 10 10\n / \\ (mirror) / \\\n 20 30 => 30 20\n / \\ / \\\n 40 60 60 40\nThe inroder traversal of mirror is\n30 10 60 20 40."
},
{
"code": null,
"e": 947,
"s": 793,
"text": "Your Task:\nJust complete the function mirror() that takes node as paramter and convert it into its mirror. The printing is done by the driver code only."
},
{
"code": null,
"e": 1028,
"s": 947,
"text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(Height of the Tree)."
},
{
"code": null,
"e": 1092,
"s": 1028,
"text": "Constraints:\n1 ≤ Number of nodes ≤ 105\n1 ≤ Data of a node ≤ 105"
},
{
"code": null,
"e": 1094,
"s": 1092,
"text": "0"
},
{
"code": null,
"e": 1121,
"s": 1094,
"text": "amarrajsmart1972 weeks ago"
},
{
"code": null,
"e": 1135,
"s": 1121,
"text": "C++ Solution."
},
{
"code": null,
"e": 1264,
"s": 1135,
"text": "if(node==NULL) return ; mirror(node->left); mirror(node->right); swap(node->left,node->right); "
},
{
"code": null,
"e": 1266,
"s": 1264,
"text": "0"
},
{
"code": null,
"e": 1290,
"s": 1266,
"text": "hharshit81182 weeks ago"
},
{
"code": null,
"e": 1368,
"s": 1290,
"text": " void mirror(Node* node) { if(node == NULL){ return; }"
},
{
"code": null,
"e": 1516,
"s": 1368,
"text": " mirror(node->left); mirror(node->right); Node* temp = node->left; node->left = node->right; node->right = temp; }"
},
{
"code": null,
"e": 1519,
"s": 1516,
"text": "+1"
},
{
"code": null,
"e": 1545,
"s": 1519,
"text": "harshsinghreal3 weeks ago"
},
{
"code": null,
"e": 1564,
"s": 1545,
"text": "C++ 4LINES OF CODE"
},
{
"code": null,
"e": 1742,
"s": 1564,
"text": "void mirror(Node* node) {\n\n\n if(node==NULL) return;\n swap(node->left,node->right);\n mirror(node->left);\n mirror(node->right);\n \n \n }"
},
{
"code": null,
"e": 1744,
"s": 1742,
"text": "0"
},
{
"code": null,
"e": 1765,
"s": 1744,
"text": "joyrockok3 weeks ago"
},
{
"code": null,
"e": 2077,
"s": 1765,
"text": "class Solution { // Function to convert a binary tree into its mirror tree. void mirror(Node node) { // Your code here if(node == null) return; Node temp = node.left; node.left = node.right; node.right = temp; mirror(node.left); mirror(node.right); }}"
},
{
"code": null,
"e": 2079,
"s": 2077,
"text": "0"
},
{
"code": null,
"e": 2106,
"s": 2079,
"text": "adityagagtiwari3 weeks ago"
},
{
"code": null,
"e": 2518,
"s": 2106,
"text": "Just swap the links of left and right nodes.\nRecursively do this for all the nodes. And voila.\n\nclass Solution {\n // Function to convert a binary tree into its mirror tree.\n void mirror(Node node) {\n // Your code here\n if(node==null)\n return;\n Node temp = node.left;\n node.left = node.right;\n node.right = temp;\n mirror(node.left);\n mirror(node.right);\n }\n}"
},
{
"code": null,
"e": 2520,
"s": 2518,
"text": "0"
},
{
"code": null,
"e": 2549,
"s": 2520,
"text": "soumyadeepdatta344 weeks ago"
},
{
"code": null,
"e": 2952,
"s": 2549,
"text": "class Solution {\n // Function to convert a binary tree into its mirror tree.\n void mirror(Node node) {\n // Your code here\n if (node == null || (node.left == null && node.right == null)) {\n return;\n } \n mirror(node.left);\n mirror(node.right);\n Node tmp;\n tmp = node.left;\n node.left = node.right;\n node.right = tmp;\n }\n}"
},
{
"code": null,
"e": 2954,
"s": 2952,
"text": "0"
},
{
"code": null,
"e": 2976,
"s": 2954,
"text": "harvey20014 weeks ago"
},
{
"code": null,
"e": 3173,
"s": 2976,
"text": "void mirror(Node* root) { if(root==NULL) return; if(root->left) mirror(root->left); if(root->right) mirror(root->right); swap(root->left,root->right); }"
},
{
"code": null,
"e": 3175,
"s": 3173,
"text": "0"
},
{
"code": null,
"e": 3205,
"s": 3175,
"text": "vainalavinayvvk0981 month ago"
},
{
"code": null,
"e": 3456,
"s": 3205,
"text": "class Solution: def mirrortraversal(self,root,res): if root: root.left,root.right = root.right,root.left self.mirrortraversal(root.left,res) res.append(root.data) self.mirrortraversal(root.right,res)"
},
{
"code": null,
"e": 3652,
"s": 3456,
"text": " return res #Function to convert a binary tree into its mirror tree. def mirror(self,root): # Code here res = [] val = self.mirrortraversal(root,res) return val"
},
{
"code": null,
"e": 3654,
"s": 3652,
"text": "0"
},
{
"code": null,
"e": 3683,
"s": 3654,
"text": "sharmaaditya130641 month ago"
},
{
"code": null,
"e": 3837,
"s": 3683,
"text": "void mirror(Node* root) {\n if(!root)return;\n swap(root->left,root->right);\n mirror(root->left);\n mirror(root->right);\n \n }"
},
{
"code": null,
"e": 3839,
"s": 3837,
"text": "0"
},
{
"code": null,
"e": 3858,
"s": 3839,
"text": "crawler1 month ago"
},
{
"code": null,
"e": 4148,
"s": 3858,
"text": " void swap(Node *node){\n Node *left = node->left;\n node->left = node->right;\n node->right = left;\n }\n void mirror(Node* node) {\n if(!node){\n return;\n }\n mirror(node->left);\n mirror(node->right);\n swap(node);\n }"
},
{
"code": null,
"e": 4294,
"s": 4148,
"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": 4330,
"s": 4294,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4340,
"s": 4330,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4350,
"s": 4340,
"text": "\nContest\n"
},
{
"code": null,
"e": 4413,
"s": 4350,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4561,
"s": 4413,
"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": 4769,
"s": 4561,
"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": 4875,
"s": 4769,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Introduction to Data Visualization in Python | by Gilbert Tanner | Towards Data Science
|
Data visualization is the discipline of trying to understand data by placing it in a visual context so that patterns, trends and correlations that might not otherwise be detected can be exposed.
Python offers multiple great graphing libraries that come packed with lots of different features. No matter if you want to create interactive, live or highly customized plots python has an excellent library for you.
To get a little overview here are a few popular plotting libraries:
Matplotlib: low level, provides lots of freedom
Pandas Visualization: easy to use interface, built on Matplotlib
Seaborn: high-level interface, great default styles
ggplot: based on R’s ggplot2, uses Grammar of Graphics
Plotly: can create interactive plots
In this article, we will learn how to create basic plots using Matplotlib, Pandas visualization and Seaborn as well as how to use some specific features of each library. This article will focus on the syntax and not on interpreting the graphs, which I will cover in another blog post.
In further articles, I will go over interactive plotting tools like Plotly, which is built on D3 and can also be used with JavaScript.
In this article, we will use two datasets which are freely available. The Iris and Wine Reviews dataset, which we can both load in using pandas read_csv method.
Matplotlib is the most popular python plotting library. It is a low-level library with a Matlab like interface which offers lots of freedom at the cost of having to write more code.
To install Matplotlib pip and conda can be used.
pip install matplotliborconda install matplotlib
Matplotlib is specifically good for creating basic graphs like line charts, bar charts, histograms and many more. It can be imported by typing:
import matplotlib.pyplot as plt
To create a scatter plot in Matplotlib we can use the scatter method. We will also create a figure and an axis using plt.subplots so we can give our plot a title and labels.
We can give the graph more meaning by coloring in each data-point by its class. This can be done by creating a dictionary which maps from class to color and then scattering each point on its own using a for-loop and passing the respective color.
In Matplotlib we can create a line chart by calling the plot method. We can also plot multiple columns in one graph, by looping through the columns we want and plotting each column on the same axis.
In Matplotlib we can create a Histogram using the hist method. If we pass it categorical data like the points column from the wine-review dataset it will automatically calculate how often each class occurs.
A bar chart can be created using the bar method. The bar-chart isn’t automatically calculating the frequency of a category so we are going to use pandas value_counts function to do this. The bar-chart is useful for categorical data that doesn’t have a lot of different categories (less than 30) because else it can get quite messy.
Pandas is an open source high-performance, easy-to-use library providing data structures, such as dataframes, and data analysis tools like the visualization tools we will use in this article.
Pandas Visualization makes it really easy to create plots out of a pandas dataframe and series. It also has a higher level API than Matplotlib and therefore we need less code for the same results.
Pandas can be installed using either pip or conda.
pip install pandasorconda install pandas
To create a scatter plot in Pandas we can call <dataset>.plot.scatter() and pass it two arguments, the name of the x-column as well as the name of the y-column. Optionally we can also pass it a title.
As you can see in the image it is automatically setting the x and y label to the column names.
To create a line-chart in Pandas we can call <dataframe>.plot.line(). Whilst in Matplotlib we needed to loop-through each column we wanted to plot, in Pandas we don’t need to do this because it automatically plots all available numeric columns (at least if we don’t specify a specific column/s).
If we have more than one feature Pandas automatically creates a legend for us, as can be seen in the image above.
In Pandas, we can create a Histogram with the plot.hist method. There aren’t any required arguments but we can optionally pass some like the bin size.
It’s also really easy to create multiple histograms.
The subplots argument specifies that we want a separate plot for each feature and the layout specifies the number of plots per row and column.
To plot a bar-chart we can use the plot.bar() method, but before we can call this we need to get our data. For this we will first count the occurrences using the value_count() method and then sort the occurrences from smallest to largest using the sort_index() method.
It’s also really simple to make a horizontal bar-chart using the plot.barh() method.
We can also plot other data then the number of occurrences.
In the example above we grouped the data by country and then took the mean of the wine prices, ordered it, and plotted the 5 countries with the highest average wine price.
Seaborn is a Python data visualization library based on Matplotlib. It provides a high-level interface for creating attractive graphs.
Seaborn has a lot to offer. You can create graphs in one line that would take you multiple tens of lines in Matplotlib. Its standard designs are awesome and it also has a nice interface for working with pandas dataframes.
It can be imported by typing:
import seaborn as sns
We can use the .scatterplot method for creating a scatterplot, and just as in Pandas we need to pass it the column names of the x and y data, but now we also need to pass the data as an additional argument because we aren’t calling the function on the data directly as we did in Pandas.
We can also highlight the points by class using the hue argument, which is a lot easier than in Matplotlib.
To create a line-chart the sns.lineplot method can be used. The only required argument is the data, which in our case are the four numeric columns from the Iris dataset. We could also use the sns.kdeplot method which rounds of the edges of the curves and therefore is cleaner if you have a lot of outliers in your dataset.
To create a histogram in Seaborn we use the sns.distplot method. We need to pass it the column we want to plot and it will calculate the occurrences itself. We can also pass it the number of bins, and if we want to plot a gaussian kernel density estimate inside the graph.
In Seaborn a bar-chart can be created using the sns.countplot method and passing it the data.
Now that you have a basic understanding of the Matplotlib, Pandas Visualization and Seaborn syntax I want to show you a few other graph types that are useful for extracting insides.
For most of them, Seaborn is the go-to library because of its high-level interface that allows for the creation of beautiful graphs in just a few lines of code.
A Box Plot is a graphical method of displaying the five-number summary. We can create box plots using seaborns sns.boxplot method and passing it the data as well as the x and y column name.
Box Plots, just like bar-charts are great for data with only a few categories but can get messy really quickly.
A Heatmap is a graphical representation of data where the individual values contained in a matrix are represented as colors. Heatmaps are perfect for exploring the correlation of features in a dataset.
To get the correlation of the features inside a dataset we can call <dataset>.corr(), which is a Pandas dataframe method. This will give us the correlation matrix.
We can now use either Matplotlib or Seaborn to create the heatmap.
Matplotlib:
To add annotations to the heatmap we need to add two for loops:
Seaborn makes it way easier to create a heatmap and add annotations:
Faceting is the act of breaking data variables up across multiple subplots and combining those subplots into a single figure.
Faceting is really helpful if you want to quickly explore your dataset.
To use one kind of faceting in Seaborn we can use the FacetGrid. First of all, we need to define the FacetGrid and pass it our data as well as a row or column, which will be used to split the data. Then we need to call the map function on our FacetGrid object and define the plot type we want to use, as well as the column we want to graph.
You can make plots a lot bigger and more complicated than the example above. You can find a few examples here.
Lastly, I will show you Seaborns pairplot and Pandas scatter_matrix , which enable you to plot a grid of pairwise relationships in a dataset.
As you can see in the images above these techniques are always plotting two features with each other. The diagonal of the graph is filled with histograms and the other plots are scatter plots.
towardsdatascience.com
Data visualization is the discipline of trying to understand data by placing it in a visual context so that patterns, trends and correlations that might not otherwise be detected can be exposed.
Python offers multiple great graphing libraries that come packed with lots of different features. In this article, we looked at Matplotlib, Pandas visualization and Seaborn.
If you liked this article consider subscribing on my Youtube Channel and following me on social media.
The code covered in this article is available as a Github Repository.
If you have any questions, recommendations or critiques, I can be reached via Twitter or the comment section.
|
[
{
"code": null,
"e": 242,
"s": 47,
"text": "Data visualization is the discipline of trying to understand data by placing it in a visual context so that patterns, trends and correlations that might not otherwise be detected can be exposed."
},
{
"code": null,
"e": 458,
"s": 242,
"text": "Python offers multiple great graphing libraries that come packed with lots of different features. No matter if you want to create interactive, live or highly customized plots python has an excellent library for you."
},
{
"code": null,
"e": 526,
"s": 458,
"text": "To get a little overview here are a few popular plotting libraries:"
},
{
"code": null,
"e": 574,
"s": 526,
"text": "Matplotlib: low level, provides lots of freedom"
},
{
"code": null,
"e": 639,
"s": 574,
"text": "Pandas Visualization: easy to use interface, built on Matplotlib"
},
{
"code": null,
"e": 691,
"s": 639,
"text": "Seaborn: high-level interface, great default styles"
},
{
"code": null,
"e": 746,
"s": 691,
"text": "ggplot: based on R’s ggplot2, uses Grammar of Graphics"
},
{
"code": null,
"e": 783,
"s": 746,
"text": "Plotly: can create interactive plots"
},
{
"code": null,
"e": 1068,
"s": 783,
"text": "In this article, we will learn how to create basic plots using Matplotlib, Pandas visualization and Seaborn as well as how to use some specific features of each library. This article will focus on the syntax and not on interpreting the graphs, which I will cover in another blog post."
},
{
"code": null,
"e": 1203,
"s": 1068,
"text": "In further articles, I will go over interactive plotting tools like Plotly, which is built on D3 and can also be used with JavaScript."
},
{
"code": null,
"e": 1364,
"s": 1203,
"text": "In this article, we will use two datasets which are freely available. The Iris and Wine Reviews dataset, which we can both load in using pandas read_csv method."
},
{
"code": null,
"e": 1546,
"s": 1364,
"text": "Matplotlib is the most popular python plotting library. It is a low-level library with a Matlab like interface which offers lots of freedom at the cost of having to write more code."
},
{
"code": null,
"e": 1595,
"s": 1546,
"text": "To install Matplotlib pip and conda can be used."
},
{
"code": null,
"e": 1644,
"s": 1595,
"text": "pip install matplotliborconda install matplotlib"
},
{
"code": null,
"e": 1788,
"s": 1644,
"text": "Matplotlib is specifically good for creating basic graphs like line charts, bar charts, histograms and many more. It can be imported by typing:"
},
{
"code": null,
"e": 1820,
"s": 1788,
"text": "import matplotlib.pyplot as plt"
},
{
"code": null,
"e": 1994,
"s": 1820,
"text": "To create a scatter plot in Matplotlib we can use the scatter method. We will also create a figure and an axis using plt.subplots so we can give our plot a title and labels."
},
{
"code": null,
"e": 2240,
"s": 1994,
"text": "We can give the graph more meaning by coloring in each data-point by its class. This can be done by creating a dictionary which maps from class to color and then scattering each point on its own using a for-loop and passing the respective color."
},
{
"code": null,
"e": 2439,
"s": 2240,
"text": "In Matplotlib we can create a line chart by calling the plot method. We can also plot multiple columns in one graph, by looping through the columns we want and plotting each column on the same axis."
},
{
"code": null,
"e": 2646,
"s": 2439,
"text": "In Matplotlib we can create a Histogram using the hist method. If we pass it categorical data like the points column from the wine-review dataset it will automatically calculate how often each class occurs."
},
{
"code": null,
"e": 2978,
"s": 2646,
"text": "A bar chart can be created using the bar method. The bar-chart isn’t automatically calculating the frequency of a category so we are going to use pandas value_counts function to do this. The bar-chart is useful for categorical data that doesn’t have a lot of different categories (less than 30) because else it can get quite messy."
},
{
"code": null,
"e": 3170,
"s": 2978,
"text": "Pandas is an open source high-performance, easy-to-use library providing data structures, such as dataframes, and data analysis tools like the visualization tools we will use in this article."
},
{
"code": null,
"e": 3367,
"s": 3170,
"text": "Pandas Visualization makes it really easy to create plots out of a pandas dataframe and series. It also has a higher level API than Matplotlib and therefore we need less code for the same results."
},
{
"code": null,
"e": 3418,
"s": 3367,
"text": "Pandas can be installed using either pip or conda."
},
{
"code": null,
"e": 3459,
"s": 3418,
"text": "pip install pandasorconda install pandas"
},
{
"code": null,
"e": 3660,
"s": 3459,
"text": "To create a scatter plot in Pandas we can call <dataset>.plot.scatter() and pass it two arguments, the name of the x-column as well as the name of the y-column. Optionally we can also pass it a title."
},
{
"code": null,
"e": 3755,
"s": 3660,
"text": "As you can see in the image it is automatically setting the x and y label to the column names."
},
{
"code": null,
"e": 4051,
"s": 3755,
"text": "To create a line-chart in Pandas we can call <dataframe>.plot.line(). Whilst in Matplotlib we needed to loop-through each column we wanted to plot, in Pandas we don’t need to do this because it automatically plots all available numeric columns (at least if we don’t specify a specific column/s)."
},
{
"code": null,
"e": 4165,
"s": 4051,
"text": "If we have more than one feature Pandas automatically creates a legend for us, as can be seen in the image above."
},
{
"code": null,
"e": 4316,
"s": 4165,
"text": "In Pandas, we can create a Histogram with the plot.hist method. There aren’t any required arguments but we can optionally pass some like the bin size."
},
{
"code": null,
"e": 4369,
"s": 4316,
"text": "It’s also really easy to create multiple histograms."
},
{
"code": null,
"e": 4512,
"s": 4369,
"text": "The subplots argument specifies that we want a separate plot for each feature and the layout specifies the number of plots per row and column."
},
{
"code": null,
"e": 4781,
"s": 4512,
"text": "To plot a bar-chart we can use the plot.bar() method, but before we can call this we need to get our data. For this we will first count the occurrences using the value_count() method and then sort the occurrences from smallest to largest using the sort_index() method."
},
{
"code": null,
"e": 4866,
"s": 4781,
"text": "It’s also really simple to make a horizontal bar-chart using the plot.barh() method."
},
{
"code": null,
"e": 4926,
"s": 4866,
"text": "We can also plot other data then the number of occurrences."
},
{
"code": null,
"e": 5098,
"s": 4926,
"text": "In the example above we grouped the data by country and then took the mean of the wine prices, ordered it, and plotted the 5 countries with the highest average wine price."
},
{
"code": null,
"e": 5233,
"s": 5098,
"text": "Seaborn is a Python data visualization library based on Matplotlib. It provides a high-level interface for creating attractive graphs."
},
{
"code": null,
"e": 5455,
"s": 5233,
"text": "Seaborn has a lot to offer. You can create graphs in one line that would take you multiple tens of lines in Matplotlib. Its standard designs are awesome and it also has a nice interface for working with pandas dataframes."
},
{
"code": null,
"e": 5485,
"s": 5455,
"text": "It can be imported by typing:"
},
{
"code": null,
"e": 5507,
"s": 5485,
"text": "import seaborn as sns"
},
{
"code": null,
"e": 5794,
"s": 5507,
"text": "We can use the .scatterplot method for creating a scatterplot, and just as in Pandas we need to pass it the column names of the x and y data, but now we also need to pass the data as an additional argument because we aren’t calling the function on the data directly as we did in Pandas."
},
{
"code": null,
"e": 5902,
"s": 5794,
"text": "We can also highlight the points by class using the hue argument, which is a lot easier than in Matplotlib."
},
{
"code": null,
"e": 6225,
"s": 5902,
"text": "To create a line-chart the sns.lineplot method can be used. The only required argument is the data, which in our case are the four numeric columns from the Iris dataset. We could also use the sns.kdeplot method which rounds of the edges of the curves and therefore is cleaner if you have a lot of outliers in your dataset."
},
{
"code": null,
"e": 6498,
"s": 6225,
"text": "To create a histogram in Seaborn we use the sns.distplot method. We need to pass it the column we want to plot and it will calculate the occurrences itself. We can also pass it the number of bins, and if we want to plot a gaussian kernel density estimate inside the graph."
},
{
"code": null,
"e": 6592,
"s": 6498,
"text": "In Seaborn a bar-chart can be created using the sns.countplot method and passing it the data."
},
{
"code": null,
"e": 6774,
"s": 6592,
"text": "Now that you have a basic understanding of the Matplotlib, Pandas Visualization and Seaborn syntax I want to show you a few other graph types that are useful for extracting insides."
},
{
"code": null,
"e": 6935,
"s": 6774,
"text": "For most of them, Seaborn is the go-to library because of its high-level interface that allows for the creation of beautiful graphs in just a few lines of code."
},
{
"code": null,
"e": 7125,
"s": 6935,
"text": "A Box Plot is a graphical method of displaying the five-number summary. We can create box plots using seaborns sns.boxplot method and passing it the data as well as the x and y column name."
},
{
"code": null,
"e": 7237,
"s": 7125,
"text": "Box Plots, just like bar-charts are great for data with only a few categories but can get messy really quickly."
},
{
"code": null,
"e": 7439,
"s": 7237,
"text": "A Heatmap is a graphical representation of data where the individual values contained in a matrix are represented as colors. Heatmaps are perfect for exploring the correlation of features in a dataset."
},
{
"code": null,
"e": 7603,
"s": 7439,
"text": "To get the correlation of the features inside a dataset we can call <dataset>.corr(), which is a Pandas dataframe method. This will give us the correlation matrix."
},
{
"code": null,
"e": 7670,
"s": 7603,
"text": "We can now use either Matplotlib or Seaborn to create the heatmap."
},
{
"code": null,
"e": 7682,
"s": 7670,
"text": "Matplotlib:"
},
{
"code": null,
"e": 7746,
"s": 7682,
"text": "To add annotations to the heatmap we need to add two for loops:"
},
{
"code": null,
"e": 7815,
"s": 7746,
"text": "Seaborn makes it way easier to create a heatmap and add annotations:"
},
{
"code": null,
"e": 7941,
"s": 7815,
"text": "Faceting is the act of breaking data variables up across multiple subplots and combining those subplots into a single figure."
},
{
"code": null,
"e": 8013,
"s": 7941,
"text": "Faceting is really helpful if you want to quickly explore your dataset."
},
{
"code": null,
"e": 8354,
"s": 8013,
"text": "To use one kind of faceting in Seaborn we can use the FacetGrid. First of all, we need to define the FacetGrid and pass it our data as well as a row or column, which will be used to split the data. Then we need to call the map function on our FacetGrid object and define the plot type we want to use, as well as the column we want to graph."
},
{
"code": null,
"e": 8465,
"s": 8354,
"text": "You can make plots a lot bigger and more complicated than the example above. You can find a few examples here."
},
{
"code": null,
"e": 8607,
"s": 8465,
"text": "Lastly, I will show you Seaborns pairplot and Pandas scatter_matrix , which enable you to plot a grid of pairwise relationships in a dataset."
},
{
"code": null,
"e": 8800,
"s": 8607,
"text": "As you can see in the images above these techniques are always plotting two features with each other. The diagonal of the graph is filled with histograms and the other plots are scatter plots."
},
{
"code": null,
"e": 8823,
"s": 8800,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9018,
"s": 8823,
"text": "Data visualization is the discipline of trying to understand data by placing it in a visual context so that patterns, trends and correlations that might not otherwise be detected can be exposed."
},
{
"code": null,
"e": 9192,
"s": 9018,
"text": "Python offers multiple great graphing libraries that come packed with lots of different features. In this article, we looked at Matplotlib, Pandas visualization and Seaborn."
},
{
"code": null,
"e": 9295,
"s": 9192,
"text": "If you liked this article consider subscribing on my Youtube Channel and following me on social media."
},
{
"code": null,
"e": 9365,
"s": 9295,
"text": "The code covered in this article is available as a Github Repository."
}
] |
Python | Scipy integrate.quad() method - GeeksforGeeks
|
23 Jan, 2020
With the help of scipy.integrate.quad() method, we can get the integration of a given function from limit a to b by using scipy.integrate.quad() method.
Syntax : scipy.integrate.quad(func, a, b)
Return : Return the integration of a polynomial.
Example #1 :In this example we can see that by using scipy.integrate.quad() method, we are able to get the integration of a polynomial from limit a to b by using this method.
# import scipy.integrate.quadfrom scipy import integrategfg = lambda x: x**2 # using scipy.integrate.quad() methodgeek = integrate.quad(gfg, 0, 3) print(geek)
Output :
9.000000000000002
Example #2 :
# import scipy.integrate.quadfrom scipy import integrategfg = lambda x: x**2 + x + 1 # using scipy.integrate.quad() methodgeek = integrate.quad(gfg, 1, 4) print(geek)
Output :
31.5
Python-scipy
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
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25581,
"s": 25553,
"text": "\n23 Jan, 2020"
},
{
"code": null,
"e": 25734,
"s": 25581,
"text": "With the help of scipy.integrate.quad() method, we can get the integration of a given function from limit a to b by using scipy.integrate.quad() method."
},
{
"code": null,
"e": 25776,
"s": 25734,
"text": "Syntax : scipy.integrate.quad(func, a, b)"
},
{
"code": null,
"e": 25825,
"s": 25776,
"text": "Return : Return the integration of a polynomial."
},
{
"code": null,
"e": 26000,
"s": 25825,
"text": "Example #1 :In this example we can see that by using scipy.integrate.quad() method, we are able to get the integration of a polynomial from limit a to b by using this method."
},
{
"code": "# import scipy.integrate.quadfrom scipy import integrategfg = lambda x: x**2 # using scipy.integrate.quad() methodgeek = integrate.quad(gfg, 0, 3) print(geek)",
"e": 26161,
"s": 26000,
"text": null
},
{
"code": null,
"e": 26170,
"s": 26161,
"text": "Output :"
},
{
"code": null,
"e": 26188,
"s": 26170,
"text": "9.000000000000002"
},
{
"code": null,
"e": 26201,
"s": 26188,
"text": "Example #2 :"
},
{
"code": "# import scipy.integrate.quadfrom scipy import integrategfg = lambda x: x**2 + x + 1 # using scipy.integrate.quad() methodgeek = integrate.quad(gfg, 1, 4) print(geek)",
"e": 26370,
"s": 26201,
"text": null
},
{
"code": null,
"e": 26379,
"s": 26370,
"text": "Output :"
},
{
"code": null,
"e": 26384,
"s": 26379,
"text": "31.5"
},
{
"code": null,
"e": 26397,
"s": 26384,
"text": "Python-scipy"
},
{
"code": null,
"e": 26404,
"s": 26397,
"text": "Python"
},
{
"code": null,
"e": 26502,
"s": 26404,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26520,
"s": 26502,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26555,
"s": 26520,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26587,
"s": 26555,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26609,
"s": 26587,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26651,
"s": 26609,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26681,
"s": 26651,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26707,
"s": 26681,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26751,
"s": 26707,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 26780,
"s": 26751,
"text": "*args and **kwargs in Python"
}
] |
AngularJS Interview Questions and Answers - GeeksforGeeks
|
06 Jan, 2020
What is AngularJS and who created it?AngularJs is a Javascript open-source front-end framework that is mainly used to develop single-page web applications(SPAs). It is a continuously growing and expanding framework which provides better ways for developing web applications. It changes the static HTML to dynamic HTML. It’s features like dynamic binding and dependency injection eliminates the need for code that we have to write otherwise.AngularJs is rapidly growing and because of this reason, we have different versions of AngularJs with the latest stable being 1.7.7. It is also important to note that Angular is different from AngularJs. It is an open-source project which can be freely used and changed by anyone. It extends HTML attributes with Directives, and data is bound with HTML.AngularJs was originally developed in 2008-2009 by Misko hevery and Adam abrons, and is now maintained by Google.What are the features of AngularJS?There are so many features in AngularJS like MVC Framework, The unique AngularJS Router, User Interface with HTML, Directives, Scope, Data Binding, Dependency Injection, Compability, Avoid Tiresome Work and High Performance.Explain what is scope and Data Binding in AngularJS?Scope: 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.Data Binding: Angular provides a function Data Binding which helps us to have an almost real-time reflection of the input given by the user i.e. it creates a connection between Model and View.How many types of data bindings are there in AngularJs?There are four kinds of data bindings in AngularJS Event Binding, Property Binding, Two way Binding and Interpolation BindingExplain the differences between one-way binding and two-way binding.Property Binding: Similar to Java, variables defined in the parent class can be inherited by child class that is templates in this case. The only difference between Interpolation and Property binding is that we should not store non-string values in variables while using interpolation. So if we have to store Boolean or other data types than use Property Binding.Interpolation Binding: Angular interpolation is used display a component property in the respective view template with double curly braces syntax. Interpolation is used to transfer properties mentioned in component class to be reflected in its template.Explain the services and expression in AngularJS.Services: Services are used to create variables/data that can be shared and can be used outside the component in which it is defined.Expression: Expressions in AngularJS are used to bind application data to HTML. The expressions are resolved by Angular and the result is returned back to where the expression is written.Explain what is the key difference between angular expressions and JavaScript expressions?AngularJS expression can be written in HTML but JavaScript expression can’t and Filters are supported by AngularJS but not by JavaScript. We cannot use conditional iterations, loops, and exceptions in AngularJs, but we can use all of these conditional properties in JavaScript expressions.Write all the steps to configure an Angular App(ng-app)?Step 1: The angular.module will be created at first.Step 2: A controller will be assigned to the module.Step 3: The module will be linked with the HTML template with an angular app(ng-app).Step 4: The HTML template will be linked with the controller with an ng-controller directive.With options on page load how you can initialize a select box?YOu can initialize a select box using ng-init directive when options on page load.<div ng-controller = " apps/dashboard/account " ng-switch
On = "! ! accounts" ng-init = " loadData ( ) ">What are Directives in AngularJS and name few of them.Directive: Directives are markers on the DOM element which tell Angular JS to attach a specified behavior to that DOM element or even transform the DOM element with its children. Simple AngularJS allows extending HTML with new attributes called Directives. AngularJS has a set of built-in directives which offers functionality to the applications. It also defines its own directives.Popular directives are ng-app, ng-controller, ng-bind, etc.What are the advantages of using AngularJS?There are several advantages to AngularJS. Supports the MVC pattern support two ways of data binding using AngularJS. It has per-defined form validationsSupported both client-server communication and animations.What AngularJS routing does?Routing in AngularJS is used when the user wants to navigate to different pages in an application but still wants it to be a single page application. AngularJS routes enable the user to create different URLs for different content in an application. The ngRoute module helps in accessing different pages of an application without reloading the entire application.How can we share the data between controllers in AngularJS?We have to create a service first. The Services are used to share data between controllers in AngularJS. We use events, $parent, next sibling, and controller by using a $rootScope.What are the steps for the compilation process of HTML?Step 1: Using the standard browser API, first, the HTML is parsed into DOMStep 2: By using the call to the $compile() method, a compilation of the DOM is performed. The method traverses the DOM and then matches the directives.Step 3: Link the template with a scope by calling the linking function returned from the previous step.What is string interpolation in AngularJS?In AngularJS, during the compilation process, it matches the text and attributes using interpolate service to see if they contain embedded expressions. As part of the normal digest cycle, these expressions are updated and registered as watches.How many types of Directives are available in AngularJS?There are four kinds of directives in AngularJS those are described below:Element directivesAttribute directivesCSS class directivesComment directivesWhat is injector?The injector in AngularJS is basically a service locator. It is used to invoked methods and for loading modules. There can be only one injector in a single AngularJS app.What is factory method in AngularJS?AngularJS Factory Method makes the development process of AngularJS application more robust. A factory is a simple function that allows us to add some logic to a created object and return the created object. The factory is also used to create/return a function in the form of reusable code which can be used anywhere within the application. Whenever we create an object using a factory it always returns a new instance for that object. The object returned by the factory can be integrated(injectible) with different components of the Angularjs framework such as controller, service, filter or directive.What is the digest cycle in AngularJS?It is the most important part of the process of data binding in AngularJS. It basically compares the old and new versions of the scope model. The digest cycle triggered automatically. If we want to trigger the digest cycle manually then we can use $apply().What is the difference between Angular and AngularJS?Angular: It is written in Microsoft’s TypeScript language, which is a superset of ECMAScript 6 (ES6). In Angular components are the directives with a template. It used Hierarchical Dependency Injection.AngularJS: It is written in JavaScript. Supports Model-View-Controller design. The view processes the information available in the model to generate the output. It does not use Dependency Injection.
What is AngularJS and who created it?AngularJs is a Javascript open-source front-end framework that is mainly used to develop single-page web applications(SPAs). It is a continuously growing and expanding framework which provides better ways for developing web applications. It changes the static HTML to dynamic HTML. It’s features like dynamic binding and dependency injection eliminates the need for code that we have to write otherwise.AngularJs is rapidly growing and because of this reason, we have different versions of AngularJs with the latest stable being 1.7.7. It is also important to note that Angular is different from AngularJs. It is an open-source project which can be freely used and changed by anyone. It extends HTML attributes with Directives, and data is bound with HTML.AngularJs was originally developed in 2008-2009 by Misko hevery and Adam abrons, and is now maintained by Google.
AngularJs was originally developed in 2008-2009 by Misko hevery and Adam abrons, and is now maintained by Google.
What are the features of AngularJS?There are so many features in AngularJS like MVC Framework, The unique AngularJS Router, User Interface with HTML, Directives, Scope, Data Binding, Dependency Injection, Compability, Avoid Tiresome Work and High Performance.
Explain what is scope and Data Binding in AngularJS?Scope: 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.Data Binding: Angular provides a function Data Binding which helps us to have an almost real-time reflection of the input given by the user i.e. it creates a connection between Model and View.
Data Binding: Angular provides a function Data Binding which helps us to have an almost real-time reflection of the input given by the user i.e. it creates a connection between Model and View.
How many types of data bindings are there in AngularJs?There are four kinds of data bindings in AngularJS Event Binding, Property Binding, Two way Binding and Interpolation Binding
Explain the differences between one-way binding and two-way binding.Property Binding: Similar to Java, variables defined in the parent class can be inherited by child class that is templates in this case. The only difference between Interpolation and Property binding is that we should not store non-string values in variables while using interpolation. So if we have to store Boolean or other data types than use Property Binding.Interpolation Binding: Angular interpolation is used display a component property in the respective view template with double curly braces syntax. Interpolation is used to transfer properties mentioned in component class to be reflected in its template.
Interpolation Binding: Angular interpolation is used display a component property in the respective view template with double curly braces syntax. Interpolation is used to transfer properties mentioned in component class to be reflected in its template.
Explain the services and expression in AngularJS.Services: Services are used to create variables/data that can be shared and can be used outside the component in which it is defined.Expression: Expressions in AngularJS are used to bind application data to HTML. The expressions are resolved by Angular and the result is returned back to where the expression is written.
Explain what is the key difference between angular expressions and JavaScript expressions?AngularJS expression can be written in HTML but JavaScript expression can’t and Filters are supported by AngularJS but not by JavaScript. We cannot use conditional iterations, loops, and exceptions in AngularJs, but we can use all of these conditional properties in JavaScript expressions.
Write all the steps to configure an Angular App(ng-app)?Step 1: The angular.module will be created at first.Step 2: A controller will be assigned to the module.Step 3: The module will be linked with the HTML template with an angular app(ng-app).Step 4: The HTML template will be linked with the controller with an ng-controller directive.
With options on page load how you can initialize a select box?YOu can initialize a select box using ng-init directive when options on page load.<div ng-controller = " apps/dashboard/account " ng-switch
On = "! ! accounts" ng-init = " loadData ( ) ">
<div ng-controller = " apps/dashboard/account " ng-switch
On = "! ! accounts" ng-init = " loadData ( ) ">
What are Directives in AngularJS and name few of them.Directive: Directives are markers on the DOM element which tell Angular JS to attach a specified behavior to that DOM element or even transform the DOM element with its children. Simple AngularJS allows extending HTML with new attributes called Directives. AngularJS has a set of built-in directives which offers functionality to the applications. It also defines its own directives.Popular directives are ng-app, ng-controller, ng-bind, etc.
What are the advantages of using AngularJS?There are several advantages to AngularJS. Supports the MVC pattern support two ways of data binding using AngularJS. It has per-defined form validationsSupported both client-server communication and animations.
What AngularJS routing does?Routing in AngularJS is used when the user wants to navigate to different pages in an application but still wants it to be a single page application. AngularJS routes enable the user to create different URLs for different content in an application. The ngRoute module helps in accessing different pages of an application without reloading the entire application.
How can we share the data between controllers in AngularJS?We have to create a service first. The Services are used to share data between controllers in AngularJS. We use events, $parent, next sibling, and controller by using a $rootScope.
What are the steps for the compilation process of HTML?Step 1: Using the standard browser API, first, the HTML is parsed into DOMStep 2: By using the call to the $compile() method, a compilation of the DOM is performed. The method traverses the DOM and then matches the directives.Step 3: Link the template with a scope by calling the linking function returned from the previous step.
What is string interpolation in AngularJS?In AngularJS, during the compilation process, it matches the text and attributes using interpolate service to see if they contain embedded expressions. As part of the normal digest cycle, these expressions are updated and registered as watches.
How many types of Directives are available in AngularJS?There are four kinds of directives in AngularJS those are described below:Element directivesAttribute directivesCSS class directivesComment directives
Element directives
Attribute directives
CSS class directives
Comment directives
What is injector?The injector in AngularJS is basically a service locator. It is used to invoked methods and for loading modules. There can be only one injector in a single AngularJS app.
What is factory method in AngularJS?AngularJS Factory Method makes the development process of AngularJS application more robust. A factory is a simple function that allows us to add some logic to a created object and return the created object. The factory is also used to create/return a function in the form of reusable code which can be used anywhere within the application. Whenever we create an object using a factory it always returns a new instance for that object. The object returned by the factory can be integrated(injectible) with different components of the Angularjs framework such as controller, service, filter or directive.
What is the digest cycle in AngularJS?It is the most important part of the process of data binding in AngularJS. It basically compares the old and new versions of the scope model. The digest cycle triggered automatically. If we want to trigger the digest cycle manually then we can use $apply().
What is the difference between Angular and AngularJS?Angular: It is written in Microsoft’s TypeScript language, which is a superset of ECMAScript 6 (ES6). In Angular components are the directives with a template. It used Hierarchical Dependency Injection.AngularJS: It is written in JavaScript. Supports Model-View-Controller design. The view processes the information available in the model to generate the output. It does not use Dependency Injection.
AngularJS: It is written in JavaScript. Supports Model-View-Controller design. The view processes the information available in the model to generate the output. It does not use Dependency Injection.
interview-preparation
AngularJS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Calendar Component
Angular PrimeNG Messages Component
Auth Guards in Angular 9/10/11
How to bundle an Angular app for production?
How to set focus on input field automatically on page load in AngularJS ?
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": 25237,
"s": 25209,
"text": "\n06 Jan, 2020"
},
{
"code": null,
"e": 32936,
"s": 25237,
"text": "What is AngularJS and who created it?AngularJs is a Javascript open-source front-end framework that is mainly used to develop single-page web applications(SPAs). It is a continuously growing and expanding framework which provides better ways for developing web applications. It changes the static HTML to dynamic HTML. It’s features like dynamic binding and dependency injection eliminates the need for code that we have to write otherwise.AngularJs is rapidly growing and because of this reason, we have different versions of AngularJs with the latest stable being 1.7.7. It is also important to note that Angular is different from AngularJs. It is an open-source project which can be freely used and changed by anyone. It extends HTML attributes with Directives, and data is bound with HTML.AngularJs was originally developed in 2008-2009 by Misko hevery and Adam abrons, and is now maintained by Google.What are the features of AngularJS?There are so many features in AngularJS like MVC Framework, The unique AngularJS Router, User Interface with HTML, Directives, Scope, Data Binding, Dependency Injection, Compability, Avoid Tiresome Work and High Performance.Explain what is scope and Data Binding in AngularJS?Scope: 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.Data Binding: Angular provides a function Data Binding which helps us to have an almost real-time reflection of the input given by the user i.e. it creates a connection between Model and View.How many types of data bindings are there in AngularJs?There are four kinds of data bindings in AngularJS Event Binding, Property Binding, Two way Binding and Interpolation BindingExplain the differences between one-way binding and two-way binding.Property Binding: Similar to Java, variables defined in the parent class can be inherited by child class that is templates in this case. The only difference between Interpolation and Property binding is that we should not store non-string values in variables while using interpolation. So if we have to store Boolean or other data types than use Property Binding.Interpolation Binding: Angular interpolation is used display a component property in the respective view template with double curly braces syntax. Interpolation is used to transfer properties mentioned in component class to be reflected in its template.Explain the services and expression in AngularJS.Services: Services are used to create variables/data that can be shared and can be used outside the component in which it is defined.Expression: Expressions in AngularJS are used to bind application data to HTML. The expressions are resolved by Angular and the result is returned back to where the expression is written.Explain what is the key difference between angular expressions and JavaScript expressions?AngularJS expression can be written in HTML but JavaScript expression can’t and Filters are supported by AngularJS but not by JavaScript. We cannot use conditional iterations, loops, and exceptions in AngularJs, but we can use all of these conditional properties in JavaScript expressions.Write all the steps to configure an Angular App(ng-app)?Step 1: The angular.module will be created at first.Step 2: A controller will be assigned to the module.Step 3: The module will be linked with the HTML template with an angular app(ng-app).Step 4: The HTML template will be linked with the controller with an ng-controller directive.With options on page load how you can initialize a select box?YOu can initialize a select box using ng-init directive when options on page load.<div ng-controller = \" apps/dashboard/account \" ng-switch\nOn = \"! ! accounts\" ng-init = \" loadData ( ) \">What are Directives in AngularJS and name few of them.Directive: Directives are markers on the DOM element which tell Angular JS to attach a specified behavior to that DOM element or even transform the DOM element with its children. Simple AngularJS allows extending HTML with new attributes called Directives. AngularJS has a set of built-in directives which offers functionality to the applications. It also defines its own directives.Popular directives are ng-app, ng-controller, ng-bind, etc.What are the advantages of using AngularJS?There are several advantages to AngularJS. Supports the MVC pattern support two ways of data binding using AngularJS. It has per-defined form validationsSupported both client-server communication and animations.What AngularJS routing does?Routing in AngularJS is used when the user wants to navigate to different pages in an application but still wants it to be a single page application. AngularJS routes enable the user to create different URLs for different content in an application. The ngRoute module helps in accessing different pages of an application without reloading the entire application.How can we share the data between controllers in AngularJS?We have to create a service first. The Services are used to share data between controllers in AngularJS. We use events, $parent, next sibling, and controller by using a $rootScope.What are the steps for the compilation process of HTML?Step 1: Using the standard browser API, first, the HTML is parsed into DOMStep 2: By using the call to the $compile() method, a compilation of the DOM is performed. The method traverses the DOM and then matches the directives.Step 3: Link the template with a scope by calling the linking function returned from the previous step.What is string interpolation in AngularJS?In AngularJS, during the compilation process, it matches the text and attributes using interpolate service to see if they contain embedded expressions. As part of the normal digest cycle, these expressions are updated and registered as watches.How many types of Directives are available in AngularJS?There are four kinds of directives in AngularJS those are described below:Element directivesAttribute directivesCSS class directivesComment directivesWhat is injector?The injector in AngularJS is basically a service locator. It is used to invoked methods and for loading modules. There can be only one injector in a single AngularJS app.What is factory method in AngularJS?AngularJS Factory Method makes the development process of AngularJS application more robust. A factory is a simple function that allows us to add some logic to a created object and return the created object. The factory is also used to create/return a function in the form of reusable code which can be used anywhere within the application. Whenever we create an object using a factory it always returns a new instance for that object. The object returned by the factory can be integrated(injectible) with different components of the Angularjs framework such as controller, service, filter or directive.What is the digest cycle in AngularJS?It is the most important part of the process of data binding in AngularJS. It basically compares the old and new versions of the scope model. The digest cycle triggered automatically. If we want to trigger the digest cycle manually then we can use $apply().What is the difference between Angular and AngularJS?Angular: It is written in Microsoft’s TypeScript language, which is a superset of ECMAScript 6 (ES6). In Angular components are the directives with a template. It used Hierarchical Dependency Injection.AngularJS: It is written in JavaScript. Supports Model-View-Controller design. The view processes the information available in the model to generate the output. It does not use Dependency Injection."
},
{
"code": null,
"e": 33843,
"s": 32936,
"text": "What is AngularJS and who created it?AngularJs is a Javascript open-source front-end framework that is mainly used to develop single-page web applications(SPAs). It is a continuously growing and expanding framework which provides better ways for developing web applications. It changes the static HTML to dynamic HTML. It’s features like dynamic binding and dependency injection eliminates the need for code that we have to write otherwise.AngularJs is rapidly growing and because of this reason, we have different versions of AngularJs with the latest stable being 1.7.7. It is also important to note that Angular is different from AngularJs. It is an open-source project which can be freely used and changed by anyone. It extends HTML attributes with Directives, and data is bound with HTML.AngularJs was originally developed in 2008-2009 by Misko hevery and Adam abrons, and is now maintained by Google."
},
{
"code": null,
"e": 33957,
"s": 33843,
"text": "AngularJs was originally developed in 2008-2009 by Misko hevery and Adam abrons, and is now maintained by Google."
},
{
"code": null,
"e": 34217,
"s": 33957,
"text": "What are the features of AngularJS?There are so many features in AngularJS like MVC Framework, The unique AngularJS Router, User Interface with HTML, Directives, Scope, Data Binding, Dependency Injection, Compability, Avoid Tiresome Work and High Performance."
},
{
"code": null,
"e": 34723,
"s": 34217,
"text": "Explain what is scope and Data Binding in AngularJS?Scope: 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.Data Binding: Angular provides a function Data Binding which helps us to have an almost real-time reflection of the input given by the user i.e. it creates a connection between Model and View."
},
{
"code": null,
"e": 34916,
"s": 34723,
"text": "Data Binding: Angular provides a function Data Binding which helps us to have an almost real-time reflection of the input given by the user i.e. it creates a connection between Model and View."
},
{
"code": null,
"e": 35097,
"s": 34916,
"text": "How many types of data bindings are there in AngularJs?There are four kinds of data bindings in AngularJS Event Binding, Property Binding, Two way Binding and Interpolation Binding"
},
{
"code": null,
"e": 35782,
"s": 35097,
"text": "Explain the differences between one-way binding and two-way binding.Property Binding: Similar to Java, variables defined in the parent class can be inherited by child class that is templates in this case. The only difference between Interpolation and Property binding is that we should not store non-string values in variables while using interpolation. So if we have to store Boolean or other data types than use Property Binding.Interpolation Binding: Angular interpolation is used display a component property in the respective view template with double curly braces syntax. Interpolation is used to transfer properties mentioned in component class to be reflected in its template."
},
{
"code": null,
"e": 36036,
"s": 35782,
"text": "Interpolation Binding: Angular interpolation is used display a component property in the respective view template with double curly braces syntax. Interpolation is used to transfer properties mentioned in component class to be reflected in its template."
},
{
"code": null,
"e": 36406,
"s": 36036,
"text": "Explain the services and expression in AngularJS.Services: Services are used to create variables/data that can be shared and can be used outside the component in which it is defined.Expression: Expressions in AngularJS are used to bind application data to HTML. The expressions are resolved by Angular and the result is returned back to where the expression is written."
},
{
"code": null,
"e": 36786,
"s": 36406,
"text": "Explain what is the key difference between angular expressions and JavaScript expressions?AngularJS expression can be written in HTML but JavaScript expression can’t and Filters are supported by AngularJS but not by JavaScript. We cannot use conditional iterations, loops, and exceptions in AngularJs, but we can use all of these conditional properties in JavaScript expressions."
},
{
"code": null,
"e": 37125,
"s": 36786,
"text": "Write all the steps to configure an Angular App(ng-app)?Step 1: The angular.module will be created at first.Step 2: A controller will be assigned to the module.Step 3: The module will be linked with the HTML template with an angular app(ng-app).Step 4: The HTML template will be linked with the controller with an ng-controller directive."
},
{
"code": null,
"e": 37375,
"s": 37125,
"text": "With options on page load how you can initialize a select box?YOu can initialize a select box using ng-init directive when options on page load.<div ng-controller = \" apps/dashboard/account \" ng-switch\nOn = \"! ! accounts\" ng-init = \" loadData ( ) \">"
},
{
"code": null,
"e": 37481,
"s": 37375,
"text": "<div ng-controller = \" apps/dashboard/account \" ng-switch\nOn = \"! ! accounts\" ng-init = \" loadData ( ) \">"
},
{
"code": null,
"e": 37978,
"s": 37481,
"text": "What are Directives in AngularJS and name few of them.Directive: Directives are markers on the DOM element which tell Angular JS to attach a specified behavior to that DOM element or even transform the DOM element with its children. Simple AngularJS allows extending HTML with new attributes called Directives. AngularJS has a set of built-in directives which offers functionality to the applications. It also defines its own directives.Popular directives are ng-app, ng-controller, ng-bind, etc."
},
{
"code": null,
"e": 38233,
"s": 37978,
"text": "What are the advantages of using AngularJS?There are several advantages to AngularJS. Supports the MVC pattern support two ways of data binding using AngularJS. It has per-defined form validationsSupported both client-server communication and animations."
},
{
"code": null,
"e": 38624,
"s": 38233,
"text": "What AngularJS routing does?Routing in AngularJS is used when the user wants to navigate to different pages in an application but still wants it to be a single page application. AngularJS routes enable the user to create different URLs for different content in an application. The ngRoute module helps in accessing different pages of an application without reloading the entire application."
},
{
"code": null,
"e": 38864,
"s": 38624,
"text": "How can we share the data between controllers in AngularJS?We have to create a service first. The Services are used to share data between controllers in AngularJS. We use events, $parent, next sibling, and controller by using a $rootScope."
},
{
"code": null,
"e": 39249,
"s": 38864,
"text": "What are the steps for the compilation process of HTML?Step 1: Using the standard browser API, first, the HTML is parsed into DOMStep 2: By using the call to the $compile() method, a compilation of the DOM is performed. The method traverses the DOM and then matches the directives.Step 3: Link the template with a scope by calling the linking function returned from the previous step."
},
{
"code": null,
"e": 39536,
"s": 39249,
"text": "What is string interpolation in AngularJS?In AngularJS, during the compilation process, it matches the text and attributes using interpolate service to see if they contain embedded expressions. As part of the normal digest cycle, these expressions are updated and registered as watches."
},
{
"code": null,
"e": 39743,
"s": 39536,
"text": "How many types of Directives are available in AngularJS?There are four kinds of directives in AngularJS those are described below:Element directivesAttribute directivesCSS class directivesComment directives"
},
{
"code": null,
"e": 39762,
"s": 39743,
"text": "Element directives"
},
{
"code": null,
"e": 39783,
"s": 39762,
"text": "Attribute directives"
},
{
"code": null,
"e": 39804,
"s": 39783,
"text": "CSS class directives"
},
{
"code": null,
"e": 39823,
"s": 39804,
"text": "Comment directives"
},
{
"code": null,
"e": 40011,
"s": 39823,
"text": "What is injector?The injector in AngularJS is basically a service locator. It is used to invoked methods and for loading modules. There can be only one injector in a single AngularJS app."
},
{
"code": null,
"e": 40651,
"s": 40011,
"text": "What is factory method in AngularJS?AngularJS Factory Method makes the development process of AngularJS application more robust. A factory is a simple function that allows us to add some logic to a created object and return the created object. The factory is also used to create/return a function in the form of reusable code which can be used anywhere within the application. Whenever we create an object using a factory it always returns a new instance for that object. The object returned by the factory can be integrated(injectible) with different components of the Angularjs framework such as controller, service, filter or directive."
},
{
"code": null,
"e": 40947,
"s": 40651,
"text": "What is the digest cycle in AngularJS?It is the most important part of the process of data binding in AngularJS. It basically compares the old and new versions of the scope model. The digest cycle triggered automatically. If we want to trigger the digest cycle manually then we can use $apply()."
},
{
"code": null,
"e": 41401,
"s": 40947,
"text": "What is the difference between Angular and AngularJS?Angular: It is written in Microsoft’s TypeScript language, which is a superset of ECMAScript 6 (ES6). In Angular components are the directives with a template. It used Hierarchical Dependency Injection.AngularJS: It is written in JavaScript. Supports Model-View-Controller design. The view processes the information available in the model to generate the output. It does not use Dependency Injection."
},
{
"code": null,
"e": 41600,
"s": 41401,
"text": "AngularJS: It is written in JavaScript. Supports Model-View-Controller design. The view processes the information available in the model to generate the output. It does not use Dependency Injection."
},
{
"code": null,
"e": 41622,
"s": 41600,
"text": "interview-preparation"
},
{
"code": null,
"e": 41632,
"s": 41622,
"text": "AngularJS"
},
{
"code": null,
"e": 41649,
"s": 41632,
"text": "Web Technologies"
},
{
"code": null,
"e": 41676,
"s": 41649,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 41774,
"s": 41676,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41809,
"s": 41774,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 41844,
"s": 41809,
"text": "Angular PrimeNG Messages Component"
},
{
"code": null,
"e": 41875,
"s": 41844,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 41920,
"s": 41875,
"text": "How to bundle an Angular app for production?"
},
{
"code": null,
"e": 41994,
"s": 41920,
"text": "How to set focus on input field automatically on page load in AngularJS ?"
},
{
"code": null,
"e": 42034,
"s": 41994,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 42067,
"s": 42034,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 42112,
"s": 42067,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 42155,
"s": 42112,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Angular10 Trigger Animation - GeeksforGeeks
|
02 Jun, 2021
In this article, we are going to see what is trigger in Angular 10 and how to use it.
The trigger in Angular10 is used to create an animation trigger containing state and transition of the animation.
Syntax:
animate(name | definations)
NgModule: Module used by trigger is:
animations
Approach:
Create an angular app that to be used.
In app.module.ts, import BrowserAnimationsModule.
In app.component.html, make a div which will contain the animation element.
In app.component.ts, import the trigger, state, style, transition, animate to be used.
Make the trigger containing state and transition for the animation.
Serve the angular app using ng serve to see the output.
Parameters:
Name: Sets an identifying string.
definations: Sets an animation defination object.
Return Value:
AnimationTriggerMetadata: An object that encapsulates the trigger data.
Example:
app.module.ts
import { LOCALE_ID, NgModule } from '@angular/core'; import { BrowserModule }from '@angular/platform-browser';import {BrowserAnimationsModule} from '@angular/platform-browser/animations';import { AppRoutingModule }from './app-routing.module';import { AppComponent }from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule ], providers: [ { provide: LOCALE_ID, useValue: 'en-GB' }, ], bootstrap: [AppComponent]})export class AppModule { }
app.component.ts
import { // Trigger is imported here trigger, state, style, transition, animate } from '@angular/animations';import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ], animations: [ // Trigger is used here trigger('geek',[ state('green', style({ 'background-color': 'green', transform: 'translateX(0)' })), state('blu', style({ 'background-color': '#49eb34', transform: 'translateX(0)' })), transition('green => blu',animate(1200)), transition('blu => green',animate(1000)) ]) ]})export class AppComponent { state = 'green'; anim(){ this.state == 'green' ? this.state = 'blu' : this.state = 'green'; }}
app.component.html
<h1>GeeksforGeeks</h1><button (click)='anim()'>Animate</button><br><br><div style="width: 150px; height: 100px; border-radius: 5px;" [@geek]='state'></div>
Output:
Reference: https://angular.io/api/animations/trigger
Angular10
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular 10 (blur) Event
Angular PrimeNG Messages Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
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": 26354,
"s": 26326,
"text": "\n02 Jun, 2021"
},
{
"code": null,
"e": 26440,
"s": 26354,
"text": "In this article, we are going to see what is trigger in Angular 10 and how to use it."
},
{
"code": null,
"e": 26554,
"s": 26440,
"text": "The trigger in Angular10 is used to create an animation trigger containing state and transition of the animation."
},
{
"code": null,
"e": 26562,
"s": 26554,
"text": "Syntax:"
},
{
"code": null,
"e": 26590,
"s": 26562,
"text": "animate(name | definations)"
},
{
"code": null,
"e": 26627,
"s": 26590,
"text": "NgModule: Module used by trigger is:"
},
{
"code": null,
"e": 26638,
"s": 26627,
"text": "animations"
},
{
"code": null,
"e": 26651,
"s": 26640,
"text": "Approach: "
},
{
"code": null,
"e": 26690,
"s": 26651,
"text": "Create an angular app that to be used."
},
{
"code": null,
"e": 26740,
"s": 26690,
"text": "In app.module.ts, import BrowserAnimationsModule."
},
{
"code": null,
"e": 26816,
"s": 26740,
"text": "In app.component.html, make a div which will contain the animation element."
},
{
"code": null,
"e": 26903,
"s": 26816,
"text": "In app.component.ts, import the trigger, state, style, transition, animate to be used."
},
{
"code": null,
"e": 26971,
"s": 26903,
"text": "Make the trigger containing state and transition for the animation."
},
{
"code": null,
"e": 27027,
"s": 26971,
"text": "Serve the angular app using ng serve to see the output."
},
{
"code": null,
"e": 27039,
"s": 27027,
"text": "Parameters:"
},
{
"code": null,
"e": 27073,
"s": 27039,
"text": "Name: Sets an identifying string."
},
{
"code": null,
"e": 27123,
"s": 27073,
"text": "definations: Sets an animation defination object."
},
{
"code": null,
"e": 27137,
"s": 27123,
"text": "Return Value:"
},
{
"code": null,
"e": 27209,
"s": 27137,
"text": "AnimationTriggerMetadata: An object that encapsulates the trigger data."
},
{
"code": null,
"e": 27218,
"s": 27209,
"text": "Example:"
},
{
"code": null,
"e": 27232,
"s": 27218,
"text": "app.module.ts"
},
{
"code": "import { LOCALE_ID, NgModule } from '@angular/core'; import { BrowserModule }from '@angular/platform-browser';import {BrowserAnimationsModule} from '@angular/platform-browser/animations';import { AppRoutingModule }from './app-routing.module';import { AppComponent }from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule ], providers: [ { provide: LOCALE_ID, useValue: 'en-GB' }, ], bootstrap: [AppComponent]})export class AppModule { }",
"e": 27775,
"s": 27232,
"text": null
},
{
"code": null,
"e": 27792,
"s": 27775,
"text": "app.component.ts"
},
{
"code": "import { // Trigger is imported here trigger, state, style, transition, animate } from '@angular/animations';import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ], animations: [ // Trigger is used here trigger('geek',[ state('green', style({ 'background-color': 'green', transform: 'translateX(0)' })), state('blu', style({ 'background-color': '#49eb34', transform: 'translateX(0)' })), transition('green => blu',animate(1200)), transition('blu => green',animate(1000)) ]) ]})export class AppComponent { state = 'green'; anim(){ this.state == 'green' ? this.state = 'blu' : this.state = 'green'; }}",
"e": 28585,
"s": 27792,
"text": null
},
{
"code": null,
"e": 28604,
"s": 28585,
"text": "app.component.html"
},
{
"code": "<h1>GeeksforGeeks</h1><button (click)='anim()'>Animate</button><br><br><div style=\"width: 150px; height: 100px; border-radius: 5px;\" [@geek]='state'></div>",
"e": 28763,
"s": 28604,
"text": null
},
{
"code": null,
"e": 28771,
"s": 28763,
"text": "Output:"
},
{
"code": null,
"e": 28824,
"s": 28771,
"text": "Reference: https://angular.io/api/animations/trigger"
},
{
"code": null,
"e": 28834,
"s": 28824,
"text": "Angular10"
},
{
"code": null,
"e": 28844,
"s": 28834,
"text": "AngularJS"
},
{
"code": null,
"e": 28861,
"s": 28844,
"text": "Web Technologies"
},
{
"code": null,
"e": 28959,
"s": 28861,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28994,
"s": 28959,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 29029,
"s": 28994,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 29053,
"s": 29029,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 29088,
"s": 29053,
"text": "Angular PrimeNG Messages Component"
},
{
"code": null,
"e": 29141,
"s": 29088,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 29181,
"s": 29141,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29214,
"s": 29181,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29259,
"s": 29214,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29302,
"s": 29259,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Adjusting Learning Rate of a Neural Network in PyTorch - GeeksforGeeks
|
22 Jan, 2021
Learning Rate is an important hyperparameter in Gradient Descent. Its value determines how fast the Neural Network would converge to minima. Usually, we choose a learning rate and depending on the results change its value to get the optimal value for LR. If the learning rate is too low for the Neural Network the process of convergence would be very slow and if it’s too high the converging would be fast but there is a chance that the loss might overshoot. So we usually tune our parameters to find the best value for the learning rate. But is there a way we can improve this process?
Instead of taking a constant learning rate, we can start with a higher value of LR and then keep decreasing its value periodically after certain iterations. This way we can initially have faster convergence whilst reducing the chances of overshooting the loss. In order to implement this we can use various scheduler in optim library in PyTorch. The format of a training loop is as following:-
epochs = 10
scheduler = <Any scheduler>
for epoch in range(epochs):
# Training Steps
# Validation Steps
scheduler.step()
PyTorch provides several methods to adjust the learning rate based on the number of epochs. Let’s have a look at a few of them:–
StepLR: Multiplies the learning rate with gamma every step_size epochs. For example, if lr = 0.1, gamma = 0.1 and step_size = 10 then after 10 epoch lr changes to lr*step_size in this case 0.01 and after another 10 epochs it becomes 0.001.
# Code format:-
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
scheduler = StepLR(optimizer, step_size=10, gamma=0.1)
# Procedure:-
lr = 0.1, gamma = 0.1 and step_size = 10
lr = 0.1 for epoch < 10
lr = 0.01 for epoch >= 10 and epoch < 20
lr = 0.001 for epoch >= 20 and epoch < 30
... and so on
MultiStepLR: This is a more customized version of StepLR in which the lr is changed after it reaches one of its epochs. Here we provide milestones that are epochs at which we want to update our learning rate.
# Code format:-
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
scheduler = MultiStepLR(optimizer, milestones=[10,30], gamma=0.1)
# Procedure:-
lr = 0.1, gamma = 0.1 and milestones=[10,30]
lr = 0.1 for epoch < 10
lr = 0.01 for epoch >= 10 and epoch < 30
lr = 0.001 for epoch >= 30
ExponentialLR: This is an aggressive version of StepLR in LR is changed after every epoch. You can think of it as StepLR with step_size = 1.
# Code format:-
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
scheduler = ExponentialLR(optimizer, gamma=0.1)
# Procedure:-
lr = 0.1, gamma = 0.1
lr = 0.1 for epoch = 1
lr = 0.01 for epoch = 2
lr = 0.001 for epoch = 3
... and so on
ReduceLROnPlateau: Reduces learning rate when a metric has stopped improving. Models often benefit from reducing the learning rate by a factor of 2-10 once learning stagnates. This scheduler reads a metrics quantity and if no improvement is seen for a patience number of epochs, the learning rate is reduced.
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
scheduler = ReduceLROnPlateau(optimizer, 'min', patience = 5)
# In min mode, lr will be reduced when the metric has stopped decreasing.
# In max mode, lr will be reduced when the metric has stopped increasing.
For this tutorial we are going to be using MNIST dataset, so we’ll start by loading our data and defining the model afterwards. Its recommended that you know how to create and train a Neural Network in PyTorch. Let’s start by loading our data.
from torchvision import datasets,transforms
from torch.utils.data import DataLoader
transform = transforms.Compose([
transforms.ToTensor()
])
train = datasets.MNIST('',train = True, download = True, transform=transform)
valid = datasets.MNIST('',train = False, download = True, transform=transform)
trainloader = DataLoader(train, batch_size= 32, shuffle=True)
validloader = DataLoader(test, batch_size= 32, shuffle=True)
Now that we have our dataloader ready we can now proceed to create our model. PyTorch model follows the following format:-
from torch import nn
class model(nn.Module):
def __init__(self):
# Define Model Here
def forward(self, x):
# Define Forward Pass Here
With that clear let’s define our model:-
import torch
from torch import nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net,self).__init__()
self.fc1 = nn.Linear(28*28,256)
self.fc2 = nn.Linear(256,128)
self.out = nn.Linear(128,10)
self.lr = 0.01
self.loss = nn.CrossEntropyLoss()
def forward(self,x):
batch_size, _, _, _ = x.size()
x = x.view(batch_size,-1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
return self.out(x)
model = Net()
# Send the model to GPU if available
if torch.cuda.is_available():
model = model.cuda()
Now that we have our model we can specify our optimizer, loss function and our lr_scheduler. We’ll be using SGD optimizer, CrossEntropyLoss for loss function and ReduceLROnPlateau for lr scheduler.
from torch.optim import SGD
from torch.optim.lr_scheduler import ReduceLROnPlateau
optimizer = SGD(model.parameters(), lr = 0.1)
loss = nn.CrossEntropyLoss()
scheduler = ReduceLROnPlateau(optimizer, 'min', patience = 5)
Let’s define the training loop. The training loop is pretty much the same as before except this time we’ll call our scheduler step method at the end of the loop.
from tqdm.notebook import trange
epoch = 25
for e in trange(epoch):
train_loss, valid_loss = 0.0, 0.0
# Set model to training mode
model.train()
for data, label in trainloader:
if torch.cuda.is_available():
data, label = data.cuda(), label.cuda()
optimizer.zero_grad()
target = model(data)
train_step_loss = loss(target, label)
train_step_loss.backward()
optimizer.step()
train_loss += train_step_loss.item() * data.size(0)
# Set model to Evaluation mode
model.eval()
for data, label in validloader:
if torch.cuda.is_available():
data, label = data.cuda(), label.cuda()
target = model(data)
valid_step_loss = loss(target, label)
valid_loss += valid_step_loss.item() * data.size(0)
curr_lr = optimizer.param_groups[0]['lr']
print(f'Epoch {e}\t \
Training Loss: {train_loss/len(trainloader)}\t \
Validation Loss:{valid_loss/len(validloader)}\t \
LR:{curr_lr}')
scheduler.step(valid_loss/len(validloader))
As you can see the scheduler kept adjusting lr when the validation loss stopped decreasing.
Code:
import torchfrom torch import nnimport torch.nn.functional as Ffrom torchvision import datasets,transformsfrom torch.utils.data import DataLoaderfrom torch.optim import SGDfrom torch.optim.lr_scheduler import ReduceLROnPlateaufrom tqdm.notebook import trange # LOADING DATAtransform = transforms.Compose([ transforms.ToTensor()]) train = datasets.MNIST('',train = True, download = True, transform=transform)valid = datasets.MNIST('',train = False, download = True, transform=transform) trainloader = DataLoader(train, batch_size= 32, shuffle=True)validloader = DataLoader(test, batch_size= 32, shuffle=True) # CREATING OUR MODELclass Net(nn.Module): def __init__(self): super(Net,self).__init__() self.fc1 = nn.Linear(28*28,64) self.fc2 = nn.Linear(64,32) self.out = nn.Linear(32,10) self.lr = 0.01 self.loss = nn.CrossEntropyLoss() def forward(self,x): batch_size, _, _, _ = x.size() x = x.view(batch_size,-1) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) return self.out(x) model = Net() # Send the model to GPU if availableif torch.cuda.is_available(): model = model.cuda() # SETTING OPTIMIZER, LOSS AND SCHEDULERoptimizer = SGD(model.parameters(), lr = 0.1)loss = nn.CrossEntropyLoss()scheduler = ReduceLROnPlateau(optimizer, 'min', patience = 5) # TRAINING THE NEURAL NETWORKepoch = 25for e in trange(epoch): train_loss, valid_loss = 0.0, 0.0 # Set model to training mode model.train() for data, label in trainloader: if torch.cuda.is_available(): data, label = data.cuda(), label.cuda() optimizer.zero_grad() target = model(data) train_step_loss = loss(target, label) train_step_loss.backward() optimizer.step() train_loss += train_step_loss.item() * data.size(0) # Set model to Evaluation mode model.eval() for data, label in validloader: if torch.cuda.is_available(): data, label = data.cuda(), label.cuda() target = model(data) valid_step_loss = loss(target, label) valid_loss += valid_step_loss.item() * data.size(0) curr_lr = optimizer.param_groups[0]['lr'] print(f'Epoch {e}\t \ Training Loss: {train_loss/len(trainloader)}\t \ Validation Loss:{valid_loss/len(validloader)}\t \ LR:{curr_lr}') scheduler.step(valid_loss/len(validloader))
Python-PyTorch
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Informed and Uninformed Search in AI
Deploy Machine Learning Model using Flask
Support Vector Machine Algorithm
Types of Environments in AI
k-nearest neighbor algorithm in Python
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": 23953,
"s": 23925,
"text": "\n22 Jan, 2021"
},
{
"code": null,
"e": 24540,
"s": 23953,
"text": "Learning Rate is an important hyperparameter in Gradient Descent. Its value determines how fast the Neural Network would converge to minima. Usually, we choose a learning rate and depending on the results change its value to get the optimal value for LR. If the learning rate is too low for the Neural Network the process of convergence would be very slow and if it’s too high the converging would be fast but there is a chance that the loss might overshoot. So we usually tune our parameters to find the best value for the learning rate. But is there a way we can improve this process?"
},
{
"code": null,
"e": 24934,
"s": 24540,
"text": "Instead of taking a constant learning rate, we can start with a higher value of LR and then keep decreasing its value periodically after certain iterations. This way we can initially have faster convergence whilst reducing the chances of overshooting the loss. In order to implement this we can use various scheduler in optim library in PyTorch. The format of a training loop is as following:-"
},
{
"code": null,
"e": 25079,
"s": 24934,
"text": "epochs = 10\nscheduler = <Any scheduler>\n\nfor epoch in range(epochs):\n # Training Steps\n \n # Validation Steps\n \n scheduler.step()"
},
{
"code": null,
"e": 25208,
"s": 25079,
"text": "PyTorch provides several methods to adjust the learning rate based on the number of epochs. Let’s have a look at a few of them:–"
},
{
"code": null,
"e": 25449,
"s": 25208,
"text": "StepLR: Multiplies the learning rate with gamma every step_size epochs. For example, if lr = 0.1, gamma = 0.1 and step_size = 10 then after 10 epoch lr changes to lr*step_size in this case 0.01 and after another 10 epochs it becomes 0.001."
},
{
"code": null,
"e": 25792,
"s": 25449,
"text": "# Code format:-\noptimizer = torch.optim.SGD(model.parameters(), lr=0.1)\nscheduler = StepLR(optimizer, step_size=10, gamma=0.1)\n\n# Procedure:-\nlr = 0.1, gamma = 0.1 and step_size = 10\nlr = 0.1 for epoch < 10\nlr = 0.01 for epoch >= 10 and epoch < 20\nlr = 0.001 for epoch >= 20 and epoch < 30\n... and so on"
},
{
"code": null,
"e": 26001,
"s": 25792,
"text": "MultiStepLR: This is a more customized version of StepLR in which the lr is changed after it reaches one of its epochs. Here we provide milestones that are epochs at which we want to update our learning rate."
},
{
"code": null,
"e": 26330,
"s": 26001,
"text": "# Code format:-\noptimizer = torch.optim.SGD(model.parameters(), lr=0.1)\nscheduler = MultiStepLR(optimizer, milestones=[10,30], gamma=0.1)\n\n# Procedure:-\nlr = 0.1, gamma = 0.1 and milestones=[10,30]\nlr = 0.1 for epoch < 10\nlr = 0.01 for epoch >= 10 and epoch < 30\nlr = 0.001 for epoch >= 30"
},
{
"code": null,
"e": 26471,
"s": 26330,
"text": "ExponentialLR: This is an aggressive version of StepLR in LR is changed after every epoch. You can think of it as StepLR with step_size = 1."
},
{
"code": null,
"e": 26753,
"s": 26471,
"text": "# Code format:-\noptimizer = torch.optim.SGD(model.parameters(), lr=0.1)\nscheduler = ExponentialLR(optimizer, gamma=0.1)\n\n# Procedure:-\nlr = 0.1, gamma = 0.1\nlr = 0.1 for epoch = 1\nlr = 0.01 for epoch = 2\nlr = 0.001 for epoch = 3\n... and so on"
},
{
"code": null,
"e": 27062,
"s": 26753,
"text": "ReduceLROnPlateau: Reduces learning rate when a metric has stopped improving. Models often benefit from reducing the learning rate by a factor of 2-10 once learning stagnates. This scheduler reads a metrics quantity and if no improvement is seen for a patience number of epochs, the learning rate is reduced."
},
{
"code": null,
"e": 27331,
"s": 27062,
"text": "optimizer = torch.optim.SGD(model.parameters(), lr=0.1)\nscheduler = ReduceLROnPlateau(optimizer, 'min', patience = 5)\n\n# In min mode, lr will be reduced when the metric has stopped decreasing. \n# In max mode, lr will be reduced when the metric has stopped increasing. "
},
{
"code": null,
"e": 27575,
"s": 27331,
"text": "For this tutorial we are going to be using MNIST dataset, so we’ll start by loading our data and defining the model afterwards. Its recommended that you know how to create and train a Neural Network in PyTorch. Let’s start by loading our data."
},
{
"code": null,
"e": 28004,
"s": 27575,
"text": "from torchvision import datasets,transforms\nfrom torch.utils.data import DataLoader\n\ntransform = transforms.Compose([\n transforms.ToTensor()\n])\n\ntrain = datasets.MNIST('',train = True, download = True, transform=transform)\nvalid = datasets.MNIST('',train = False, download = True, transform=transform)\n\ntrainloader = DataLoader(train, batch_size= 32, shuffle=True)\nvalidloader = DataLoader(test, batch_size= 32, shuffle=True)"
},
{
"code": null,
"e": 28127,
"s": 28004,
"text": "Now that we have our dataloader ready we can now proceed to create our model. PyTorch model follows the following format:-"
},
{
"code": null,
"e": 28295,
"s": 28127,
"text": "from torch import nn\n\nclass model(nn.Module):\n def __init__(self):\n # Define Model Here\n \n def forward(self, x):\n # Define Forward Pass Here"
},
{
"code": null,
"e": 28336,
"s": 28295,
"text": "With that clear let’s define our model:-"
},
{
"code": null,
"e": 28966,
"s": 28336,
"text": "import torch\nfrom torch import nn\nimport torch.nn.functional as F\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net,self).__init__()\n self.fc1 = nn.Linear(28*28,256)\n self.fc2 = nn.Linear(256,128)\n self.out = nn.Linear(128,10)\n self.lr = 0.01\n self.loss = nn.CrossEntropyLoss()\n \n def forward(self,x):\n batch_size, _, _, _ = x.size()\n x = x.view(batch_size,-1)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n return self.out(x)\n\nmodel = Net()\n\n# Send the model to GPU if available\nif torch.cuda.is_available():\n model = model.cuda()"
},
{
"code": null,
"e": 29164,
"s": 28966,
"text": "Now that we have our model we can specify our optimizer, loss function and our lr_scheduler. We’ll be using SGD optimizer, CrossEntropyLoss for loss function and ReduceLROnPlateau for lr scheduler."
},
{
"code": null,
"e": 29385,
"s": 29164,
"text": "from torch.optim import SGD\nfrom torch.optim.lr_scheduler import ReduceLROnPlateau\n\noptimizer = SGD(model.parameters(), lr = 0.1)\nloss = nn.CrossEntropyLoss()\nscheduler = ReduceLROnPlateau(optimizer, 'min', patience = 5)"
},
{
"code": null,
"e": 29547,
"s": 29385,
"text": "Let’s define the training loop. The training loop is pretty much the same as before except this time we’ll call our scheduler step method at the end of the loop."
},
{
"code": null,
"e": 30655,
"s": 29547,
"text": "from tqdm.notebook import trange\n\nepoch = 25\nfor e in trange(epoch):\n train_loss, valid_loss = 0.0, 0.0\n \n # Set model to training mode\n model.train()\n for data, label in trainloader:\n if torch.cuda.is_available():\n data, label = data.cuda(), label.cuda()\n\n optimizer.zero_grad()\n target = model(data)\n train_step_loss = loss(target, label)\n train_step_loss.backward()\n optimizer.step()\n\n train_loss += train_step_loss.item() * data.size(0)\n\n # Set model to Evaluation mode\n model.eval()\n for data, label in validloader:\n if torch.cuda.is_available():\n data, label = data.cuda(), label.cuda()\n\n target = model(data)\n valid_step_loss = loss(target, label)\n\n valid_loss += valid_step_loss.item() * data.size(0)\n \n curr_lr = optimizer.param_groups[0]['lr']\n\n print(f'Epoch {e}\\t \\\n Training Loss: {train_loss/len(trainloader)}\\t \\\n Validation Loss:{valid_loss/len(validloader)}\\t \\\n LR:{curr_lr}')\n scheduler.step(valid_loss/len(validloader))"
},
{
"code": null,
"e": 30747,
"s": 30655,
"text": "As you can see the scheduler kept adjusting lr when the validation loss stopped decreasing."
},
{
"code": null,
"e": 30753,
"s": 30747,
"text": "Code:"
},
{
"code": "import torchfrom torch import nnimport torch.nn.functional as Ffrom torchvision import datasets,transformsfrom torch.utils.data import DataLoaderfrom torch.optim import SGDfrom torch.optim.lr_scheduler import ReduceLROnPlateaufrom tqdm.notebook import trange # LOADING DATAtransform = transforms.Compose([ transforms.ToTensor()]) train = datasets.MNIST('',train = True, download = True, transform=transform)valid = datasets.MNIST('',train = False, download = True, transform=transform) trainloader = DataLoader(train, batch_size= 32, shuffle=True)validloader = DataLoader(test, batch_size= 32, shuffle=True) # CREATING OUR MODELclass Net(nn.Module): def __init__(self): super(Net,self).__init__() self.fc1 = nn.Linear(28*28,64) self.fc2 = nn.Linear(64,32) self.out = nn.Linear(32,10) self.lr = 0.01 self.loss = nn.CrossEntropyLoss() def forward(self,x): batch_size, _, _, _ = x.size() x = x.view(batch_size,-1) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) return self.out(x) model = Net() # Send the model to GPU if availableif torch.cuda.is_available(): model = model.cuda() # SETTING OPTIMIZER, LOSS AND SCHEDULERoptimizer = SGD(model.parameters(), lr = 0.1)loss = nn.CrossEntropyLoss()scheduler = ReduceLROnPlateau(optimizer, 'min', patience = 5) # TRAINING THE NEURAL NETWORKepoch = 25for e in trange(epoch): train_loss, valid_loss = 0.0, 0.0 # Set model to training mode model.train() for data, label in trainloader: if torch.cuda.is_available(): data, label = data.cuda(), label.cuda() optimizer.zero_grad() target = model(data) train_step_loss = loss(target, label) train_step_loss.backward() optimizer.step() train_loss += train_step_loss.item() * data.size(0) # Set model to Evaluation mode model.eval() for data, label in validloader: if torch.cuda.is_available(): data, label = data.cuda(), label.cuda() target = model(data) valid_step_loss = loss(target, label) valid_loss += valid_step_loss.item() * data.size(0) curr_lr = optimizer.param_groups[0]['lr'] print(f'Epoch {e}\\t \\ Training Loss: {train_loss/len(trainloader)}\\t \\ Validation Loss:{valid_loss/len(validloader)}\\t \\ LR:{curr_lr}') scheduler.step(valid_loss/len(validloader))",
"e": 33193,
"s": 30753,
"text": null
},
{
"code": null,
"e": 33208,
"s": 33193,
"text": "Python-PyTorch"
},
{
"code": null,
"e": 33225,
"s": 33208,
"text": "Machine Learning"
},
{
"code": null,
"e": 33232,
"s": 33225,
"text": "Python"
},
{
"code": null,
"e": 33249,
"s": 33232,
"text": "Machine Learning"
},
{
"code": null,
"e": 33347,
"s": 33249,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33356,
"s": 33347,
"text": "Comments"
},
{
"code": null,
"e": 33369,
"s": 33356,
"text": "Old Comments"
},
{
"code": null,
"e": 33425,
"s": 33369,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 33467,
"s": 33425,
"text": "Deploy Machine Learning Model using Flask"
},
{
"code": null,
"e": 33500,
"s": 33467,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 33528,
"s": 33500,
"text": "Types of Environments in AI"
},
{
"code": null,
"e": 33567,
"s": 33528,
"text": "k-nearest neighbor algorithm in Python"
},
{
"code": null,
"e": 33595,
"s": 33567,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 33645,
"s": 33595,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 33667,
"s": 33645,
"text": "Python map() function"
}
] |
Golang - Environment Variables - GeeksforGeeks
|
04 Feb, 2021
An Environment Variable is a dynamic object pair on the Operating System. These value pairs can be manipulated with the help of the operating system. These value pairs can be used to store file path, user profile, authentication keys, execution mode, etc.
In Golang, we can use the os package to read and write environment variables.
1. Set an environment variable with os.Setenv(). This method accepts both parameters as strings. It returns an error if any.
os.Setenv(key,value)
2. Get environment variable value with os.Getenv(). This method returns the value of the variable if the variable is present else it returns an empty value.
os.Getenv(key)
3. Delete or Unset a single environment variable using os.Unsetenv() method. This method returns an error if any.
os.Unsetenv(key)
4. Get environment variable value and a boolean with os.LookupEnv(). Boolean indicates that a key is present or not. If the key is not present false is returned.
os.LookupEnv(key)
5. List all the environment variable and their values with os.Environ(). This method returns a copy of strings, of the “key=value” format.
os.Environ()
6. Delete all environment variables with os.Clearenv().
os.Clearenv()
Example 1:
Go
// Golang program to show the usage of// Setenv(), Getenv and Unsetenv method package main import ( "fmt" "os") // Main functionfunc main() { // set environment variable GEEKS os.Setenv("GEEKS", "geeks") // returns value of GEEKS fmt.Println("GEEKS:", os.Getenv("GEEKS")) // Unset environment variable GEEKS os.Unsetenv("GEEKS") // returns empty string and false, // because we removed the GEEKS variable value, ok := os.LookupEnv("GEEKS") fmt.Println("GEEKS:", value, " Is present:", ok) }
Output:
Example 2:
Go
// Golang program to show the// usage of os.Environ() Methodpackage main import ( "fmt" "os") // Main functionfunc main() { // list all environment variables and their values for _, env := range os.Environ() { fmt.Println(env) }}
Output:
Example 3:
Go
// Golang program to show the// usage of os.Clearenv() Methodpackage main import ( "fmt" "os") // Main functionfunc main() { // this delete's all environment variables // Don't try this in the home environment, // if you do so you will end up deleting // all env variables os.Clearenv() fmt.Println("All environment variables cleared") }
Output:
All environment variables cleared
Golang-Packages
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Parse JSON in Golang?
Defer Keyword in Golang
Rune in Golang
Anonymous function in Go Language
Loops in Go Language
Class and Object in Golang
Structures in Golang
Time Durations in Golang
Strings in Golang
How to iterate over an Array using for loop in Golang?
|
[
{
"code": null,
"e": 24069,
"s": 24041,
"text": "\n04 Feb, 2021"
},
{
"code": null,
"e": 24325,
"s": 24069,
"text": "An Environment Variable is a dynamic object pair on the Operating System. These value pairs can be manipulated with the help of the operating system. These value pairs can be used to store file path, user profile, authentication keys, execution mode, etc."
},
{
"code": null,
"e": 24403,
"s": 24325,
"text": "In Golang, we can use the os package to read and write environment variables."
},
{
"code": null,
"e": 24528,
"s": 24403,
"text": "1. Set an environment variable with os.Setenv(). This method accepts both parameters as strings. It returns an error if any."
},
{
"code": null,
"e": 24551,
"s": 24528,
"text": "os.Setenv(key,value) "
},
{
"code": null,
"e": 24708,
"s": 24551,
"text": "2. Get environment variable value with os.Getenv(). This method returns the value of the variable if the variable is present else it returns an empty value."
},
{
"code": null,
"e": 24723,
"s": 24708,
"text": "os.Getenv(key)"
},
{
"code": null,
"e": 24837,
"s": 24723,
"text": "3. Delete or Unset a single environment variable using os.Unsetenv() method. This method returns an error if any."
},
{
"code": null,
"e": 24854,
"s": 24837,
"text": "os.Unsetenv(key)"
},
{
"code": null,
"e": 25016,
"s": 24854,
"text": "4. Get environment variable value and a boolean with os.LookupEnv(). Boolean indicates that a key is present or not. If the key is not present false is returned."
},
{
"code": null,
"e": 25034,
"s": 25016,
"text": "os.LookupEnv(key)"
},
{
"code": null,
"e": 25173,
"s": 25034,
"text": "5. List all the environment variable and their values with os.Environ(). This method returns a copy of strings, of the “key=value” format."
},
{
"code": null,
"e": 25186,
"s": 25173,
"text": "os.Environ()"
},
{
"code": null,
"e": 25242,
"s": 25186,
"text": "6. Delete all environment variables with os.Clearenv()."
},
{
"code": null,
"e": 25256,
"s": 25242,
"text": "os.Clearenv()"
},
{
"code": null,
"e": 25267,
"s": 25256,
"text": "Example 1:"
},
{
"code": null,
"e": 25270,
"s": 25267,
"text": "Go"
},
{
"code": "// Golang program to show the usage of// Setenv(), Getenv and Unsetenv method package main import ( \"fmt\" \"os\") // Main functionfunc main() { // set environment variable GEEKS os.Setenv(\"GEEKS\", \"geeks\") // returns value of GEEKS fmt.Println(\"GEEKS:\", os.Getenv(\"GEEKS\")) // Unset environment variable GEEKS os.Unsetenv(\"GEEKS\") // returns empty string and false, // because we removed the GEEKS variable value, ok := os.LookupEnv(\"GEEKS\") fmt.Println(\"GEEKS:\", value, \" Is present:\", ok) }",
"e": 25811,
"s": 25270,
"text": null
},
{
"code": null,
"e": 25819,
"s": 25811,
"text": "Output:"
},
{
"code": null,
"e": 25830,
"s": 25819,
"text": "Example 2:"
},
{
"code": null,
"e": 25833,
"s": 25830,
"text": "Go"
},
{
"code": "// Golang program to show the// usage of os.Environ() Methodpackage main import ( \"fmt\" \"os\") // Main functionfunc main() { // list all environment variables and their values for _, env := range os.Environ() { fmt.Println(env) }}",
"e": 26089,
"s": 25833,
"text": null
},
{
"code": null,
"e": 26097,
"s": 26089,
"text": "Output:"
},
{
"code": null,
"e": 26109,
"s": 26097,
"text": "Example 3: "
},
{
"code": null,
"e": 26112,
"s": 26109,
"text": "Go"
},
{
"code": "// Golang program to show the// usage of os.Clearenv() Methodpackage main import ( \"fmt\" \"os\") // Main functionfunc main() { // this delete's all environment variables // Don't try this in the home environment, // if you do so you will end up deleting // all env variables os.Clearenv() fmt.Println(\"All environment variables cleared\") }",
"e": 26482,
"s": 26112,
"text": null
},
{
"code": null,
"e": 26490,
"s": 26482,
"text": "Output:"
},
{
"code": null,
"e": 26524,
"s": 26490,
"text": "All environment variables cleared"
},
{
"code": null,
"e": 26540,
"s": 26524,
"text": "Golang-Packages"
},
{
"code": null,
"e": 26552,
"s": 26540,
"text": "Go Language"
},
{
"code": null,
"e": 26650,
"s": 26552,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26659,
"s": 26650,
"text": "Comments"
},
{
"code": null,
"e": 26672,
"s": 26659,
"text": "Old Comments"
},
{
"code": null,
"e": 26701,
"s": 26672,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 26725,
"s": 26701,
"text": "Defer Keyword in Golang"
},
{
"code": null,
"e": 26740,
"s": 26725,
"text": "Rune in Golang"
},
{
"code": null,
"e": 26774,
"s": 26740,
"text": "Anonymous function in Go Language"
},
{
"code": null,
"e": 26795,
"s": 26774,
"text": "Loops in Go Language"
},
{
"code": null,
"e": 26822,
"s": 26795,
"text": "Class and Object in Golang"
},
{
"code": null,
"e": 26843,
"s": 26822,
"text": "Structures in Golang"
},
{
"code": null,
"e": 26868,
"s": 26843,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 26886,
"s": 26868,
"text": "Strings in Golang"
}
] |
Deleting Lambda Function
|
Deleting AWS Lambda function will remove the AWS Lambda from the AWS console. There are 2 ways to delete AWS Lambda function.
Using AWS console.
Using AWS CLI command
This chapter discusses these two ways in detail.
For deleting a Lambda function using AWS console, follow the steps given below −
Login to AWS console and go to AWS Lambda service. You can find that AWS lambda functions created so far are listed in AWS console as shown below −
The list shows that there are 23 AWS Lambda functions created so far. You can view them using the pagination provided on the top or search the AWS Lambda by using the search box.
Observe that there is a radio button across each of the AWS Lambda function. Select the function you want to delete. Observe the screenshot shown below −
Once you select the AWS Lambda function, the Action dropdown which was earlier grayed out is highlighted now. Now, open the combo box and it will display options as shown −
Select the Delete button to delete the AWS Lambda function. Once you click Delete, it displays the message as follows −
Read the message carefully and later click Delete button to remove the AWS lambda function permanently.
Note − Deleting aws lambda will not delete the role linked. To remove the role, you need to go to IAM and remove the role.
The list of roles created so far is shown below. Observe that there is a Create role button and Delete role button.
Click the checkbox across the role you want to delete. You can also select multiple roles to delete at a time.
You will see a confirmation message as shown below once you click Delete button −
Now, read the details mentioned carefully and later click Yes, delete button.
Let us first create a Lambda function using aws cli and delete the same using the same command. Follow the Steps given below for this purpose −
aws lambda create-function
--function-name "lambdatestcli"
--runtime "nodejs8.10"
--role "arn:aws:iam::625297745038:role/lambdaapipolicy"
--handler "index.handler"
--timeout 5
--memory-size 256
--zip-file "fileb://C:\demotest\index.zip"
The corresponding output is shown here −
The AWS Lambda function created is lambdatestcli. We have used existing role arn to create the lambda function.
Then you can find this function displayed in AWS console as shown below −
aws lambda invoke --function-name "lambdatestcli" --log-type Tail
C:\demotest\outputfile.txt
This command will give you the output as shown −
Command
delete-function
--function-name <value>
[--qualifier <value>]
[--cli-input-json <value>]
[--generate-cli-skeleton <value>]
Options
--function-name(string) − This will take the Lambda function name or the arn of the AWS Lambda function.
--qualifier (string) − This is optional. Here you can specify the version of AWS Lambda that needs to be deleted.
-- cli-input-json(string) − Performs service operation based on the JSON string provided. The JSON string follows the format provided by --generate-cli-skeleton. If other arguments are provided on the command line, the CLI values will override the JSON-provided values.
--generate-cli-skeleton(string) − it prints json skeleton to standard output without sending the API request.
Command with values
aws lambda delete-function --function-name "lambdatestcli"
The corresponding output is shown below −
35 Lectures
7.5 hours
Mr. Pradeep Kshetrapal
30 Lectures
3.5 hours
Priyanka Choudhary
44 Lectures
7.5 hours
Eduonix Learning Solutions
51 Lectures
6 hours
Manuj Aggarwal
41 Lectures
5 hours
AR Shankar
14 Lectures
1 hours
Zach Miller
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2532,
"s": 2406,
"text": "Deleting AWS Lambda function will remove the AWS Lambda from the AWS console. There are 2 ways to delete AWS Lambda function."
},
{
"code": null,
"e": 2551,
"s": 2532,
"text": "Using AWS console."
},
{
"code": null,
"e": 2573,
"s": 2551,
"text": "Using AWS CLI command"
},
{
"code": null,
"e": 2622,
"s": 2573,
"text": "This chapter discusses these two ways in detail."
},
{
"code": null,
"e": 2703,
"s": 2622,
"text": "For deleting a Lambda function using AWS console, follow the steps given below −"
},
{
"code": null,
"e": 2851,
"s": 2703,
"text": "Login to AWS console and go to AWS Lambda service. You can find that AWS lambda functions created so far are listed in AWS console as shown below −"
},
{
"code": null,
"e": 3030,
"s": 2851,
"text": "The list shows that there are 23 AWS Lambda functions created so far. You can view them using the pagination provided on the top or search the AWS Lambda by using the search box."
},
{
"code": null,
"e": 3184,
"s": 3030,
"text": "Observe that there is a radio button across each of the AWS Lambda function. Select the function you want to delete. Observe the screenshot shown below −"
},
{
"code": null,
"e": 3357,
"s": 3184,
"text": "Once you select the AWS Lambda function, the Action dropdown which was earlier grayed out is highlighted now. Now, open the combo box and it will display options as shown −"
},
{
"code": null,
"e": 3477,
"s": 3357,
"text": "Select the Delete button to delete the AWS Lambda function. Once you click Delete, it displays the message as follows −"
},
{
"code": null,
"e": 3581,
"s": 3477,
"text": "Read the message carefully and later click Delete button to remove the AWS lambda function permanently."
},
{
"code": null,
"e": 3704,
"s": 3581,
"text": "Note − Deleting aws lambda will not delete the role linked. To remove the role, you need to go to IAM and remove the role."
},
{
"code": null,
"e": 3820,
"s": 3704,
"text": "The list of roles created so far is shown below. Observe that there is a Create role button and Delete role button."
},
{
"code": null,
"e": 3931,
"s": 3820,
"text": "Click the checkbox across the role you want to delete. You can also select multiple roles to delete at a time."
},
{
"code": null,
"e": 4013,
"s": 3931,
"text": "You will see a confirmation message as shown below once you click Delete button −"
},
{
"code": null,
"e": 4091,
"s": 4013,
"text": "Now, read the details mentioned carefully and later click Yes, delete button."
},
{
"code": null,
"e": 4235,
"s": 4091,
"text": "Let us first create a Lambda function using aws cli and delete the same using the same command. Follow the Steps given below for this purpose −"
},
{
"code": null,
"e": 4480,
"s": 4235,
"text": "aws lambda create-function \n--function-name \"lambdatestcli\" \n--runtime \"nodejs8.10\" \n--role \"arn:aws:iam::625297745038:role/lambdaapipolicy\" \n--handler \"index.handler\" \n--timeout 5 \n--memory-size 256 \n--zip-file \"fileb://C:\\demotest\\index.zip\"\n"
},
{
"code": null,
"e": 4521,
"s": 4480,
"text": "The corresponding output is shown here −"
},
{
"code": null,
"e": 4633,
"s": 4521,
"text": "The AWS Lambda function created is lambdatestcli. We have used existing role arn to create the lambda function."
},
{
"code": null,
"e": 4707,
"s": 4633,
"text": "Then you can find this function displayed in AWS console as shown below −"
},
{
"code": null,
"e": 4802,
"s": 4707,
"text": "aws lambda invoke --function-name \"lambdatestcli\" --log-type Tail \nC:\\demotest\\outputfile.txt\n"
},
{
"code": null,
"e": 4851,
"s": 4802,
"text": "This command will give you the output as shown −"
},
{
"code": null,
"e": 4859,
"s": 4851,
"text": "Command"
},
{
"code": null,
"e": 4983,
"s": 4859,
"text": "delete-function\n--function-name <value>\n[--qualifier <value>]\n[--cli-input-json <value>]\n[--generate-cli-skeleton <value>]\n"
},
{
"code": null,
"e": 4991,
"s": 4983,
"text": "Options"
},
{
"code": null,
"e": 5096,
"s": 4991,
"text": "--function-name(string) − This will take the Lambda function name or the arn of the AWS Lambda function."
},
{
"code": null,
"e": 5210,
"s": 5096,
"text": "--qualifier (string) − This is optional. Here you can specify the version of AWS Lambda that needs to be deleted."
},
{
"code": null,
"e": 5480,
"s": 5210,
"text": "-- cli-input-json(string) − Performs service operation based on the JSON string provided. The JSON string follows the format provided by --generate-cli-skeleton. If other arguments are provided on the command line, the CLI values will override the JSON-provided values."
},
{
"code": null,
"e": 5590,
"s": 5480,
"text": "--generate-cli-skeleton(string) − it prints json skeleton to standard output without sending the API request."
},
{
"code": null,
"e": 5610,
"s": 5590,
"text": "Command with values"
},
{
"code": null,
"e": 5670,
"s": 5610,
"text": "aws lambda delete-function --function-name \"lambdatestcli\"\n"
},
{
"code": null,
"e": 5712,
"s": 5670,
"text": "The corresponding output is shown below −"
},
{
"code": null,
"e": 5747,
"s": 5712,
"text": "\n 35 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5771,
"s": 5747,
"text": " Mr. Pradeep Kshetrapal"
},
{
"code": null,
"e": 5806,
"s": 5771,
"text": "\n 30 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5826,
"s": 5806,
"text": " Priyanka Choudhary"
},
{
"code": null,
"e": 5861,
"s": 5826,
"text": "\n 44 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5889,
"s": 5861,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5922,
"s": 5889,
"text": "\n 51 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5938,
"s": 5922,
"text": " Manuj Aggarwal"
},
{
"code": null,
"e": 5971,
"s": 5938,
"text": "\n 41 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5983,
"s": 5971,
"text": " AR Shankar"
},
{
"code": null,
"e": 6016,
"s": 5983,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6029,
"s": 6016,
"text": " Zach Miller"
},
{
"code": null,
"e": 6036,
"s": 6029,
"text": " Print"
},
{
"code": null,
"e": 6047,
"s": 6036,
"text": " Add Notes"
}
] |
Training a Convolutional Neural Network from scratch | by Victor Zhou | Towards Data Science
|
In this post, we’re going to do a deep-dive on something most introductions to Convolutional Neural Networks (CNNs) lack: how to train a CNN, including deriving gradients, implementing backprop from scratch (using only numpy), and ultimately building a full training pipeline!
This post assumes a basic knowledge of CNNs. My introduction to CNNs covers everything you need to know, so I’d highly recommend reading that first. If you’re here because you’ve already read that, welcome back!
Parts of this post also assume a basic knowledge of multivariable calculus. You can skip those sections if you want, but I recommend reading them even if you don’t understand everything. We’ll incrementally write code as we derive results, and even a surface-level understanding can be helpful.
Buckle up! Time to get into it.
We’ll pick back up where my introduction to CNNs left off. We were using a CNN to tackle the MNIST handwritten digit classification problem:
Our (simple) CNN consisted of a Conv layer, a Max Pooling layer, and a Softmax layer. Here’s that diagram of our CNN again:
We’d written 3 classes, one for each layer: Conv3x3, MaxPool, and Softmax. Each class implemented a forward() method that we used to build the forward pass of the CNN:
You can view the code or run the CNN in your browser. It’s also available on Github.
Here’s what the output of our CNN looks like right now:
MNIST CNN initialized![Step 100] Past 100 steps: Average Loss 2.302 | Accuracy: 11%[Step 200] Past 100 steps: Average Loss 2.302 | Accuracy: 8%[Step 300] Past 100 steps: Average Loss 2.302 | Accuracy: 3%[Step 400] Past 100 steps: Average Loss 2.302 | Accuracy: 12%
Obviously, we’d like to do better than 10% accuracy... let’s teach this CNN a lesson.
Training a neural network typically consists of two phases:
A forward phase, where the input is passed completely through the network.A backward phase, where gradients are backpropagated (backprop) and weights are updated.
A forward phase, where the input is passed completely through the network.
A backward phase, where gradients are backpropagated (backprop) and weights are updated.
We’ll follow this pattern to train our CNN. There are also two major implementation-specific ideas we’ll use:
During the forward phase, each layer will cache any data (like inputs, intermediate values, etc) it’ll need for the backward phase. This means that any backward phase must be preceded by a corresponding forward phase.
During the backward phase, each layer will receive a gradient and also return a gradient. It will receive the gradient of loss with respect to its outputs (∂L / ∂out) and return the gradient of loss with respect to its inputs (∂L / ∂in).
These two ideas will help keep our training implementation clean and organized. The best way to see why is probably by looking at code. Training our CNN will ultimately look something like this:
See how nice and clean that looks? Now imagine building a network with 50 layers instead of 3 — it’s even more valuable then to have good systems in place.
We’ll start our way from the end and work our way towards the beginning, since that’s how backprop works. First, recall the cross-entropy loss:
where p_c is the predicted probability for the correct class c (in other words, what digit our current image actually is).
Want a longer explanation? Read the Cross-Entropy Loss section of my introduction to CNNs.
The first thing we need to calculate is the input to the Softmax layer’s backward phase, ∂L / ∂out_s, where out_s is the output from the Softmax layer: a vector of 10 probabilities. This is pretty easy, since only p_i shows up in the loss equation:
That’s our initial gradient you saw referenced above:
We’re almost ready to implement our first backward phase — we just need to first perform the forward phase caching we discussed earlier:
We cache 3 things here that will be useful for implementing the backward phase:
The input's shape before we flatten it.
The input after we flatten it.
The totals, which are the values passed in to the softmax activation.
With that out of the way, we can start deriving the gradients for the backprop phase. We’ve already derived the input to the Softmax backward phase: ∂L / ∂out_s. One fact we can use about ∂L / ∂out_s is that it’s only nonzero for c, the correct class. That means that we can ignore everything but out_s(c)!
First, let’s calculate the gradient of out_s(c) with respect to the totals (the values passed in to the softmax activation). Let t_i be the total for class i. Then we can write out_s(c) as:
You should recognize the equation above from the Softmax section of my CNNs tutorial.
Now, consider some class k such that k is not c. We can rewrite out_s(c) as:
and use Chain Rule to derive:
Remember, that was assuming k doesn’t equal c. Now let’s do the derivation for c, this time using Quotient Rule:
Phew. That was the hardest bit of calculus in this entire post — it only gets easier from here! Let’s start implementing this:
Remember how ∂L / ∂out_s is only nonzero for the correct class, c? We start by looking for c by looking for a nonzero gradient in d_L_d_out. Once we find that, we calculate the gradient ∂out_s(i) / ∂t (d_out_d_totals) using the results we derived above:
Let’s keep going. We ultimately want the gradients of loss against weights, biases, and input:
We’ll use the weights gradient, ∂L / ∂w , to update our layer’s weights.
We’ll use the biases gradient, ∂L / ∂b , to update our layer’s biases.
We’ll return the input gradient, ∂L / ∂input , from our backprop() method so the next layer can use it. This is the return gradient we talked about in the Training Overview section!
To calculate those 3 loss gradients, we first need to derive 3 more results: the gradients of totals against weights, biases, and input. The relevant equation here is:
These gradients are easy!
Putting everything together:
Putting this into code is a little less straightforward:
First, we pre-calculate d_L_d_t since we'll use it several times. Then, we calculate each gradient:
d_L_d_w: We need 2d arrays to do matrix multiplication (@), but d_t_d_w and d_L_d_t are 1d arrays. np.newaxis lets us easily create a new axis of length one, so we end up multiplying matrices with dimensions (input_len, 1) and (1, nodes). Thus, the final result for d_L_d_w will have shape (input_len, nodes), which is the same as self.weights!
d_L_d_b: This one is straightforward, since d_t_d_b is 1.
d_L_d_inputs: We multiply matrices with dimensions (input_len, nodes) and (nodes, 1) to get a result with length input_len.
Try working through small examples of the calculations above, especially the matrix multiplications for d_L_d_w and d_L_d_inputs. That's the best way to understand why this code correctly computes the gradients.
With all the gradients computed, all that’s left is to actually train the Softmax layer! We’ll update the weights and bias using Stochastic Gradient Descent (SGD) just like we did in my introduction to Neural Networks and then return d_L_d_inputs:
Notice that we added a learn_rate parameter that controls how fast we update our weights. Also, we have to reshape() before returning d_L_d_inputs because we flattened the input during our forward pass:
Reshaping to last_input_shape ensures that this layer returns gradients for its input in the same format that the input was originally given to it.
We’ve finished our first backprop implementation! Let’s quickly test it to see if it’s any good. We’ll start implementing a train()method from my CNNs introduction:
Running this gives results similar to:
MNIST CNN initialized![Step 100] Past 100 steps: Average Loss 2.239 | Accuracy: 18%[Step 200] Past 100 steps: Average Loss 2.140 | Accuracy: 32%[Step 300] Past 100 steps: Average Loss 1.998 | Accuracy: 48%[Step 400] Past 100 steps: Average Loss 1.861 | Accuracy: 59%[Step 500] Past 100 steps: Average Loss 1.789 | Accuracy: 56%[Step 600] Past 100 steps: Average Loss 1.809 | Accuracy: 48%[Step 700] Past 100 steps: Average Loss 1.718 | Accuracy: 63%[Step 800] Past 100 steps: Average Loss 1.588 | Accuracy: 69%[Step 900] Past 100 steps: Average Loss 1.509 | Accuracy: 71%[Step 1000] Past 100 steps: Average Loss 1.481 | Accuracy: 70%
The loss is going down and the accuracy is going up — our CNN is already learning!
A Max Pooling layer can’t be trained because it doesn’t actually have any weights, but we still need to implement a method for it to calculate gradients. We’ll start by adding forward phase caching again. All we need to cache this time is the input:
During the forward pass, the Max Pooling layer takes an input volume and halves its width and height dimensions by picking the max values over 2x2 blocks. The backward pass does the opposite: we’ll double the width and height of the loss gradient by assigning each gradient value to where the original max value was in its corresponding 2x2 block.
Here’s an example. Consider this forward phase for a Max Pooling layer:
The backward phase of that same layer would look like this:
Each gradient value is assigned to where the original max value was, and every other value is zero.
Why does the backward phase for a Max Pooling layer work like this? Think about what ∂L / ∂inputs intuitively should be. An input pixel that isn’t the max value in its 2x2 block would have zero marginal effect on the loss, because changing that value slightly wouldn’t change the output at all! In other words, ∂L / ∂inputs = 0 for non-max pixels. On the other hand, an input pixel that is the max value would have its value passed through to the output, so ∂output / ∂input = 1, meaning ∂L / ∂input = ∂L / ∂output.
We can implement this pretty quickly using the helper method we wrote in my introduction to CNNs. I’ll include it again as a reminder:
For each pixel in each 2x2 image region in each filter, we copy the gradient from d_L_d_out to d_L_d_input if it was the max value during the forward pass.
That’s it! On to our final layer.
We’re finally here: backpropagating through a Conv layer is the core of training a CNN. The forward phase caching is simple:
Reminder about our implementation: for simplicity, we assume the input to our conv layer is a 2d array. This only works for us because we use it as the first layer in our network. If we were building a bigger network that needed to use Conv3x3 multiple times, we'd have to make the input be a 3d array.
We’re primarily interested in the loss gradient for the filters in our conv layer, since we need that to update our filter weights. We already have ∂L / ∂out for the conv layer, so we just need ∂out / ∂filters. To calculate that, we ask ourselves this: how would changing a filter’s weight affect the conv layer’s output?
The reality is that changing any filter weights would affect the entire output image for that filter, since every output pixel uses every pixel weight during convolution. To make this even easier to think about, let’s just think about one output pixel at a time: how would modifying a filter change the output of one specific output pixel?
Here’s a super simple example to help think about this question:
We have a 3x3 image convolved with a 3x3 filter of all zeros to produce a 1x1 output. What if we increased the center filter weight by 1? The output would increase by the center image value, 80:
Similarly, increasing any of the other filter weights by 1 would increase the output by the value of the corresponding image pixel! This suggests that the derivative of a specific output pixel with respect to a specific filter weight is just the corresponding image pixel value. Doing the math confirms this:
We can put it all together to find the loss gradient for specific filter weights:
We’re ready to implement backprop for our conv layer!
We apply our derived equation by iterating over every image region / filter and incrementally building the loss gradients. Once we’ve covered everything, we update self.filters using SGD just as before. Note the comment explaining why we're returning - the derivation for the loss gradient of the inputs is very similar to what we just did and is left as an exercise to the reader :).
With that, we’re done! We’ve implemented a full backward pass through our CNN. Time to test it out...
We’ll train our CNN for a few epochs, track its progress during training, and then test it on a separate test set. Here’s the full code:
Example output from running the code:
MNIST CNN initialized!--- Epoch 1 ---[Step 100] Past 100 steps: Average Loss 2.254 | Accuracy: 18%[Step 200] Past 100 steps: Average Loss 2.167 | Accuracy: 30%[Step 300] Past 100 steps: Average Loss 1.676 | Accuracy: 52%[Step 400] Past 100 steps: Average Loss 1.212 | Accuracy: 63%[Step 500] Past 100 steps: Average Loss 0.949 | Accuracy: 72%[Step 600] Past 100 steps: Average Loss 0.848 | Accuracy: 74%[Step 700] Past 100 steps: Average Loss 0.954 | Accuracy: 68%[Step 800] Past 100 steps: Average Loss 0.671 | Accuracy: 81%[Step 900] Past 100 steps: Average Loss 0.923 | Accuracy: 67%[Step 1000] Past 100 steps: Average Loss 0.571 | Accuracy: 83%--- Epoch 2 ---[Step 100] Past 100 steps: Average Loss 0.447 | Accuracy: 89%[Step 200] Past 100 steps: Average Loss 0.401 | Accuracy: 86%[Step 300] Past 100 steps: Average Loss 0.608 | Accuracy: 81%[Step 400] Past 100 steps: Average Loss 0.511 | Accuracy: 83%[Step 500] Past 100 steps: Average Loss 0.584 | Accuracy: 89%[Step 600] Past 100 steps: Average Loss 0.782 | Accuracy: 72%[Step 700] Past 100 steps: Average Loss 0.397 | Accuracy: 84%[Step 800] Past 100 steps: Average Loss 0.560 | Accuracy: 80%[Step 900] Past 100 steps: Average Loss 0.356 | Accuracy: 92%[Step 1000] Past 100 steps: Average Loss 0.576 | Accuracy: 85%--- Epoch 3 ---[Step 100] Past 100 steps: Average Loss 0.367 | Accuracy: 89%[Step 200] Past 100 steps: Average Loss 0.370 | Accuracy: 89%[Step 300] Past 100 steps: Average Loss 0.464 | Accuracy: 84%[Step 400] Past 100 steps: Average Loss 0.254 | Accuracy: 95%[Step 500] Past 100 steps: Average Loss 0.366 | Accuracy: 89%[Step 600] Past 100 steps: Average Loss 0.493 | Accuracy: 89%[Step 700] Past 100 steps: Average Loss 0.390 | Accuracy: 91%[Step 800] Past 100 steps: Average Loss 0.459 | Accuracy: 87%[Step 900] Past 100 steps: Average Loss 0.316 | Accuracy: 92%[Step 1000] Past 100 steps: Average Loss 0.460 | Accuracy: 87%--- Testing the CNN ---Test Loss: 0.5979384893783474Test Accuracy: 0.78
Our code works! In only 3000 training steps, we went from a model with 2.3 loss and 10% accuracy to 0.6 loss and 78% accuracy.
Want to try or tinker with this code yourself? Run this CNN in your browser. It’s also available on Github.
We only used a subset of the entire MNIST dataset for this example in the interest of time — our CNN implementation isn’t particularly fast. If we wanted to train a MNIST CNN for real, we’d use an ML library like Keras. To illustrate the power of our CNN, I used Keras to implement and train the exact same CNN we just built from scratch:
Running that code on the full MNIST dataset (60k training images) gives us results like this:
Epoch 1loss: 0.2433 - acc: 0.9276 - val_loss: 0.1176 - val_acc: 0.9634Epoch 2loss: 0.1184 - acc: 0.9648 - val_loss: 0.0936 - val_acc: 0.9721Epoch 3loss: 0.0930 - acc: 0.9721 - val_loss: 0.0778 - val_acc: 0.9744
We achieve 97.4% test accuracy with this simple CNN! With a better CNN architecture, we could improve that even more — in this official Keras MNIST CNN example, they achieve 99.25% test accuracy after 12 epochs. That’s a really good accuracy.
All code from this post is available on Github.
We’re done! In this post, we did a full walkthrough of how to train a Convolutional Neural Network. This is just the beginning, though. There’s a lot more you could do:
Experiment with bigger / better CNN using proper ML libraries like Tensorflow, Keras, or PyTorch.
Learn about using Batch Normalization with CNNs.
Understand how Data Augmentation can be used to improve image training sets.
Read about the ImageNet project and its famous Computer Vision contest, the ImageNet Large Scale Visual Recognition Challenge (ILSVRC).
Originally published at https://victorzhou.com.
|
[
{
"code": null,
"e": 448,
"s": 171,
"text": "In this post, we’re going to do a deep-dive on something most introductions to Convolutional Neural Networks (CNNs) lack: how to train a CNN, including deriving gradients, implementing backprop from scratch (using only numpy), and ultimately building a full training pipeline!"
},
{
"code": null,
"e": 660,
"s": 448,
"text": "This post assumes a basic knowledge of CNNs. My introduction to CNNs covers everything you need to know, so I’d highly recommend reading that first. If you’re here because you’ve already read that, welcome back!"
},
{
"code": null,
"e": 955,
"s": 660,
"text": "Parts of this post also assume a basic knowledge of multivariable calculus. You can skip those sections if you want, but I recommend reading them even if you don’t understand everything. We’ll incrementally write code as we derive results, and even a surface-level understanding can be helpful."
},
{
"code": null,
"e": 987,
"s": 955,
"text": "Buckle up! Time to get into it."
},
{
"code": null,
"e": 1128,
"s": 987,
"text": "We’ll pick back up where my introduction to CNNs left off. We were using a CNN to tackle the MNIST handwritten digit classification problem:"
},
{
"code": null,
"e": 1252,
"s": 1128,
"text": "Our (simple) CNN consisted of a Conv layer, a Max Pooling layer, and a Softmax layer. Here’s that diagram of our CNN again:"
},
{
"code": null,
"e": 1420,
"s": 1252,
"text": "We’d written 3 classes, one for each layer: Conv3x3, MaxPool, and Softmax. Each class implemented a forward() method that we used to build the forward pass of the CNN:"
},
{
"code": null,
"e": 1505,
"s": 1420,
"text": "You can view the code or run the CNN in your browser. It’s also available on Github."
},
{
"code": null,
"e": 1561,
"s": 1505,
"text": "Here’s what the output of our CNN looks like right now:"
},
{
"code": null,
"e": 1826,
"s": 1561,
"text": "MNIST CNN initialized![Step 100] Past 100 steps: Average Loss 2.302 | Accuracy: 11%[Step 200] Past 100 steps: Average Loss 2.302 | Accuracy: 8%[Step 300] Past 100 steps: Average Loss 2.302 | Accuracy: 3%[Step 400] Past 100 steps: Average Loss 2.302 | Accuracy: 12%"
},
{
"code": null,
"e": 1912,
"s": 1826,
"text": "Obviously, we’d like to do better than 10% accuracy... let’s teach this CNN a lesson."
},
{
"code": null,
"e": 1972,
"s": 1912,
"text": "Training a neural network typically consists of two phases:"
},
{
"code": null,
"e": 2135,
"s": 1972,
"text": "A forward phase, where the input is passed completely through the network.A backward phase, where gradients are backpropagated (backprop) and weights are updated."
},
{
"code": null,
"e": 2210,
"s": 2135,
"text": "A forward phase, where the input is passed completely through the network."
},
{
"code": null,
"e": 2299,
"s": 2210,
"text": "A backward phase, where gradients are backpropagated (backprop) and weights are updated."
},
{
"code": null,
"e": 2409,
"s": 2299,
"text": "We’ll follow this pattern to train our CNN. There are also two major implementation-specific ideas we’ll use:"
},
{
"code": null,
"e": 2627,
"s": 2409,
"text": "During the forward phase, each layer will cache any data (like inputs, intermediate values, etc) it’ll need for the backward phase. This means that any backward phase must be preceded by a corresponding forward phase."
},
{
"code": null,
"e": 2865,
"s": 2627,
"text": "During the backward phase, each layer will receive a gradient and also return a gradient. It will receive the gradient of loss with respect to its outputs (∂L / ∂out) and return the gradient of loss with respect to its inputs (∂L / ∂in)."
},
{
"code": null,
"e": 3060,
"s": 2865,
"text": "These two ideas will help keep our training implementation clean and organized. The best way to see why is probably by looking at code. Training our CNN will ultimately look something like this:"
},
{
"code": null,
"e": 3216,
"s": 3060,
"text": "See how nice and clean that looks? Now imagine building a network with 50 layers instead of 3 — it’s even more valuable then to have good systems in place."
},
{
"code": null,
"e": 3360,
"s": 3216,
"text": "We’ll start our way from the end and work our way towards the beginning, since that’s how backprop works. First, recall the cross-entropy loss:"
},
{
"code": null,
"e": 3484,
"s": 3360,
"text": "where p_c is the predicted probability for the correct class c (in other words, what digit our current image actually is)."
},
{
"code": null,
"e": 3575,
"s": 3484,
"text": "Want a longer explanation? Read the Cross-Entropy Loss section of my introduction to CNNs."
},
{
"code": null,
"e": 3827,
"s": 3575,
"text": "The first thing we need to calculate is the input to the Softmax layer’s backward phase, ∂L / ∂out_s, where out_s is the output from the Softmax layer: a vector of 10 probabilities. This is pretty easy, since only p_i shows up in the loss equation:"
},
{
"code": null,
"e": 3881,
"s": 3827,
"text": "That’s our initial gradient you saw referenced above:"
},
{
"code": null,
"e": 4018,
"s": 3881,
"text": "We’re almost ready to implement our first backward phase — we just need to first perform the forward phase caching we discussed earlier:"
},
{
"code": null,
"e": 4098,
"s": 4018,
"text": "We cache 3 things here that will be useful for implementing the backward phase:"
},
{
"code": null,
"e": 4138,
"s": 4098,
"text": "The input's shape before we flatten it."
},
{
"code": null,
"e": 4169,
"s": 4138,
"text": "The input after we flatten it."
},
{
"code": null,
"e": 4239,
"s": 4169,
"text": "The totals, which are the values passed in to the softmax activation."
},
{
"code": null,
"e": 4548,
"s": 4239,
"text": "With that out of the way, we can start deriving the gradients for the backprop phase. We’ve already derived the input to the Softmax backward phase: ∂L / ∂out_s. One fact we can use about ∂L / ∂out_s is that it’s only nonzero for c, the correct class. That means that we can ignore everything but out_s(c)!"
},
{
"code": null,
"e": 4739,
"s": 4548,
"text": "First, let’s calculate the gradient of out_s(c) with respect to the totals (the values passed in to the softmax activation). Let t_i be the total for class i. Then we can write out_s(c) as:"
},
{
"code": null,
"e": 4825,
"s": 4739,
"text": "You should recognize the equation above from the Softmax section of my CNNs tutorial."
},
{
"code": null,
"e": 4902,
"s": 4825,
"text": "Now, consider some class k such that k is not c. We can rewrite out_s(c) as:"
},
{
"code": null,
"e": 4932,
"s": 4902,
"text": "and use Chain Rule to derive:"
},
{
"code": null,
"e": 5045,
"s": 4932,
"text": "Remember, that was assuming k doesn’t equal c. Now let’s do the derivation for c, this time using Quotient Rule:"
},
{
"code": null,
"e": 5172,
"s": 5045,
"text": "Phew. That was the hardest bit of calculus in this entire post — it only gets easier from here! Let’s start implementing this:"
},
{
"code": null,
"e": 5426,
"s": 5172,
"text": "Remember how ∂L / ∂out_s is only nonzero for the correct class, c? We start by looking for c by looking for a nonzero gradient in d_L_d_out. Once we find that, we calculate the gradient ∂out_s(i) / ∂t (d_out_d_totals) using the results we derived above:"
},
{
"code": null,
"e": 5521,
"s": 5426,
"text": "Let’s keep going. We ultimately want the gradients of loss against weights, biases, and input:"
},
{
"code": null,
"e": 5594,
"s": 5521,
"text": "We’ll use the weights gradient, ∂L / ∂w , to update our layer’s weights."
},
{
"code": null,
"e": 5665,
"s": 5594,
"text": "We’ll use the biases gradient, ∂L / ∂b , to update our layer’s biases."
},
{
"code": null,
"e": 5847,
"s": 5665,
"text": "We’ll return the input gradient, ∂L / ∂input , from our backprop() method so the next layer can use it. This is the return gradient we talked about in the Training Overview section!"
},
{
"code": null,
"e": 6015,
"s": 5847,
"text": "To calculate those 3 loss gradients, we first need to derive 3 more results: the gradients of totals against weights, biases, and input. The relevant equation here is:"
},
{
"code": null,
"e": 6041,
"s": 6015,
"text": "These gradients are easy!"
},
{
"code": null,
"e": 6070,
"s": 6041,
"text": "Putting everything together:"
},
{
"code": null,
"e": 6127,
"s": 6070,
"text": "Putting this into code is a little less straightforward:"
},
{
"code": null,
"e": 6227,
"s": 6127,
"text": "First, we pre-calculate d_L_d_t since we'll use it several times. Then, we calculate each gradient:"
},
{
"code": null,
"e": 6572,
"s": 6227,
"text": "d_L_d_w: We need 2d arrays to do matrix multiplication (@), but d_t_d_w and d_L_d_t are 1d arrays. np.newaxis lets us easily create a new axis of length one, so we end up multiplying matrices with dimensions (input_len, 1) and (1, nodes). Thus, the final result for d_L_d_w will have shape (input_len, nodes), which is the same as self.weights!"
},
{
"code": null,
"e": 6630,
"s": 6572,
"text": "d_L_d_b: This one is straightforward, since d_t_d_b is 1."
},
{
"code": null,
"e": 6754,
"s": 6630,
"text": "d_L_d_inputs: We multiply matrices with dimensions (input_len, nodes) and (nodes, 1) to get a result with length input_len."
},
{
"code": null,
"e": 6966,
"s": 6754,
"text": "Try working through small examples of the calculations above, especially the matrix multiplications for d_L_d_w and d_L_d_inputs. That's the best way to understand why this code correctly computes the gradients."
},
{
"code": null,
"e": 7214,
"s": 6966,
"text": "With all the gradients computed, all that’s left is to actually train the Softmax layer! We’ll update the weights and bias using Stochastic Gradient Descent (SGD) just like we did in my introduction to Neural Networks and then return d_L_d_inputs:"
},
{
"code": null,
"e": 7417,
"s": 7214,
"text": "Notice that we added a learn_rate parameter that controls how fast we update our weights. Also, we have to reshape() before returning d_L_d_inputs because we flattened the input during our forward pass:"
},
{
"code": null,
"e": 7565,
"s": 7417,
"text": "Reshaping to last_input_shape ensures that this layer returns gradients for its input in the same format that the input was originally given to it."
},
{
"code": null,
"e": 7730,
"s": 7565,
"text": "We’ve finished our first backprop implementation! Let’s quickly test it to see if it’s any good. We’ll start implementing a train()method from my CNNs introduction:"
},
{
"code": null,
"e": 7769,
"s": 7730,
"text": "Running this gives results similar to:"
},
{
"code": null,
"e": 8403,
"s": 7769,
"text": "MNIST CNN initialized![Step 100] Past 100 steps: Average Loss 2.239 | Accuracy: 18%[Step 200] Past 100 steps: Average Loss 2.140 | Accuracy: 32%[Step 300] Past 100 steps: Average Loss 1.998 | Accuracy: 48%[Step 400] Past 100 steps: Average Loss 1.861 | Accuracy: 59%[Step 500] Past 100 steps: Average Loss 1.789 | Accuracy: 56%[Step 600] Past 100 steps: Average Loss 1.809 | Accuracy: 48%[Step 700] Past 100 steps: Average Loss 1.718 | Accuracy: 63%[Step 800] Past 100 steps: Average Loss 1.588 | Accuracy: 69%[Step 900] Past 100 steps: Average Loss 1.509 | Accuracy: 71%[Step 1000] Past 100 steps: Average Loss 1.481 | Accuracy: 70%"
},
{
"code": null,
"e": 8486,
"s": 8403,
"text": "The loss is going down and the accuracy is going up — our CNN is already learning!"
},
{
"code": null,
"e": 8736,
"s": 8486,
"text": "A Max Pooling layer can’t be trained because it doesn’t actually have any weights, but we still need to implement a method for it to calculate gradients. We’ll start by adding forward phase caching again. All we need to cache this time is the input:"
},
{
"code": null,
"e": 9084,
"s": 8736,
"text": "During the forward pass, the Max Pooling layer takes an input volume and halves its width and height dimensions by picking the max values over 2x2 blocks. The backward pass does the opposite: we’ll double the width and height of the loss gradient by assigning each gradient value to where the original max value was in its corresponding 2x2 block."
},
{
"code": null,
"e": 9156,
"s": 9084,
"text": "Here’s an example. Consider this forward phase for a Max Pooling layer:"
},
{
"code": null,
"e": 9216,
"s": 9156,
"text": "The backward phase of that same layer would look like this:"
},
{
"code": null,
"e": 9316,
"s": 9216,
"text": "Each gradient value is assigned to where the original max value was, and every other value is zero."
},
{
"code": null,
"e": 9832,
"s": 9316,
"text": "Why does the backward phase for a Max Pooling layer work like this? Think about what ∂L / ∂inputs intuitively should be. An input pixel that isn’t the max value in its 2x2 block would have zero marginal effect on the loss, because changing that value slightly wouldn’t change the output at all! In other words, ∂L / ∂inputs = 0 for non-max pixels. On the other hand, an input pixel that is the max value would have its value passed through to the output, so ∂output / ∂input = 1, meaning ∂L / ∂input = ∂L / ∂output."
},
{
"code": null,
"e": 9967,
"s": 9832,
"text": "We can implement this pretty quickly using the helper method we wrote in my introduction to CNNs. I’ll include it again as a reminder:"
},
{
"code": null,
"e": 10123,
"s": 9967,
"text": "For each pixel in each 2x2 image region in each filter, we copy the gradient from d_L_d_out to d_L_d_input if it was the max value during the forward pass."
},
{
"code": null,
"e": 10157,
"s": 10123,
"text": "That’s it! On to our final layer."
},
{
"code": null,
"e": 10282,
"s": 10157,
"text": "We’re finally here: backpropagating through a Conv layer is the core of training a CNN. The forward phase caching is simple:"
},
{
"code": null,
"e": 10585,
"s": 10282,
"text": "Reminder about our implementation: for simplicity, we assume the input to our conv layer is a 2d array. This only works for us because we use it as the first layer in our network. If we were building a bigger network that needed to use Conv3x3 multiple times, we'd have to make the input be a 3d array."
},
{
"code": null,
"e": 10909,
"s": 10585,
"text": "We’re primarily interested in the loss gradient for the filters in our conv layer, since we need that to update our filter weights. We already have ∂L / ∂out for the conv layer, so we just need ∂out / ∂filters. To calculate that, we ask ourselves this: how would changing a filter’s weight affect the conv layer’s output?"
},
{
"code": null,
"e": 11249,
"s": 10909,
"text": "The reality is that changing any filter weights would affect the entire output image for that filter, since every output pixel uses every pixel weight during convolution. To make this even easier to think about, let’s just think about one output pixel at a time: how would modifying a filter change the output of one specific output pixel?"
},
{
"code": null,
"e": 11314,
"s": 11249,
"text": "Here’s a super simple example to help think about this question:"
},
{
"code": null,
"e": 11509,
"s": 11314,
"text": "We have a 3x3 image convolved with a 3x3 filter of all zeros to produce a 1x1 output. What if we increased the center filter weight by 1? The output would increase by the center image value, 80:"
},
{
"code": null,
"e": 11818,
"s": 11509,
"text": "Similarly, increasing any of the other filter weights by 1 would increase the output by the value of the corresponding image pixel! This suggests that the derivative of a specific output pixel with respect to a specific filter weight is just the corresponding image pixel value. Doing the math confirms this:"
},
{
"code": null,
"e": 11900,
"s": 11818,
"text": "We can put it all together to find the loss gradient for specific filter weights:"
},
{
"code": null,
"e": 11954,
"s": 11900,
"text": "We’re ready to implement backprop for our conv layer!"
},
{
"code": null,
"e": 12339,
"s": 11954,
"text": "We apply our derived equation by iterating over every image region / filter and incrementally building the loss gradients. Once we’ve covered everything, we update self.filters using SGD just as before. Note the comment explaining why we're returning - the derivation for the loss gradient of the inputs is very similar to what we just did and is left as an exercise to the reader :)."
},
{
"code": null,
"e": 12441,
"s": 12339,
"text": "With that, we’re done! We’ve implemented a full backward pass through our CNN. Time to test it out..."
},
{
"code": null,
"e": 12578,
"s": 12441,
"text": "We’ll train our CNN for a few epochs, track its progress during training, and then test it on a separate test set. Here’s the full code:"
},
{
"code": null,
"e": 12616,
"s": 12578,
"text": "Example output from running the code:"
},
{
"code": null,
"e": 14588,
"s": 12616,
"text": "MNIST CNN initialized!--- Epoch 1 ---[Step 100] Past 100 steps: Average Loss 2.254 | Accuracy: 18%[Step 200] Past 100 steps: Average Loss 2.167 | Accuracy: 30%[Step 300] Past 100 steps: Average Loss 1.676 | Accuracy: 52%[Step 400] Past 100 steps: Average Loss 1.212 | Accuracy: 63%[Step 500] Past 100 steps: Average Loss 0.949 | Accuracy: 72%[Step 600] Past 100 steps: Average Loss 0.848 | Accuracy: 74%[Step 700] Past 100 steps: Average Loss 0.954 | Accuracy: 68%[Step 800] Past 100 steps: Average Loss 0.671 | Accuracy: 81%[Step 900] Past 100 steps: Average Loss 0.923 | Accuracy: 67%[Step 1000] Past 100 steps: Average Loss 0.571 | Accuracy: 83%--- Epoch 2 ---[Step 100] Past 100 steps: Average Loss 0.447 | Accuracy: 89%[Step 200] Past 100 steps: Average Loss 0.401 | Accuracy: 86%[Step 300] Past 100 steps: Average Loss 0.608 | Accuracy: 81%[Step 400] Past 100 steps: Average Loss 0.511 | Accuracy: 83%[Step 500] Past 100 steps: Average Loss 0.584 | Accuracy: 89%[Step 600] Past 100 steps: Average Loss 0.782 | Accuracy: 72%[Step 700] Past 100 steps: Average Loss 0.397 | Accuracy: 84%[Step 800] Past 100 steps: Average Loss 0.560 | Accuracy: 80%[Step 900] Past 100 steps: Average Loss 0.356 | Accuracy: 92%[Step 1000] Past 100 steps: Average Loss 0.576 | Accuracy: 85%--- Epoch 3 ---[Step 100] Past 100 steps: Average Loss 0.367 | Accuracy: 89%[Step 200] Past 100 steps: Average Loss 0.370 | Accuracy: 89%[Step 300] Past 100 steps: Average Loss 0.464 | Accuracy: 84%[Step 400] Past 100 steps: Average Loss 0.254 | Accuracy: 95%[Step 500] Past 100 steps: Average Loss 0.366 | Accuracy: 89%[Step 600] Past 100 steps: Average Loss 0.493 | Accuracy: 89%[Step 700] Past 100 steps: Average Loss 0.390 | Accuracy: 91%[Step 800] Past 100 steps: Average Loss 0.459 | Accuracy: 87%[Step 900] Past 100 steps: Average Loss 0.316 | Accuracy: 92%[Step 1000] Past 100 steps: Average Loss 0.460 | Accuracy: 87%--- Testing the CNN ---Test Loss: 0.5979384893783474Test Accuracy: 0.78"
},
{
"code": null,
"e": 14715,
"s": 14588,
"text": "Our code works! In only 3000 training steps, we went from a model with 2.3 loss and 10% accuracy to 0.6 loss and 78% accuracy."
},
{
"code": null,
"e": 14823,
"s": 14715,
"text": "Want to try or tinker with this code yourself? Run this CNN in your browser. It’s also available on Github."
},
{
"code": null,
"e": 15162,
"s": 14823,
"text": "We only used a subset of the entire MNIST dataset for this example in the interest of time — our CNN implementation isn’t particularly fast. If we wanted to train a MNIST CNN for real, we’d use an ML library like Keras. To illustrate the power of our CNN, I used Keras to implement and train the exact same CNN we just built from scratch:"
},
{
"code": null,
"e": 15256,
"s": 15162,
"text": "Running that code on the full MNIST dataset (60k training images) gives us results like this:"
},
{
"code": null,
"e": 15467,
"s": 15256,
"text": "Epoch 1loss: 0.2433 - acc: 0.9276 - val_loss: 0.1176 - val_acc: 0.9634Epoch 2loss: 0.1184 - acc: 0.9648 - val_loss: 0.0936 - val_acc: 0.9721Epoch 3loss: 0.0930 - acc: 0.9721 - val_loss: 0.0778 - val_acc: 0.9744"
},
{
"code": null,
"e": 15710,
"s": 15467,
"text": "We achieve 97.4% test accuracy with this simple CNN! With a better CNN architecture, we could improve that even more — in this official Keras MNIST CNN example, they achieve 99.25% test accuracy after 12 epochs. That’s a really good accuracy."
},
{
"code": null,
"e": 15758,
"s": 15710,
"text": "All code from this post is available on Github."
},
{
"code": null,
"e": 15927,
"s": 15758,
"text": "We’re done! In this post, we did a full walkthrough of how to train a Convolutional Neural Network. This is just the beginning, though. There’s a lot more you could do:"
},
{
"code": null,
"e": 16025,
"s": 15927,
"text": "Experiment with bigger / better CNN using proper ML libraries like Tensorflow, Keras, or PyTorch."
},
{
"code": null,
"e": 16074,
"s": 16025,
"text": "Learn about using Batch Normalization with CNNs."
},
{
"code": null,
"e": 16151,
"s": 16074,
"text": "Understand how Data Augmentation can be used to improve image training sets."
},
{
"code": null,
"e": 16287,
"s": 16151,
"text": "Read about the ImageNet project and its famous Computer Vision contest, the ImageNet Large Scale Visual Recognition Challenge (ILSVRC)."
}
] |
The Serious Downsides To The Julia Language In 1.0.3 | by Emmett Boudreau | Towards Data Science
|
I have talked a lot about how much I love Julia. If I was asked what my favorite programming language right now, “ Julia” would certainly be my reply. On the other hand, something I don’t talk about as much are the things I don’t like about Julia. Although today I would like to address some of these weaknesses and personal gripes I have with the language, I firmly believe that the benefits outweigh any compromises that might have to be made to use Julia. If you have never used Julia, I would highly encourage you to check it out! And with my recommendation, I’m also going to prelude my gripes with the reasons I love it so much.
Julia is very much a functional language, and loves being functional. With that, a great example is what I demonstrated in my looping speed test, Julia works really well with functional recursion.
Functional recursive loops are my personal favorite appearance-wise to utilize when doing statistical work. Typically in other languages however, like Python, we run into roadblocks in speed whenever recursion is used, and this is a big disadvantage in my opinion for statistical computing.
Okay, so Julia is a functional language for statistics...
Must be pretty low-level.
Julia really does break the rules, and every year it seems to inch closer and closer to being as versatile as Python.
Genie is a great example, as it is actually a framework for developing web-back-ends and pipelines inside of Julia, which is pretty high-level if I do say so myself.
Julia is fast, and I’m not just saying that. Julia’s typical run speeds are similar to that of C. This makes deployment quicker than a traditional Python-based web-app that needs to do calculations, especially if you’re deploying to an inactive server, like on Heroku for example. Julia is capable of processing and manipulating data that you can’t even read into Python. Julia’s speed and efficiency is really trifling when working with data-sets of twenty — thirty million, and still coming out with a calculation time below twenty seconds.
While I wouldn’t say Julia is necessarily a replacement for Scala, what I will say is that it certainly could have the potential to replace Scala. I find myself hardly ever needing to utilize Spark when I can use Julia, which is great because of my next advantage:
Now quick isn’t in reference to the speed we discussed, of course, but in reference to effort time. Typically in a powerful language like Julia, a significant downside is some pretty meaty syntax, and if the language is unique, as Julia is, this can be daunting and off-putting. Julia is easy to setup, and even has ways to be integrated into Spark as well as Python. If you’d like to learn more about Julia and Spark, check this out!
Though fairly critical and minor, the biggest one that I wanted to mention out of the gate is DataFrames.jl. Now don’t get me wrong, I like DataFrames to some degree... But particularly annoying is the way that DataFrames are displayed to the user, and I don’t really understand the reasons for doing such a thing this way. Of course, this could be a case of a performance issue I’m unaware of, but I’m definitely uncertain.
Firstly, to read in a CSV file, we don’t use DataFrames.jl like we would use Pandas in Python, or even use R’s internal tables. First, we have to
Pkg.add("CSV")
which will add an entire module for the single purpose of reading a CSV, more on this later.
Whenever we go to read in our CSV after adding CSV though, we are greated with a message at the top of our DataFrame:
“ omitted printing of 68 columns”
Of course, that’s no issue, but how do we show all of the columns? Well it’s nothing too complicated, just:
show(df,allcols=true)
But the issue that I have is what returns after that:
Oh my goodness! What year is this?
Maybe you could argue this isn’t too serious, but try sorting through hundreds and hundreds of features inside of this little iframe, rather than just running
df.head()
and then try to not complain about it. Compared to Pandas, and R DataFrames, Julia certainly takes last place for this! With that in mind, with some thought applied, I consider it quite possible that they fully intend for you to use Pandas with PyCall, but this is purely speculation.
Remember what I was talking about with using CSV.jl as apposed to being able to read a CSV with DataFrames.jl? (which you can, DataFrames.read_table, but it does some really funky stuff and throws a deprecation warning.) Well that whole scattering of functions and packages carries over into nearly everything in Julia.
If I wanted to use a decision tree, for example, I’d have to google up DecisionTree.jl and Pkg.add() it.
Pkg.add("DecisionTree")
Well that’s simple enough, so what’s the problem?
Every single model you want is contained inside of a different module, all with their own individual methods, parameters, constructors, syntax, and documentation. On the documentation spectrum, it can go from two example lines of code that don’t really explain anything all the way up to completely overwhelming one-page documentation (which is my favorite kind!)
My third and final gripe is with Julia’s package manager, Pkg. Pkg is great, I actually love it, and the fact that Pkg has its own REPL that you can enter from the Julia REPL with ] at anytime makes it that much sweeter.
However, these packages do have a fair bit of bugs, dependency issues, and random little quirks. Typically this is not too bad, but occasionally you’ll install a new module and end up rebuilding twenty different packages over and over again, and the process can get a bit annoying if you have to do it with a Genie web-app for example, not only committing the execution on your personal computer, but also doing the same on your server.
Although I will admit: these are fairly small gripes, and often don’t disturb the Julia ecosystem too much, I do feel like this is some information someone looking to try Julia out would like to know. Julia is great now, but with eyes into the future rather than the present, I could certainly see Julia taking off and becoming a core language among Data Scientists. A lot of people might not realize that Julia is still a baby, having just entered 1.0 last year. And with a language being so young, of course the packages are going to be scattered!
Since I have been working in Julia, Julia has already seen substantial package growth. I often find I think of something that I want to do, and there’s a package up on GitHub to do it exactly, which is awesome. The packages are expanding, and that truly is what makes a the language DS-viable for the future. For ML we have XGBoost.jl, Lathe.jl, MLBase, and Flux.jl:
Pkg.add("XGBoost")Pkg.add("Lathe")Pkg.add("Flux")Pkg.add("MLBase")
For stats we have StatsBase.jl, GLM.jl, Lathe.jl, and Distributions.jl:
Pkg.add("StatsBase")Pkg.add("GLM")Pkg.add("Lathe")Pkg.add("Distributions")
For Preprocessing we have MLDataUtils.jl, and Lathe.jl:
Pkg.add("MLDataUtils")Pkg.add("Lathe")
And with Julia’s superior package manager, development of said packages is surprisingly easy!
So I definitely encourage anybody who has an interest sparked(pun intended) in Julia to jump into it now, and help develop the language and the package base. I strongly believe that with its speed and use, we’ll see a rise in the use of Julia in corporate ecosystems around the globe. I’m very excited for the future of Julia, and It’ll probably always hold its place as my favorite language.
|
[
{
"code": null,
"e": 806,
"s": 171,
"text": "I have talked a lot about how much I love Julia. If I was asked what my favorite programming language right now, “ Julia” would certainly be my reply. On the other hand, something I don’t talk about as much are the things I don’t like about Julia. Although today I would like to address some of these weaknesses and personal gripes I have with the language, I firmly believe that the benefits outweigh any compromises that might have to be made to use Julia. If you have never used Julia, I would highly encourage you to check it out! And with my recommendation, I’m also going to prelude my gripes with the reasons I love it so much."
},
{
"code": null,
"e": 1003,
"s": 806,
"text": "Julia is very much a functional language, and loves being functional. With that, a great example is what I demonstrated in my looping speed test, Julia works really well with functional recursion."
},
{
"code": null,
"e": 1294,
"s": 1003,
"text": "Functional recursive loops are my personal favorite appearance-wise to utilize when doing statistical work. Typically in other languages however, like Python, we run into roadblocks in speed whenever recursion is used, and this is a big disadvantage in my opinion for statistical computing."
},
{
"code": null,
"e": 1352,
"s": 1294,
"text": "Okay, so Julia is a functional language for statistics..."
},
{
"code": null,
"e": 1378,
"s": 1352,
"text": "Must be pretty low-level."
},
{
"code": null,
"e": 1496,
"s": 1378,
"text": "Julia really does break the rules, and every year it seems to inch closer and closer to being as versatile as Python."
},
{
"code": null,
"e": 1662,
"s": 1496,
"text": "Genie is a great example, as it is actually a framework for developing web-back-ends and pipelines inside of Julia, which is pretty high-level if I do say so myself."
},
{
"code": null,
"e": 2205,
"s": 1662,
"text": "Julia is fast, and I’m not just saying that. Julia’s typical run speeds are similar to that of C. This makes deployment quicker than a traditional Python-based web-app that needs to do calculations, especially if you’re deploying to an inactive server, like on Heroku for example. Julia is capable of processing and manipulating data that you can’t even read into Python. Julia’s speed and efficiency is really trifling when working with data-sets of twenty — thirty million, and still coming out with a calculation time below twenty seconds."
},
{
"code": null,
"e": 2470,
"s": 2205,
"text": "While I wouldn’t say Julia is necessarily a replacement for Scala, what I will say is that it certainly could have the potential to replace Scala. I find myself hardly ever needing to utilize Spark when I can use Julia, which is great because of my next advantage:"
},
{
"code": null,
"e": 2905,
"s": 2470,
"text": "Now quick isn’t in reference to the speed we discussed, of course, but in reference to effort time. Typically in a powerful language like Julia, a significant downside is some pretty meaty syntax, and if the language is unique, as Julia is, this can be daunting and off-putting. Julia is easy to setup, and even has ways to be integrated into Spark as well as Python. If you’d like to learn more about Julia and Spark, check this out!"
},
{
"code": null,
"e": 3330,
"s": 2905,
"text": "Though fairly critical and minor, the biggest one that I wanted to mention out of the gate is DataFrames.jl. Now don’t get me wrong, I like DataFrames to some degree... But particularly annoying is the way that DataFrames are displayed to the user, and I don’t really understand the reasons for doing such a thing this way. Of course, this could be a case of a performance issue I’m unaware of, but I’m definitely uncertain."
},
{
"code": null,
"e": 3476,
"s": 3330,
"text": "Firstly, to read in a CSV file, we don’t use DataFrames.jl like we would use Pandas in Python, or even use R’s internal tables. First, we have to"
},
{
"code": null,
"e": 3491,
"s": 3476,
"text": "Pkg.add(\"CSV\")"
},
{
"code": null,
"e": 3584,
"s": 3491,
"text": "which will add an entire module for the single purpose of reading a CSV, more on this later."
},
{
"code": null,
"e": 3702,
"s": 3584,
"text": "Whenever we go to read in our CSV after adding CSV though, we are greated with a message at the top of our DataFrame:"
},
{
"code": null,
"e": 3736,
"s": 3702,
"text": "“ omitted printing of 68 columns”"
},
{
"code": null,
"e": 3844,
"s": 3736,
"text": "Of course, that’s no issue, but how do we show all of the columns? Well it’s nothing too complicated, just:"
},
{
"code": null,
"e": 3866,
"s": 3844,
"text": "show(df,allcols=true)"
},
{
"code": null,
"e": 3920,
"s": 3866,
"text": "But the issue that I have is what returns after that:"
},
{
"code": null,
"e": 3955,
"s": 3920,
"text": "Oh my goodness! What year is this?"
},
{
"code": null,
"e": 4114,
"s": 3955,
"text": "Maybe you could argue this isn’t too serious, but try sorting through hundreds and hundreds of features inside of this little iframe, rather than just running"
},
{
"code": null,
"e": 4124,
"s": 4114,
"text": "df.head()"
},
{
"code": null,
"e": 4409,
"s": 4124,
"text": "and then try to not complain about it. Compared to Pandas, and R DataFrames, Julia certainly takes last place for this! With that in mind, with some thought applied, I consider it quite possible that they fully intend for you to use Pandas with PyCall, but this is purely speculation."
},
{
"code": null,
"e": 4729,
"s": 4409,
"text": "Remember what I was talking about with using CSV.jl as apposed to being able to read a CSV with DataFrames.jl? (which you can, DataFrames.read_table, but it does some really funky stuff and throws a deprecation warning.) Well that whole scattering of functions and packages carries over into nearly everything in Julia."
},
{
"code": null,
"e": 4834,
"s": 4729,
"text": "If I wanted to use a decision tree, for example, I’d have to google up DecisionTree.jl and Pkg.add() it."
},
{
"code": null,
"e": 4858,
"s": 4834,
"text": "Pkg.add(\"DecisionTree\")"
},
{
"code": null,
"e": 4908,
"s": 4858,
"text": "Well that’s simple enough, so what’s the problem?"
},
{
"code": null,
"e": 5272,
"s": 4908,
"text": "Every single model you want is contained inside of a different module, all with their own individual methods, parameters, constructors, syntax, and documentation. On the documentation spectrum, it can go from two example lines of code that don’t really explain anything all the way up to completely overwhelming one-page documentation (which is my favorite kind!)"
},
{
"code": null,
"e": 5493,
"s": 5272,
"text": "My third and final gripe is with Julia’s package manager, Pkg. Pkg is great, I actually love it, and the fact that Pkg has its own REPL that you can enter from the Julia REPL with ] at anytime makes it that much sweeter."
},
{
"code": null,
"e": 5930,
"s": 5493,
"text": "However, these packages do have a fair bit of bugs, dependency issues, and random little quirks. Typically this is not too bad, but occasionally you’ll install a new module and end up rebuilding twenty different packages over and over again, and the process can get a bit annoying if you have to do it with a Genie web-app for example, not only committing the execution on your personal computer, but also doing the same on your server."
},
{
"code": null,
"e": 6480,
"s": 5930,
"text": "Although I will admit: these are fairly small gripes, and often don’t disturb the Julia ecosystem too much, I do feel like this is some information someone looking to try Julia out would like to know. Julia is great now, but with eyes into the future rather than the present, I could certainly see Julia taking off and becoming a core language among Data Scientists. A lot of people might not realize that Julia is still a baby, having just entered 1.0 last year. And with a language being so young, of course the packages are going to be scattered!"
},
{
"code": null,
"e": 6847,
"s": 6480,
"text": "Since I have been working in Julia, Julia has already seen substantial package growth. I often find I think of something that I want to do, and there’s a package up on GitHub to do it exactly, which is awesome. The packages are expanding, and that truly is what makes a the language DS-viable for the future. For ML we have XGBoost.jl, Lathe.jl, MLBase, and Flux.jl:"
},
{
"code": null,
"e": 6914,
"s": 6847,
"text": "Pkg.add(\"XGBoost\")Pkg.add(\"Lathe\")Pkg.add(\"Flux\")Pkg.add(\"MLBase\")"
},
{
"code": null,
"e": 6986,
"s": 6914,
"text": "For stats we have StatsBase.jl, GLM.jl, Lathe.jl, and Distributions.jl:"
},
{
"code": null,
"e": 7061,
"s": 6986,
"text": "Pkg.add(\"StatsBase\")Pkg.add(\"GLM\")Pkg.add(\"Lathe\")Pkg.add(\"Distributions\")"
},
{
"code": null,
"e": 7117,
"s": 7061,
"text": "For Preprocessing we have MLDataUtils.jl, and Lathe.jl:"
},
{
"code": null,
"e": 7156,
"s": 7117,
"text": "Pkg.add(\"MLDataUtils\")Pkg.add(\"Lathe\")"
},
{
"code": null,
"e": 7250,
"s": 7156,
"text": "And with Julia’s superior package manager, development of said packages is surprisingly easy!"
}
] |
Convert text to lowercase with CSS
|
To convert text to lowercase with CSS, use the text-transform property with value lowercase.
You can try to run the following code to convert text to lowercase:
<html>
<head>
</head>
<body>
<p>Normal Text</p>
<p style = "text-transform:lowercase;">
Normal Text! This will be in lowercase!
</p>
</body>
</html>
|
[
{
"code": null,
"e": 1155,
"s": 1062,
"text": "To convert text to lowercase with CSS, use the text-transform property with value lowercase."
},
{
"code": null,
"e": 1223,
"s": 1155,
"text": "You can try to run the following code to convert text to lowercase:"
},
{
"code": null,
"e": 1411,
"s": 1223,
"text": "<html>\n <head>\n </head>\n <body>\n <p>Normal Text</p>\n <p style = \"text-transform:lowercase;\">\n Normal Text! This will be in lowercase!\n </p>\n </body>\n</html>"
}
] |
Cross Validation Explained: Evaluating estimator performance. | by Rahil Shaikh | Towards Data Science
|
The ultimate goal of a Machine Learning Engineer or a Data Scientist is to develop a Model in order to get Predictions on New Data or Forecast some events for future on Unseen data. A Good Model is not the one that gives accurate predictions on the known data or training data but the one which gives good predictions on the new data and avoids overfitting and underfitting.
After completing this tutorial, you will know:
That why to use cross validation is a procedure used to estimate the skill of the model on new data.
There are common tactics that you can use to select the value of k for your dataset.
There are commonly used variations on cross-validation such as stratified and LOOCV that are available in scikit-learn.
Practical Implementation of k-Fold Cross Validation in Python
To derive a solution we should first understand the problem. Before we proceed to Understanding Cross Validation let us first understand Overfitting and Underfitting
Overfit Model: Overfitting occurs when a statistical model or machine learning algorithm captures the noise of the data. Intuitively, overfitting occurs when the model or the algorithm fits the data too well.
Overfitting a model result in good accuracy for training data set but poor results on new data sets. Such a model is not of any use in the real world as it is not able to predict outcomes for new cases.
Underfit Model: Underfitting occurs when a statistical model or machine learning algorithm cannot capture the underlying trend of the data. Intuitively, underfitting occurs when the model or the algorithm does not fit the data well enough. Underfitting is often a result of an excessively simple model. By simple we mean that the missing data is not handled properly, no outlier treatment, removing of irrelevant features or features which do not contribute much to the predictor variable.
The answer is Cross Validation
A key challenge with overfitting, and with machine learning in general, is that we can’t know how well our model will perform on new data until we actually test it.
To address this, we can split our initial dataset into separate training and test subsets.
There are different types of Cross Validation Techniques but the overall concept remains the same,
• To partition the data into a number of subsets
• Hold out a set at a time and train the model on remaining set
• Test model on hold out set
Repeat the process for each subset of the dataset
•K-Fold Cross Validation
•Stratified K-fold Cross Validation
•Leave One Out Cross Validation
The procedure has a single parameter called k that refers to the number of groups that a given data sample is to be split into. As such, the procedure is often called k-fold cross-validation. When a specific value for k is chosen, it may be used in place of k in the reference to the model, such as k=10 becoming 10-fold cross-validation.
If k=5 the dataset will be divided into 5 equal parts and the below process will run 5 times, each time with a different holdout set.
1. Take the group as a holdout or test data set
2. Take the remaining groups as a training data set
3. Fit a model on the training set and evaluate it on the test set
4. Retain the evaluation score and discard the model
At the end of the above process Summarize the skill of the model using the sample of model evaluation scores.
How to decide the value of k?
The value for k is chosen such that each train/test group of data samples is large enough to be statistically representative of the broader dataset.
A value of k=10 is very common in the field of applied machine learning, and is recommend if you are struggling to choose a value for your dataset.
If a value for k is chosen that does not evenly split the data sample, then one group will contain a remainder of the examples. It is preferable to split the data sample into k groups with the same number of samples, such that the sample of model skill scores are all equivalent.
Same as K-Fold Cross Validation, just a slight difference
The splitting of data into folds may be governed by criteria such as ensuring that each fold has the same proportion of observations with a given categorical value, such as the class outcome value. This is called stratified cross-validation.
In below image, the stratified k-fold validation is set on basis of Gender whether M or F
This approach leaves 1 data point out of training data, i.e. if there are n data points in the original sample then, n-1 samples are used to train the model and p points are used as the validation set. This is repeated for all combinations in which the original sample can be separated this way, and then the error is averaged for all trials, to give overall effectiveness.
The number of possible combinations is equal to the number of data points in the original sample or n.
Cross Validation is a very useful technique for assessing the effectiveness of your model, particularly in cases where you need to mitigate over-fitting.
We do not need to call the fit method separately while using cross validation, the cross_val_score method fits the data itself while implementing the cross-validation on data. Below is the example for using k-fold cross validation.
import pandas as pdimport numpy as npfrom sklearn.metrics import accuracy_score, confusion_matrixfrom sklearn.ensemble import RandomForestClassifierfrom sklearn import svmfrom sklearn.model_selection import cross_val_score#read csv filedata = pd.read_csv("D://RAhil//Kaggle//Data//Iris.csv")#Create Dependent and Independent Datasets based on our Dependent #and Independent featuresX = data[['SepalLengthCm','SepalWidthCm','PetalLengthCm']]y= data['Species']model = svm.SVC()accuracy = cross_val_score(model, X, y, scoring='accuracy', cv = 10)print(accuracy)#get the mean of each fold print("Accuracy of Model with Cross Validation is:",accuracy.mean() * 100)
Output:
The Accuracy of the model is the average of the accuracy of each fold.
In this tutorial, you discovered why do we need to use Cross Validation, gentle introduction to different types of cross validation techniques and practical example of k-fold cross validation procedure for estimating the skill of machine learning models.
Specifically, you learned:
That cross validation is a procedure used to avoid overfitting and estimate the skill of the model on new data.
There are common tactics that you can use to select the value of k for your dataset.
There are commonly used variations on cross-validation, such as stratified and repeated, that are available in scikit-learn.
If you liked this blog give it some CLAPS and SHARE it with your friends, you can find more interesting articles here, stay tuned for more interesting techniques and concepts of Machine Learning.
|
[
{
"code": null,
"e": 547,
"s": 172,
"text": "The ultimate goal of a Machine Learning Engineer or a Data Scientist is to develop a Model in order to get Predictions on New Data or Forecast some events for future on Unseen data. A Good Model is not the one that gives accurate predictions on the known data or training data but the one which gives good predictions on the new data and avoids overfitting and underfitting."
},
{
"code": null,
"e": 594,
"s": 547,
"text": "After completing this tutorial, you will know:"
},
{
"code": null,
"e": 695,
"s": 594,
"text": "That why to use cross validation is a procedure used to estimate the skill of the model on new data."
},
{
"code": null,
"e": 780,
"s": 695,
"text": "There are common tactics that you can use to select the value of k for your dataset."
},
{
"code": null,
"e": 900,
"s": 780,
"text": "There are commonly used variations on cross-validation such as stratified and LOOCV that are available in scikit-learn."
},
{
"code": null,
"e": 962,
"s": 900,
"text": "Practical Implementation of k-Fold Cross Validation in Python"
},
{
"code": null,
"e": 1128,
"s": 962,
"text": "To derive a solution we should first understand the problem. Before we proceed to Understanding Cross Validation let us first understand Overfitting and Underfitting"
},
{
"code": null,
"e": 1337,
"s": 1128,
"text": "Overfit Model: Overfitting occurs when a statistical model or machine learning algorithm captures the noise of the data. Intuitively, overfitting occurs when the model or the algorithm fits the data too well."
},
{
"code": null,
"e": 1540,
"s": 1337,
"text": "Overfitting a model result in good accuracy for training data set but poor results on new data sets. Such a model is not of any use in the real world as it is not able to predict outcomes for new cases."
},
{
"code": null,
"e": 2030,
"s": 1540,
"text": "Underfit Model: Underfitting occurs when a statistical model or machine learning algorithm cannot capture the underlying trend of the data. Intuitively, underfitting occurs when the model or the algorithm does not fit the data well enough. Underfitting is often a result of an excessively simple model. By simple we mean that the missing data is not handled properly, no outlier treatment, removing of irrelevant features or features which do not contribute much to the predictor variable."
},
{
"code": null,
"e": 2061,
"s": 2030,
"text": "The answer is Cross Validation"
},
{
"code": null,
"e": 2226,
"s": 2061,
"text": "A key challenge with overfitting, and with machine learning in general, is that we can’t know how well our model will perform on new data until we actually test it."
},
{
"code": null,
"e": 2317,
"s": 2226,
"text": "To address this, we can split our initial dataset into separate training and test subsets."
},
{
"code": null,
"e": 2416,
"s": 2317,
"text": "There are different types of Cross Validation Techniques but the overall concept remains the same,"
},
{
"code": null,
"e": 2465,
"s": 2416,
"text": "• To partition the data into a number of subsets"
},
{
"code": null,
"e": 2529,
"s": 2465,
"text": "• Hold out a set at a time and train the model on remaining set"
},
{
"code": null,
"e": 2558,
"s": 2529,
"text": "• Test model on hold out set"
},
{
"code": null,
"e": 2608,
"s": 2558,
"text": "Repeat the process for each subset of the dataset"
},
{
"code": null,
"e": 2633,
"s": 2608,
"text": "•K-Fold Cross Validation"
},
{
"code": null,
"e": 2669,
"s": 2633,
"text": "•Stratified K-fold Cross Validation"
},
{
"code": null,
"e": 2701,
"s": 2669,
"text": "•Leave One Out Cross Validation"
},
{
"code": null,
"e": 3040,
"s": 2701,
"text": "The procedure has a single parameter called k that refers to the number of groups that a given data sample is to be split into. As such, the procedure is often called k-fold cross-validation. When a specific value for k is chosen, it may be used in place of k in the reference to the model, such as k=10 becoming 10-fold cross-validation."
},
{
"code": null,
"e": 3174,
"s": 3040,
"text": "If k=5 the dataset will be divided into 5 equal parts and the below process will run 5 times, each time with a different holdout set."
},
{
"code": null,
"e": 3222,
"s": 3174,
"text": "1. Take the group as a holdout or test data set"
},
{
"code": null,
"e": 3274,
"s": 3222,
"text": "2. Take the remaining groups as a training data set"
},
{
"code": null,
"e": 3341,
"s": 3274,
"text": "3. Fit a model on the training set and evaluate it on the test set"
},
{
"code": null,
"e": 3394,
"s": 3341,
"text": "4. Retain the evaluation score and discard the model"
},
{
"code": null,
"e": 3504,
"s": 3394,
"text": "At the end of the above process Summarize the skill of the model using the sample of model evaluation scores."
},
{
"code": null,
"e": 3534,
"s": 3504,
"text": "How to decide the value of k?"
},
{
"code": null,
"e": 3683,
"s": 3534,
"text": "The value for k is chosen such that each train/test group of data samples is large enough to be statistically representative of the broader dataset."
},
{
"code": null,
"e": 3831,
"s": 3683,
"text": "A value of k=10 is very common in the field of applied machine learning, and is recommend if you are struggling to choose a value for your dataset."
},
{
"code": null,
"e": 4111,
"s": 3831,
"text": "If a value for k is chosen that does not evenly split the data sample, then one group will contain a remainder of the examples. It is preferable to split the data sample into k groups with the same number of samples, such that the sample of model skill scores are all equivalent."
},
{
"code": null,
"e": 4169,
"s": 4111,
"text": "Same as K-Fold Cross Validation, just a slight difference"
},
{
"code": null,
"e": 4411,
"s": 4169,
"text": "The splitting of data into folds may be governed by criteria such as ensuring that each fold has the same proportion of observations with a given categorical value, such as the class outcome value. This is called stratified cross-validation."
},
{
"code": null,
"e": 4501,
"s": 4411,
"text": "In below image, the stratified k-fold validation is set on basis of Gender whether M or F"
},
{
"code": null,
"e": 4875,
"s": 4501,
"text": "This approach leaves 1 data point out of training data, i.e. if there are n data points in the original sample then, n-1 samples are used to train the model and p points are used as the validation set. This is repeated for all combinations in which the original sample can be separated this way, and then the error is averaged for all trials, to give overall effectiveness."
},
{
"code": null,
"e": 4978,
"s": 4875,
"text": "The number of possible combinations is equal to the number of data points in the original sample or n."
},
{
"code": null,
"e": 5132,
"s": 4978,
"text": "Cross Validation is a very useful technique for assessing the effectiveness of your model, particularly in cases where you need to mitigate over-fitting."
},
{
"code": null,
"e": 5364,
"s": 5132,
"text": "We do not need to call the fit method separately while using cross validation, the cross_val_score method fits the data itself while implementing the cross-validation on data. Below is the example for using k-fold cross validation."
},
{
"code": null,
"e": 6027,
"s": 5364,
"text": "import pandas as pdimport numpy as npfrom sklearn.metrics import accuracy_score, confusion_matrixfrom sklearn.ensemble import RandomForestClassifierfrom sklearn import svmfrom sklearn.model_selection import cross_val_score#read csv filedata = pd.read_csv(\"D://RAhil//Kaggle//Data//Iris.csv\")#Create Dependent and Independent Datasets based on our Dependent #and Independent featuresX = data[['SepalLengthCm','SepalWidthCm','PetalLengthCm']]y= data['Species']model = svm.SVC()accuracy = cross_val_score(model, X, y, scoring='accuracy', cv = 10)print(accuracy)#get the mean of each fold print(\"Accuracy of Model with Cross Validation is:\",accuracy.mean() * 100)"
},
{
"code": null,
"e": 6035,
"s": 6027,
"text": "Output:"
},
{
"code": null,
"e": 6106,
"s": 6035,
"text": "The Accuracy of the model is the average of the accuracy of each fold."
},
{
"code": null,
"e": 6361,
"s": 6106,
"text": "In this tutorial, you discovered why do we need to use Cross Validation, gentle introduction to different types of cross validation techniques and practical example of k-fold cross validation procedure for estimating the skill of machine learning models."
},
{
"code": null,
"e": 6388,
"s": 6361,
"text": "Specifically, you learned:"
},
{
"code": null,
"e": 6500,
"s": 6388,
"text": "That cross validation is a procedure used to avoid overfitting and estimate the skill of the model on new data."
},
{
"code": null,
"e": 6585,
"s": 6500,
"text": "There are common tactics that you can use to select the value of k for your dataset."
},
{
"code": null,
"e": 6710,
"s": 6585,
"text": "There are commonly used variations on cross-validation, such as stratified and repeated, that are available in scikit-learn."
}
] |
Tryit Editor v3.7
|
Tryit: Use a PNG image as the mask layer
|
[] |
Why do we use const qualifier in C++?
|
We use the const qualifier to declare a variable as constant. That means that we cannot change the value once the variable has been initialized. Using const has a very big benefit. For example, if you have a constant value of the value of PI, you wouldn't like any part of the program to modify that value. So you should declare that as a const.
Objects declared with const-qualified types may be placed in read-only memory by the compiler, and if the address of a const object is never taken in a program, it may not be stored at all. For example,
#include<iostream>
using namespace std;
int main() {
const int x = 10;
x = 12;
return 0;
}
This program would produce an error as we have tried to reassign a const value.
|
[
{
"code": null,
"e": 1408,
"s": 1062,
"text": "We use the const qualifier to declare a variable as constant. That means that we cannot change the value once the variable has been initialized. Using const has a very big benefit. For example, if you have a constant value of the value of PI, you wouldn't like any part of the program to modify that value. So you should declare that as a const."
},
{
"code": null,
"e": 1612,
"s": 1408,
"text": "Objects declared with const-qualified types may be placed in read-only memory by the compiler, and if the address of a const object is never taken in a program, it may not be stored at all. For example,"
},
{
"code": null,
"e": 1712,
"s": 1612,
"text": "#include<iostream>\nusing namespace std;\nint main() {\n const int x = 10;\n x = 12;\n return 0;\n}"
},
{
"code": null,
"e": 1792,
"s": 1712,
"text": "This program would produce an error as we have tried to reassign a const value."
}
] |
Interactive Problems in Competitive Programming - GeeksforGeeks
|
13 Jan, 2022
Interactive Problems are those problems in which our solution or code interacts with the judge in real time. When we develop a solution for an Interactive Problem then the input data given to our solution may not be predetermined but is built for that problem specifically. The solution performs a series of exchange of data with the judge and at the end of the conversation the judge decides whether our solution was correct or not.
In this problem the user has to guess the number during a communication with the judge. The user is provided with the upper and lower bound and he/she can ask the judge whether a number is the number to be guessed. The judge replies with -1 if the number is smaller than the number to be guessed or 1 if number is greater than the number to be guessed or 0 if it is equal to the number to be guessed.
The user can query the judge for all the numbers between lower limit and upper limit to find the solution.
C++
Java
Python3
C#
#include <bits/stdc++.h>using namespace std; int main(){ int lower_bound = 2; int upper_bound = 10; // Number to be guessed is 6 // Iterating from lower_bound to upper_bound for (int i = lower_bound; i <= upper_bound; i++) { cout << i << endl; // Input the response from the judge int response; cin >> response; if (response == 0) { cout << "Number guessed is :" << i; break; } } return 0;} // This code is contributed by divyeshrabadiya07
import java.util.*;class GFG { public static void main(String[] args) { Scanner sc1 = new Scanner(System.in); int lower_bound = 2; int upper_bound = 10; // Number to be guessed is 6 // Iterating from lower_bound to upper_bound for (int i = lower_bound; i <= upper_bound; i++) { System.out.println(i); // Input the response from the judge int response = sc1.nextInt(); if (response == 0) { System.out.println("Number guessed is :" + i); break; } } }}
if __name__=='__main__': lower_bound = 2; upper_bound = 10; # Number to be guessed is 6 # Iterating from lower_bound to upper_bound for i in range(lower_bound, upper_bound + 1): print(i) # Input the response from the judge response = int(input()) if (response == 0): print("Number guessed is :", i, end = '') break; # This code is contributed by rutvik_56
using System;class GFG{ public static void Main(string[] args) { int lower_bound = 2; int upper_bound = 10; // Number to be guessed is 6 // Iterating from lower_bound to upper_bound for (int i = lower_bound; i <= upper_bound; i++) { Console.WriteLine(i); // Input the response from the judge int response = int.Parse(Console.ReadLine()); if (response == 0) { Console.WriteLine("Number guessed is :" + i); break; } } }} // This code is contributed by Pratham76
2
Number guessed is :2
Time Complexity: O(n)
We can also apply binary search interactively to find the solution. This solution is efficient as compared to the previous approach.
Java
C#
Python3
import java.util.*;class GFG { public static void main(String[] args) { Scanner sc1 = new Scanner(System.in); int lower_bound = 2; int upper_bound = 10; // Number to be guessed is 9 // Applying Binary Search interactively while (lower_bound <= upper_bound) { int mid = (lower_bound + upper_bound) / 2; // Print the guessed number System.out.println(mid); // Input the response from the judge int response = sc1.nextInt(); if (response == -1) { lower_bound = mid + 1; } else if (response == 1) { upper_bound = mid - 1; } else if (response == 0) { System.out.println("Number guessed is :" + mid); break; } } }}
using System;class GFG { static void Main() { int lower_bound = 2; int upper_bound = 10; // Number to be guessed is 9 // Applying Binary Search interactively while (lower_bound <= upper_bound) { int mid = (lower_bound + upper_bound) / 2; // Print the guessed number Console.WriteLine(mid); // Input the response from the judge int response = Convert.ToInt32(Console.ReadLine()); if (response == -1) { lower_bound = mid + 1; } else if (response == 1) { upper_bound = mid - 1; } else if (response == 0) { Console.WriteLine("Number guessed is :" + mid); break; } } }} // This code is contributed by divyesh072019
lower_bound = 2upper_bound = 10 # Number to be guessed is 9 # Applying Binary Search interactivelywhile (lower_bound <= upper_bound) : mid = (lower_bound + upper_bound) // 2 # Print guessed number print(mid) # Input the response from the judge response = int(input()) if (response == -1) : lower_bound = mid + 1 elif (response == 1) : upper_bound = mid - 1 elif (response == 0) : print("Number guessed is :", mid) break
6
Number guessed is :6
Time Complexity: O(logn) Algorithm Paradigm: Divide and Conquer
divyeshrabadiya07
divyesh072019
pratham76
rutvik_56
amartyaghoshgfg
khushboogoyal499
Searching Quiz
Algorithms
Competitive Programming
Divide and Conquer
Divide and Conquer
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
How to write a Pseudo Code?
Difference between Informed and Uninformed Search in AI
Arrow operator -> in C/C++ with Examples
Modulo 10^9+7 (1000000007)
Competitive Programming - A Complete Guide
Prefix Sum Array - Implementation and Applications in Competitive Programming
Fast I/O for Competitive Programming
|
[
{
"code": null,
"e": 24761,
"s": 24733,
"text": "\n13 Jan, 2022"
},
{
"code": null,
"e": 25196,
"s": 24761,
"text": "Interactive Problems are those problems in which our solution or code interacts with the judge in real time. When we develop a solution for an Interactive Problem then the input data given to our solution may not be predetermined but is built for that problem specifically. The solution performs a series of exchange of data with the judge and at the end of the conversation the judge decides whether our solution was correct or not. "
},
{
"code": null,
"e": 25598,
"s": 25196,
"text": "In this problem the user has to guess the number during a communication with the judge. The user is provided with the upper and lower bound and he/she can ask the judge whether a number is the number to be guessed. The judge replies with -1 if the number is smaller than the number to be guessed or 1 if number is greater than the number to be guessed or 0 if it is equal to the number to be guessed. "
},
{
"code": null,
"e": 25707,
"s": 25598,
"text": "The user can query the judge for all the numbers between lower limit and upper limit to find the solution. "
},
{
"code": null,
"e": 25713,
"s": 25709,
"text": "C++"
},
{
"code": null,
"e": 25718,
"s": 25713,
"text": "Java"
},
{
"code": null,
"e": 25726,
"s": 25718,
"text": "Python3"
},
{
"code": null,
"e": 25729,
"s": 25726,
"text": "C#"
},
{
"code": "#include <bits/stdc++.h>using namespace std; int main(){ int lower_bound = 2; int upper_bound = 10; // Number to be guessed is 6 // Iterating from lower_bound to upper_bound for (int i = lower_bound; i <= upper_bound; i++) { cout << i << endl; // Input the response from the judge int response; cin >> response; if (response == 0) { cout << \"Number guessed is :\" << i; break; } } return 0;} // This code is contributed by divyeshrabadiya07",
"e": 26259,
"s": 25729,
"text": null
},
{
"code": "import java.util.*;class GFG { public static void main(String[] args) { Scanner sc1 = new Scanner(System.in); int lower_bound = 2; int upper_bound = 10; // Number to be guessed is 6 // Iterating from lower_bound to upper_bound for (int i = lower_bound; i <= upper_bound; i++) { System.out.println(i); // Input the response from the judge int response = sc1.nextInt(); if (response == 0) { System.out.println(\"Number guessed is :\" + i); break; } } }}",
"e": 26856,
"s": 26259,
"text": null
},
{
"code": "if __name__=='__main__': lower_bound = 2; upper_bound = 10; # Number to be guessed is 6 # Iterating from lower_bound to upper_bound for i in range(lower_bound, upper_bound + 1): print(i) # Input the response from the judge response = int(input()) if (response == 0): print(\"Number guessed is :\", i, end = '') break; # This code is contributed by rutvik_56",
"e": 27293,
"s": 26856,
"text": null
},
{
"code": "using System;class GFG{ public static void Main(string[] args) { int lower_bound = 2; int upper_bound = 10; // Number to be guessed is 6 // Iterating from lower_bound to upper_bound for (int i = lower_bound; i <= upper_bound; i++) { Console.WriteLine(i); // Input the response from the judge int response = int.Parse(Console.ReadLine()); if (response == 0) { Console.WriteLine(\"Number guessed is :\" + i); break; } } }} // This code is contributed by Pratham76",
"e": 27910,
"s": 27293,
"text": null
},
{
"code": null,
"e": 27933,
"s": 27910,
"text": "2\nNumber guessed is :2"
},
{
"code": null,
"e": 27956,
"s": 27933,
"text": "Time Complexity: O(n) "
},
{
"code": null,
"e": 28090,
"s": 27956,
"text": "We can also apply binary search interactively to find the solution. This solution is efficient as compared to the previous approach. "
},
{
"code": null,
"e": 28097,
"s": 28092,
"text": "Java"
},
{
"code": null,
"e": 28100,
"s": 28097,
"text": "C#"
},
{
"code": null,
"e": 28108,
"s": 28100,
"text": "Python3"
},
{
"code": "import java.util.*;class GFG { public static void main(String[] args) { Scanner sc1 = new Scanner(System.in); int lower_bound = 2; int upper_bound = 10; // Number to be guessed is 9 // Applying Binary Search interactively while (lower_bound <= upper_bound) { int mid = (lower_bound + upper_bound) / 2; // Print the guessed number System.out.println(mid); // Input the response from the judge int response = sc1.nextInt(); if (response == -1) { lower_bound = mid + 1; } else if (response == 1) { upper_bound = mid - 1; } else if (response == 0) { System.out.println(\"Number guessed is :\" + mid); break; } } }}",
"e": 28961,
"s": 28108,
"text": null
},
{
"code": "using System;class GFG { static void Main() { int lower_bound = 2; int upper_bound = 10; // Number to be guessed is 9 // Applying Binary Search interactively while (lower_bound <= upper_bound) { int mid = (lower_bound + upper_bound) / 2; // Print the guessed number Console.WriteLine(mid); // Input the response from the judge int response = Convert.ToInt32(Console.ReadLine()); if (response == -1) { lower_bound = mid + 1; } else if (response == 1) { upper_bound = mid - 1; } else if (response == 0) { Console.WriteLine(\"Number guessed is :\" + mid); break; } } }} // This code is contributed by divyesh072019",
"e": 29717,
"s": 28961,
"text": null
},
{
"code": "lower_bound = 2upper_bound = 10 # Number to be guessed is 9 # Applying Binary Search interactivelywhile (lower_bound <= upper_bound) : mid = (lower_bound + upper_bound) // 2 # Print guessed number print(mid) # Input the response from the judge response = int(input()) if (response == -1) : lower_bound = mid + 1 elif (response == 1) : upper_bound = mid - 1 elif (response == 0) : print(\"Number guessed is :\", mid) break",
"e": 30202,
"s": 29717,
"text": null
},
{
"code": null,
"e": 30225,
"s": 30202,
"text": "6\nNumber guessed is :6"
},
{
"code": null,
"e": 30290,
"s": 30225,
"text": "Time Complexity: O(logn) Algorithm Paradigm: Divide and Conquer "
},
{
"code": null,
"e": 30308,
"s": 30290,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 30322,
"s": 30308,
"text": "divyesh072019"
},
{
"code": null,
"e": 30332,
"s": 30322,
"text": "pratham76"
},
{
"code": null,
"e": 30342,
"s": 30332,
"text": "rutvik_56"
},
{
"code": null,
"e": 30358,
"s": 30342,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 30375,
"s": 30358,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 30390,
"s": 30375,
"text": "Searching Quiz"
},
{
"code": null,
"e": 30401,
"s": 30390,
"text": "Algorithms"
},
{
"code": null,
"e": 30425,
"s": 30401,
"text": "Competitive Programming"
},
{
"code": null,
"e": 30444,
"s": 30425,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 30463,
"s": 30444,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 30474,
"s": 30463,
"text": "Algorithms"
},
{
"code": null,
"e": 30572,
"s": 30474,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30581,
"s": 30572,
"text": "Comments"
},
{
"code": null,
"e": 30594,
"s": 30581,
"text": "Old Comments"
},
{
"code": null,
"e": 30643,
"s": 30594,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 30668,
"s": 30643,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 30695,
"s": 30668,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 30723,
"s": 30695,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 30779,
"s": 30723,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 30820,
"s": 30779,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 30847,
"s": 30820,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 30890,
"s": 30847,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 30968,
"s": 30890,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
}
] |
Python Pandas – Count the Observations
|
To count the observations, first use the groupby() and then use count() on the result. At first, import the required library −
dataFrame = pd.DataFrame({'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Camera', 'Graphic Card', 'Earphone'],'Product Category': ['Computer', 'Mobile Phone', 'Electronics','Electronics', 'Computer', 'Mobile Phone'],'Quantity': [10, 50, 10, 20, 25, 50]})
Group the column with duplicate values −
group = dataFrame.groupby("Product Category")
Get the count −
group.count()
Following is the code −
import pandas as pd
# create a dataframe
dataFrame = pd.DataFrame({'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Camera', 'Graphic Card', 'Earphone'],'Product Category': ['Computer', 'Mobile Phone', 'Electronics','Electronics', 'Computer', 'Mobile Phone'],'Quantity': [10, 50, 10, 20, 25, 50]})
# dataframe
print"Dataframe...\n",dataFrame
# count the observations
group = dataFrame.groupby("Product Category")
print"\nResultant DataFrame...\n",group.count()
This will produce the following output −
Dataframe...
Product Category Product Name Quantity
0 Computer Keyboard 10
1 Mobile Phone Charger 50
2 Electronics SmartTV 10
3 Electronics Camera 20
4 Computer Graphic Card 25
5 Mobile Phone Earphone 50
Resultant DataFrame...
Product Name Quantity
Product Category
Computer 2 2
Electronics 2 2
Mobile Phone 2 2
|
[
{
"code": null,
"e": 1189,
"s": 1062,
"text": "To count the observations, first use the groupby() and then use count() on the result. At first, import the required library −"
},
{
"code": null,
"e": 1449,
"s": 1189,
"text": "dataFrame = pd.DataFrame({'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Camera', 'Graphic Card', 'Earphone'],'Product Category': ['Computer', 'Mobile Phone', 'Electronics','Electronics', 'Computer', 'Mobile Phone'],'Quantity': [10, 50, 10, 20, 25, 50]})"
},
{
"code": null,
"e": 1490,
"s": 1449,
"text": "Group the column with duplicate values −"
},
{
"code": null,
"e": 1537,
"s": 1490,
"text": "group = dataFrame.groupby(\"Product Category\")\n"
},
{
"code": null,
"e": 1553,
"s": 1537,
"text": "Get the count −"
},
{
"code": null,
"e": 1567,
"s": 1553,
"text": "group.count()"
},
{
"code": null,
"e": 1591,
"s": 1567,
"text": "Following is the code −"
},
{
"code": null,
"e": 2059,
"s": 1591,
"text": "import pandas as pd\n\n# create a dataframe\ndataFrame = pd.DataFrame({'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Camera', 'Graphic Card', 'Earphone'],'Product Category': ['Computer', 'Mobile Phone', 'Electronics','Electronics', 'Computer', 'Mobile Phone'],'Quantity': [10, 50, 10, 20, 25, 50]})\n\n# dataframe\nprint\"Dataframe...\\n\",dataFrame\n\n# count the observations\ngroup = dataFrame.groupby(\"Product Category\")\n\nprint\"\\nResultant DataFrame...\\n\",group.count()"
},
{
"code": null,
"e": 2100,
"s": 2059,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2642,
"s": 2100,
"text": "Dataframe...\n Product Category Product Name Quantity\n0 Computer Keyboard 10\n1 Mobile Phone Charger 50\n2 Electronics SmartTV 10\n3 Electronics Camera 20\n4 Computer Graphic Card 25\n5 Mobile Phone Earphone 50\n\nResultant DataFrame...\n Product Name Quantity\nProduct Category\nComputer 2 2\nElectronics 2 2\nMobile Phone 2 2"
}
] |
Create Postman collection from Flask application using flask2postman - GeeksforGeeks
|
28 Apr, 2022
Prerequisite: Introduction to Postman, First App using Flask
Since Postman is gaining popularity in the development domain, this article explains a way in which it can be easily integrated with Flask APIs using command-line utility written in Python. We will be using the flask2postman module. But you will be why this module. Here’s why –
It is a straightforward tool to generate Postman collection from Flask APIs.
It works in Command-Line.
Various customizations provided such as configurable base URLs, etc.
Output is a JSON file, which can be easily imported to the postman.
To install this type the below command in the terminal.
pip install flask2postman
flask2postman [-h] [-n NAME] [-b BASE_URL] [-a] [-i] [-f] flask_instance
Parameters:
Positional arguments: flask_instance
Optional arguments:
-h, –help: Prints help and exits
-n NAME, –name NAME: Name of postman Collection. Defaults to name of app/current directory
-b BASE_URL, –base_url BASE_URL: Base url ( Server ) of all APIs in Postman Collection. Defaults to {{base_url}}.
-a, –all: If provided generations OPTION/HEAD methods.
-s, –static: Generate static files in folder /static/{{filename}}.
-i, –indent: Intends the output in created .json() file.
-f, –folders: If blueprints provided, adds subfolders for it.
Step 1: Importing libraries and initializing app context
Python3
from flask import Flask, render_template app = Flask(__name__)
Step 2: Adding API routes
Python3
# GET [email protected]('/')def index(): return render_template('index.html') # POST [email protected]('/add', methods = ['POST'])def post_data(): return render_template('form.html') # GET API with path [email protected]('/gfg/<int:page>')def gfg(page): return render_template('gfg.html', page=page)
Step 3: Running app
Python3
if __name__ == '__main__': app.run()
Working
Run the command on the command line.
flask2postman flask-postman.app > gfg_postman.json
Creates a JSON file with the name: gfg_postman.json
{“id”: “516d259f-77b8-4aa9-9f13-59feb59d0cb4”, “name”: “gfg”, “timestamp”: 1621215826922, “requests”: [{“id”: “95f002e8-9923-4123-b7a8-dd39a38c6e20”, “data”: [], “description”: “”, “headers”: “”, “method”: “GET”, “name”: “gfg”, “time”: 1621215826922, “url”: “{{base_url}}/gfg/{{page}}”, “collectionId”: “516d259f-77b8-4aa9-9f13-59feb59d0cb4”, “dataMode”: “params”}, {“id”: “0ca2ca2f-33b6-4a37-936e-bba48a5592fa”, “data”: [], “description”: “”, “headers”: “”, “method”: “GET”, “name”: “index”, “time”: 1621215826922, “url”: “{{base_url}}/”, “collectionId”: “516d259f-77b8-4aa9-9f13-59feb59d0cb4”, “dataMode”: “params”}, {“id”: “234d7de4-d1c8-4d14-b86b-d2c71e338b54”, “data”: [], “description”: “”, “headers”: “”, “method”: “POST”, “name”: “data”, “time”: 1621215826922, “url”: “{{base_url}}/add”, “collectionId”: “516d259f-77b8-4aa9-9f13-59feb59d0cb4”, “dataMode”: “params”}], “order”: [“95f002e8-9923-4123-b7a8-dd39a38c6e20”, “0ca2ca2f-33b6-4a37-936e-bba48a5592fa”, “234d7de4-d1c8-4d14-b86b-d2c71e338b54”], “folders”: []}
The next step is to import the collection into postman.
Output:
Imported Postman Collection
Notice the default {{base_url}} and path parameter appended.
Example
flask2postman flask-postman.app –name “GFG Flask Collection” –base_url 127.0.0.1:5000 –i > custom_gfg_postman.json
custom_gfg_postman.json ( Indented now )
{
"folders": [],
"id": "e76915b6-2051-445c-934d-625059e82ed1",
"name": "GFG Flask Collection",
"order": [
"7c303b3b-d9cc-4c87-80f0-2e6ddbd8ec07",
"a08769de-09ee-49e1-b528-08d38293fe48",
"3259b993-364b-421c-adc1-df3f57ea9048"
],
"requests": [
{
"collectionId": "e76915b6-2051-445c-934d-625059e82ed1",
"data": [],
"dataMode": "params",
"description": "",
"headers": "",
"id": "7c303b3b-d9cc-4c87-80f0-2e6ddbd8ec07",
"method": "GET",
"name": "gfg",
"time": 1621216574211,
"url": "127.0.0.1:5000/gfg/{{page}}"
},
{
"collectionId": "e76915b6-2051-445c-934d-625059e82ed1",
"data": [],
"dataMode": "params",
"description": "",
"headers": "",
"id": "a08769de-09ee-49e1-b528-08d38293fe48",
"method": "GET",
"name": "index",
"time": 1621216574211,
"url": "127.0.0.1:5000/"
},
{
"collectionId": "e76915b6-2051-445c-934d-625059e82ed1",
"data": [],
"dataMode": "params",
"description": "",
"headers": "",
"id": "3259b993-364b-421c-adc1-df3f57ea9048",
"method": "POST",
"name": "data",
"time": 1621216574211,
"url": "127.0.0.1:5000/add"
}
],
"timestamp": 1621216574211
}
Output :
Customized Postman Collection
Notice the collection name, base URL, and indentations being added in JSON collection.
sweetyty
Python Flask
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n28 Apr, 2022"
},
{
"code": null,
"e": 24353,
"s": 24292,
"text": "Prerequisite: Introduction to Postman, First App using Flask"
},
{
"code": null,
"e": 24633,
"s": 24353,
"text": "Since Postman is gaining popularity in the development domain, this article explains a way in which it can be easily integrated with Flask APIs using command-line utility written in Python. We will be using the flask2postman module. But you will be why this module. Here’s why – "
},
{
"code": null,
"e": 24710,
"s": 24633,
"text": "It is a straightforward tool to generate Postman collection from Flask APIs."
},
{
"code": null,
"e": 24736,
"s": 24710,
"text": "It works in Command-Line."
},
{
"code": null,
"e": 24805,
"s": 24736,
"text": "Various customizations provided such as configurable base URLs, etc."
},
{
"code": null,
"e": 24873,
"s": 24805,
"text": "Output is a JSON file, which can be easily imported to the postman."
},
{
"code": null,
"e": 24929,
"s": 24873,
"text": "To install this type the below command in the terminal."
},
{
"code": null,
"e": 24955,
"s": 24929,
"text": "pip install flask2postman"
},
{
"code": null,
"e": 25028,
"s": 24955,
"text": "flask2postman [-h] [-n NAME] [-b BASE_URL] [-a] [-i] [-f] flask_instance"
},
{
"code": null,
"e": 25040,
"s": 25028,
"text": "Parameters:"
},
{
"code": null,
"e": 25077,
"s": 25040,
"text": "Positional arguments: flask_instance"
},
{
"code": null,
"e": 25097,
"s": 25077,
"text": "Optional arguments:"
},
{
"code": null,
"e": 25130,
"s": 25097,
"text": "-h, –help: Prints help and exits"
},
{
"code": null,
"e": 25221,
"s": 25130,
"text": "-n NAME, –name NAME: Name of postman Collection. Defaults to name of app/current directory"
},
{
"code": null,
"e": 25335,
"s": 25221,
"text": "-b BASE_URL, –base_url BASE_URL: Base url ( Server ) of all APIs in Postman Collection. Defaults to {{base_url}}."
},
{
"code": null,
"e": 25390,
"s": 25335,
"text": "-a, –all: If provided generations OPTION/HEAD methods."
},
{
"code": null,
"e": 25457,
"s": 25390,
"text": "-s, –static: Generate static files in folder /static/{{filename}}."
},
{
"code": null,
"e": 25514,
"s": 25457,
"text": "-i, –indent: Intends the output in created .json() file."
},
{
"code": null,
"e": 25576,
"s": 25514,
"text": "-f, –folders: If blueprints provided, adds subfolders for it."
},
{
"code": null,
"e": 25633,
"s": 25576,
"text": "Step 1: Importing libraries and initializing app context"
},
{
"code": null,
"e": 25641,
"s": 25633,
"text": "Python3"
},
{
"code": "from flask import Flask, render_template app = Flask(__name__)",
"e": 25704,
"s": 25641,
"text": null
},
{
"code": null,
"e": 25730,
"s": 25704,
"text": "Step 2: Adding API routes"
},
{
"code": null,
"e": 25738,
"s": 25730,
"text": "Python3"
},
{
"code": "# GET [email protected]('/')def index(): return render_template('index.html') # POST [email protected]('/add', methods = ['POST'])def post_data(): return render_template('form.html') # GET API with path [email protected]('/gfg/<int:page>')def gfg(page): return render_template('gfg.html', page=page)",
"e": 26039,
"s": 25738,
"text": null
},
{
"code": null,
"e": 26059,
"s": 26039,
"text": "Step 3: Running app"
},
{
"code": null,
"e": 26067,
"s": 26059,
"text": "Python3"
},
{
"code": "if __name__ == '__main__': app.run()",
"e": 26107,
"s": 26067,
"text": null
},
{
"code": null,
"e": 26116,
"s": 26107,
"text": "Working "
},
{
"code": null,
"e": 26153,
"s": 26116,
"text": "Run the command on the command line."
},
{
"code": null,
"e": 26204,
"s": 26153,
"text": "flask2postman flask-postman.app > gfg_postman.json"
},
{
"code": null,
"e": 26256,
"s": 26204,
"text": "Creates a JSON file with the name: gfg_postman.json"
},
{
"code": null,
"e": 27278,
"s": 26256,
"text": "{“id”: “516d259f-77b8-4aa9-9f13-59feb59d0cb4”, “name”: “gfg”, “timestamp”: 1621215826922, “requests”: [{“id”: “95f002e8-9923-4123-b7a8-dd39a38c6e20”, “data”: [], “description”: “”, “headers”: “”, “method”: “GET”, “name”: “gfg”, “time”: 1621215826922, “url”: “{{base_url}}/gfg/{{page}}”, “collectionId”: “516d259f-77b8-4aa9-9f13-59feb59d0cb4”, “dataMode”: “params”}, {“id”: “0ca2ca2f-33b6-4a37-936e-bba48a5592fa”, “data”: [], “description”: “”, “headers”: “”, “method”: “GET”, “name”: “index”, “time”: 1621215826922, “url”: “{{base_url}}/”, “collectionId”: “516d259f-77b8-4aa9-9f13-59feb59d0cb4”, “dataMode”: “params”}, {“id”: “234d7de4-d1c8-4d14-b86b-d2c71e338b54”, “data”: [], “description”: “”, “headers”: “”, “method”: “POST”, “name”: “data”, “time”: 1621215826922, “url”: “{{base_url}}/add”, “collectionId”: “516d259f-77b8-4aa9-9f13-59feb59d0cb4”, “dataMode”: “params”}], “order”: [“95f002e8-9923-4123-b7a8-dd39a38c6e20”, “0ca2ca2f-33b6-4a37-936e-bba48a5592fa”, “234d7de4-d1c8-4d14-b86b-d2c71e338b54”], “folders”: []}"
},
{
"code": null,
"e": 27335,
"s": 27278,
"text": "The next step is to import the collection into postman. "
},
{
"code": null,
"e": 27343,
"s": 27335,
"text": "Output:"
},
{
"code": null,
"e": 27371,
"s": 27343,
"text": "Imported Postman Collection"
},
{
"code": null,
"e": 27433,
"s": 27371,
"text": "Notice the default {{base_url}} and path parameter appended. "
},
{
"code": null,
"e": 27441,
"s": 27433,
"text": "Example"
},
{
"code": null,
"e": 27557,
"s": 27441,
"text": "flask2postman flask-postman.app –name “GFG Flask Collection” –base_url 127.0.0.1:5000 –i > custom_gfg_postman.json"
},
{
"code": null,
"e": 27598,
"s": 27557,
"text": "custom_gfg_postman.json ( Indented now )"
},
{
"code": null,
"e": 29119,
"s": 27598,
"text": "{\n \"folders\": [],\n \"id\": \"e76915b6-2051-445c-934d-625059e82ed1\",\n \"name\": \"GFG Flask Collection\",\n \"order\": [\n \"7c303b3b-d9cc-4c87-80f0-2e6ddbd8ec07\",\n \"a08769de-09ee-49e1-b528-08d38293fe48\",\n \"3259b993-364b-421c-adc1-df3f57ea9048\"\n ],\n \"requests\": [\n {\n \"collectionId\": \"e76915b6-2051-445c-934d-625059e82ed1\",\n \"data\": [],\n \"dataMode\": \"params\",\n \"description\": \"\",\n \"headers\": \"\",\n \"id\": \"7c303b3b-d9cc-4c87-80f0-2e6ddbd8ec07\",\n \"method\": \"GET\",\n \"name\": \"gfg\",\n \"time\": 1621216574211,\n \"url\": \"127.0.0.1:5000/gfg/{{page}}\"\n },\n {\n \"collectionId\": \"e76915b6-2051-445c-934d-625059e82ed1\",\n \"data\": [],\n \"dataMode\": \"params\",\n \"description\": \"\",\n \"headers\": \"\",\n \"id\": \"a08769de-09ee-49e1-b528-08d38293fe48\",\n \"method\": \"GET\",\n \"name\": \"index\",\n \"time\": 1621216574211,\n \"url\": \"127.0.0.1:5000/\"\n },\n {\n \"collectionId\": \"e76915b6-2051-445c-934d-625059e82ed1\",\n \"data\": [],\n \"dataMode\": \"params\",\n \"description\": \"\",\n \"headers\": \"\",\n \"id\": \"3259b993-364b-421c-adc1-df3f57ea9048\",\n \"method\": \"POST\",\n \"name\": \"data\",\n \"time\": 1621216574211,\n \"url\": \"127.0.0.1:5000/add\"\n }\n ],\n \"timestamp\": 1621216574211\n}"
},
{
"code": null,
"e": 29128,
"s": 29119,
"text": "Output :"
},
{
"code": null,
"e": 29158,
"s": 29128,
"text": "Customized Postman Collection"
},
{
"code": null,
"e": 29246,
"s": 29158,
"text": "Notice the collection name, base URL, and indentations being added in JSON collection. "
},
{
"code": null,
"e": 29255,
"s": 29246,
"text": "sweetyty"
},
{
"code": null,
"e": 29268,
"s": 29255,
"text": "Python Flask"
},
{
"code": null,
"e": 29275,
"s": 29268,
"text": "Python"
},
{
"code": null,
"e": 29373,
"s": 29275,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29405,
"s": 29373,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29447,
"s": 29405,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29503,
"s": 29447,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29545,
"s": 29503,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29576,
"s": 29545,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29631,
"s": 29576,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 29653,
"s": 29631,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29692,
"s": 29653,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29721,
"s": 29692,
"text": "Create a directory in Python"
}
] |
Python | Plotting scatter charts in excel sheet using XlsxWriter module
|
01 Jul, 2022
Prerequisite: Creat and Write on an excel file. XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different type of Scatter charts using realtime data. Charts are composed of at least one series of one or more data points. Series themselves are comprised of references to cell ranges. For plotting the charts on an excel sheet, firstly, create chart object of specific chart type( i.e Scatter etc.). After creating chart objects, insert data in it and lastly, add that chart object in the sheet object. Code #1 : Plot the simple Scatter Chart. For plotting the simple Scatter chart on an excel sheet, use add_chart() method with type ‘Scatter’ keyword argument of a workbook object.
Python3
# import xlsxwriter moduleimport xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create.workbook = xlsxwriter.Workbook('chart_scatter.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method. worksheet = workbook.add_worksheet() # Create a new Format object to formats cells# in worksheets using add_format() method . # here we create bold format object .bold = workbook.add_format({'bold': 1}) # create a data list .headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [80, 80, 100, 60, 50, 100], [60, 50, 60, 20, 10, 20],] # Write a row of data starting from 'A1'# with bold format .worksheet.write_row('A1', headings, bold) # Write a column of data starting from # 'A2', 'B2', 'C2' respectively .worksheet.write_column('A2', data[0])worksheet.write_column('B2', data[1])worksheet.write_column('C2', data[2]) # Create a chart object that can be added# to a worksheet using add_chart() method. # here we create a scatter chart object .chart1 = workbook.add_chart({'type': 'scatter'}) # Add a data series to a chart# using add_series method. # Configure the first series.# = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0]. # note : spaces is not inserted in b / w# = and Sheet1, Sheet1 and !# if space is inserted it throws warning.chart1.add_series({ 'name': '= Sheet1 !$B$1', 'categories': '= Sheet1 !$A$2:$A$7', 'values': '= Sheet1 !$B$2:$B$7',}) # Configure a second series.# Note use of alternative syntax to define ranges.# [sheetname, first_row, first_col, last_row, last_col].chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2],}) # Add a chart title chart1.set_title ({'name': 'Results of data analysis'}) # Add x-axis labelchart1.set_x_axis({'name': 'Test number'}) # Add y-axis labelchart1.set_y_axis({'name': 'Data length (mm)'}) # Set an Excel chart style.chart1.set_style(11) # add chart to the worksheet # the top-left corner of a chart # is anchored to cell E2 . worksheet.insert_chart('E2', chart1) # Finally, close the Excel file # via the close() method. workbook.close()
Output: Code #2 : Plot the Scatter Chart sub-type with straight lines and markers. For plotting this type of chart on an excel sheet, use add_chart() method with type ‘scatter’ and subtype ‘straight_with_markers’ keyword argument of a workbook object.
Python3
# import xlsxwriter moduleimport xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create.workbook = xlsxwriter.Workbook('chart_scatter2.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method. worksheet = workbook.add_worksheet() # Create a new Format object to formats cells# in worksheets using add_format() method . # here we create bold format object .bold = workbook.add_format({'bold': 1}) # create a data list .headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [80, 80, 100, 60, 50, 100], [60, 50, 60, 20, 10, 20],] # Write a row of data starting from 'A1'# with bold format .worksheet.write_row('A1', headings, bold) # Write a column of data starting from# 'A2', 'B2', 'C2' respectively .worksheet.write_column('A2', data[0])worksheet.write_column('B2', data[1])worksheet.write_column('C2', data[2]) # Create a chart object that can be added# to a worksheet using add_chart() method. # here we create a Scatter chart sub-type with# straight lines and markers object .chart1 = workbook.add_chart({'type': 'scatter', 'subtype': 'straight_with_markers'}) # Add a data series to a chart# using add_series method. # Configure the first series.# = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0].chart1.add_series({ 'name': '= Sheet1 !$B$1', 'categories': '= Sheet1 !$A$2:$A$7', 'values': '= Sheet1 !$B$2:$B$7',}) # Configure a second series.# Note use of alternative syntax to define ranges.# [sheetname, first_row, first_col, last_row, last_col].chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2],}) # Add a chart title chart1.set_title ({'name': 'Results of data analysis'}) # Add x-axis labelchart1.set_x_axis({'name': 'Test number'}) # Add y-axis labelchart1.set_y_axis({'name': 'Data length (mm)'}) # Set an Excel chart style.chart1.set_style(11) # add chart to the worksheet # the top-left corner of a chart # is anchored to cell E2 . worksheet.insert_chart('E2', chart1) # Finally, close the Excel file # via the close() method. workbook.close()
Output: Code #3 : Plot the Scatter Chart sub-type with straight lines and no markers. For plotting this type of chart on an excel sheet, use add_chart() method with type ‘scatter’ and subtype ‘straight’ keyword argument of a workbook object.
Python3
# import xlsxwriter moduleimport xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create.workbook = xlsxwriter.Workbook('chart_scatter3.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method. worksheet = workbook.add_worksheet() # Create a new Format object to formats cells# in worksheets using add_format() method . # here we create bold format object .bold = workbook.add_format({'bold': 1}) # create a data list .headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [80, 80, 100, 60, 50, 100], [60, 50, 60, 20, 10, 20],] # Write a row of data starting from 'A1'# with bold format .worksheet.write_row('A1', headings, bold) # Write a column of data starting from# 'A2', 'B2', 'C2' respectively .worksheet.write_column('A2', data[0])worksheet.write_column('B2', data[1])worksheet.write_column('C2', data[2]) # Create a chart object that can be added# to a worksheet using add_chart() method. # here we create a Scatter chart sub-type with# straight lines and no markers object .chart1 = workbook.add_chart({'type': 'scatter', 'subtype': 'straight'}) # Add a data series to a chart# using add_series method. # Configure the first series.# = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0].chart1.add_series({ 'name': '= Sheet1 !$B$1', 'categories': '= Sheet1 !$A$2:$A$7', 'values': '= Sheet1 !$B$2:$B$7',}) # Configure a second series.# Note use of alternative syntax to define ranges.# [sheetname, first_row, first_col, last_row, last_col].chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2],}) # Add a chart title chart1.set_title ({'name': 'Results of data analysis'}) # Add x-axis labelchart1.set_x_axis({'name': 'Test number'}) # Add y-axis labelchart1.set_y_axis({'name': 'Data length (mm)'}) # Set an Excel chart style.chart1.set_style(11) # add chart to the worksheet # the top-left corner of a chart # is anchored to cell E2 . worksheet.insert_chart('E2', chart1) # Finally, close the Excel file # via the close() method. workbook.close()
Output: Code #4 : Plot the Scatter Chart sub-type with smooth lines and markers. For plotting this type of chart on an excel sheet, use add_chart() method with type ‘scatter’ and subtype ‘smooth_with_markers’ keyword argument of a workbook object.
Python3
# import xlsxwriter moduleimport xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create.workbook = xlsxwriter.Workbook('chart_scatter4.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method. worksheet = workbook.add_worksheet() # Create a new Format object to formats cells# in worksheets using add_format() method . # here we create bold format object .bold = workbook.add_format({'bold': 1}) # create a data list .headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [80, 80, 100, 60, 50, 100], [60, 50, 60, 20, 10, 20],] # Write a row of data starting from 'A1'# with bold format .worksheet.write_row('A1', headings, bold) # Write a column of data starting from# 'A2', 'B2', 'C2' respectively .worksheet.write_column('A2', data[0])worksheet.write_column('B2', data[1])worksheet.write_column('C2', data[2]) # Create a chart object that can be added# to a worksheet using add_chart() method. # here we create a Scatter chart sub-type with# smooth lines and markers object .chart1 = workbook.add_chart({'type': 'scatter', 'subtype': 'smooth_with_markers'}) # Add a data series to a chart# using add_series method. # Configure the first series.# = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0].chart1.add_series({ 'name': '= Sheet1 !$B$1', 'categories': '= Sheet1 !$A$2:$A$7', 'values': '= Sheet1 !$B$2:$B$7',}) # Configure a second series.# Note use of alternative syntax to define ranges.# [sheetname, first_row, first_col, last_row, last_col].chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2],}) # Add a chart title chart1.set_title ({'name': 'Results of data analysis'}) # Add x-axis labelchart1.set_x_axis({'name': 'Test number'}) # Add y-axis labelchart1.set_y_axis({'name': 'Data length (mm)'}) # Set an Excel chart style.chart1.set_style(11) # add chart to the worksheet # the top-left corner of a chart # is anchored to cell E2 . worksheet.insert_chart('E2', chart1) # Finally, close the Excel file # via the close() method. workbook.close()
Output : Code #5 : Plot the Scatter Chart sub-type with smooth lines and no markers. For plotting this type of chart on an excel sheet, use add_chart() method with type ‘scatter’ and subtype ‘smooth’ keyword argument of a workbook object.
Python3
# import xlsxwriter moduleimport xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create.workbook = xlsxwriter.Workbook('chart_scatter5.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method. worksheet = workbook.add_worksheet() # Create a new Format object to formats cells# in worksheets using add_format() method . # here we create bold format object .bold = workbook.add_format({'bold': 1}) # create a data list .headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [80, 80, 100, 60, 50, 100], [60, 50, 60, 20, 10, 20],] # Write a row of data starting from 'A1'# with bold format .worksheet.write_row('A1', headings, bold) # Write a column of data starting from# 'A2', 'B2', 'C2' respectively .worksheet.write_column('A2', data[0])worksheet.write_column('B2', data[1])worksheet.write_column('C2', data[2]) # Create a chart object that can be added# to a worksheet using add_chart() method. # here we create a Scatter chart sub-type with# smooth lines and no markers object .chart1 = workbook.add_chart({'type': 'scatter', 'subtype': 'smooth'}) # Add a data series to a chart# using add_series method. # Configure the first series.# = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0].chart1.add_series({ 'name': '= Sheet1 !$B$1', 'categories': '= Sheet1 !$A$2:$A$7', 'values': '= Sheet1 !$B$2:$B$7',}) # Configure a second series.# Note use of alternative syntax to define ranges.# [sheetname, first_row, first_col, last_row, last_col].chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2],}) # Add a chart title chart1.set_title ({'name': 'Results of data analysis'}) # Add x-axis labelchart1.set_x_axis({'name': 'Test number'}) # Add y-axis labelchart1.set_y_axis({'name': 'Data length (mm)'}) # Set an Excel chart style.chart1.set_style(11) # add chart to the worksheet # the top-left corner of a chart # is anchored to cell E2 . worksheet.insert_chart('E2', chart1) # Finally, close the Excel file # via the close() method. workbook.close()
Output:
sweetyty
Python-excel
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Jul, 2022"
},
{
"code": null,
"e": 845,
"s": 28,
"text": "Prerequisite: Creat and Write on an excel file. XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different type of Scatter charts using realtime data. Charts are composed of at least one series of one or more data points. Series themselves are comprised of references to cell ranges. For plotting the charts on an excel sheet, firstly, create chart object of specific chart type( i.e Scatter etc.). After creating chart objects, insert data in it and lastly, add that chart object in the sheet object. Code #1 : Plot the simple Scatter Chart. For plotting the simple Scatter chart on an excel sheet, use add_chart() method with type ‘Scatter’ keyword argument of a workbook object. "
},
{
"code": null,
"e": 853,
"s": 845,
"text": "Python3"
},
{
"code": "# import xlsxwriter moduleimport xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create.workbook = xlsxwriter.Workbook('chart_scatter.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method. worksheet = workbook.add_worksheet() # Create a new Format object to formats cells# in worksheets using add_format() method . # here we create bold format object .bold = workbook.add_format({'bold': 1}) # create a data list .headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [80, 80, 100, 60, 50, 100], [60, 50, 60, 20, 10, 20],] # Write a row of data starting from 'A1'# with bold format .worksheet.write_row('A1', headings, bold) # Write a column of data starting from # 'A2', 'B2', 'C2' respectively .worksheet.write_column('A2', data[0])worksheet.write_column('B2', data[1])worksheet.write_column('C2', data[2]) # Create a chart object that can be added# to a worksheet using add_chart() method. # here we create a scatter chart object .chart1 = workbook.add_chart({'type': 'scatter'}) # Add a data series to a chart# using add_series method. # Configure the first series.# = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0]. # note : spaces is not inserted in b / w# = and Sheet1, Sheet1 and !# if space is inserted it throws warning.chart1.add_series({ 'name': '= Sheet1 !$B$1', 'categories': '= Sheet1 !$A$2:$A$7', 'values': '= Sheet1 !$B$2:$B$7',}) # Configure a second series.# Note use of alternative syntax to define ranges.# [sheetname, first_row, first_col, last_row, last_col].chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2],}) # Add a chart title chart1.set_title ({'name': 'Results of data analysis'}) # Add x-axis labelchart1.set_x_axis({'name': 'Test number'}) # Add y-axis labelchart1.set_y_axis({'name': 'Data length (mm)'}) # Set an Excel chart style.chart1.set_style(11) # add chart to the worksheet # the top-left corner of a chart # is anchored to cell E2 . worksheet.insert_chart('E2', chart1) # Finally, close the Excel file # via the close() method. workbook.close()",
"e": 3105,
"s": 853,
"text": null
},
{
"code": null,
"e": 3361,
"s": 3105,
"text": "Output: Code #2 : Plot the Scatter Chart sub-type with straight lines and markers. For plotting this type of chart on an excel sheet, use add_chart() method with type ‘scatter’ and subtype ‘straight_with_markers’ keyword argument of a workbook object. "
},
{
"code": null,
"e": 3369,
"s": 3361,
"text": "Python3"
},
{
"code": "# import xlsxwriter moduleimport xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create.workbook = xlsxwriter.Workbook('chart_scatter2.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method. worksheet = workbook.add_worksheet() # Create a new Format object to formats cells# in worksheets using add_format() method . # here we create bold format object .bold = workbook.add_format({'bold': 1}) # create a data list .headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [80, 80, 100, 60, 50, 100], [60, 50, 60, 20, 10, 20],] # Write a row of data starting from 'A1'# with bold format .worksheet.write_row('A1', headings, bold) # Write a column of data starting from# 'A2', 'B2', 'C2' respectively .worksheet.write_column('A2', data[0])worksheet.write_column('B2', data[1])worksheet.write_column('C2', data[2]) # Create a chart object that can be added# to a worksheet using add_chart() method. # here we create a Scatter chart sub-type with# straight lines and markers object .chart1 = workbook.add_chart({'type': 'scatter', 'subtype': 'straight_with_markers'}) # Add a data series to a chart# using add_series method. # Configure the first series.# = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0].chart1.add_series({ 'name': '= Sheet1 !$B$1', 'categories': '= Sheet1 !$A$2:$A$7', 'values': '= Sheet1 !$B$2:$B$7',}) # Configure a second series.# Note use of alternative syntax to define ranges.# [sheetname, first_row, first_col, last_row, last_col].chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2],}) # Add a chart title chart1.set_title ({'name': 'Results of data analysis'}) # Add x-axis labelchart1.set_x_axis({'name': 'Test number'}) # Add y-axis labelchart1.set_y_axis({'name': 'Data length (mm)'}) # Set an Excel chart style.chart1.set_style(11) # add chart to the worksheet # the top-left corner of a chart # is anchored to cell E2 . worksheet.insert_chart('E2', chart1) # Finally, close the Excel file # via the close() method. workbook.close()",
"e": 5590,
"s": 3369,
"text": null
},
{
"code": null,
"e": 5836,
"s": 5590,
"text": "Output: Code #3 : Plot the Scatter Chart sub-type with straight lines and no markers. For plotting this type of chart on an excel sheet, use add_chart() method with type ‘scatter’ and subtype ‘straight’ keyword argument of a workbook object. "
},
{
"code": null,
"e": 5844,
"s": 5836,
"text": "Python3"
},
{
"code": "# import xlsxwriter moduleimport xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create.workbook = xlsxwriter.Workbook('chart_scatter3.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method. worksheet = workbook.add_worksheet() # Create a new Format object to formats cells# in worksheets using add_format() method . # here we create bold format object .bold = workbook.add_format({'bold': 1}) # create a data list .headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [80, 80, 100, 60, 50, 100], [60, 50, 60, 20, 10, 20],] # Write a row of data starting from 'A1'# with bold format .worksheet.write_row('A1', headings, bold) # Write a column of data starting from# 'A2', 'B2', 'C2' respectively .worksheet.write_column('A2', data[0])worksheet.write_column('B2', data[1])worksheet.write_column('C2', data[2]) # Create a chart object that can be added# to a worksheet using add_chart() method. # here we create a Scatter chart sub-type with# straight lines and no markers object .chart1 = workbook.add_chart({'type': 'scatter', 'subtype': 'straight'}) # Add a data series to a chart# using add_series method. # Configure the first series.# = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0].chart1.add_series({ 'name': '= Sheet1 !$B$1', 'categories': '= Sheet1 !$A$2:$A$7', 'values': '= Sheet1 !$B$2:$B$7',}) # Configure a second series.# Note use of alternative syntax to define ranges.# [sheetname, first_row, first_col, last_row, last_col].chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2],}) # Add a chart title chart1.set_title ({'name': 'Results of data analysis'}) # Add x-axis labelchart1.set_x_axis({'name': 'Test number'}) # Add y-axis labelchart1.set_y_axis({'name': 'Data length (mm)'}) # Set an Excel chart style.chart1.set_style(11) # add chart to the worksheet # the top-left corner of a chart # is anchored to cell E2 . worksheet.insert_chart('E2', chart1) # Finally, close the Excel file # via the close() method. workbook.close()",
"e": 8055,
"s": 5844,
"text": null
},
{
"code": null,
"e": 8307,
"s": 8055,
"text": "Output: Code #4 : Plot the Scatter Chart sub-type with smooth lines and markers. For plotting this type of chart on an excel sheet, use add_chart() method with type ‘scatter’ and subtype ‘smooth_with_markers’ keyword argument of a workbook object. "
},
{
"code": null,
"e": 8315,
"s": 8307,
"text": "Python3"
},
{
"code": "# import xlsxwriter moduleimport xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create.workbook = xlsxwriter.Workbook('chart_scatter4.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method. worksheet = workbook.add_worksheet() # Create a new Format object to formats cells# in worksheets using add_format() method . # here we create bold format object .bold = workbook.add_format({'bold': 1}) # create a data list .headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [80, 80, 100, 60, 50, 100], [60, 50, 60, 20, 10, 20],] # Write a row of data starting from 'A1'# with bold format .worksheet.write_row('A1', headings, bold) # Write a column of data starting from# 'A2', 'B2', 'C2' respectively .worksheet.write_column('A2', data[0])worksheet.write_column('B2', data[1])worksheet.write_column('C2', data[2]) # Create a chart object that can be added# to a worksheet using add_chart() method. # here we create a Scatter chart sub-type with# smooth lines and markers object .chart1 = workbook.add_chart({'type': 'scatter', 'subtype': 'smooth_with_markers'}) # Add a data series to a chart# using add_series method. # Configure the first series.# = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0].chart1.add_series({ 'name': '= Sheet1 !$B$1', 'categories': '= Sheet1 !$A$2:$A$7', 'values': '= Sheet1 !$B$2:$B$7',}) # Configure a second series.# Note use of alternative syntax to define ranges.# [sheetname, first_row, first_col, last_row, last_col].chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2],}) # Add a chart title chart1.set_title ({'name': 'Results of data analysis'}) # Add x-axis labelchart1.set_x_axis({'name': 'Test number'}) # Add y-axis labelchart1.set_y_axis({'name': 'Data length (mm)'}) # Set an Excel chart style.chart1.set_style(11) # add chart to the worksheet # the top-left corner of a chart # is anchored to cell E2 . worksheet.insert_chart('E2', chart1) # Finally, close the Excel file # via the close() method. workbook.close()",
"e": 10532,
"s": 8315,
"text": null
},
{
"code": null,
"e": 10775,
"s": 10532,
"text": "Output : Code #5 : Plot the Scatter Chart sub-type with smooth lines and no markers. For plotting this type of chart on an excel sheet, use add_chart() method with type ‘scatter’ and subtype ‘smooth’ keyword argument of a workbook object. "
},
{
"code": null,
"e": 10783,
"s": 10775,
"text": "Python3"
},
{
"code": "# import xlsxwriter moduleimport xlsxwriter # Workbook() takes one, non-optional, argument # which is the filename that we want to create.workbook = xlsxwriter.Workbook('chart_scatter5.xlsx') # The workbook object is then used to add new # worksheet via the add_worksheet() method. worksheet = workbook.add_worksheet() # Create a new Format object to formats cells# in worksheets using add_format() method . # here we create bold format object .bold = workbook.add_format({'bold': 1}) # create a data list .headings = ['Number', 'Batch 1', 'Batch 2'] data = [ [2, 3, 4, 5, 6, 7], [80, 80, 100, 60, 50, 100], [60, 50, 60, 20, 10, 20],] # Write a row of data starting from 'A1'# with bold format .worksheet.write_row('A1', headings, bold) # Write a column of data starting from# 'A2', 'B2', 'C2' respectively .worksheet.write_column('A2', data[0])worksheet.write_column('B2', data[1])worksheet.write_column('C2', data[2]) # Create a chart object that can be added# to a worksheet using add_chart() method. # here we create a Scatter chart sub-type with# smooth lines and no markers object .chart1 = workbook.add_chart({'type': 'scatter', 'subtype': 'smooth'}) # Add a data series to a chart# using add_series method. # Configure the first series.# = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0].chart1.add_series({ 'name': '= Sheet1 !$B$1', 'categories': '= Sheet1 !$A$2:$A$7', 'values': '= Sheet1 !$B$2:$B$7',}) # Configure a second series.# Note use of alternative syntax to define ranges.# [sheetname, first_row, first_col, last_row, last_col].chart1.add_series({ 'name': ['Sheet1', 0, 2], 'categories': ['Sheet1', 1, 0, 6, 0], 'values': ['Sheet1', 1, 2, 6, 2],}) # Add a chart title chart1.set_title ({'name': 'Results of data analysis'}) # Add x-axis labelchart1.set_x_axis({'name': 'Test number'}) # Add y-axis labelchart1.set_y_axis({'name': 'Data length (mm)'}) # Set an Excel chart style.chart1.set_style(11) # add chart to the worksheet # the top-left corner of a chart # is anchored to cell E2 . worksheet.insert_chart('E2', chart1) # Finally, close the Excel file # via the close() method. workbook.close()",
"e": 12990,
"s": 10783,
"text": null
},
{
"code": null,
"e": 12999,
"s": 12990,
"text": "Output: "
},
{
"code": null,
"e": 13008,
"s": 12999,
"text": "sweetyty"
},
{
"code": null,
"e": 13021,
"s": 13008,
"text": "Python-excel"
},
{
"code": null,
"e": 13028,
"s": 13021,
"text": "Python"
}
] |
Logical Functions in Tableau
|
24 Oct, 2020
In this article, we will learn about logical functions and it’s used in Tableau. For this first look into two terms :
Tableau: Tableau is a very powerful data visualization tool that can be used by data analysts, scientists, statisticians, etc. to visualize the data and get a clear opinion based on the data analysis. Tableau is very famous as it can take in data and produce the required data visualization output in a very short time.
Logical Function: Tableau provides various Logical Functions to perform logical operations on our data. They are Tableau AND, NOT, OR, IF, ELSEIF, IF Else, CASE, ISNULL, IFNULL, ZN, IIF, etc.
Let’s discuss every logical function one by one with an example. Dataset used in the given examples is Dataset.
AND Function: The AND Function is employed to see multiple expressions. The syntax of the AND Function is as shown below:
Expression_1 AND Expression_2
If both the conditions are True, it returns True. Otherwise, it returns False.
To demonstrate this logical function in Tableau, we have to use Calculated Fields.
To create a calculated field, please navigate to Analysis Tab and choose the Create Calculated Field... option.
Use the expression in the newly created field.
OR Function: The Tableau OR function is like an either-or statement in English. If both the conditions are False, Tableau or will return False; otherwise, it returns True. The syntax of this Tableau OR Function is:
Expression_1 OR Expression_2
To demonstrate this logical function in Tableau, we have to use Calculated Fields.
To create a calculated field, please navigate to Analysis Tab and choose the Create Calculated Field... option.
Use the expression in the newly created field.
IIF Function: The Tableau IIF function is that the simple version of the If Else Function. If both the condition is True, then it’ll return First Statement otherwise, the second statement. The syntax of this Tableau IIF Function is:
IIF(Expression, True_statement, False_Statement)
To demonstrate this logical function in Tableau, we have to use Calculated Fields.
To create a calculated field, please navigate to Analysis Tab and choose the Create Calculated Field... option.
Use the expression in the newly created field.
NOT Function: The Tableau NOT function return the exact opposite. I mean, True will become false and vice versa. The syntax of this Tableau NOT Function is:
NOT(Expression)
To demonstrate this logical function in Tableau, we have to use Calculated Fields.
To create a calculated field, please navigate to Analysis Tab and choose the Create Calculated Field... option.
Use the expression in the newly created field.
ISNULL Function: Tableau ISNULL function will check whether it is NULL or Not. If it’s NULL, then it returns TRUE; otherwise, False will return. The syntax of the Tableau ISNULL Function is:
ISNULL(Expression)
To demonstrate this logical function in Tableau, we have to use Calculated Fields.
To create a calculated field, please navigate to Analysis Tab and choose the Create Calculated Field... option.
Use the expression in the newly created field.
ZN Function: Tableau ZN function will return the first values of Not Null values, and 0 for Null values. In simple English, ZN in Tableau is employed to exchange the NULL values with 0. The syntax of the Tableau ZN Function is:
ZN(Expression)
To demonstrate this logical function in Tableau, we have to use Calculated Fields.
To create a calculated field, please navigate to Analysis Tab and choose the Create Calculated Field... option.
Use the expression in the newly created field.
IFNULL Function: Tableau IFNULL function is employed to exchange the NULL values together with your own. The syntax of the Tableau IFNULL Function is:
IFNULL(Expression, Value)
To demonstrate this logical function in Tableau, we have to use Calculated Fields.
To create a calculated field, please navigate to Analysis Tab and choose the Create Calculated Field... option.
Use the expression in the newly created field.
IF Function: Tableau If Function is one of the foremost useful decision-making functions. If the function tests the condition and depending upon the condition result, it’ll return the output.
IF <Expression1> THEN <Statement1>
ELSEIF <Expression2> THEN <Statement2>
ELSEIF <Expression3> THEN <Statement3>
.....
ELSEIF <ExpressionN> THEN <StatementN>
ELSE <Statement>
END
IF-END
In this example, we simply create a new calculated field by using the IF function on a field.
View new calculated field.
Use in Visualization.
It has a drawback that creates null values in case of the false condition.
IF-ELSE-END
In this example, we simply edit that previously calculated field by using the IF-ELSE function in the same field.
View a new calculated field.
Use in Visualization.
It overcomes a drawback that creates null values in case of the false condition.
IF-ELSEIF-ELSE-END
In this example, we simply create a new calculated field by using the IF-ELSEIF-ELSE function on a field.
View a new calculated field.
Use in Visualization.
Case Function: Case Function is the part of Logical functions in Tableau. These functions are used to perform the logical test and return the required value when the test expression is true.
CASE [<expression>]
WHEN <expression> THEN <expression>
WHEN <expression> THEN <expression>
ELSE <expression>
END
To demonstrate this logical function in Tableau, we have to use Calculated Fields.
To create a calculated field, please navigate to Analysis Tab and choose the Create Calculated Field... option.
Use the expression in the newly created field.
Tableau
Tableau
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Oct, 2020"
},
{
"code": null,
"e": 146,
"s": 28,
"text": "In this article, we will learn about logical functions and it’s used in Tableau. For this first look into two terms :"
},
{
"code": null,
"e": 466,
"s": 146,
"text": "Tableau: Tableau is a very powerful data visualization tool that can be used by data analysts, scientists, statisticians, etc. to visualize the data and get a clear opinion based on the data analysis. Tableau is very famous as it can take in data and produce the required data visualization output in a very short time."
},
{
"code": null,
"e": 658,
"s": 466,
"text": "Logical Function: Tableau provides various Logical Functions to perform logical operations on our data. They are Tableau AND, NOT, OR, IF, ELSEIF, IF Else, CASE, ISNULL, IFNULL, ZN, IIF, etc."
},
{
"code": null,
"e": 770,
"s": 658,
"text": "Let’s discuss every logical function one by one with an example. Dataset used in the given examples is Dataset."
},
{
"code": null,
"e": 892,
"s": 770,
"text": "AND Function: The AND Function is employed to see multiple expressions. The syntax of the AND Function is as shown below:"
},
{
"code": null,
"e": 923,
"s": 892,
"text": "Expression_1 AND Expression_2\n"
},
{
"code": null,
"e": 1002,
"s": 923,
"text": "If both the conditions are True, it returns True. Otherwise, it returns False."
},
{
"code": null,
"e": 1085,
"s": 1002,
"text": "To demonstrate this logical function in Tableau, we have to use Calculated Fields."
},
{
"code": null,
"e": 1197,
"s": 1085,
"text": "To create a calculated field, please navigate to Analysis Tab and choose the Create Calculated Field... option."
},
{
"code": null,
"e": 1244,
"s": 1197,
"text": "Use the expression in the newly created field."
},
{
"code": null,
"e": 1459,
"s": 1244,
"text": "OR Function: The Tableau OR function is like an either-or statement in English. If both the conditions are False, Tableau or will return False; otherwise, it returns True. The syntax of this Tableau OR Function is:"
},
{
"code": null,
"e": 1489,
"s": 1459,
"text": "Expression_1 OR Expression_2\n"
},
{
"code": null,
"e": 1572,
"s": 1489,
"text": "To demonstrate this logical function in Tableau, we have to use Calculated Fields."
},
{
"code": null,
"e": 1684,
"s": 1572,
"text": "To create a calculated field, please navigate to Analysis Tab and choose the Create Calculated Field... option."
},
{
"code": null,
"e": 1731,
"s": 1684,
"text": "Use the expression in the newly created field."
},
{
"code": null,
"e": 1964,
"s": 1731,
"text": "IIF Function: The Tableau IIF function is that the simple version of the If Else Function. If both the condition is True, then it’ll return First Statement otherwise, the second statement. The syntax of this Tableau IIF Function is:"
},
{
"code": null,
"e": 2014,
"s": 1964,
"text": "IIF(Expression, True_statement, False_Statement)\n"
},
{
"code": null,
"e": 2097,
"s": 2014,
"text": "To demonstrate this logical function in Tableau, we have to use Calculated Fields."
},
{
"code": null,
"e": 2209,
"s": 2097,
"text": "To create a calculated field, please navigate to Analysis Tab and choose the Create Calculated Field... option."
},
{
"code": null,
"e": 2256,
"s": 2209,
"text": "Use the expression in the newly created field."
},
{
"code": null,
"e": 2413,
"s": 2256,
"text": "NOT Function: The Tableau NOT function return the exact opposite. I mean, True will become false and vice versa. The syntax of this Tableau NOT Function is:"
},
{
"code": null,
"e": 2430,
"s": 2413,
"text": "NOT(Expression)\n"
},
{
"code": null,
"e": 2513,
"s": 2430,
"text": "To demonstrate this logical function in Tableau, we have to use Calculated Fields."
},
{
"code": null,
"e": 2625,
"s": 2513,
"text": "To create a calculated field, please navigate to Analysis Tab and choose the Create Calculated Field... option."
},
{
"code": null,
"e": 2672,
"s": 2625,
"text": "Use the expression in the newly created field."
},
{
"code": null,
"e": 2863,
"s": 2672,
"text": "ISNULL Function: Tableau ISNULL function will check whether it is NULL or Not. If it’s NULL, then it returns TRUE; otherwise, False will return. The syntax of the Tableau ISNULL Function is:"
},
{
"code": null,
"e": 2883,
"s": 2863,
"text": "ISNULL(Expression)\n"
},
{
"code": null,
"e": 2966,
"s": 2883,
"text": "To demonstrate this logical function in Tableau, we have to use Calculated Fields."
},
{
"code": null,
"e": 3078,
"s": 2966,
"text": "To create a calculated field, please navigate to Analysis Tab and choose the Create Calculated Field... option."
},
{
"code": null,
"e": 3125,
"s": 3078,
"text": "Use the expression in the newly created field."
},
{
"code": null,
"e": 3353,
"s": 3125,
"text": "ZN Function: Tableau ZN function will return the first values of Not Null values, and 0 for Null values. In simple English, ZN in Tableau is employed to exchange the NULL values with 0. The syntax of the Tableau ZN Function is:"
},
{
"code": null,
"e": 3369,
"s": 3353,
"text": "ZN(Expression)\n"
},
{
"code": null,
"e": 3452,
"s": 3369,
"text": "To demonstrate this logical function in Tableau, we have to use Calculated Fields."
},
{
"code": null,
"e": 3564,
"s": 3452,
"text": "To create a calculated field, please navigate to Analysis Tab and choose the Create Calculated Field... option."
},
{
"code": null,
"e": 3611,
"s": 3564,
"text": "Use the expression in the newly created field."
},
{
"code": null,
"e": 3762,
"s": 3611,
"text": "IFNULL Function: Tableau IFNULL function is employed to exchange the NULL values together with your own. The syntax of the Tableau IFNULL Function is:"
},
{
"code": null,
"e": 3789,
"s": 3762,
"text": "IFNULL(Expression, Value)\n"
},
{
"code": null,
"e": 3872,
"s": 3789,
"text": "To demonstrate this logical function in Tableau, we have to use Calculated Fields."
},
{
"code": null,
"e": 3984,
"s": 3872,
"text": "To create a calculated field, please navigate to Analysis Tab and choose the Create Calculated Field... option."
},
{
"code": null,
"e": 4031,
"s": 3984,
"text": "Use the expression in the newly created field."
},
{
"code": null,
"e": 4223,
"s": 4031,
"text": "IF Function: Tableau If Function is one of the foremost useful decision-making functions. If the function tests the condition and depending upon the condition result, it’ll return the output."
},
{
"code": null,
"e": 4403,
"s": 4223,
"text": "IF <Expression1> THEN <Statement1>\nELSEIF <Expression2> THEN <Statement2>\nELSEIF <Expression3> THEN <Statement3>\n.....\nELSEIF <ExpressionN> THEN <StatementN>\nELSE <Statement>\nEND\n"
},
{
"code": null,
"e": 4410,
"s": 4403,
"text": "IF-END"
},
{
"code": null,
"e": 4504,
"s": 4410,
"text": "In this example, we simply create a new calculated field by using the IF function on a field."
},
{
"code": null,
"e": 4531,
"s": 4504,
"text": "View new calculated field."
},
{
"code": null,
"e": 4553,
"s": 4531,
"text": "Use in Visualization."
},
{
"code": null,
"e": 4628,
"s": 4553,
"text": "It has a drawback that creates null values in case of the false condition."
},
{
"code": null,
"e": 4640,
"s": 4628,
"text": "IF-ELSE-END"
},
{
"code": null,
"e": 4754,
"s": 4640,
"text": "In this example, we simply edit that previously calculated field by using the IF-ELSE function in the same field."
},
{
"code": null,
"e": 4783,
"s": 4754,
"text": "View a new calculated field."
},
{
"code": null,
"e": 4805,
"s": 4783,
"text": "Use in Visualization."
},
{
"code": null,
"e": 4886,
"s": 4805,
"text": "It overcomes a drawback that creates null values in case of the false condition."
},
{
"code": null,
"e": 4905,
"s": 4886,
"text": "IF-ELSEIF-ELSE-END"
},
{
"code": null,
"e": 5011,
"s": 4905,
"text": "In this example, we simply create a new calculated field by using the IF-ELSEIF-ELSE function on a field."
},
{
"code": null,
"e": 5040,
"s": 5011,
"text": "View a new calculated field."
},
{
"code": null,
"e": 5062,
"s": 5040,
"text": "Use in Visualization."
},
{
"code": null,
"e": 5253,
"s": 5062,
"text": "Case Function: Case Function is the part of Logical functions in Tableau. These functions are used to perform the logical test and return the required value when the test expression is true."
},
{
"code": null,
"e": 5380,
"s": 5253,
"text": "CASE [<expression>]\n WHEN <expression> THEN <expression>\n WHEN <expression> THEN <expression>\n ELSE <expression>\nEND\n"
},
{
"code": null,
"e": 5463,
"s": 5380,
"text": "To demonstrate this logical function in Tableau, we have to use Calculated Fields."
},
{
"code": null,
"e": 5575,
"s": 5463,
"text": "To create a calculated field, please navigate to Analysis Tab and choose the Create Calculated Field... option."
},
{
"code": null,
"e": 5622,
"s": 5575,
"text": "Use the expression in the newly created field."
},
{
"code": null,
"e": 5630,
"s": 5622,
"text": "Tableau"
},
{
"code": null,
"e": 5638,
"s": 5630,
"text": "Tableau"
}
] |
Pair with given sum in a sorted array | Practice | GeeksforGeeks
|
You are given an array Arr of size N. You need to find all pairs in the array that sum to a number K. If no such pair exists then output will be -1. The elements of the array are distinct and are in sorted order.
Note: (a,b) and (b,a) are considered same. Also, an element cannot pair with itself, i.e., (a,a) is invalid.
Example 1:
​Input:
n = 7
arr[] = {1, 2, 3, 4, 5, 6, 7}
K = 8
Output:
3
Explanation:
We find 3 such pairs that
sum to 8 (1,7) (2,6) (3,5)
​Example 2:
Input:
n = 7
arr[] = {1, 2, 3, 4, 5, 6, 7}
K = 98
Output:
-1
Your Task:
This is a function problem. The input is already taken care of by the driver code. You only need to complete the function Countpair() that takes an array (arr), sizeOfArray (n), an integer K and return the count of the pairs which add up to the sum K. The driver code takes care of the printing.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).
Constraints:
0 <= Ai <=107
2 <= N <= 107
0 <= K <= 107
0
krishnendughosh6 hours ago
Java Solution : 0.25/15.42
tc : O(n), one iteration
sc : O(1)
class Solution{
int Countpair(int arr[], int n, int sum){
int i = 0, j = n-1, k = 0, pair = 0;
while(i<j){
k = arr[i] + arr[j];
if(k==sum){
pair+=1;
i++; j--;
}else if(k<sum) i++;
else j--;
}
if(pair==0) return -1;
else return pair;
}
}
0
yashaggarwal55552 days ago
class Solution{ public: int Countpair(int arr[], int n, int sum){ // Complete the function unordered_map<int,int> m; int pair=0; for(int i=0;i<n;i++) { int b=sum-arr[i]; if(m[b]) { pair++; } ++m[arr[i]]; } if(pair==0) return -1; else return pair; }};
0
sharib_saifi1 week ago
//Simple java Solution
class Solution{ int Countpair(int a[], int n, int sum) { // Complete the function int temp=0; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(a[i] + a[j] == sum){ temp++; } } } if(temp == 0){ return -1; } else{ return temp; } } }
0
tuwodabhinav071 week ago
int count=0; for(int i=0;i<n;i++) { int low=i+1; int high=n-1; while(low<=high) { int mid=low+(high-low)/2; if(arr[i]+arr[mid]==sum) { count++; break; } else if(arr[i]+arr[mid]<sum) { low=mid+1; } else if(arr[i]+arr[mid]>sum) { high=mid-1; } } } if(count==0) return -1; else return count;
0
imkprakash2 weeks ago
C++ solution :
Time taken : 0.01/ 2.62
class Solution{
public:
int Countpair(int arr[], int n, int sum){
// Complete the function
int count=0;
int i=0, j=n-1;
while(i<j){
if(arr[i]+arr[j] == sum){
count++;
i++;
j--;
}
else if(arr[i]+arr[j]<sum){
i++;
}
else{
j--;
}
}
if(count) return count;
return -1;
}
};
0
kmani33072 weeks ago
int c=0; // Complete the function int i=0,j=1; while(i<n){ if(j<n && arr[i]+arr[j]<sum){ j++; } else if(arr[i]+arr[j]==sum){ c+=1; i++; j=i+1; } else{ i++; j=i+1; } } return c>0?c:-1;
0
2020bec0654 weeks ago
// Complete the function sort(arr,arr+n); int l=0; int r=n-1; int ans=-1; while(l<r) { if(arr[l]+arr[r]==sum) { ans++; } if(arr[l]+arr[r]>sum) { r--; } else { l++; } } if(ans==-1){ return ans; } return ans+1; }
0
patildhiren441 month ago
JAVA -
int Countpair(int[] arr, int n, int tar)
{
int i = 0;
int j = arr.length - 1;
int cou = 0;
while (i < j) {
int sum = arr[i] + arr[j];
if (sum == tar) {
i++;
j--;
cou++;
} else if (sum > tar) {
j--;
} else {
i++;
}
}
if (cou == 0)
return -1;
return cou;
}
0
vishwakarma123411 month ago
int Countpair(int arr[], int n, int k){
// Complete the function
map<int ,int>mc;
int count=0;
for(int i=0;i<n;i++)
{
int b=k-arr[i];//b=k-arr[i]
if(mc[b]);//freq of b
count+=mc[b];//adding freq to count
mc[arr[i]]++;//incrementing occurences(hashing)
}
if(count)
return count;
else
return -1;
}
0
ssrkb1 month ago
TIME COMPLEXITY - 0.02/2.62
int count=0; int l=0,r=n-1; while(l<r){ if(a[l]+a[r] == sum){ count++; l++; r--; } else{ if(a[l]+a[r]<sum) l++; else r--; } } return count==0?-1:count;
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints.
|
[
{
"code": null,
"e": 548,
"s": 226,
"text": "You are given an array Arr of size N. You need to find all pairs in the array that sum to a number K. If no such pair exists then output will be -1. The elements of the array are distinct and are in sorted order.\nNote: (a,b) and (b,a) are considered same. Also, an element cannot pair with itself, i.e., (a,a) is invalid."
},
{
"code": null,
"e": 559,
"s": 548,
"text": "Example 1:"
},
{
"code": null,
"e": 689,
"s": 559,
"text": "​Input:\nn = 7\narr[] = {1, 2, 3, 4, 5, 6, 7}\nK = 8\nOutput:\n3\nExplanation:\nWe find 3 such pairs that\nsum to 8 (1,7) (2,6) (3,5)\n"
},
{
"code": null,
"e": 705,
"s": 689,
"text": "\n​Example 2:"
},
{
"code": null,
"e": 768,
"s": 705,
"text": "Input:\nn = 7\narr[] = {1, 2, 3, 4, 5, 6, 7}\nK = 98 \nOutput:\n-1 "
},
{
"code": null,
"e": 1077,
"s": 770,
"text": "Your Task:\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function Countpair() that takes an array (arr), sizeOfArray (n), an integer K and return the count of the pairs which add up to the sum K. The driver code takes care of the printing."
},
{
"code": null,
"e": 1142,
"s": 1077,
"text": "\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 1199,
"s": 1144,
"text": "Constraints:\n0 <= Ai <=107\n2 <= N <= 107\n0 <= K <= 107"
},
{
"code": null,
"e": 1201,
"s": 1199,
"text": "0"
},
{
"code": null,
"e": 1228,
"s": 1201,
"text": "krishnendughosh6 hours ago"
},
{
"code": null,
"e": 1255,
"s": 1228,
"text": "Java Solution : 0.25/15.42"
},
{
"code": null,
"e": 1280,
"s": 1255,
"text": "tc : O(n), one iteration"
},
{
"code": null,
"e": 1290,
"s": 1280,
"text": "sc : O(1)"
},
{
"code": null,
"e": 1664,
"s": 1290,
"text": "class Solution{\n int Countpair(int arr[], int n, int sum){\n int i = 0, j = n-1, k = 0, pair = 0;\n while(i<j){\n k = arr[i] + arr[j];\n if(k==sum){\n pair+=1;\n i++; j--;\n }else if(k<sum) i++;\n else j--;\n }\n \n if(pair==0) return -1;\n else return pair;\n }\n}"
},
{
"code": null,
"e": 1666,
"s": 1664,
"text": "0"
},
{
"code": null,
"e": 1693,
"s": 1666,
"text": "yashaggarwal55552 days ago"
},
{
"code": null,
"e": 2043,
"s": 1693,
"text": "class Solution{ public: int Countpair(int arr[], int n, int sum){ // Complete the function unordered_map<int,int> m; int pair=0; for(int i=0;i<n;i++) { int b=sum-arr[i]; if(m[b]) { pair++; } ++m[arr[i]]; } if(pair==0) return -1; else return pair; }};"
},
{
"code": null,
"e": 2045,
"s": 2043,
"text": "0"
},
{
"code": null,
"e": 2068,
"s": 2045,
"text": "sharib_saifi1 week ago"
},
{
"code": null,
"e": 2091,
"s": 2068,
"text": "//Simple java Solution"
},
{
"code": null,
"e": 2469,
"s": 2091,
"text": "class Solution{ int Countpair(int a[], int n, int sum) { // Complete the function int temp=0; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(a[i] + a[j] == sum){ temp++; } } } if(temp == 0){ return -1; } else{ return temp; } } }"
},
{
"code": null,
"e": 2471,
"s": 2469,
"text": "0"
},
{
"code": null,
"e": 2496,
"s": 2471,
"text": "tuwodabhinav071 week ago"
},
{
"code": null,
"e": 3103,
"s": 2496,
"text": "int count=0; for(int i=0;i<n;i++) { int low=i+1; int high=n-1; while(low<=high) { int mid=low+(high-low)/2; if(arr[i]+arr[mid]==sum) { count++; break; } else if(arr[i]+arr[mid]<sum) { low=mid+1; } else if(arr[i]+arr[mid]>sum) { high=mid-1; } } } if(count==0) return -1; else return count; "
},
{
"code": null,
"e": 3105,
"s": 3103,
"text": "0"
},
{
"code": null,
"e": 3127,
"s": 3105,
"text": "imkprakash2 weeks ago"
},
{
"code": null,
"e": 3142,
"s": 3127,
"text": "C++ solution :"
},
{
"code": null,
"e": 3166,
"s": 3142,
"text": "Time taken : 0.01/ 2.62"
},
{
"code": null,
"e": 3662,
"s": 3166,
"text": "class Solution{\n public:\n int Countpair(int arr[], int n, int sum){\n \n // Complete the function\n int count=0;\n int i=0, j=n-1;\n while(i<j){\n if(arr[i]+arr[j] == sum){\n count++;\n i++;\n j--;\n }\n else if(arr[i]+arr[j]<sum){\n i++;\n }\n else{\n j--;\n }\n }\n if(count) return count;\n return -1;\n }\n};"
},
{
"code": null,
"e": 3664,
"s": 3662,
"text": "0"
},
{
"code": null,
"e": 3685,
"s": 3664,
"text": "kmani33072 weeks ago"
},
{
"code": null,
"e": 4043,
"s": 3685,
"text": "int c=0; // Complete the function int i=0,j=1; while(i<n){ if(j<n && arr[i]+arr[j]<sum){ j++; } else if(arr[i]+arr[j]==sum){ c+=1; i++; j=i+1; } else{ i++; j=i+1; } } return c>0?c:-1;"
},
{
"code": null,
"e": 4045,
"s": 4043,
"text": "0"
},
{
"code": null,
"e": 4067,
"s": 4045,
"text": "2020bec0654 weeks ago"
},
{
"code": null,
"e": 4468,
"s": 4067,
"text": " // Complete the function sort(arr,arr+n); int l=0; int r=n-1; int ans=-1; while(l<r) { if(arr[l]+arr[r]==sum) { ans++; } if(arr[l]+arr[r]>sum) { r--; } else { l++; } } if(ans==-1){ return ans; } return ans+1; }"
},
{
"code": null,
"e": 4470,
"s": 4468,
"text": "0"
},
{
"code": null,
"e": 4495,
"s": 4470,
"text": "patildhiren441 month ago"
},
{
"code": null,
"e": 4503,
"s": 4495,
"text": "JAVA - "
},
{
"code": null,
"e": 4975,
"s": 4503,
"text": "int Countpair(int[] arr, int n, int tar)\n {\n int i = 0;\n int j = arr.length - 1;\n int cou = 0;\n while (i < j) {\n int sum = arr[i] + arr[j];\n\n if (sum == tar) {\n i++;\n j--;\n cou++;\n } else if (sum > tar) {\n j--;\n } else {\n i++;\n }\n }\n if (cou == 0)\n return -1;\n return cou;\n }"
},
{
"code": null,
"e": 4977,
"s": 4975,
"text": "0"
},
{
"code": null,
"e": 5005,
"s": 4977,
"text": "vishwakarma123411 month ago"
},
{
"code": null,
"e": 5455,
"s": 5005,
"text": "int Countpair(int arr[], int n, int k){\n \n // Complete the function\n map<int ,int>mc;\n int count=0;\n for(int i=0;i<n;i++)\n {\n int b=k-arr[i];//b=k-arr[i]\n if(mc[b]);//freq of b\n count+=mc[b];//adding freq to count\n mc[arr[i]]++;//incrementing occurences(hashing)\n }\n if(count)\n return count;\n else \n return -1;\n }"
},
{
"code": null,
"e": 5457,
"s": 5455,
"text": "0"
},
{
"code": null,
"e": 5474,
"s": 5457,
"text": "ssrkb1 month ago"
},
{
"code": null,
"e": 5509,
"s": 5474,
"text": " TIME COMPLEXITY - 0.02/2.62"
},
{
"code": null,
"e": 5802,
"s": 5509,
"text": " int count=0; int l=0,r=n-1; while(l<r){ if(a[l]+a[r] == sum){ count++; l++; r--; } else{ if(a[l]+a[r]<sum) l++; else r--; } } return count==0?-1:count;"
},
{
"code": null,
"e": 5948,
"s": 5802,
"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": 5984,
"s": 5948,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5994,
"s": 5984,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6004,
"s": 5994,
"text": "\nContest\n"
},
{
"code": null,
"e": 6067,
"s": 6004,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6252,
"s": 6067,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6536,
"s": 6252,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 6682,
"s": 6536,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 6759,
"s": 6682,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 6800,
"s": 6759,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 6828,
"s": 6800,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 6899,
"s": 6828,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 7086,
"s": 6899,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
Python | Tools in the world of Web Scraping
|
03 May, 2018
Web page scraping can be done using multiple tools or using different frameworks in Python. There are variety of options available for scraping data from a web page, each suiting different needs.
First, let’s understand the difference between web-scraping and web-crawling. Web crawling is used to index the information on the page using bots also known as Crawlers. On the other hand, Web-scraping is an automated way of extracting the information/content using bots also known as Scrapers.
Let see some most commonly used web Scraping tools for Python3 :
Urllib2RequestsBeautifulSoupLxmlSeleniumMechanicalSoup
Urllib2
Requests
BeautifulSoup
Lxml
Selenium
MechanicalSoup
Among all the available frameworks/ tools, only urllib2 come pre-installed with Python. So all other tools need to be installed, if needed. Let’s discuss all these tools in detail.
Urllib2 : Urllib2 is a python module used for fetching URL’s. It offers a very simple interface, in the form of urlopen function, which is capable of fetching URL’s using different protocols like HTTP, FTP etc.# Using urllib2 modulefrom urllib.request import urlopen html = urlopen("http://geeksforgeeks.org") print(html.read())Output :Requests : Requests does not come pre-installed with Python. Requests allows to send HTTP/1.1 requests. One can add headers, form data, multipart files and parameters with simple Python dictionaries and access the response data in the same way.Installing requests can be done using pip.pip install requests# Using requests moduleimport requests # get URLreq = requests.get('https://www.geeksforgeeks.org/') print(req.encoding) print(req.status_code) print(req.elapsed) print(req.url) print(req.history) print(req.headers['Content-Type'])Output :BeautifulSoup : Beautiful soup is a parsing library that can use different parsers. Beautiful Soup’s default parser comes from Python’s standard library. It creates a parse tree that can be used to extract data from HTML; a toolkit for dissecting a document and extracting what you need. It automatically converts incoming documents to Unicode and outgoing documents to UTF-8.pip can be used to install BeautifulSoup :pip install beautifulsoup4# importing BeautifulSoup form# bs4 modulefrom bs4 import BeautifulSoup # importing requestsimport requests # get URLr = requests.get("https://www.geeksforgeeks.org") data = r.textsoup = BeautifulSoup(data) for link in soup.find_all('a'): print(link.get('href'))Output :Lxml : Lxml is a high-performance, production-quality HTML and XML parsing library. If the user need speed, then go for Lxml. Lxml has many modules and one of the module is etree , which is responsible for creating elements and structure using these elements.One can start using lxml by installing it as a python package using pip tool :pip install lxml# importing etree from lxml modulefrom lxml import etree root_elem = etree.Element('html')etree.SubElement(root_elem, 'head')etree.SubElement(root_elem, 'title')etree.SubElement(root_elem, 'body') print(etree.tostring(root_elem, pretty_print = True).decode("utf-8"))Output :Selenium : Some websites use javascript to serve content. For example, they might wait until you scroll down on the page or click a button before loading certain content. For these websites, selenium is needed. Selenium is a tool that automates browsers, also known as web-drivers. It also comes with Python bindings for controlling it right from your application.pip package is used to install selenium :pip install selenium# importing webdriver from selenium modulefrom selenium import webdriver # path for chromedriverpath_to_chromedriver ='/Users/Admin/Desktop/chromedriver' browser = webdriver.Chrome(executable_path = path_to_chromedriver) url = 'https://www.geeksforgeeks.org'browser.get(url)Output :MechanicalSoup : MechanicalSoup is a Python library for automating interaction with websites. It automatically stores and sends cookies, follows redirects, and can follow links and submit forms. It doesn’t do JavaScript.One can use following command to install MechanicalSoup :pip install MechanicalSoup# importing mechanicalsoupimport mechanicalsoup browser = mechanicalsoup.StatefulBrowser()value = browser.open("http://geeksforgeeks.org/")print(value) value1 = browser.get_url()print(value1) value2 = browser.follow_link("forms")print(value2) value = browser.get_url()print(value)Scrapy : Scrapy is an open source and collaborative web crawling framework for extracting the data needed from websites. It was originally designed for web scraping. It can be used to manage requests, preserve user sessions follow redirects and handle output pipelines.There are 2-methods to install scrapy :Using pip :pip install scrapyUsing Anaconda : First install Anaconda or Miniconda and then use following command to install scrapy :conda install -c conda-forge scrapy# importing scrapy moduleimport scrapy class GeeksSpider(scrapy.Spider): name = "geeks_spider" start_urls = ['https://www.geeksforgeeks.org'] # Parse function def parse(self, response): SET_SELECTOR = 'geeks' for geek in response.css(SET_SELECTOR): passUse following command to run a scrapy code :scrapy runspider samplescapy.pyOutput :
Urllib2 : Urllib2 is a python module used for fetching URL’s. It offers a very simple interface, in the form of urlopen function, which is capable of fetching URL’s using different protocols like HTTP, FTP etc.# Using urllib2 modulefrom urllib.request import urlopen html = urlopen("http://geeksforgeeks.org") print(html.read())Output :
# Using urllib2 modulefrom urllib.request import urlopen html = urlopen("http://geeksforgeeks.org") print(html.read())
Output :
Requests : Requests does not come pre-installed with Python. Requests allows to send HTTP/1.1 requests. One can add headers, form data, multipart files and parameters with simple Python dictionaries and access the response data in the same way.Installing requests can be done using pip.pip install requests# Using requests moduleimport requests # get URLreq = requests.get('https://www.geeksforgeeks.org/') print(req.encoding) print(req.status_code) print(req.elapsed) print(req.url) print(req.history) print(req.headers['Content-Type'])Output :
Installing requests can be done using pip.
pip install requests
# Using requests moduleimport requests # get URLreq = requests.get('https://www.geeksforgeeks.org/') print(req.encoding) print(req.status_code) print(req.elapsed) print(req.url) print(req.history) print(req.headers['Content-Type'])
Output :
BeautifulSoup : Beautiful soup is a parsing library that can use different parsers. Beautiful Soup’s default parser comes from Python’s standard library. It creates a parse tree that can be used to extract data from HTML; a toolkit for dissecting a document and extracting what you need. It automatically converts incoming documents to Unicode and outgoing documents to UTF-8.pip can be used to install BeautifulSoup :pip install beautifulsoup4# importing BeautifulSoup form# bs4 modulefrom bs4 import BeautifulSoup # importing requestsimport requests # get URLr = requests.get("https://www.geeksforgeeks.org") data = r.textsoup = BeautifulSoup(data) for link in soup.find_all('a'): print(link.get('href'))Output :
pip can be used to install BeautifulSoup :
pip install beautifulsoup4
# importing BeautifulSoup form# bs4 modulefrom bs4 import BeautifulSoup # importing requestsimport requests # get URLr = requests.get("https://www.geeksforgeeks.org") data = r.textsoup = BeautifulSoup(data) for link in soup.find_all('a'): print(link.get('href'))
Output :
Lxml : Lxml is a high-performance, production-quality HTML and XML parsing library. If the user need speed, then go for Lxml. Lxml has many modules and one of the module is etree , which is responsible for creating elements and structure using these elements.One can start using lxml by installing it as a python package using pip tool :pip install lxml# importing etree from lxml modulefrom lxml import etree root_elem = etree.Element('html')etree.SubElement(root_elem, 'head')etree.SubElement(root_elem, 'title')etree.SubElement(root_elem, 'body') print(etree.tostring(root_elem, pretty_print = True).decode("utf-8"))Output :
One can start using lxml by installing it as a python package using pip tool :
pip install lxml
# importing etree from lxml modulefrom lxml import etree root_elem = etree.Element('html')etree.SubElement(root_elem, 'head')etree.SubElement(root_elem, 'title')etree.SubElement(root_elem, 'body') print(etree.tostring(root_elem, pretty_print = True).decode("utf-8"))
Output :
Selenium : Some websites use javascript to serve content. For example, they might wait until you scroll down on the page or click a button before loading certain content. For these websites, selenium is needed. Selenium is a tool that automates browsers, also known as web-drivers. It also comes with Python bindings for controlling it right from your application.pip package is used to install selenium :pip install selenium# importing webdriver from selenium modulefrom selenium import webdriver # path for chromedriverpath_to_chromedriver ='/Users/Admin/Desktop/chromedriver' browser = webdriver.Chrome(executable_path = path_to_chromedriver) url = 'https://www.geeksforgeeks.org'browser.get(url)Output :
pip package is used to install selenium :
pip install selenium
# importing webdriver from selenium modulefrom selenium import webdriver # path for chromedriverpath_to_chromedriver ='/Users/Admin/Desktop/chromedriver' browser = webdriver.Chrome(executable_path = path_to_chromedriver) url = 'https://www.geeksforgeeks.org'browser.get(url)
Output :
MechanicalSoup : MechanicalSoup is a Python library for automating interaction with websites. It automatically stores and sends cookies, follows redirects, and can follow links and submit forms. It doesn’t do JavaScript.One can use following command to install MechanicalSoup :pip install MechanicalSoup# importing mechanicalsoupimport mechanicalsoup browser = mechanicalsoup.StatefulBrowser()value = browser.open("http://geeksforgeeks.org/")print(value) value1 = browser.get_url()print(value1) value2 = browser.follow_link("forms")print(value2) value = browser.get_url()print(value)
One can use following command to install MechanicalSoup :
pip install MechanicalSoup
# importing mechanicalsoupimport mechanicalsoup browser = mechanicalsoup.StatefulBrowser()value = browser.open("http://geeksforgeeks.org/")print(value) value1 = browser.get_url()print(value1) value2 = browser.follow_link("forms")print(value2) value = browser.get_url()print(value)
Scrapy : Scrapy is an open source and collaborative web crawling framework for extracting the data needed from websites. It was originally designed for web scraping. It can be used to manage requests, preserve user sessions follow redirects and handle output pipelines.There are 2-methods to install scrapy :Using pip :pip install scrapyUsing Anaconda : First install Anaconda or Miniconda and then use following command to install scrapy :conda install -c conda-forge scrapy# importing scrapy moduleimport scrapy class GeeksSpider(scrapy.Spider): name = "geeks_spider" start_urls = ['https://www.geeksforgeeks.org'] # Parse function def parse(self, response): SET_SELECTOR = 'geeks' for geek in response.css(SET_SELECTOR): passUse following command to run a scrapy code :scrapy runspider samplescapy.pyOutput :
There are 2-methods to install scrapy :
Using pip :pip install scrapyUsing Anaconda : First install Anaconda or Miniconda and then use following command to install scrapy :conda install -c conda-forge scrapy
Using pip :pip install scrapy
pip install scrapy
Using Anaconda : First install Anaconda or Miniconda and then use following command to install scrapy :conda install -c conda-forge scrapy
conda install -c conda-forge scrapy
# importing scrapy moduleimport scrapy class GeeksSpider(scrapy.Spider): name = "geeks_spider" start_urls = ['https://www.geeksforgeeks.org'] # Parse function def parse(self, response): SET_SELECTOR = 'geeks' for geek in response.css(SET_SELECTOR): pass
Use following command to run a scrapy code :
scrapy runspider samplescapy.py
Output :
Above discussed module are most commonly used scrappers for Python3. Although there are few more but no longer compatible with Python3 like Mechanize, Scrapemark.
References :
https://elitedatascience.com/python-web-scraping-librarieshttps://python.gotrained.com/python-web-scraping-libraries/http://blog.datahut.co/beginners-guide-to-web-scraping-with-python-lxml/
https://elitedatascience.com/python-web-scraping-libraries
https://python.gotrained.com/python-web-scraping-libraries/
http://blog.datahut.co/beginners-guide-to-web-scraping-with-python-lxml/
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 May, 2018"
},
{
"code": null,
"e": 250,
"s": 54,
"text": "Web page scraping can be done using multiple tools or using different frameworks in Python. There are variety of options available for scraping data from a web page, each suiting different needs."
},
{
"code": null,
"e": 546,
"s": 250,
"text": "First, let’s understand the difference between web-scraping and web-crawling. Web crawling is used to index the information on the page using bots also known as Crawlers. On the other hand, Web-scraping is an automated way of extracting the information/content using bots also known as Scrapers."
},
{
"code": null,
"e": 611,
"s": 546,
"text": "Let see some most commonly used web Scraping tools for Python3 :"
},
{
"code": null,
"e": 666,
"s": 611,
"text": "Urllib2RequestsBeautifulSoupLxmlSeleniumMechanicalSoup"
},
{
"code": null,
"e": 674,
"s": 666,
"text": "Urllib2"
},
{
"code": null,
"e": 683,
"s": 674,
"text": "Requests"
},
{
"code": null,
"e": 697,
"s": 683,
"text": "BeautifulSoup"
},
{
"code": null,
"e": 702,
"s": 697,
"text": "Lxml"
},
{
"code": null,
"e": 711,
"s": 702,
"text": "Selenium"
},
{
"code": null,
"e": 726,
"s": 711,
"text": "MechanicalSoup"
},
{
"code": null,
"e": 907,
"s": 726,
"text": "Among all the available frameworks/ tools, only urllib2 come pre-installed with Python. So all other tools need to be installed, if needed. Let’s discuss all these tools in detail."
},
{
"code": null,
"e": 5337,
"s": 907,
"text": "Urllib2 : Urllib2 is a python module used for fetching URL’s. It offers a very simple interface, in the form of urlopen function, which is capable of fetching URL’s using different protocols like HTTP, FTP etc.# Using urllib2 modulefrom urllib.request import urlopen html = urlopen(\"http://geeksforgeeks.org\") print(html.read())Output :Requests : Requests does not come pre-installed with Python. Requests allows to send HTTP/1.1 requests. One can add headers, form data, multipart files and parameters with simple Python dictionaries and access the response data in the same way.Installing requests can be done using pip.pip install requests# Using requests moduleimport requests # get URLreq = requests.get('https://www.geeksforgeeks.org/') print(req.encoding) print(req.status_code) print(req.elapsed) print(req.url) print(req.history) print(req.headers['Content-Type'])Output :BeautifulSoup : Beautiful soup is a parsing library that can use different parsers. Beautiful Soup’s default parser comes from Python’s standard library. It creates a parse tree that can be used to extract data from HTML; a toolkit for dissecting a document and extracting what you need. It automatically converts incoming documents to Unicode and outgoing documents to UTF-8.pip can be used to install BeautifulSoup :pip install beautifulsoup4# importing BeautifulSoup form# bs4 modulefrom bs4 import BeautifulSoup # importing requestsimport requests # get URLr = requests.get(\"https://www.geeksforgeeks.org\") data = r.textsoup = BeautifulSoup(data) for link in soup.find_all('a'): print(link.get('href'))Output :Lxml : Lxml is a high-performance, production-quality HTML and XML parsing library. If the user need speed, then go for Lxml. Lxml has many modules and one of the module is etree , which is responsible for creating elements and structure using these elements.One can start using lxml by installing it as a python package using pip tool :pip install lxml# importing etree from lxml modulefrom lxml import etree root_elem = etree.Element('html')etree.SubElement(root_elem, 'head')etree.SubElement(root_elem, 'title')etree.SubElement(root_elem, 'body') print(etree.tostring(root_elem, pretty_print = True).decode(\"utf-8\"))Output :Selenium : Some websites use javascript to serve content. For example, they might wait until you scroll down on the page or click a button before loading certain content. For these websites, selenium is needed. Selenium is a tool that automates browsers, also known as web-drivers. It also comes with Python bindings for controlling it right from your application.pip package is used to install selenium :pip install selenium# importing webdriver from selenium modulefrom selenium import webdriver # path for chromedriverpath_to_chromedriver ='/Users/Admin/Desktop/chromedriver' browser = webdriver.Chrome(executable_path = path_to_chromedriver) url = 'https://www.geeksforgeeks.org'browser.get(url)Output :MechanicalSoup : MechanicalSoup is a Python library for automating interaction with websites. It automatically stores and sends cookies, follows redirects, and can follow links and submit forms. It doesn’t do JavaScript.One can use following command to install MechanicalSoup :pip install MechanicalSoup# importing mechanicalsoupimport mechanicalsoup browser = mechanicalsoup.StatefulBrowser()value = browser.open(\"http://geeksforgeeks.org/\")print(value) value1 = browser.get_url()print(value1) value2 = browser.follow_link(\"forms\")print(value2) value = browser.get_url()print(value)Scrapy : Scrapy is an open source and collaborative web crawling framework for extracting the data needed from websites. It was originally designed for web scraping. It can be used to manage requests, preserve user sessions follow redirects and handle output pipelines.There are 2-methods to install scrapy :Using pip :pip install scrapyUsing Anaconda : First install Anaconda or Miniconda and then use following command to install scrapy :conda install -c conda-forge scrapy# importing scrapy moduleimport scrapy class GeeksSpider(scrapy.Spider): name = \"geeks_spider\" start_urls = ['https://www.geeksforgeeks.org'] # Parse function def parse(self, response): SET_SELECTOR = 'geeks' for geek in response.css(SET_SELECTOR): passUse following command to run a scrapy code :scrapy runspider samplescapy.pyOutput :"
},
{
"code": null,
"e": 5676,
"s": 5337,
"text": "Urllib2 : Urllib2 is a python module used for fetching URL’s. It offers a very simple interface, in the form of urlopen function, which is capable of fetching URL’s using different protocols like HTTP, FTP etc.# Using urllib2 modulefrom urllib.request import urlopen html = urlopen(\"http://geeksforgeeks.org\") print(html.read())Output :"
},
{
"code": "# Using urllib2 modulefrom urllib.request import urlopen html = urlopen(\"http://geeksforgeeks.org\") print(html.read())",
"e": 5797,
"s": 5676,
"text": null
},
{
"code": null,
"e": 5806,
"s": 5797,
"text": "Output :"
},
{
"code": null,
"e": 6374,
"s": 5806,
"text": "Requests : Requests does not come pre-installed with Python. Requests allows to send HTTP/1.1 requests. One can add headers, form data, multipart files and parameters with simple Python dictionaries and access the response data in the same way.Installing requests can be done using pip.pip install requests# Using requests moduleimport requests # get URLreq = requests.get('https://www.geeksforgeeks.org/') print(req.encoding) print(req.status_code) print(req.elapsed) print(req.url) print(req.history) print(req.headers['Content-Type'])Output :"
},
{
"code": null,
"e": 6417,
"s": 6374,
"text": "Installing requests can be done using pip."
},
{
"code": null,
"e": 6438,
"s": 6417,
"text": "pip install requests"
},
{
"code": "# Using requests moduleimport requests # get URLreq = requests.get('https://www.geeksforgeeks.org/') print(req.encoding) print(req.status_code) print(req.elapsed) print(req.url) print(req.history) print(req.headers['Content-Type'])",
"e": 6692,
"s": 6438,
"text": null
},
{
"code": null,
"e": 6701,
"s": 6692,
"text": "Output :"
},
{
"code": null,
"e": 7423,
"s": 6701,
"text": "BeautifulSoup : Beautiful soup is a parsing library that can use different parsers. Beautiful Soup’s default parser comes from Python’s standard library. It creates a parse tree that can be used to extract data from HTML; a toolkit for dissecting a document and extracting what you need. It automatically converts incoming documents to Unicode and outgoing documents to UTF-8.pip can be used to install BeautifulSoup :pip install beautifulsoup4# importing BeautifulSoup form# bs4 modulefrom bs4 import BeautifulSoup # importing requestsimport requests # get URLr = requests.get(\"https://www.geeksforgeeks.org\") data = r.textsoup = BeautifulSoup(data) for link in soup.find_all('a'): print(link.get('href'))Output :"
},
{
"code": null,
"e": 7466,
"s": 7423,
"text": "pip can be used to install BeautifulSoup :"
},
{
"code": null,
"e": 7493,
"s": 7466,
"text": "pip install beautifulsoup4"
},
{
"code": "# importing BeautifulSoup form# bs4 modulefrom bs4 import BeautifulSoup # importing requestsimport requests # get URLr = requests.get(\"https://www.geeksforgeeks.org\") data = r.textsoup = BeautifulSoup(data) for link in soup.find_all('a'): print(link.get('href'))",
"e": 7763,
"s": 7493,
"text": null
},
{
"code": null,
"e": 7772,
"s": 7763,
"text": "Output :"
},
{
"code": null,
"e": 8402,
"s": 7772,
"text": "Lxml : Lxml is a high-performance, production-quality HTML and XML parsing library. If the user need speed, then go for Lxml. Lxml has many modules and one of the module is etree , which is responsible for creating elements and structure using these elements.One can start using lxml by installing it as a python package using pip tool :pip install lxml# importing etree from lxml modulefrom lxml import etree root_elem = etree.Element('html')etree.SubElement(root_elem, 'head')etree.SubElement(root_elem, 'title')etree.SubElement(root_elem, 'body') print(etree.tostring(root_elem, pretty_print = True).decode(\"utf-8\"))Output :"
},
{
"code": null,
"e": 8481,
"s": 8402,
"text": "One can start using lxml by installing it as a python package using pip tool :"
},
{
"code": null,
"e": 8498,
"s": 8481,
"text": "pip install lxml"
},
{
"code": "# importing etree from lxml modulefrom lxml import etree root_elem = etree.Element('html')etree.SubElement(root_elem, 'head')etree.SubElement(root_elem, 'title')etree.SubElement(root_elem, 'body') print(etree.tostring(root_elem, pretty_print = True).decode(\"utf-8\"))",
"e": 8767,
"s": 8498,
"text": null
},
{
"code": null,
"e": 8776,
"s": 8767,
"text": "Output :"
},
{
"code": null,
"e": 9487,
"s": 8776,
"text": "Selenium : Some websites use javascript to serve content. For example, they might wait until you scroll down on the page or click a button before loading certain content. For these websites, selenium is needed. Selenium is a tool that automates browsers, also known as web-drivers. It also comes with Python bindings for controlling it right from your application.pip package is used to install selenium :pip install selenium# importing webdriver from selenium modulefrom selenium import webdriver # path for chromedriverpath_to_chromedriver ='/Users/Admin/Desktop/chromedriver' browser = webdriver.Chrome(executable_path = path_to_chromedriver) url = 'https://www.geeksforgeeks.org'browser.get(url)Output :"
},
{
"code": null,
"e": 9529,
"s": 9487,
"text": "pip package is used to install selenium :"
},
{
"code": null,
"e": 9550,
"s": 9529,
"text": "pip install selenium"
},
{
"code": "# importing webdriver from selenium modulefrom selenium import webdriver # path for chromedriverpath_to_chromedriver ='/Users/Admin/Desktop/chromedriver' browser = webdriver.Chrome(executable_path = path_to_chromedriver) url = 'https://www.geeksforgeeks.org'browser.get(url)",
"e": 9828,
"s": 9550,
"text": null
},
{
"code": null,
"e": 9837,
"s": 9828,
"text": "Output :"
},
{
"code": null,
"e": 10425,
"s": 9837,
"text": "MechanicalSoup : MechanicalSoup is a Python library for automating interaction with websites. It automatically stores and sends cookies, follows redirects, and can follow links and submit forms. It doesn’t do JavaScript.One can use following command to install MechanicalSoup :pip install MechanicalSoup# importing mechanicalsoupimport mechanicalsoup browser = mechanicalsoup.StatefulBrowser()value = browser.open(\"http://geeksforgeeks.org/\")print(value) value1 = browser.get_url()print(value1) value2 = browser.follow_link(\"forms\")print(value2) value = browser.get_url()print(value)"
},
{
"code": null,
"e": 10483,
"s": 10425,
"text": "One can use following command to install MechanicalSoup :"
},
{
"code": null,
"e": 10510,
"s": 10483,
"text": "pip install MechanicalSoup"
},
{
"code": "# importing mechanicalsoupimport mechanicalsoup browser = mechanicalsoup.StatefulBrowser()value = browser.open(\"http://geeksforgeeks.org/\")print(value) value1 = browser.get_url()print(value1) value2 = browser.follow_link(\"forms\")print(value2) value = browser.get_url()print(value)",
"e": 10795,
"s": 10510,
"text": null
},
{
"code": null,
"e": 11673,
"s": 10795,
"text": "Scrapy : Scrapy is an open source and collaborative web crawling framework for extracting the data needed from websites. It was originally designed for web scraping. It can be used to manage requests, preserve user sessions follow redirects and handle output pipelines.There are 2-methods to install scrapy :Using pip :pip install scrapyUsing Anaconda : First install Anaconda or Miniconda and then use following command to install scrapy :conda install -c conda-forge scrapy# importing scrapy moduleimport scrapy class GeeksSpider(scrapy.Spider): name = \"geeks_spider\" start_urls = ['https://www.geeksforgeeks.org'] # Parse function def parse(self, response): SET_SELECTOR = 'geeks' for geek in response.css(SET_SELECTOR): passUse following command to run a scrapy code :scrapy runspider samplescapy.pyOutput :"
},
{
"code": null,
"e": 11713,
"s": 11673,
"text": "There are 2-methods to install scrapy :"
},
{
"code": null,
"e": 11881,
"s": 11713,
"text": "Using pip :pip install scrapyUsing Anaconda : First install Anaconda or Miniconda and then use following command to install scrapy :conda install -c conda-forge scrapy"
},
{
"code": null,
"e": 11911,
"s": 11881,
"text": "Using pip :pip install scrapy"
},
{
"code": null,
"e": 11930,
"s": 11911,
"text": "pip install scrapy"
},
{
"code": null,
"e": 12069,
"s": 11930,
"text": "Using Anaconda : First install Anaconda or Miniconda and then use following command to install scrapy :conda install -c conda-forge scrapy"
},
{
"code": null,
"e": 12105,
"s": 12069,
"text": "conda install -c conda-forge scrapy"
},
{
"code": "# importing scrapy moduleimport scrapy class GeeksSpider(scrapy.Spider): name = \"geeks_spider\" start_urls = ['https://www.geeksforgeeks.org'] # Parse function def parse(self, response): SET_SELECTOR = 'geeks' for geek in response.css(SET_SELECTOR): pass",
"e": 12425,
"s": 12105,
"text": null
},
{
"code": null,
"e": 12470,
"s": 12425,
"text": "Use following command to run a scrapy code :"
},
{
"code": null,
"e": 12502,
"s": 12470,
"text": "scrapy runspider samplescapy.py"
},
{
"code": null,
"e": 12511,
"s": 12502,
"text": "Output :"
},
{
"code": null,
"e": 12674,
"s": 12511,
"text": "Above discussed module are most commonly used scrappers for Python3. Although there are few more but no longer compatible with Python3 like Mechanize, Scrapemark."
},
{
"code": null,
"e": 12687,
"s": 12674,
"text": "References :"
},
{
"code": null,
"e": 12877,
"s": 12687,
"text": "https://elitedatascience.com/python-web-scraping-librarieshttps://python.gotrained.com/python-web-scraping-libraries/http://blog.datahut.co/beginners-guide-to-web-scraping-with-python-lxml/"
},
{
"code": null,
"e": 12936,
"s": 12877,
"text": "https://elitedatascience.com/python-web-scraping-libraries"
},
{
"code": null,
"e": 12996,
"s": 12936,
"text": "https://python.gotrained.com/python-web-scraping-libraries/"
},
{
"code": null,
"e": 13069,
"s": 12996,
"text": "http://blog.datahut.co/beginners-guide-to-web-scraping-with-python-lxml/"
},
{
"code": null,
"e": 13084,
"s": 13069,
"text": "python-modules"
},
{
"code": null,
"e": 13091,
"s": 13084,
"text": "Python"
}
] |
Check if two nodes in a Binary Tree are siblings
|
18 Aug, 2021
Given a binary tree and two nodes, the task is to check if the nodes are siblings of each other or not.
Two nodes are said to be siblings if they are present at the same level, and their parents are same.
Examples:
Input :
1
/ \
2 3
/ \ / \
4 5 6 7
First node is 4 and Second node is 6.
Output : No, they are not siblings.
Input :
1
/ \
5 6
/ / \
7 3 4
First node is 3 and Second node is 4
Output : Yes
Approach: On observing carefully, it can be concluded that any node in a binary tree can have maximum of two child nodes. So, since the parent of two siblings must be same, so the idea is to simply traverse the tree and for every node check if the two given nodes are its children. If it is true for any node in the tree then print YES otherwise print NO.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to check if two nodes are// siblings #include <bits/stdc++.h>using namespace std; // Binary Tree Nodestruct Node { int data; Node *left, *right;}; // Utility function to create a new nodestruct Node* newNode(int data){ struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node);} // Function to find out if two nodes are siblingsbool CheckIfNodesAreSiblings(Node* root, int data_one, int data_two){ if (!root) return false; // Compare the two given nodes with // the childrens of current node if (root->left && root->right) { int left = root->left->data; int right = root->right->data; if (left == data_one && right == data_two) return true; else if (left == data_two && right == data_one) return true; } // Check for left subtree if (root->left) if(CheckIfNodesAreSiblings(root->left, data_one, data_two)) return true; // Check for right subtree if (root->right) if(CheckIfNodesAreSiblings(root->right, data_one, data_two)) return true;} // Driver codeint main(){ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->right->left = newNode(5); root->right->right = newNode(6); root->left->left->right = newNode(7); int data_one = 5; int data_two = 6; if (CheckIfNodesAreSiblings(root, data_one, data_two)) cout << "YES"; else cout << "NO"; return 0;}
// Java program to check if two nodes// are siblingsimport java.util.*; class GFG{ // Binary Tree Nodestatic class Node{ int data; Node left, right;}; // Utility function to create a// new nodestatic Node newNode(int data){ Node node = new Node(); node.data = data; node.left = node.right = null; return (node);}static Node root = null; // Function to find out if two nodes are siblingsstatic boolean CheckIfNodesAreSiblings(Node root, int data_one, int data_two){ if (root == null) return false; // Compare the two given nodes with // the childrens of current node if (root.left != null && root.right != null) { int left = root.left.data; int right = root.right.data; if (left == data_one && right == data_two) return true; else if (left == data_two && right == data_one) return true; } // Check for left subtree if (root.left != null) CheckIfNodesAreSiblings(root.left, data_one, data_two); // Check for right subtree if (root.right != null) CheckIfNodesAreSiblings(root.right, data_one, data_two); return true;} // Driver codepublic static void main(String[] args){ root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.right.left = newNode(5); root.right.right = newNode(6); root.left.left.right = newNode(7); int data_one = 5; int data_two = 6; if (CheckIfNodesAreSiblings(root, data_one, data_two)) System.out.print("YES"); else System.out.print("NO");}} // This code is contributed by Rajput-Ji
# Python3 program to check if two# nodes are siblings # Binary Tree Nodeclass Node: def __init__(self, key): self.data = key self.left = None self.right = None # Function to find out if two nodes are siblingsdef CheckIfNodesAreSiblings(root, data_one, data_two): if (root == None): return False # Compare the two given nodes with # the childrens of current node ans = False if (root.left != None and root.right != None): left = root.left.data right = root.right.data if (left == data_one and right == data_two): return True elif (left == data_two and right == data_one): return True # Check for left subtree if (root.left != None): ans = ans or CheckIfNodesAreSiblings(root.left, data_one, data_two) # Check for right subtree if (root.right != None): ans = ans or CheckIfNodesAreSiblings(root.right, data_one, data_two) return ans # Driver codeif __name__ == '__main__': root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.right.left = Node(5) root.right.right = Node(6) root.left.left.right = Node(7) data_one = 5 data_two = 6 if (CheckIfNodesAreSiblings(root, data_one, data_two)): print("YES") else: print("NO") # This code is contributed by mohit kumar 29
// C# program to check if two nodes// are siblingsusing System; // Binary Tree Nodepublic class Node{ public int data; public Node left, right; // Utility function to create a // new node public Node(int item) { data = item; left = right = null; }} class GFG{ static Node root = null; // Function to find out if two// nodes are siblingsstatic bool CheckIfNodesAreSiblings(Node root, int data_one, int data_two){ if (root == null) { return false; } // Compare the two given nodes with // the childrens of current node if (root.left != null && root.right != null) { int left = root.left.data; int right = root.right.data; if (left == data_one && right == data_two) { return true; } else if (left == data_two && right == data_one) { return true; } } // Check for left subtree if (root.left != null) { CheckIfNodesAreSiblings(root.left, data_one, data_two); } // Check for right subtree if (root.right != null) { CheckIfNodesAreSiblings(root.right, data_one, data_two); } return true;} // Driver codestatic public void Main(){ GFG.root = new Node(1); GFG.root.left = new Node(2); GFG.root.right = new Node(3); GFG.root.left.left = new Node(4); GFG.root.right.left = new Node(5); GFG.root.right.right = new Node(6); GFG.root.left.left.right = new Node(7); int data_one = 5; int data_two = 6; if (CheckIfNodesAreSiblings(root, data_one, data_two)) { Console.WriteLine("YES"); } else { Console.WriteLine("NO"); }}} // This code is contributed by avanitrachhadiya2155
<script> // Javascript program to check if two nodes// are siblings // Binary Tree Nodeclass Node{ constructor(data) { this.data = data; this.left = this.right = null; }} let root = null; // Function to find out if two nodes are siblingsfunction CheckIfNodesAreSiblings( root, data_one, data_two){ if (root == null) return false; // Compare the two given nodes with // the childrens of current node if (root.left != null && root.right != null) { let left = root.left.data; let right = root.right.data; if (left == data_one && right == data_two) return true; else if (left == data_two && right == data_one) return true; } // Check for left subtree if (root.left != null) CheckIfNodesAreSiblings(root.left, data_one, data_two); // Check for right subtree if (root.right != null) CheckIfNodesAreSiblings(root.right, data_one, data_two); return true;} // Driver coderoot = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.right.left = new Node(5);root.right.right = new Node(6);root.left.left.right = new Node(7); let data_one = 5;let data_two = 6; if (CheckIfNodesAreSiblings(root, data_one, data_two)) document.write("YES");else document.write("NO"); // This code is contributed by unknown2108 </script>
YES
mohit kumar 29
Rajput-Ji
avanitrachhadiya2155
vaibhav tandon
unknown2108
rcrohith2011
Binary Tree
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Aug, 2021"
},
{
"code": null,
"e": 156,
"s": 52,
"text": "Given a binary tree and two nodes, the task is to check if the nodes are siblings of each other or not."
},
{
"code": null,
"e": 257,
"s": 156,
"text": "Two nodes are said to be siblings if they are present at the same level, and their parents are same."
},
{
"code": null,
"e": 268,
"s": 257,
"text": "Examples: "
},
{
"code": null,
"e": 540,
"s": 268,
"text": "Input : \n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\nFirst node is 4 and Second node is 6.\nOutput : No, they are not siblings.\n\nInput :\n 1\n / \\\n 5 6\n / / \\\n 7 3 4\nFirst node is 3 and Second node is 4\nOutput : Yes"
},
{
"code": null,
"e": 896,
"s": 540,
"text": "Approach: On observing carefully, it can be concluded that any node in a binary tree can have maximum of two child nodes. So, since the parent of two siblings must be same, so the idea is to simply traverse the tree and for every node check if the two given nodes are its children. If it is true for any node in the tree then print YES otherwise print NO."
},
{
"code": null,
"e": 949,
"s": 896,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 953,
"s": 949,
"text": "C++"
},
{
"code": null,
"e": 958,
"s": 953,
"text": "Java"
},
{
"code": null,
"e": 966,
"s": 958,
"text": "Python3"
},
{
"code": null,
"e": 969,
"s": 966,
"text": "C#"
},
{
"code": null,
"e": 980,
"s": 969,
"text": "Javascript"
},
{
"code": "// C++ program to check if two nodes are// siblings #include <bits/stdc++.h>using namespace std; // Binary Tree Nodestruct Node { int data; Node *left, *right;}; // Utility function to create a new nodestruct Node* newNode(int data){ struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node);} // Function to find out if two nodes are siblingsbool CheckIfNodesAreSiblings(Node* root, int data_one, int data_two){ if (!root) return false; // Compare the two given nodes with // the childrens of current node if (root->left && root->right) { int left = root->left->data; int right = root->right->data; if (left == data_one && right == data_two) return true; else if (left == data_two && right == data_one) return true; } // Check for left subtree if (root->left) if(CheckIfNodesAreSiblings(root->left, data_one, data_two)) return true; // Check for right subtree if (root->right) if(CheckIfNodesAreSiblings(root->right, data_one, data_two)) return true;} // Driver codeint main(){ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->right->left = newNode(5); root->right->right = newNode(6); root->left->left->right = newNode(7); int data_one = 5; int data_two = 6; if (CheckIfNodesAreSiblings(root, data_one, data_two)) cout << \"YES\"; else cout << \"NO\"; return 0;}",
"e": 2633,
"s": 980,
"text": null
},
{
"code": "// Java program to check if two nodes// are siblingsimport java.util.*; class GFG{ // Binary Tree Nodestatic class Node{ int data; Node left, right;}; // Utility function to create a// new nodestatic Node newNode(int data){ Node node = new Node(); node.data = data; node.left = node.right = null; return (node);}static Node root = null; // Function to find out if two nodes are siblingsstatic boolean CheckIfNodesAreSiblings(Node root, int data_one, int data_two){ if (root == null) return false; // Compare the two given nodes with // the childrens of current node if (root.left != null && root.right != null) { int left = root.left.data; int right = root.right.data; if (left == data_one && right == data_two) return true; else if (left == data_two && right == data_one) return true; } // Check for left subtree if (root.left != null) CheckIfNodesAreSiblings(root.left, data_one, data_two); // Check for right subtree if (root.right != null) CheckIfNodesAreSiblings(root.right, data_one, data_two); return true;} // Driver codepublic static void main(String[] args){ root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.right.left = newNode(5); root.right.right = newNode(6); root.left.left.right = newNode(7); int data_one = 5; int data_two = 6; if (CheckIfNodesAreSiblings(root, data_one, data_two)) System.out.print(\"YES\"); else System.out.print(\"NO\");}} // This code is contributed by Rajput-Ji",
"e": 4546,
"s": 2633,
"text": null
},
{
"code": "# Python3 program to check if two# nodes are siblings # Binary Tree Nodeclass Node: def __init__(self, key): self.data = key self.left = None self.right = None # Function to find out if two nodes are siblingsdef CheckIfNodesAreSiblings(root, data_one, data_two): if (root == None): return False # Compare the two given nodes with # the childrens of current node ans = False if (root.left != None and root.right != None): left = root.left.data right = root.right.data if (left == data_one and right == data_two): return True elif (left == data_two and right == data_one): return True # Check for left subtree if (root.left != None): ans = ans or CheckIfNodesAreSiblings(root.left, data_one, data_two) # Check for right subtree if (root.right != None): ans = ans or CheckIfNodesAreSiblings(root.right, data_one, data_two) return ans # Driver codeif __name__ == '__main__': root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.right.left = Node(5) root.right.right = Node(6) root.left.left.right = Node(7) data_one = 5 data_two = 6 if (CheckIfNodesAreSiblings(root, data_one, data_two)): print(\"YES\") else: print(\"NO\") # This code is contributed by mohit kumar 29",
"e": 6253,
"s": 4546,
"text": null
},
{
"code": "// C# program to check if two nodes// are siblingsusing System; // Binary Tree Nodepublic class Node{ public int data; public Node left, right; // Utility function to create a // new node public Node(int item) { data = item; left = right = null; }} class GFG{ static Node root = null; // Function to find out if two// nodes are siblingsstatic bool CheckIfNodesAreSiblings(Node root, int data_one, int data_two){ if (root == null) { return false; } // Compare the two given nodes with // the childrens of current node if (root.left != null && root.right != null) { int left = root.left.data; int right = root.right.data; if (left == data_one && right == data_two) { return true; } else if (left == data_two && right == data_one) { return true; } } // Check for left subtree if (root.left != null) { CheckIfNodesAreSiblings(root.left, data_one, data_two); } // Check for right subtree if (root.right != null) { CheckIfNodesAreSiblings(root.right, data_one, data_two); } return true;} // Driver codestatic public void Main(){ GFG.root = new Node(1); GFG.root.left = new Node(2); GFG.root.right = new Node(3); GFG.root.left.left = new Node(4); GFG.root.right.left = new Node(5); GFG.root.right.right = new Node(6); GFG.root.left.left.right = new Node(7); int data_one = 5; int data_two = 6; if (CheckIfNodesAreSiblings(root, data_one, data_two)) { Console.WriteLine(\"YES\"); } else { Console.WriteLine(\"NO\"); }}} // This code is contributed by avanitrachhadiya2155",
"e": 8163,
"s": 6253,
"text": null
},
{
"code": "<script> // Javascript program to check if two nodes// are siblings // Binary Tree Nodeclass Node{ constructor(data) { this.data = data; this.left = this.right = null; }} let root = null; // Function to find out if two nodes are siblingsfunction CheckIfNodesAreSiblings( root, data_one, data_two){ if (root == null) return false; // Compare the two given nodes with // the childrens of current node if (root.left != null && root.right != null) { let left = root.left.data; let right = root.right.data; if (left == data_one && right == data_two) return true; else if (left == data_two && right == data_one) return true; } // Check for left subtree if (root.left != null) CheckIfNodesAreSiblings(root.left, data_one, data_two); // Check for right subtree if (root.right != null) CheckIfNodesAreSiblings(root.right, data_one, data_two); return true;} // Driver coderoot = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.right.left = new Node(5);root.right.right = new Node(6);root.left.left.right = new Node(7); let data_one = 5;let data_two = 6; if (CheckIfNodesAreSiblings(root, data_one, data_two)) document.write(\"YES\");else document.write(\"NO\"); // This code is contributed by unknown2108 </script>",
"e": 9771,
"s": 8163,
"text": null
},
{
"code": null,
"e": 9775,
"s": 9771,
"text": "YES"
},
{
"code": null,
"e": 9792,
"s": 9777,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 9802,
"s": 9792,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 9823,
"s": 9802,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 9838,
"s": 9823,
"text": "vaibhav tandon"
},
{
"code": null,
"e": 9850,
"s": 9838,
"text": "unknown2108"
},
{
"code": null,
"e": 9863,
"s": 9850,
"text": "rcrohith2011"
},
{
"code": null,
"e": 9875,
"s": 9863,
"text": "Binary Tree"
},
{
"code": null,
"e": 9880,
"s": 9875,
"text": "Tree"
},
{
"code": null,
"e": 9885,
"s": 9880,
"text": "Tree"
}
] |
Log functions in Python
|
31 Oct, 2021
Python offers many inbuild logarithmic functions under the module “math” which allows us to compute logs using a single line. There are 4 variants of logarithmic functions, all of which are discussed in this article.1. log(a,(Base)) : This function is used to compute the natural logarithm (Base e) of a. If 2 arguments are passed, it computes the logarithm of the desired base of argument a, numerically value of log(a)/log(Base).
Syntax :
math.log(a,Base)
Parameters :
a : The numeric value
Base : Base to which the logarithm has to be computed.
Return Value :
Returns natural log if 1 argument is passed and log with
specified base if 2 arguments are passed.
Exceptions :
Raises ValueError if a negative no. is passed as argument.
Python3
# Python code to demonstrate the working of# log(a,Base) import math # Printing the log base e of 14print ("Natural logarithm of 14 is : ", end="")print (math.log(14)) # Printing the log base 5 of 14print ("Logarithm base 5 of 14 is : ", end="")print (math.log(14,5))
Output :
Natural logarithm of 14 is : 2.6390573296152584
Logarithm base 5 of 14 is : 1.6397385131955606
2. log2(a) : This function is used to compute the logarithm base 2 of a. Displays more accurate result than log(a,2).
Syntax :
math.log2(a)
Parameters :
a : The numeric value
Return Value :
Returns logarithm base 2 of a
Exceptions :
Raises ValueError if a negative no. is passed as argument.
Python3
# Python code to demonstrate the working of# log2(a) import math # Printing the log base 2 of 14print ("Logarithm base 2 of 14 is : ", end="")print (math.log2(14))
Output :
Logarithm base 2 of 14 is : 3.807354922057604
3. log10(a) : This function is used to compute the logarithm base 10 of a. Displays more accurate result than log(a,10).
Syntax :
math.log10(a)
Parameters :
a : The numeric value
Return Value :
Returns logarithm base 10 of a
Exceptions :
Raises ValueError if a negative no. is passed as argument.
Python3
# Python code to demonstrate the working of# log10(a) import math # Printing the log base 10 of 14print ("Logarithm base 10 of 14 is : ", end="")print (math.log10(14))
Output :
Logarithm base 10 of 14 is : 1.146128035678238
3. log1p(a) : This function is used to compute logarithm(1+a) .
Syntax :
math.log1p(a)
Parameters :
a : The numeric value
Return Value :
Returns log(1+a)
Exceptions :
Raises ValueError if a negative no. is passed as argument.
Python3
# Python code to demonstrate the working of# log1p(a) import math # Printing the log(1+a) of 14print ("Logarithm(1+a) value of 14 is : ", end="")print (math.log1p(14))
Output :
Logarithm(1+a) value of 14 is : 2.70805020110221
1. ValueError : This function returns value error if number is negative.
Python3
# Python code to demonstrate the Exception of# log(a) import math # Printing the log(a) of -14# Throws Exceptionprint ("log(a) value of -14 is : ", end="")print (math.log(-14))
Output :
log(a) value of -14 is :
Runtime Error :
Traceback (most recent call last):
File "/home/8a74e9d7e5adfdb902ab15712cbaafe2.py", line 9, in
print (math.log(-14))
ValueError: math domain error
One of the application of log10() function is that it is used to compute the no. of digits of a number. Code below illustrates the same.
Python3
# Python code to demonstrate the Application of# log10(a) import math # Printing no. of digits in 73293print ("The number of digits in 73293 are : ", end="")print (int(math.log10(73293) + 1))
Output :
The number of digits in 73293 are : 5
This article is contributed by Manjeet Singh. 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.
jatinchellani02
Python-Library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n31 Oct, 2021"
},
{
"code": null,
"e": 486,
"s": 53,
"text": "Python offers many inbuild logarithmic functions under the module “math” which allows us to compute logs using a single line. There are 4 variants of logarithmic functions, all of which are discussed in this article.1. log(a,(Base)) : This function is used to compute the natural logarithm (Base e) of a. If 2 arguments are passed, it computes the logarithm of the desired base of argument a, numerically value of log(a)/log(Base). "
},
{
"code": null,
"e": 792,
"s": 486,
"text": "Syntax :\nmath.log(a,Base)\nParameters : \na : The numeric value\nBase : Base to which the logarithm has to be computed.\nReturn Value : \nReturns natural log if 1 argument is passed and log with\nspecified base if 2 arguments are passed.\nExceptions : \nRaises ValueError if a negative no. is passed as argument."
},
{
"code": null,
"e": 800,
"s": 792,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of# log(a,Base) import math # Printing the log base e of 14print (\"Natural logarithm of 14 is : \", end=\"\")print (math.log(14)) # Printing the log base 5 of 14print (\"Logarithm base 5 of 14 is : \", end=\"\")print (math.log(14,5))",
"e": 1068,
"s": 800,
"text": null
},
{
"code": null,
"e": 1078,
"s": 1068,
"text": "Output : "
},
{
"code": null,
"e": 1173,
"s": 1078,
"text": "Natural logarithm of 14 is : 2.6390573296152584\nLogarithm base 5 of 14 is : 1.6397385131955606"
},
{
"code": null,
"e": 1291,
"s": 1173,
"text": "2. log2(a) : This function is used to compute the logarithm base 2 of a. Displays more accurate result than log(a,2)."
},
{
"code": null,
"e": 1468,
"s": 1291,
"text": "Syntax :\nmath.log2(a)\nParameters : \na : The numeric value\nReturn Value : \nReturns logarithm base 2 of a\nExceptions : \nRaises ValueError if a negative no. is passed as argument."
},
{
"code": null,
"e": 1476,
"s": 1468,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of# log2(a) import math # Printing the log base 2 of 14print (\"Logarithm base 2 of 14 is : \", end=\"\")print (math.log2(14))",
"e": 1640,
"s": 1476,
"text": null
},
{
"code": null,
"e": 1650,
"s": 1640,
"text": "Output : "
},
{
"code": null,
"e": 1696,
"s": 1650,
"text": "Logarithm base 2 of 14 is : 3.807354922057604"
},
{
"code": null,
"e": 1817,
"s": 1696,
"text": "3. log10(a) : This function is used to compute the logarithm base 10 of a. Displays more accurate result than log(a,10)."
},
{
"code": null,
"e": 1996,
"s": 1817,
"text": "Syntax :\nmath.log10(a)\nParameters : \na : The numeric value\nReturn Value : \nReturns logarithm base 10 of a\nExceptions : \nRaises ValueError if a negative no. is passed as argument."
},
{
"code": null,
"e": 2004,
"s": 1996,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of# log10(a) import math # Printing the log base 10 of 14print (\"Logarithm base 10 of 14 is : \", end=\"\")print (math.log10(14))",
"e": 2172,
"s": 2004,
"text": null
},
{
"code": null,
"e": 2182,
"s": 2172,
"text": "Output : "
},
{
"code": null,
"e": 2229,
"s": 2182,
"text": "Logarithm base 10 of 14 is : 1.146128035678238"
},
{
"code": null,
"e": 2294,
"s": 2229,
"text": "3. log1p(a) : This function is used to compute logarithm(1+a) . "
},
{
"code": null,
"e": 2459,
"s": 2294,
"text": "Syntax :\nmath.log1p(a)\nParameters : \na : The numeric value\nReturn Value : \nReturns log(1+a)\nExceptions : \nRaises ValueError if a negative no. is passed as argument."
},
{
"code": null,
"e": 2467,
"s": 2459,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of# log1p(a) import math # Printing the log(1+a) of 14print (\"Logarithm(1+a) value of 14 is : \", end=\"\")print (math.log1p(14))",
"e": 2635,
"s": 2467,
"text": null
},
{
"code": null,
"e": 2645,
"s": 2635,
"text": "Output : "
},
{
"code": null,
"e": 2694,
"s": 2645,
"text": "Logarithm(1+a) value of 14 is : 2.70805020110221"
},
{
"code": null,
"e": 2768,
"s": 2694,
"text": "1. ValueError : This function returns value error if number is negative. "
},
{
"code": null,
"e": 2776,
"s": 2768,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the Exception of# log(a) import math # Printing the log(a) of -14# Throws Exceptionprint (\"log(a) value of -14 is : \", end=\"\")print (math.log(-14))",
"e": 2953,
"s": 2776,
"text": null
},
{
"code": null,
"e": 2963,
"s": 2953,
"text": "Output : "
},
{
"code": null,
"e": 2989,
"s": 2963,
"text": "log(a) value of -14 is : "
},
{
"code": null,
"e": 3006,
"s": 2989,
"text": "Runtime Error : "
},
{
"code": null,
"e": 3161,
"s": 3006,
"text": "Traceback (most recent call last):\n File \"/home/8a74e9d7e5adfdb902ab15712cbaafe2.py\", line 9, in \n print (math.log(-14))\nValueError: math domain error"
},
{
"code": null,
"e": 3298,
"s": 3161,
"text": "One of the application of log10() function is that it is used to compute the no. of digits of a number. Code below illustrates the same."
},
{
"code": null,
"e": 3306,
"s": 3298,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the Application of# log10(a) import math # Printing no. of digits in 73293print (\"The number of digits in 73293 are : \", end=\"\")print (int(math.log10(73293) + 1))",
"e": 3499,
"s": 3306,
"text": null
},
{
"code": null,
"e": 3509,
"s": 3499,
"text": "Output : "
},
{
"code": null,
"e": 3547,
"s": 3509,
"text": "The number of digits in 73293 are : 5"
},
{
"code": null,
"e": 3968,
"s": 3547,
"text": "This article is contributed by Manjeet Singh. 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": 3984,
"s": 3968,
"text": "jatinchellani02"
},
{
"code": null,
"e": 3999,
"s": 3984,
"text": "Python-Library"
},
{
"code": null,
"e": 4006,
"s": 3999,
"text": "Python"
}
] |
A better way for asynchronous programming: asyncio over multi-threading | by Qian (Aria) Li | Towards Data Science
|
If you’ve come here, it is probably because you have heard of asyncio module that’s introduced in Python 3.4. You might have been wondering whether you should begin using it. I remember the moment I got stunned by its brilliant performance. Before I learned about asyncio, I was using multi-processing and threading to speed jobs up. They worked well until one day I hit a bottleneck handling hundreds of millions of URL calls. The challenge pushed me to look for other feasible solutions to the I/O bound task. Though its syntax and concept seem complex at first, asyncio turns out to be a life-changer.
Asyncio is all about asynchronous programming, but it is not the only option that runs jobs asynchronously. You might pause me here and ask, what’s asynchronous programming? In simple words, asynchronous programming allows different tasks to start execution without waiting for the previous one to be completed. This is huge because the vast portion of the time taken to read the URLs is due to the network delay. It’s unnecessary to suffer from high latencies and keep the machines idle while waiting for a response from another server. Asynchronous programming solves the exact problem.
Multi-threading is a traditional solution that performs tasks asynchronously. Both asyncio and multi-threading run concurrently. Oh, wait, what’s concurrency? Concurrency is a concept that opposes to parallelism; it means executing multiple tasks at the same time but not necessarily simultaneously while parallelism means executing tasks simultaneously. The difference between these two concepts is not important in the blog (see here for more about the difference), but keep in mind that we are not exploring parallelism solution in this blog. As good as it sounds, parallelism is not ideal for I/O bound tasks; it works well with CPU bound job.
So why asyncio is faster than multi-threading if they both belong to asynchronous programming? It’s because asyncio is more robust with task scheduling and provides the user with full control of code execution. You can pause the code by using the await keyword and during the wait, you could run nothing or go ahead executing other code. As a result, resources are not locked down during the wait.
The way the tasks take turns for multi-threading is completely different. In threading, the Python interpreter is responsible for task scheduling. Having no prior knowledge of the code or the tasks, the interpreter gives each thread a slice of time to utilize the resources in turns before switching to the next thread. There is some level of inefficiency in this line of arrangement. A simple task could be cut off in the middle no matter how trivial it is. Resources could be locked down to a thread where the task is still waiting for a response from an outside server and therefore not ready to proceed. Consequently, there is still some waste in both time and resources.
Before we get to asyncio, let’s use multi-threading as a benchmark! My machine has 8 CPUs for all the examples.
All libraries for the test are imported in the front. Yes, I use logging. I’ve basically dropped print and switched to logging. And remember to always use exceptions. A detailed exception is best. But if you don’t know or care about it, use general Exception!
There are two functions in the code snippet.
The first function, fetch_url uses requests module and GET method to retrieve data from a specified URL. The try and except block catch server or timeout error so we would run multi-threading without interruption.
The second function, fetch_all uses a pool of threads to execute the first function asynchronously via ThreadPoolExecutor() from the concurrent.futures module. The map method gathers responses from all threads.
Outside the two functions, it calls fetch_all several times. Each time, we pass a URL list of a different length and record the time it takes.
Now let’s look at some performance results:
INFO:root:Fetch 1 urls takes 0.7269587516784668 secondsINFO:root:Fetch 10 urls takes 0.7232849597930908 secondsINFO:root:Fetch 100 urls takes 5.631572008132935 secondsINFO:root:Fetch 500 urls takes 10.897085905075073 secondsINFO:root:Fetch 1000 urls takes 20.450702905654907 seconds
The result is not bad at all. You can see that multi-threading has done a decent job reading 1000 URLs.
import asynciofrom aiohttp import ClientSessionasync def fetch(url): async with ClientSession() as session: async with session.get(url) as response: return await response.read()
This is basically asyncio version of fetch_url. I use aiohttp because it provides an excellent client session where we can make HTTP requests asynchronously.
Besides aiohttp.ClientSession, the code probably looks strange with async and await syntax. These two are the key symbols of asyncio. The async def and async with statement create coroutine objects whose execution can be suspended; the await keyword tells the program which execution to wait for. The use of the two keywords makes it possible for the code to run asynchronously.
We don’t directly call the fetch function to fire up asynchronous execution. Instead, we need to create an event loop and add tasks in the loop. The below two lines of code help you get started with fetching only one URL.
loop = asyncio.get_event_loop()loop.run_until_complete(fetch(url))
To run multiple URLs and asynchronously gather all responses, you would need to utilize ensure_future and gather functions from asyncio.
I hope you still remember the previous multi-threading example because I’m presenting you with a complete asyncio version! The code snippet has the same structure as the multi-threading example.
It has an upgraded version of fetch function from the previous asyncio introduction. It’s upgraded by enabling additional exceptions. Another big change is that the client session has become an argument of the function.
The fetch_async is an asyncio version of fetch_all. The function has created a client session and inside it, an event loop is created and loaded with tasks, where one URL request is one task. It’s an important lesson learned that having one client session for all your HTTP requests is a preferred and faster way.
The result of the asynchronous operation is a future object and a gather method is used in fetch_async to aggregate the results.
A timer is wrapped around the fetch_async function call to track time.
The code was executed on the same 8-CPU machine as before and results are displayed below:
INFO:root:Fetch 1 urls takes 1.5993337631225586 secondsINFO:root:Fetch 10 urls takes 1.2335288524627686 secondsINFO:root:Fetch 100 urls takes 2.6485719680786133 secondsINFO:root:Fetch 500 urls takes 4.8839111328125 secondsINFO:root:Fetch 1000 urls takes 6.814634084701538 seconds
You might have noticed that in both examples, the time it takes for 1 URL is slightly longer than the time for 10 URLs. This might look contrary to common practice. But think about it. Both multi-threading and asyncio are meant for “parallel” jobs, and they both have fired up extra resources to complete the jobs faster. Using either of them to read one URL won’t save your time if not waste your time.
Between 1 to 10 URLs, asyncio takes more time in seconds to send requests and gather responses. It could mean that multi-threading is preferred for small I/O bound tasks.
From somewhere between 10 to 100 URLs, the execution time of asyncio drops under that of multi-threading. With the increase in the number of URLs, the time difference between the two solutions is getting larger. That concludes the superior performance of asyncio on a large load of URL requests.
|
[
{
"code": null,
"e": 652,
"s": 47,
"text": "If you’ve come here, it is probably because you have heard of asyncio module that’s introduced in Python 3.4. You might have been wondering whether you should begin using it. I remember the moment I got stunned by its brilliant performance. Before I learned about asyncio, I was using multi-processing and threading to speed jobs up. They worked well until one day I hit a bottleneck handling hundreds of millions of URL calls. The challenge pushed me to look for other feasible solutions to the I/O bound task. Though its syntax and concept seem complex at first, asyncio turns out to be a life-changer."
},
{
"code": null,
"e": 1241,
"s": 652,
"text": "Asyncio is all about asynchronous programming, but it is not the only option that runs jobs asynchronously. You might pause me here and ask, what’s asynchronous programming? In simple words, asynchronous programming allows different tasks to start execution without waiting for the previous one to be completed. This is huge because the vast portion of the time taken to read the URLs is due to the network delay. It’s unnecessary to suffer from high latencies and keep the machines idle while waiting for a response from another server. Asynchronous programming solves the exact problem."
},
{
"code": null,
"e": 1889,
"s": 1241,
"text": "Multi-threading is a traditional solution that performs tasks asynchronously. Both asyncio and multi-threading run concurrently. Oh, wait, what’s concurrency? Concurrency is a concept that opposes to parallelism; it means executing multiple tasks at the same time but not necessarily simultaneously while parallelism means executing tasks simultaneously. The difference between these two concepts is not important in the blog (see here for more about the difference), but keep in mind that we are not exploring parallelism solution in this blog. As good as it sounds, parallelism is not ideal for I/O bound tasks; it works well with CPU bound job."
},
{
"code": null,
"e": 2287,
"s": 1889,
"text": "So why asyncio is faster than multi-threading if they both belong to asynchronous programming? It’s because asyncio is more robust with task scheduling and provides the user with full control of code execution. You can pause the code by using the await keyword and during the wait, you could run nothing or go ahead executing other code. As a result, resources are not locked down during the wait."
},
{
"code": null,
"e": 2963,
"s": 2287,
"text": "The way the tasks take turns for multi-threading is completely different. In threading, the Python interpreter is responsible for task scheduling. Having no prior knowledge of the code or the tasks, the interpreter gives each thread a slice of time to utilize the resources in turns before switching to the next thread. There is some level of inefficiency in this line of arrangement. A simple task could be cut off in the middle no matter how trivial it is. Resources could be locked down to a thread where the task is still waiting for a response from an outside server and therefore not ready to proceed. Consequently, there is still some waste in both time and resources."
},
{
"code": null,
"e": 3075,
"s": 2963,
"text": "Before we get to asyncio, let’s use multi-threading as a benchmark! My machine has 8 CPUs for all the examples."
},
{
"code": null,
"e": 3335,
"s": 3075,
"text": "All libraries for the test are imported in the front. Yes, I use logging. I’ve basically dropped print and switched to logging. And remember to always use exceptions. A detailed exception is best. But if you don’t know or care about it, use general Exception!"
},
{
"code": null,
"e": 3380,
"s": 3335,
"text": "There are two functions in the code snippet."
},
{
"code": null,
"e": 3594,
"s": 3380,
"text": "The first function, fetch_url uses requests module and GET method to retrieve data from a specified URL. The try and except block catch server or timeout error so we would run multi-threading without interruption."
},
{
"code": null,
"e": 3805,
"s": 3594,
"text": "The second function, fetch_all uses a pool of threads to execute the first function asynchronously via ThreadPoolExecutor() from the concurrent.futures module. The map method gathers responses from all threads."
},
{
"code": null,
"e": 3948,
"s": 3805,
"text": "Outside the two functions, it calls fetch_all several times. Each time, we pass a URL list of a different length and record the time it takes."
},
{
"code": null,
"e": 3992,
"s": 3948,
"text": "Now let’s look at some performance results:"
},
{
"code": null,
"e": 4275,
"s": 3992,
"text": "INFO:root:Fetch 1 urls takes 0.7269587516784668 secondsINFO:root:Fetch 10 urls takes 0.7232849597930908 secondsINFO:root:Fetch 100 urls takes 5.631572008132935 secondsINFO:root:Fetch 500 urls takes 10.897085905075073 secondsINFO:root:Fetch 1000 urls takes 20.450702905654907 seconds"
},
{
"code": null,
"e": 4379,
"s": 4275,
"text": "The result is not bad at all. You can see that multi-threading has done a decent job reading 1000 URLs."
},
{
"code": null,
"e": 4578,
"s": 4379,
"text": "import asynciofrom aiohttp import ClientSessionasync def fetch(url): async with ClientSession() as session: async with session.get(url) as response: return await response.read()"
},
{
"code": null,
"e": 4736,
"s": 4578,
"text": "This is basically asyncio version of fetch_url. I use aiohttp because it provides an excellent client session where we can make HTTP requests asynchronously."
},
{
"code": null,
"e": 5115,
"s": 4736,
"text": "Besides aiohttp.ClientSession, the code probably looks strange with async and await syntax. These two are the key symbols of asyncio. The async def and async with statement create coroutine objects whose execution can be suspended; the await keyword tells the program which execution to wait for. The use of the two keywords makes it possible for the code to run asynchronously."
},
{
"code": null,
"e": 5337,
"s": 5115,
"text": "We don’t directly call the fetch function to fire up asynchronous execution. Instead, we need to create an event loop and add tasks in the loop. The below two lines of code help you get started with fetching only one URL."
},
{
"code": null,
"e": 5404,
"s": 5337,
"text": "loop = asyncio.get_event_loop()loop.run_until_complete(fetch(url))"
},
{
"code": null,
"e": 5541,
"s": 5404,
"text": "To run multiple URLs and asynchronously gather all responses, you would need to utilize ensure_future and gather functions from asyncio."
},
{
"code": null,
"e": 5736,
"s": 5541,
"text": "I hope you still remember the previous multi-threading example because I’m presenting you with a complete asyncio version! The code snippet has the same structure as the multi-threading example."
},
{
"code": null,
"e": 5956,
"s": 5736,
"text": "It has an upgraded version of fetch function from the previous asyncio introduction. It’s upgraded by enabling additional exceptions. Another big change is that the client session has become an argument of the function."
},
{
"code": null,
"e": 6270,
"s": 5956,
"text": "The fetch_async is an asyncio version of fetch_all. The function has created a client session and inside it, an event loop is created and loaded with tasks, where one URL request is one task. It’s an important lesson learned that having one client session for all your HTTP requests is a preferred and faster way."
},
{
"code": null,
"e": 6399,
"s": 6270,
"text": "The result of the asynchronous operation is a future object and a gather method is used in fetch_async to aggregate the results."
},
{
"code": null,
"e": 6470,
"s": 6399,
"text": "A timer is wrapped around the fetch_async function call to track time."
},
{
"code": null,
"e": 6561,
"s": 6470,
"text": "The code was executed on the same 8-CPU machine as before and results are displayed below:"
},
{
"code": null,
"e": 6841,
"s": 6561,
"text": "INFO:root:Fetch 1 urls takes 1.5993337631225586 secondsINFO:root:Fetch 10 urls takes 1.2335288524627686 secondsINFO:root:Fetch 100 urls takes 2.6485719680786133 secondsINFO:root:Fetch 500 urls takes 4.8839111328125 secondsINFO:root:Fetch 1000 urls takes 6.814634084701538 seconds"
},
{
"code": null,
"e": 7245,
"s": 6841,
"text": "You might have noticed that in both examples, the time it takes for 1 URL is slightly longer than the time for 10 URLs. This might look contrary to common practice. But think about it. Both multi-threading and asyncio are meant for “parallel” jobs, and they both have fired up extra resources to complete the jobs faster. Using either of them to read one URL won’t save your time if not waste your time."
},
{
"code": null,
"e": 7416,
"s": 7245,
"text": "Between 1 to 10 URLs, asyncio takes more time in seconds to send requests and gather responses. It could mean that multi-threading is preferred for small I/O bound tasks."
}
] |
ReactJS - Redux
|
React redux is an advanced state management library for React. As we learned earlier, React only supports component level state management. In a big and complex application, large number of components are used. React recommends to move the state to the top level component and pass the state to the nested component using properties. It helps to some extent but it becomes complex when the components increases.
React redux chips in and helps to maintain state at the application level. React redux allows any component to access the state at any time. Also, it allows any component to change the state of the application at any time.
Let us learn about the how to write a React application using React redux in this chapter.
React redux maintains the state of the application in a single place called Redux store. React component can get the latest state from the store as well as change the state at any time. Redux provides a simple process to get and set the current state of the application and involves below concepts.
Store − The central place to store the state of the application.
Actions − Action is an plain object with the type of the action to be done and the input (called payload) necessary to do the action. For example, action for adding an item in the store contains ADD_ITEM as type and an object with item’s details as payload. The action can be represented as −
{
type: 'ADD_ITEM',
payload: { name: '..', ... }
}
Reducers − Reducers are pure functions used to create a new state based on the existing state and the current action. It returns the newly created state. For example, in add item scenario, it creates a new item list and merges the item from the state and new item and returns the newly created list.
Action creators − Action creator creates an action with proper action type and data necessary for the action and returns the action. For example, addItem action creator returns below object −
{
type: 'ADD_ITEM',
payload: { name: '..', ... }
}
Component − Component can connect to the store to get the current state and dispatch action to the store so that the store executes the action and updates it’s current state.
The workflow of a typical redux store can be represented as shown below.
React component subscribes to the store and get the latest state during initialization of the application.
To change the state, React component creates necessary action and dispatches the action.
Reducer creates a new state based on the action and returns it. Store updates itself with the new state.
Once the state changes, store sends the updated state to all its subscribed component.
Redux provides a single api, connect which will connect a components to the store and allows the component to get and set the state of the store.
The signature of the connect API is −
function connect(mapStateToProps?, mapDispatchToProps?, mergeProps?, options?)
All parameters are optional and it returns a HOC (higher order component). A higher order component is a function which wraps a component and returns a new component.
let hoc = connect(mapStateToProps, mapDispatchToProps)
let connectedComponent = hoc(component)
Let us see the first two parameters which will be enough for most cases.
mapStateToProps − Accepts a function with below signature.
mapStateToProps − Accepts a function with below signature.
(state, ownProps?) => Object
Here, state refers current state of the store and Object refers the new props of the component. It gets called whenever the state of the store is updated.
(state) => { prop1: this.state.anyvalue }
mapDispatchToProps − Accepts a function with below signature.
mapDispatchToProps − Accepts a function with below signature.
Object | (dispatch, ownProps?) => Object
Here, dispatch refers the dispatch object used to dispatch action in the redux store and Object refers one or more dispatch functions as props of the component.
(dispatch) => {
addDispatcher: (dispatch) => dispatch({ type: 'ADD_ITEM', payload: { } }),
removeispatcher: (dispatch) => dispatch({ type: 'REMOVE_ITEM', payload: { } }),
}
React Redux provides a Provider component and its sole purpose to make the Redux store available to its all nested components connected to store using connect API. The sample code is given below −
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import { App } from './App'
import createStore from './createReduxStore'
const store = createStore()
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
Now, all the component inside the App component can get access to the Redux store by using connect API.
Let us recreate our expense manager application and uses the React redux concept to maintain the state of the application.
First, create a new react application, react-message-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter.
Next, install Redux and React redux library.
npm install redux react-redux --save
Next, install uuid library to generate unique identifier for new expenses.
npm install uuid --save
Next, open the application in your favorite editor.
Next, create src folder under the root directory of the application.
Next, create actions folder under src folder.
Next, create a file, types.js under src/actions folder and start editing.
Next, add two action type, one for add expense and one for remove expense.
export const ADD_EXPENSE = 'ADD_EXPENSE';
export const DELETE_EXPENSE = 'DELETE_EXPENSE';
Next, create a file, index.js under src/actions folder to add action and start editing.
Next, import uuid to create unique identifier.
import { v4 as uuidv4 } from 'uuid';
Next, import action types.
import { ADD_EXPENSE, DELETE_EXPENSE } from './types';
Next, add a new function to return action type for adding an expense and export it.
export const addExpense = ({ name, amount, spendDate, category }) => ({
type: ADD_EXPENSE,
payload: {
id: uuidv4(),
name,
amount,
spendDate,
category
}
});
Here, the function expects expense object and return action type of ADD_EXPENSE along with a payload of expense information.
Next, add a new function to return action type for deleting an expense and export it.
export const deleteExpense = id => ({
type: DELETE_EXPENSE,
payload: {
id
}
});
Here, the function expects id of the expense item to be deleted and return action type of ‘DELETE_EXPENSE’ along with a payload of expense id.
The complete source code of the action is given below −
import { v4 as uuidv4 } from 'uuid';
import { ADD_EXPENSE, DELETE_EXPENSE } from './types';
export const addExpense = ({ name, amount, spendDate, category }) => ({
type: ADD_EXPENSE,
payload: {
id: uuidv4(),
name,
amount,
spendDate,
category
}
});
export const deleteExpense = id => ({
type: DELETE_EXPENSE,
payload: {
id
}
});
Next, create a new folder, reducers under src folder.
Next, create a file, index.js under src/reducers to write reducer function and start editing.
Next, import the action types.
import { ADD_EXPENSE, DELETE_EXPENSE } from '../actions/types';
Next, add a function, expensesReducer to do the actual feature of adding and updating expenses in the redux store.
export default function expensesReducer(state = [], action) {
switch (action.type) {
case ADD_EXPENSE:
return [...state, action.payload];
case DELETE_EXPENSE:
return state.filter(expense => expense.id !== action.payload.id);
default:
return state;
}
}
The complete source code of the reducer is given below −
import { ADD_EXPENSE, DELETE_EXPENSE } from '../actions/types';
export default function expensesReducer(state = [], action) {
switch (action.type) {
case ADD_EXPENSE:
return [...state, action.payload];
case DELETE_EXPENSE:
return state.filter(expense => expense.id !== action.payload.id);
default:
return state;
}
}
Here, the reducer checks the action type and execute the relevant code.
Next, create components folder under src folder.
Next, create a file, ExpenseEntryItemList.css under src/components folder and add generic style for the html tables.
html {
font-family: sans-serif;
}
table {
border-collapse: collapse;
border: 2px solid rgb(200,200,200);
letter-spacing: 1px;
font-size: 0.8rem;
}
td, th {
border: 1px solid rgb(190,190,190);
padding: 10px 20px;
}
th {
background-color: rgb(235,235,235);
}
td, th {
text-align: left;
}
tr:nth-child(even) td {
background-color: rgb(250,250,250);
}
tr:nth-child(odd) td {
background-color: rgb(245,245,245);
}
caption {
padding: 10px;
}
tr.highlight td {
background-color: #a6a8bd;
}
Next, create a file, ExpenseEntryItemList.js under src/components folder and start editing.
Next, import React and React redux library.
import React from 'react';
import { connect } from 'react-redux';
Next, import ExpenseEntryItemList.css file.
import './ExpenseEntryItemList.css';
Next, import action creators.
import { deleteExpense } from '../actions';
import { addExpense } from '../actions';
Next, create a class, ExpenseEntryItemList and call constructor with props.
class ExpenseEntryItemList extends React.Component {
constructor(props) {
super(props);
}
}
Next, create mapStateToProps function.
const mapStateToProps = state => {
return {
expenses: state
};
};
Here, we copied the input state to expenses props of the component.
Next, create mapDispatchToProps function.
const mapDispatchToProps = dispatch => {
return {
onAddExpense: expense => {
dispatch(addExpense(expense));
},
onDelete: id => {
dispatch(deleteExpense(id));
}
};
};
Here, we created two function, one to dispatch add expense (addExpense) function and another to dispatch delete expense (deleteExpense) function and mapped those function to props of the component.
Next, export the component using connect api.
export default connect(
mapStateToProps,
mapDispatchToProps
)(ExpenseEntryItemList);
Now, the component gets three new properties given below −
expenses − list of expense
expenses − list of expense
onAddExpense − function to dispatch addExpense function
onAddExpense − function to dispatch addExpense function
onDelete − function to dispatch deleteExpense function
onDelete − function to dispatch deleteExpense function
Next, add few expense into the redux store in the constructor using onAddExpense property.
if (this.props.expenses.length == 0)
{
const items = [
{ id: 1, name: "Pizza", amount: 80, spendDate: "2020-10-10", category: "Food" },
{ id: 2, name: "Grape Juice", amount: 30, spendDate: "2020-10-12", category: "Food" },
{ id: 3, name: "Cinema", amount: 210, spendDate: "2020-10-16", category: "Entertainment" },
{ id: 4, name: "Java Programming book", amount: 242, spendDate: "2020-10-15", category: "Academic" },
{ id: 5, name: "Mango Juice", amount: 35, spendDate: "2020-10-16", category: "Food" },
{ id: 6, name: "Dress", amount: 2000, spendDate: "2020-10-25", category: "Cloth" },
{ id: 7, name: "Tour", amount: 2555, spendDate: "2020-10-29", category: "Entertainment" },
{ id: 8, name: "Meals", amount: 300, spendDate: "2020-10-30", category: "Food" },
{ id: 9, name: "Mobile", amount: 3500, spendDate: "2020-11-02", category: "Gadgets" },
{ id: 10, name: "Exam Fees", amount: 1245, spendDate: "2020-11-04", category: "Academic" }
]
items.forEach((item) => {
this.props.onAddExpense(
{
name: item.name,
amount: item.amount,
spendDate: item.spendDate,
category: item.category
}
);
})
}
Next, add an event handler to delete the expense item using expense id.
handleDelete = (id,e) => {
e.preventDefault();
this.props.onDelete(id);
}
Here, the event handler calls the onDelete dispatcher, which call deleteExpense along with the expense id.
Next, add a method to calculate the total amount of all expenses.
getTotal() {
let total = 0;
for (var i = 0; i < this.props.expenses.length; i++) {
total += this.props.expenses[i].amount
}
return total;
}
Next, add render() method and list the expense item in the tabular format.
render() {
const lists = this.props.expenses.map(
(item) =>
<tr key={item.id}>
<td>{item.name}</td>
<td>{item.amount}</td>
<td>{new Date(item.spendDate).toDateString()}</td>
<td>{item.category}</td>
<td><a href="#"
onClick={(e) => this.handleDelete(item.id, e)}>Remove</a></td>
</tr>
);
return (
<div>
<table>
<thead>
<tr>
<th>Item</th>
<th>Amount</th>
<th>Date</th>
<th>Category</th>
<th>Remove</th>
</tr>
</thead>
<tbody>
{lists}
<tr>
<td colSpan="1" style={{ textAlign: "right" }}>Total Amount</td>
<td colSpan="4" style={{ textAlign: "left" }}>
{this.getTotal()}
</td>
</tr>
</tbody>
</table>
</div>
);
}
Here, we set the event handler handleDelete to remove the expense from the store.
The complete source code of the ExpenseEntryItemList component is given below −
import React from 'react';
import { connect } from 'react-redux';
import './ExpenseEntryItemList.css';
import { deleteExpense } from '../actions';
import { addExpense } from '../actions';
class ExpenseEntryItemList extends React.Component {
constructor(props) {
super(props);
if (this.props.expenses.length == 0){
const items = [
{ id: 1, name: "Pizza", amount: 80, spendDate: "2020-10-10", category: "Food" },
{ id: 2, name: "Grape Juice", amount: 30, spendDate: "2020-10-12", category: "Food" },
{ id: 3, name: "Cinema", amount: 210, spendDate: "2020-10-16", category: "Entertainment" },
{ id: 4, name: "Java Programming book", amount: 242, spendDate: "2020-10-15", category: "Academic" },
{ id: 5, name: "Mango Juice", amount: 35, spendDate: "2020-10-16", category: "Food" },
{ id: 6, name: "Dress", amount: 2000, spendDate: "2020-10-25", category: "Cloth" },
{ id: 7, name: "Tour", amount: 2555, spendDate: "2020-10-29", category: "Entertainment" },
{ id: 8, name: "Meals", amount: 300, spendDate: "2020-10-30", category: "Food" },
{ id: 9, name: "Mobile", amount: 3500, spendDate: "2020-11-02", category: "Gadgets" },
{ id: 10, name: "Exam Fees", amount: 1245, spendDate: "2020-11-04", category: "Academic" }
]
items.forEach((item) => {
this.props.onAddExpense(
{
name: item.name,
amount: item.amount,
spendDate: item.spendDate,
category: item.category
}
);
})
}
}
handleDelete = (id,e) => {
e.preventDefault();
this.props.onDelete(id);
}
getTotal() {
let total = 0;
for (var i = 0; i < this.props.expenses.length; i++) {
total += this.props.expenses[i].amount
}
return total;
}
render() {
const lists = this.props.expenses.map((item) =>
<tr key={item.id}>
<td>{item.name}</td>
<td>{item.amount}</td>
<td>{new Date(item.spendDate).toDateString()}</td>
<td>{item.category}</td>
<td><a href="#"
onClick={(e) => this.handleDelete(item.id, e)}>Remove</a></td>
</tr>
);
return (
<div>
<table>
<thead>
<tr>
<th>Item</th>
<th>Amount</th>
<th>Date</th>
<th>Category</th>
<th>Remove</th>
</tr>
</thead>
<tbody>
{lists}
<tr>
<td colSpan="1" style={{ textAlign: "right" }}>Total Amount</td>
<td colSpan="4" style={{ textAlign: "left" }}>
{this.getTotal()}
</td>
</tr>
</tbody>
</table>
</div>
);
}
}
const mapStateToProps = state => {
return {
expenses: state
};
};
const mapDispatchToProps = dispatch => {
return {
onAddExpense: expense => {
dispatch(addExpense(expense));
},
onDelete: id => {
dispatch(deleteExpense(id));
}
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(ExpenseEntryItemList);
Next, create a file, App.js under the src/components folder and use ExpenseEntryItemList component.
import React, { Component } from 'react';
import ExpenseEntryItemList from './ExpenseEntryItemList';
class App extends Component {
render() {
return (
<div>
<ExpenseEntryItemList />
</div>
);
}
}
export default App;
Next, create a file, index.js under src folder.
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import rootReducer from './reducers';
import App from './components/App';
const store = createStore(rootReducer);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
Here,
Create a store using createStore by attaching the our reducer.
Create a store using createStore by attaching the our reducer.
Used Provider component from React redux library and set the store as props, which enables all the nested component to connect to store using connect api.
Used Provider component from React redux library and set the store as props, which enables all the nested component to connect to store using connect api.
Finally, create a public folder under the root folder and create index.html file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>React Containment App</title>
</head>
<body>
<div id="root"></div>
<script type="text/JavaScript" src="./index.js"></script>
</body>
</html>
Next, serve the application using npm command.
npm start
Next, open the browser and enter http://localhost:3000 in the address bar and press enter.
Clicking the remove link will remove the item from redux store.
20 Lectures
1.5 hours
Anadi Sharma
60 Lectures
4.5 hours
Skillbakerystudios
165 Lectures
13 hours
Paul Carlo Tordecilla
63 Lectures
9.5 hours
TELCOMA Global
17 Lectures
2 hours
Mohd Raqif Warsi
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2445,
"s": 2033,
"text": "React redux is an advanced state management library for React. As we learned earlier, React only supports component level state management. In a big and complex application, large number of components are used. React recommends to move the state to the top level component and pass the state to the nested component using properties. It helps to some extent but it becomes complex when the components increases."
},
{
"code": null,
"e": 2668,
"s": 2445,
"text": "React redux chips in and helps to maintain state at the application level. React redux allows any component to access the state at any time. Also, it allows any component to change the state of the application at any time."
},
{
"code": null,
"e": 2759,
"s": 2668,
"text": "Let us learn about the how to write a React application using React redux in this chapter."
},
{
"code": null,
"e": 3058,
"s": 2759,
"text": "React redux maintains the state of the application in a single place called Redux store. React component can get the latest state from the store as well as change the state at any time. Redux provides a simple process to get and set the current state of the application and involves below concepts."
},
{
"code": null,
"e": 3123,
"s": 3058,
"text": "Store − The central place to store the state of the application."
},
{
"code": null,
"e": 3416,
"s": 3123,
"text": "Actions − Action is an plain object with the type of the action to be done and the input (called payload) necessary to do the action. For example, action for adding an item in the store contains ADD_ITEM as type and an object with item’s details as payload. The action can be represented as −"
},
{
"code": null,
"e": 3476,
"s": 3416,
"text": "{ \n type: 'ADD_ITEM', \n payload: { name: '..', ... }\n}\n"
},
{
"code": null,
"e": 3776,
"s": 3476,
"text": "Reducers − Reducers are pure functions used to create a new state based on the existing state and the current action. It returns the newly created state. For example, in add item scenario, it creates a new item list and merges the item from the state and new item and returns the newly created list."
},
{
"code": null,
"e": 3968,
"s": 3776,
"text": "Action creators − Action creator creates an action with proper action type and data necessary for the action and returns the action. For example, addItem action creator returns below object −"
},
{
"code": null,
"e": 4028,
"s": 3968,
"text": "{ \n type: 'ADD_ITEM', \n payload: { name: '..', ... }\n}\n"
},
{
"code": null,
"e": 4203,
"s": 4028,
"text": "Component − Component can connect to the store to get the current state and dispatch action to the store so that the store executes the action and updates it’s current state."
},
{
"code": null,
"e": 4276,
"s": 4203,
"text": "The workflow of a typical redux store can be represented as shown below."
},
{
"code": null,
"e": 4383,
"s": 4276,
"text": "React component subscribes to the store and get the latest state during initialization of the application."
},
{
"code": null,
"e": 4472,
"s": 4383,
"text": "To change the state, React component creates necessary action and dispatches the action."
},
{
"code": null,
"e": 4577,
"s": 4472,
"text": "Reducer creates a new state based on the action and returns it. Store updates itself with the new state."
},
{
"code": null,
"e": 4664,
"s": 4577,
"text": "Once the state changes, store sends the updated state to all its subscribed component."
},
{
"code": null,
"e": 4810,
"s": 4664,
"text": "Redux provides a single api, connect which will connect a components to the store and allows the component to get and set the state of the store."
},
{
"code": null,
"e": 4848,
"s": 4810,
"text": "The signature of the connect API is −"
},
{
"code": null,
"e": 4928,
"s": 4848,
"text": "function connect(mapStateToProps?, mapDispatchToProps?, mergeProps?, options?)\n"
},
{
"code": null,
"e": 5095,
"s": 4928,
"text": "All parameters are optional and it returns a HOC (higher order component). A higher order component is a function which wraps a component and returns a new component."
},
{
"code": null,
"e": 5192,
"s": 5095,
"text": "let hoc = connect(mapStateToProps, mapDispatchToProps) \nlet connectedComponent = hoc(component)\n"
},
{
"code": null,
"e": 5265,
"s": 5192,
"text": "Let us see the first two parameters which will be enough for most cases."
},
{
"code": null,
"e": 5324,
"s": 5265,
"text": "mapStateToProps − Accepts a function with below signature."
},
{
"code": null,
"e": 5383,
"s": 5324,
"text": "mapStateToProps − Accepts a function with below signature."
},
{
"code": null,
"e": 5413,
"s": 5383,
"text": "(state, ownProps?) => Object\n"
},
{
"code": null,
"e": 5568,
"s": 5413,
"text": "Here, state refers current state of the store and Object refers the new props of the component. It gets called whenever the state of the store is updated."
},
{
"code": null,
"e": 5611,
"s": 5568,
"text": "(state) => { prop1: this.state.anyvalue }\n"
},
{
"code": null,
"e": 5673,
"s": 5611,
"text": "mapDispatchToProps − Accepts a function with below signature."
},
{
"code": null,
"e": 5735,
"s": 5673,
"text": "mapDispatchToProps − Accepts a function with below signature."
},
{
"code": null,
"e": 5777,
"s": 5735,
"text": "Object | (dispatch, ownProps?) => Object\n"
},
{
"code": null,
"e": 5938,
"s": 5777,
"text": "Here, dispatch refers the dispatch object used to dispatch action in the redux store and Object refers one or more dispatch functions as props of the component."
},
{
"code": null,
"e": 6118,
"s": 5938,
"text": "(dispatch) => {\n addDispatcher: (dispatch) => dispatch({ type: 'ADD_ITEM', payload: { } }),\n removeispatcher: (dispatch) => dispatch({ type: 'REMOVE_ITEM', payload: { } }),\n}\n"
},
{
"code": null,
"e": 6315,
"s": 6118,
"text": "React Redux provides a Provider component and its sole purpose to make the Redux store available to its all nested components connected to store using connect API. The sample code is given below −"
},
{
"code": null,
"e": 6628,
"s": 6315,
"text": "import React from 'react'\nimport ReactDOM from 'react-dom'\nimport { Provider } from 'react-redux'\nimport { App } from './App'\nimport createStore from './createReduxStore'\n\nconst store = createStore()\n\nReactDOM.render(\n <Provider store={store}>\n <App />\n </Provider>,\n document.getElementById('root')\n)"
},
{
"code": null,
"e": 6732,
"s": 6628,
"text": "Now, all the component inside the App component can get access to the Redux store by using connect API."
},
{
"code": null,
"e": 6855,
"s": 6732,
"text": "Let us recreate our expense manager application and uses the React redux concept to maintain the state of the application."
},
{
"code": null,
"e": 7019,
"s": 6855,
"text": "First, create a new react application, react-message-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter."
},
{
"code": null,
"e": 7064,
"s": 7019,
"text": "Next, install Redux and React redux library."
},
{
"code": null,
"e": 7102,
"s": 7064,
"text": "npm install redux react-redux --save\n"
},
{
"code": null,
"e": 7177,
"s": 7102,
"text": "Next, install uuid library to generate unique identifier for new expenses."
},
{
"code": null,
"e": 7202,
"s": 7177,
"text": "npm install uuid --save\n"
},
{
"code": null,
"e": 7254,
"s": 7202,
"text": "Next, open the application in your favorite editor."
},
{
"code": null,
"e": 7323,
"s": 7254,
"text": "Next, create src folder under the root directory of the application."
},
{
"code": null,
"e": 7369,
"s": 7323,
"text": "Next, create actions folder under src folder."
},
{
"code": null,
"e": 7443,
"s": 7369,
"text": "Next, create a file, types.js under src/actions folder and start editing."
},
{
"code": null,
"e": 7518,
"s": 7443,
"text": "Next, add two action type, one for add expense and one for remove expense."
},
{
"code": null,
"e": 7610,
"s": 7518,
"text": "export const ADD_EXPENSE = 'ADD_EXPENSE'; \nexport const DELETE_EXPENSE = 'DELETE_EXPENSE';\n"
},
{
"code": null,
"e": 7698,
"s": 7610,
"text": "Next, create a file, index.js under src/actions folder to add action and start editing."
},
{
"code": null,
"e": 7745,
"s": 7698,
"text": "Next, import uuid to create unique identifier."
},
{
"code": null,
"e": 7783,
"s": 7745,
"text": "import { v4 as uuidv4 } from 'uuid';\n"
},
{
"code": null,
"e": 7810,
"s": 7783,
"text": "Next, import action types."
},
{
"code": null,
"e": 7866,
"s": 7810,
"text": "import { ADD_EXPENSE, DELETE_EXPENSE } from './types';\n"
},
{
"code": null,
"e": 7950,
"s": 7866,
"text": "Next, add a new function to return action type for adding an expense and export it."
},
{
"code": null,
"e": 8145,
"s": 7950,
"text": "export const addExpense = ({ name, amount, spendDate, category }) => ({\n type: ADD_EXPENSE,\n payload: {\n id: uuidv4(),\n name,\n amount,\n spendDate,\n category\n }\n});"
},
{
"code": null,
"e": 8270,
"s": 8145,
"text": "Here, the function expects expense object and return action type of ADD_EXPENSE along with a payload of expense information."
},
{
"code": null,
"e": 8356,
"s": 8270,
"text": "Next, add a new function to return action type for deleting an expense and export it."
},
{
"code": null,
"e": 8451,
"s": 8356,
"text": "export const deleteExpense = id => ({\n type: DELETE_EXPENSE,\n payload: {\n id\n }\n});"
},
{
"code": null,
"e": 8594,
"s": 8451,
"text": "Here, the function expects id of the expense item to be deleted and return action type of ‘DELETE_EXPENSE’ along with a payload of expense id."
},
{
"code": null,
"e": 8650,
"s": 8594,
"text": "The complete source code of the action is given below −"
},
{
"code": null,
"e": 9033,
"s": 8650,
"text": "import { v4 as uuidv4 } from 'uuid';\nimport { ADD_EXPENSE, DELETE_EXPENSE } from './types';\n\nexport const addExpense = ({ name, amount, spendDate, category }) => ({\n type: ADD_EXPENSE,\n payload: {\n id: uuidv4(),\n name,\n amount,\n spendDate,\n category\n }\n});\nexport const deleteExpense = id => ({\n type: DELETE_EXPENSE,\n payload: {\n id\n }\n});"
},
{
"code": null,
"e": 9087,
"s": 9033,
"text": "Next, create a new folder, reducers under src folder."
},
{
"code": null,
"e": 9181,
"s": 9087,
"text": "Next, create a file, index.js under src/reducers to write reducer function and start editing."
},
{
"code": null,
"e": 9212,
"s": 9181,
"text": "Next, import the action types."
},
{
"code": null,
"e": 9277,
"s": 9212,
"text": "import { ADD_EXPENSE, DELETE_EXPENSE } from '../actions/types';\n"
},
{
"code": null,
"e": 9392,
"s": 9277,
"text": "Next, add a function, expensesReducer to do the actual feature of adding and updating expenses in the redux store."
},
{
"code": null,
"e": 9695,
"s": 9392,
"text": "export default function expensesReducer(state = [], action) {\n switch (action.type) {\n case ADD_EXPENSE:\n return [...state, action.payload];\n case DELETE_EXPENSE:\n return state.filter(expense => expense.id !== action.payload.id);\n default:\n return state;\n }\n}"
},
{
"code": null,
"e": 9752,
"s": 9695,
"text": "The complete source code of the reducer is given below −"
},
{
"code": null,
"e": 10120,
"s": 9752,
"text": "import { ADD_EXPENSE, DELETE_EXPENSE } from '../actions/types';\n\nexport default function expensesReducer(state = [], action) {\n switch (action.type) {\n case ADD_EXPENSE:\n return [...state, action.payload];\n case DELETE_EXPENSE:\n return state.filter(expense => expense.id !== action.payload.id);\n default:\n return state;\n }\n}"
},
{
"code": null,
"e": 10192,
"s": 10120,
"text": "Here, the reducer checks the action type and execute the relevant code."
},
{
"code": null,
"e": 10241,
"s": 10192,
"text": "Next, create components folder under src folder."
},
{
"code": null,
"e": 10358,
"s": 10241,
"text": "Next, create a file, ExpenseEntryItemList.css under src/components folder and add generic style for the html tables."
},
{
"code": null,
"e": 10881,
"s": 10358,
"text": "html {\n font-family: sans-serif;\n}\ntable {\n border-collapse: collapse;\n border: 2px solid rgb(200,200,200);\n letter-spacing: 1px;\n font-size: 0.8rem;\n}\ntd, th {\n border: 1px solid rgb(190,190,190);\n padding: 10px 20px;\n}\nth {\n background-color: rgb(235,235,235);\n}\ntd, th {\n text-align: left;\n}\ntr:nth-child(even) td {\n background-color: rgb(250,250,250);\n}\ntr:nth-child(odd) td {\n background-color: rgb(245,245,245);\n}\ncaption {\n padding: 10px;\n}\ntr.highlight td { \n background-color: #a6a8bd;\n}"
},
{
"code": null,
"e": 10973,
"s": 10881,
"text": "Next, create a file, ExpenseEntryItemList.js under src/components folder and start editing."
},
{
"code": null,
"e": 11017,
"s": 10973,
"text": "Next, import React and React redux library."
},
{
"code": null,
"e": 11085,
"s": 11017,
"text": "import React from 'react'; \nimport { connect } from 'react-redux';\n"
},
{
"code": null,
"e": 11129,
"s": 11085,
"text": "Next, import ExpenseEntryItemList.css file."
},
{
"code": null,
"e": 11167,
"s": 11129,
"text": "import './ExpenseEntryItemList.css';\n"
},
{
"code": null,
"e": 11197,
"s": 11167,
"text": "Next, import action creators."
},
{
"code": null,
"e": 11284,
"s": 11197,
"text": "import { deleteExpense } from '../actions'; \nimport { addExpense } from '../actions';\n"
},
{
"code": null,
"e": 11360,
"s": 11284,
"text": "Next, create a class, ExpenseEntryItemList and call constructor with props."
},
{
"code": null,
"e": 11464,
"s": 11360,
"text": "class ExpenseEntryItemList extends React.Component {\n constructor(props) {\n super(props);\n }\n}"
},
{
"code": null,
"e": 11503,
"s": 11464,
"text": "Next, create mapStateToProps function."
},
{
"code": null,
"e": 11581,
"s": 11503,
"text": "const mapStateToProps = state => {\n return {\n expenses: state\n };\n};"
},
{
"code": null,
"e": 11649,
"s": 11581,
"text": "Here, we copied the input state to expenses props of the component."
},
{
"code": null,
"e": 11691,
"s": 11649,
"text": "Next, create mapDispatchToProps function."
},
{
"code": null,
"e": 11905,
"s": 11691,
"text": "const mapDispatchToProps = dispatch => {\n return {\n onAddExpense: expense => {\n dispatch(addExpense(expense));\n },\n onDelete: id => {\n dispatch(deleteExpense(id));\n }\n };\n};"
},
{
"code": null,
"e": 12103,
"s": 11905,
"text": "Here, we created two function, one to dispatch add expense (addExpense) function and another to dispatch delete expense (deleteExpense) function and mapped those function to props of the component."
},
{
"code": null,
"e": 12149,
"s": 12103,
"text": "Next, export the component using connect api."
},
{
"code": null,
"e": 12240,
"s": 12149,
"text": "export default connect(\n mapStateToProps,\n mapDispatchToProps\n)(ExpenseEntryItemList);"
},
{
"code": null,
"e": 12299,
"s": 12240,
"text": "Now, the component gets three new properties given below −"
},
{
"code": null,
"e": 12326,
"s": 12299,
"text": "expenses − list of expense"
},
{
"code": null,
"e": 12353,
"s": 12326,
"text": "expenses − list of expense"
},
{
"code": null,
"e": 12409,
"s": 12353,
"text": "onAddExpense − function to dispatch addExpense function"
},
{
"code": null,
"e": 12465,
"s": 12409,
"text": "onAddExpense − function to dispatch addExpense function"
},
{
"code": null,
"e": 12520,
"s": 12465,
"text": "onDelete − function to dispatch deleteExpense function"
},
{
"code": null,
"e": 12575,
"s": 12520,
"text": "onDelete − function to dispatch deleteExpense function"
},
{
"code": null,
"e": 12666,
"s": 12575,
"text": "Next, add few expense into the redux store in the constructor using onAddExpense property."
},
{
"code": null,
"e": 13914,
"s": 12666,
"text": "if (this.props.expenses.length == 0)\n{\n const items = [\n { id: 1, name: \"Pizza\", amount: 80, spendDate: \"2020-10-10\", category: \"Food\" },\n { id: 2, name: \"Grape Juice\", amount: 30, spendDate: \"2020-10-12\", category: \"Food\" },\n { id: 3, name: \"Cinema\", amount: 210, spendDate: \"2020-10-16\", category: \"Entertainment\" },\n { id: 4, name: \"Java Programming book\", amount: 242, spendDate: \"2020-10-15\", category: \"Academic\" },\n { id: 5, name: \"Mango Juice\", amount: 35, spendDate: \"2020-10-16\", category: \"Food\" },\n { id: 6, name: \"Dress\", amount: 2000, spendDate: \"2020-10-25\", category: \"Cloth\" },\n { id: 7, name: \"Tour\", amount: 2555, spendDate: \"2020-10-29\", category: \"Entertainment\" },\n { id: 8, name: \"Meals\", amount: 300, spendDate: \"2020-10-30\", category: \"Food\" },\n { id: 9, name: \"Mobile\", amount: 3500, spendDate: \"2020-11-02\", category: \"Gadgets\" },\n { id: 10, name: \"Exam Fees\", amount: 1245, spendDate: \"2020-11-04\", category: \"Academic\" }\n ]\n items.forEach((item) => {\n this.props.onAddExpense(\n { \n name: item.name, \n amount: item.amount, \n spendDate: item.spendDate, \n category: item.category \n }\n );\n })\n}"
},
{
"code": null,
"e": 13986,
"s": 13914,
"text": "Next, add an event handler to delete the expense item using expense id."
},
{
"code": null,
"e": 14066,
"s": 13986,
"text": "handleDelete = (id,e) => {\n e.preventDefault();\n this.props.onDelete(id);\n}"
},
{
"code": null,
"e": 14173,
"s": 14066,
"text": "Here, the event handler calls the onDelete dispatcher, which call deleteExpense along with the expense id."
},
{
"code": null,
"e": 14239,
"s": 14173,
"text": "Next, add a method to calculate the total amount of all expenses."
},
{
"code": null,
"e": 14397,
"s": 14239,
"text": "getTotal() {\n let total = 0;\n for (var i = 0; i < this.props.expenses.length; i++) {\n total += this.props.expenses[i].amount\n }\n return total;\n}"
},
{
"code": null,
"e": 14472,
"s": 14397,
"text": "Next, add render() method and list the expense item in the tabular format."
},
{
"code": null,
"e": 15486,
"s": 14472,
"text": "render() {\n const lists = this.props.expenses.map(\n (item) =>\n <tr key={item.id}>\n <td>{item.name}</td>\n <td>{item.amount}</td>\n <td>{new Date(item.spendDate).toDateString()}</td>\n <td>{item.category}</td>\n <td><a href=\"#\"\n onClick={(e) => this.handleDelete(item.id, e)}>Remove</a></td>\n </tr>\n );\n return (\n <div>\n <table>\n <thead>\n <tr>\n <th>Item</th>\n <th>Amount</th>\n <th>Date</th>\n <th>Category</th>\n <th>Remove</th>\n </tr>\n </thead>\n <tbody>\n {lists}\n <tr>\n <td colSpan=\"1\" style={{ textAlign: \"right\" }}>Total Amount</td>\n <td colSpan=\"4\" style={{ textAlign: \"left\" }}>\n {this.getTotal()}\n </td>\n </tr>\n </tbody>\n </table>\n </div>\n );\n}"
},
{
"code": null,
"e": 15568,
"s": 15486,
"text": "Here, we set the event handler handleDelete to remove the expense from the store."
},
{
"code": null,
"e": 15648,
"s": 15568,
"text": "The complete source code of the ExpenseEntryItemList component is given below −"
},
{
"code": null,
"e": 19102,
"s": 15648,
"text": "import React from 'react';\nimport { connect } from 'react-redux';\nimport './ExpenseEntryItemList.css';\nimport { deleteExpense } from '../actions';\nimport { addExpense } from '../actions';\n\nclass ExpenseEntryItemList extends React.Component {\n constructor(props) {\n super(props);\n\n if (this.props.expenses.length == 0){\n const items = [\n { id: 1, name: \"Pizza\", amount: 80, spendDate: \"2020-10-10\", category: \"Food\" },\n { id: 2, name: \"Grape Juice\", amount: 30, spendDate: \"2020-10-12\", category: \"Food\" },\n { id: 3, name: \"Cinema\", amount: 210, spendDate: \"2020-10-16\", category: \"Entertainment\" },\n { id: 4, name: \"Java Programming book\", amount: 242, spendDate: \"2020-10-15\", category: \"Academic\" },\n { id: 5, name: \"Mango Juice\", amount: 35, spendDate: \"2020-10-16\", category: \"Food\" },\n { id: 6, name: \"Dress\", amount: 2000, spendDate: \"2020-10-25\", category: \"Cloth\" },\n { id: 7, name: \"Tour\", amount: 2555, spendDate: \"2020-10-29\", category: \"Entertainment\" },\n { id: 8, name: \"Meals\", amount: 300, spendDate: \"2020-10-30\", category: \"Food\" },\n { id: 9, name: \"Mobile\", amount: 3500, spendDate: \"2020-11-02\", category: \"Gadgets\" },\n { id: 10, name: \"Exam Fees\", amount: 1245, spendDate: \"2020-11-04\", category: \"Academic\" }\n ]\n items.forEach((item) => {\n this.props.onAddExpense(\n { \n name: item.name, \n amount: item.amount, \n spendDate: item.spendDate, \n category: item.category \n }\n );\n })\n }\n }\n handleDelete = (id,e) => {\n e.preventDefault();\n this.props.onDelete(id);\n }\n getTotal() {\n let total = 0;\n for (var i = 0; i < this.props.expenses.length; i++) {\n total += this.props.expenses[i].amount\n }\n return total;\n }\n render() {\n const lists = this.props.expenses.map((item) =>\n <tr key={item.id}>\n <td>{item.name}</td>\n <td>{item.amount}</td>\n <td>{new Date(item.spendDate).toDateString()}</td>\n <td>{item.category}</td>\n <td><a href=\"#\"\n onClick={(e) => this.handleDelete(item.id, e)}>Remove</a></td>\n </tr>\n );\n return (\n <div>\n <table>\n <thead>\n <tr>\n <th>Item</th>\n <th>Amount</th>\n <th>Date</th>\n <th>Category</th>\n <th>Remove</th>\n </tr>\n </thead>\n <tbody>\n {lists}\n <tr>\n <td colSpan=\"1\" style={{ textAlign: \"right\" }}>Total Amount</td>\n <td colSpan=\"4\" style={{ textAlign: \"left\" }}>\n {this.getTotal()}\n </td>\n </tr>\n </tbody>\n </table>\n </div>\n );\n }\n}\nconst mapStateToProps = state => {\n return {\n expenses: state\n };\n};\nconst mapDispatchToProps = dispatch => {\n return {\n onAddExpense: expense => {\n dispatch(addExpense(expense));\n },\n onDelete: id => {\n dispatch(deleteExpense(id));\n }\n };\n};\nexport default connect(\n mapStateToProps,\n mapDispatchToProps\n)(ExpenseEntryItemList);"
},
{
"code": null,
"e": 19202,
"s": 19102,
"text": "Next, create a file, App.js under the src/components folder and use ExpenseEntryItemList component."
},
{
"code": null,
"e": 19467,
"s": 19202,
"text": "import React, { Component } from 'react';\nimport ExpenseEntryItemList from './ExpenseEntryItemList';\n\nclass App extends Component {\n render() {\n return (\n <div>\n <ExpenseEntryItemList />\n </div>\n );\n }\n}\nexport default App;"
},
{
"code": null,
"e": 19515,
"s": 19467,
"text": "Next, create a file, index.js under src folder."
},
{
"code": null,
"e": 19882,
"s": 19515,
"text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport { createStore } from 'redux';\nimport { Provider } from 'react-redux';\nimport rootReducer from './reducers';\nimport App from './components/App';\n\nconst store = createStore(rootReducer);\n\nReactDOM.render(\n <Provider store={store}>\n <App />\n </Provider>,\n document.getElementById('root')\n);"
},
{
"code": null,
"e": 19888,
"s": 19882,
"text": "Here,"
},
{
"code": null,
"e": 19951,
"s": 19888,
"text": "Create a store using createStore by attaching the our reducer."
},
{
"code": null,
"e": 20014,
"s": 19951,
"text": "Create a store using createStore by attaching the our reducer."
},
{
"code": null,
"e": 20169,
"s": 20014,
"text": "Used Provider component from React redux library and set the store as props, which enables all the nested component to connect to store using connect api."
},
{
"code": null,
"e": 20324,
"s": 20169,
"text": "Used Provider component from React redux library and set the store as props, which enables all the nested component to connect to store using connect api."
},
{
"code": null,
"e": 20406,
"s": 20324,
"text": "Finally, create a public folder under the root folder and create index.html file."
},
{
"code": null,
"e": 20653,
"s": 20406,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>React Containment App</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"text/JavaScript\" src=\"./index.js\"></script>\n </body>\n</html>"
},
{
"code": null,
"e": 20700,
"s": 20653,
"text": "Next, serve the application using npm command."
},
{
"code": null,
"e": 20711,
"s": 20700,
"text": "npm start\n"
},
{
"code": null,
"e": 20802,
"s": 20711,
"text": "Next, open the browser and enter http://localhost:3000 in the address bar and press enter."
},
{
"code": null,
"e": 20866,
"s": 20802,
"text": "Clicking the remove link will remove the item from redux store."
},
{
"code": null,
"e": 20901,
"s": 20866,
"text": "\n 20 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 20915,
"s": 20901,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 20950,
"s": 20915,
"text": "\n 60 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 20970,
"s": 20950,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 21005,
"s": 20970,
"text": "\n 165 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 21028,
"s": 21005,
"text": " Paul Carlo Tordecilla"
},
{
"code": null,
"e": 21063,
"s": 21028,
"text": "\n 63 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 21079,
"s": 21063,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 21112,
"s": 21079,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 21130,
"s": 21112,
"text": " Mohd Raqif Warsi"
},
{
"code": null,
"e": 21137,
"s": 21130,
"text": " Print"
},
{
"code": null,
"e": 21148,
"s": 21137,
"text": " Add Notes"
}
] |
How to implement a program to count the number in Java?
|
The program uses a JLabel to hold a count label, a JTextField component to hold the number count, JButton component to create add, remove and reset buttons. When we click the add button, the count in the JTextField will get incremented by '1' and by clicking the remove button the count will be decremented by '1'. If we click the Reset button, it will reset the count to '0'.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CounterTest extends JFrame implements ActionListener {
private JLabel label;
private JTextField text;
private JButton addBtn, removeBtn, resetBtn;
private int count;
public CounterTest() {
setTitle("Counter Test");
setLayout(new FlowLayout());
count = 0;
label = new JLabel("Count:");
text = new JTextField("0", 4);
addBtn = new JButton("Add");
removeBtn = new JButton("Remove");
resetBtn = new JButton("Reset");
addBtn.addActionListener(this);
removeBtn.addActionListener(this);
resetBtn.addActionListener(this);
add(label);
add(text);
add(addBtn);
add(removeBtn);
add(resetBtn);
setSize(375, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == addBtn) {
count++; // increment the coiunt by 1
text.setText(String.valueOf(count));
repaint();
} else if (ae.getSource() == removeBtn) {
count--; // decrement the count by 1
text.setText(String.valueOf(count));
repaint();
} else if (ae.getSource() == resetBtn) {
count = 0; // reset the count to 0
text.setText(String.valueOf(count));
repaint();
}
}
public static void main(String[] args) {
new CounterTest();
}
}
|
[
{
"code": null,
"e": 1439,
"s": 1062,
"text": "The program uses a JLabel to hold a count label, a JTextField component to hold the number count, JButton component to create add, remove and reset buttons. When we click the add button, the count in the JTextField will get incremented by '1' and by clicking the remove button the count will be decremented by '1'. If we click the Reset button, it will reset the count to '0'."
},
{
"code": null,
"e": 2959,
"s": 1439,
"text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\npublic class CounterTest extends JFrame implements ActionListener {\n private JLabel label;\n private JTextField text;\n private JButton addBtn, removeBtn, resetBtn;\n private int count;\n public CounterTest() {\n setTitle(\"Counter Test\");\n setLayout(new FlowLayout());\n count = 0;\n label = new JLabel(\"Count:\");\n text = new JTextField(\"0\", 4);\n addBtn = new JButton(\"Add\");\n removeBtn = new JButton(\"Remove\");\n resetBtn = new JButton(\"Reset\");\n addBtn.addActionListener(this);\n removeBtn.addActionListener(this);\n resetBtn.addActionListener(this);\n add(label);\n add(text);\n add(addBtn);\n add(removeBtn);\n add(resetBtn);\n setSize(375, 250);\n setLocationRelativeTo(null);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setVisible(true);\n }\n public void actionPerformed(ActionEvent ae) {\n if (ae.getSource() == addBtn) {\n count++; // increment the coiunt by 1\n text.setText(String.valueOf(count));\n repaint();\n } else if (ae.getSource() == removeBtn) {\n count--; // decrement the count by 1\n text.setText(String.valueOf(count));\n repaint();\n } else if (ae.getSource() == resetBtn) {\n count = 0; // reset the count to 0\n text.setText(String.valueOf(count));\n repaint();\n }\n }\n public static void main(String[] args) {\n new CounterTest();\n }\n}"
}
] |
Iterate through elements of TreeSet in Java
|
First, create a TreeSet and add elements −
TreeSet<String> set = new TreeSet<String>();
set.add("34");
set.add("12");
set.add("67");
set.add("54");
set.add("76");
set.add("49");
Now, let us iterate through the elements −
Iterator<String> i = set.iterator();
while(i.hasNext()){
System.out.println(i.next());
}
The following is an example that iterate through elements of TreeSet −
Live Demo
import java.util.*;
public class Demo {
public static void main(String args[]){
TreeSet<String> set = new TreeSet<String>();
set.add("34");
set.add("12");
set.add("67");
set.add("54");
set.add("76");
set.add("49");
System.out.println("TreeSet elements...");
Iterator<String> i = set.iterator();
while(i.hasNext()){
System.out.println(i.next());
}
}
}
TreeSet elements...
12
34
49
54
67
76
|
[
{
"code": null,
"e": 1105,
"s": 1062,
"text": "First, create a TreeSet and add elements −"
},
{
"code": null,
"e": 1240,
"s": 1105,
"text": "TreeSet<String> set = new TreeSet<String>();\nset.add(\"34\");\nset.add(\"12\");\nset.add(\"67\");\nset.add(\"54\");\nset.add(\"76\");\nset.add(\"49\");"
},
{
"code": null,
"e": 1283,
"s": 1240,
"text": "Now, let us iterate through the elements −"
},
{
"code": null,
"e": 1375,
"s": 1283,
"text": "Iterator<String> i = set.iterator();\nwhile(i.hasNext()){\n System.out.println(i.next());\n}"
},
{
"code": null,
"e": 1446,
"s": 1375,
"text": "The following is an example that iterate through elements of TreeSet −"
},
{
"code": null,
"e": 1457,
"s": 1446,
"text": " Live Demo"
},
{
"code": null,
"e": 1889,
"s": 1457,
"text": "import java.util.*;\npublic class Demo {\n public static void main(String args[]){\n TreeSet<String> set = new TreeSet<String>();\n set.add(\"34\");\n set.add(\"12\");\n set.add(\"67\");\n set.add(\"54\");\n set.add(\"76\");\n set.add(\"49\");\n System.out.println(\"TreeSet elements...\");\n Iterator<String> i = set.iterator();\n while(i.hasNext()){\n System.out.println(i.next());\n }\n }\n}"
},
{
"code": null,
"e": 1927,
"s": 1889,
"text": "TreeSet elements...\n12\n34\n49\n54\n67\n76"
}
] |
Buy and Hold Trading Strategy. Calculating the performance of the... | by Roman Orac | Towards Data Science
|
Buy and Hold strategy is when you simply buy an asset with the first incoming data point and see what the portfolio value is available with the last data point.
The Buy and Hold strategy is sometimes also used as a baseline for testing the performance of other strategies. If a carefully crafted logic cannot beat a simple buy and hold approach, the strategy is probably not worth a dime.
While it is not hard to measure the performance of the Buy and Hold strategy by hand, it is useful to have a backtesting framework — you can further work on improving the strategy and it usually comes with plotting capability.
See my other articles about this topic:
romanorac.medium.com
Here are a few links that might interest you:
- Labeling and Data Engineering for Conversational AI and Analytics- Data Science for Business Leaders [Course]- Intro to Machine Learning with PyTorch [Course]- Become a Growth Product Manager [Course]- Deep Learning (Adaptive Computation and ML series) [Ebook]- Free skill tests for Data Scientists & Machine Learning Engineers
Some of the links above are affiliate links and if you go through them to make a purchase I’ll earn a commission. Keep in mind that I link courses because of their quality and not because of the commission I receive from your purchases.
Backtrader is an open-source Python framework for backtesting and trading. It allows you to focus on writing reusable trading strategies, indicators and analyzers instead of having to spend time building infrastructure.
Before installing it, make you have TA-LIB dependency installed:
# Mac OS Xbrew install ta-lib# see https://github.com/mrjbq7/ta-lib for other platforms
To install Backtrader is as simple as with every python package:
pip install backtrader[plotting]
We are going to calculate how much would we gain if we would invest $10.000 in Microsoft on the 1st of January 2010 and hold it till now.
We only need a few lines of code to implement the Buy and Hold Strategy with Backtrader.
Explanation of the code below:
start method sets the initial amount of cash.
the nextstart method is called exactly once with the first data point. This is perfect for implementing buy and hold strategy.
All the available cash is used to buy a fixed amount of stocks. It is truncated to int as all the brokers don’t support the fractional stocks.
the returns are calculated in the stop method, using the current value of the portfolio and the initial amount of cash.
import backtrader as btclass BuyAndHold_Buy(bt.Strategy): def start(self): # set the starting cash self.val_start = self.broker.get_cash() def nextstart(self): # Buy stocks with all the available cash size = int(self.val_start / self.data) self.buy(size=size) def stop(self): # calculate the actual returns self.roi = (self.broker.get_value() / self.val_start) - 1.0 print("ROI: %.2f, Cash: %.2f" % (100.0 * self.roi, self.broker.get_value()))
As already mentioned above, we would like to calculate how much would we gain by holding Microsoft stock for ~10 years.
We define the ticker, date parameters and initialize the data feed:
from datetime import datetimedata = bt.feeds.YahooFinanceData( dataname="MSFT", fromdate=datetime(2010, 1, 1), todate=datetime(2020, 10, 23))
Then we initialize the Cerebro engine:
cerebro = bt.Cerebro()
Add the data feed to the engine:
cerebro.adddata(data)
Add the strategy to the engine:
cerebro.addstrategy(BuyAndHold_Buy, "HODL")
Set the cash:
cerebro.broker.setcash(100000.0)
Run the backtest:
cerebro.run()# The outputROI: 788.00, Cash: 88800.40
We would make a crazy return of 788%. If we could only go back in time 😊
We all heard the saying “A picture is worth a thousand words”. This is where Backtrader shines.
Backtrader can visualize a strategy with entry and exit points. In our example, we only have one entry point so the trading strategy visualization won’t be as dramatic. But we would need to spend a considerable amount of time to make a visualization that we get out of the box with Backtrader
Let’s try it (command below works in JupyterLab):
cerebro.plot(iplot=False)
To learn more about the Buy and Hold strategy, visit Backtraders docs.
As usual, you can download this Jupyter Notebook to try examples on your machine.
Follow me on Twitter, where I regularly tweet about Data Science and Machine Learning.
|
[
{
"code": null,
"e": 208,
"s": 47,
"text": "Buy and Hold strategy is when you simply buy an asset with the first incoming data point and see what the portfolio value is available with the last data point."
},
{
"code": null,
"e": 436,
"s": 208,
"text": "The Buy and Hold strategy is sometimes also used as a baseline for testing the performance of other strategies. If a carefully crafted logic cannot beat a simple buy and hold approach, the strategy is probably not worth a dime."
},
{
"code": null,
"e": 663,
"s": 436,
"text": "While it is not hard to measure the performance of the Buy and Hold strategy by hand, it is useful to have a backtesting framework — you can further work on improving the strategy and it usually comes with plotting capability."
},
{
"code": null,
"e": 703,
"s": 663,
"text": "See my other articles about this topic:"
},
{
"code": null,
"e": 724,
"s": 703,
"text": "romanorac.medium.com"
},
{
"code": null,
"e": 770,
"s": 724,
"text": "Here are a few links that might interest you:"
},
{
"code": null,
"e": 1100,
"s": 770,
"text": "- Labeling and Data Engineering for Conversational AI and Analytics- Data Science for Business Leaders [Course]- Intro to Machine Learning with PyTorch [Course]- Become a Growth Product Manager [Course]- Deep Learning (Adaptive Computation and ML series) [Ebook]- Free skill tests for Data Scientists & Machine Learning Engineers"
},
{
"code": null,
"e": 1337,
"s": 1100,
"text": "Some of the links above are affiliate links and if you go through them to make a purchase I’ll earn a commission. Keep in mind that I link courses because of their quality and not because of the commission I receive from your purchases."
},
{
"code": null,
"e": 1557,
"s": 1337,
"text": "Backtrader is an open-source Python framework for backtesting and trading. It allows you to focus on writing reusable trading strategies, indicators and analyzers instead of having to spend time building infrastructure."
},
{
"code": null,
"e": 1622,
"s": 1557,
"text": "Before installing it, make you have TA-LIB dependency installed:"
},
{
"code": null,
"e": 1710,
"s": 1622,
"text": "# Mac OS Xbrew install ta-lib# see https://github.com/mrjbq7/ta-lib for other platforms"
},
{
"code": null,
"e": 1775,
"s": 1710,
"text": "To install Backtrader is as simple as with every python package:"
},
{
"code": null,
"e": 1808,
"s": 1775,
"text": "pip install backtrader[plotting]"
},
{
"code": null,
"e": 1946,
"s": 1808,
"text": "We are going to calculate how much would we gain if we would invest $10.000 in Microsoft on the 1st of January 2010 and hold it till now."
},
{
"code": null,
"e": 2035,
"s": 1946,
"text": "We only need a few lines of code to implement the Buy and Hold Strategy with Backtrader."
},
{
"code": null,
"e": 2066,
"s": 2035,
"text": "Explanation of the code below:"
},
{
"code": null,
"e": 2112,
"s": 2066,
"text": "start method sets the initial amount of cash."
},
{
"code": null,
"e": 2239,
"s": 2112,
"text": "the nextstart method is called exactly once with the first data point. This is perfect for implementing buy and hold strategy."
},
{
"code": null,
"e": 2382,
"s": 2239,
"text": "All the available cash is used to buy a fixed amount of stocks. It is truncated to int as all the brokers don’t support the fractional stocks."
},
{
"code": null,
"e": 2502,
"s": 2382,
"text": "the returns are calculated in the stop method, using the current value of the portfolio and the initial amount of cash."
},
{
"code": null,
"e": 3012,
"s": 2502,
"text": "import backtrader as btclass BuyAndHold_Buy(bt.Strategy): def start(self): # set the starting cash self.val_start = self.broker.get_cash() def nextstart(self): # Buy stocks with all the available cash size = int(self.val_start / self.data) self.buy(size=size) def stop(self): # calculate the actual returns self.roi = (self.broker.get_value() / self.val_start) - 1.0 print(\"ROI: %.2f, Cash: %.2f\" % (100.0 * self.roi, self.broker.get_value()))"
},
{
"code": null,
"e": 3132,
"s": 3012,
"text": "As already mentioned above, we would like to calculate how much would we gain by holding Microsoft stock for ~10 years."
},
{
"code": null,
"e": 3200,
"s": 3132,
"text": "We define the ticker, date parameters and initialize the data feed:"
},
{
"code": null,
"e": 3345,
"s": 3200,
"text": "from datetime import datetimedata = bt.feeds.YahooFinanceData( dataname=\"MSFT\", fromdate=datetime(2010, 1, 1), todate=datetime(2020, 10, 23))"
},
{
"code": null,
"e": 3384,
"s": 3345,
"text": "Then we initialize the Cerebro engine:"
},
{
"code": null,
"e": 3407,
"s": 3384,
"text": "cerebro = bt.Cerebro()"
},
{
"code": null,
"e": 3440,
"s": 3407,
"text": "Add the data feed to the engine:"
},
{
"code": null,
"e": 3462,
"s": 3440,
"text": "cerebro.adddata(data)"
},
{
"code": null,
"e": 3494,
"s": 3462,
"text": "Add the strategy to the engine:"
},
{
"code": null,
"e": 3538,
"s": 3494,
"text": "cerebro.addstrategy(BuyAndHold_Buy, \"HODL\")"
},
{
"code": null,
"e": 3552,
"s": 3538,
"text": "Set the cash:"
},
{
"code": null,
"e": 3585,
"s": 3552,
"text": "cerebro.broker.setcash(100000.0)"
},
{
"code": null,
"e": 3603,
"s": 3585,
"text": "Run the backtest:"
},
{
"code": null,
"e": 3656,
"s": 3603,
"text": "cerebro.run()# The outputROI: 788.00, Cash: 88800.40"
},
{
"code": null,
"e": 3729,
"s": 3656,
"text": "We would make a crazy return of 788%. If we could only go back in time 😊"
},
{
"code": null,
"e": 3825,
"s": 3729,
"text": "We all heard the saying “A picture is worth a thousand words”. This is where Backtrader shines."
},
{
"code": null,
"e": 4118,
"s": 3825,
"text": "Backtrader can visualize a strategy with entry and exit points. In our example, we only have one entry point so the trading strategy visualization won’t be as dramatic. But we would need to spend a considerable amount of time to make a visualization that we get out of the box with Backtrader"
},
{
"code": null,
"e": 4168,
"s": 4118,
"text": "Let’s try it (command below works in JupyterLab):"
},
{
"code": null,
"e": 4194,
"s": 4168,
"text": "cerebro.plot(iplot=False)"
},
{
"code": null,
"e": 4265,
"s": 4194,
"text": "To learn more about the Buy and Hold strategy, visit Backtraders docs."
},
{
"code": null,
"e": 4347,
"s": 4265,
"text": "As usual, you can download this Jupyter Notebook to try examples on your machine."
}
] |
Repeating Annotations in Java 8 | @Repeatable | 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
Repeating Annotations in Java 8 are introduced for the support of having multiple same annotations to a declaration. Before Java 8 duplication annotations are not allowed.
Let’s take a use case of having a class Products which has variables with names of products and we want to attach annotations to define the names of countries where the product is manufactured. Prior to Java 8, since we don’t have support for multiple same annotations on the same declaration or type case, we create two different annotations and place on products variable as below.
Example:
Country1.java
Country1.java
public @interface Country1 {
String name() default "";
}
Country2.java
Country2.java
public @interface Country2 {
String name() default "";
}
Products.java
Products.java
public class Products {
@Country1(name = "India")
@Country2(name = "China")
private String footBall;
}
Country1.java
Country1.java
public @interface Country1 {
String name() default "";
}
public @interface Country1 {
String name() default "";
}
Country2.java
Country2.java
public @interface Country2 {
String name() default "";
}
public @interface Country2 {
String name() default "";
}
Products.java
Products.java
public class Products {
@Country1(name = "India")
@Country2(name = "China")
private String footBall;
}
public class Products {
@Country1(name = "India")
@Country2(name = "China")
private String footBall;
}
Java 8 has introduced an annotation type called java.lang.annotation.Repeatable for annotating another annotation to inform the compiler that this annotation is Repeatable. This gives the developer flexibility to have multiple same annotations on a variable.
Usage:
Repeatable Annotation: The Repeating Annotation has to be annotated with @Repeatable to have the capability to repeat. We have to pass the class name as a parameter to the meta-annotation @Repeatable where the compiler can store all the multiple annotations and that acts as a container for values.
Example: Country.java
Country.java
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(value = Countries.class)
public @interface Country {
String name();
}
Container Annotation: The container annotation can be declared as normal annotation and it has to have a value variable whose type is an array of above Repeatable annotation.
Example: Countries.java
Countries.java
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Countries {
Country[] value() default {};
}
Implementation: Now the products class can define the same annotation multiple times on a single product.
Example: Products.
Products.java
public class Products {
@Country(name = "India")
@Country(name = "China")
private String volleyBall;
}
Retrieving Annotations: We can retrieve annotation data by using Reflection API. getAnnotationsByType() is used to retrieve the annotation values. We can also use getAnnotation() method passing the Container Annotation class as input to it to retrieve the values.
RepeatingAnnotationsTest.java
import java.lang.reflect.Field;
public class RepeatingAnnotationsTest {
public static void main(String[] args) throws NoSuchFieldException,
SecurityException {
Products products = new Products();
Class<?> c = products.getClass();
Field fd = c.getDeclaredField("volleyBall");
Country[] countries = fd.getAnnotationsByType(Country.class);
for (Country country : countries) {
System.out.println(country.name());
}
}
}
Repeatable Annotation: The Repeating Annotation has to be annotated with @Repeatable to have the capability to repeat. We have to pass the class name as a parameter to the meta-annotation @Repeatable where the compiler can store all the multiple annotations and that acts as a container for values.
Example: Country.java
Country.java
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(value = Countries.class)
public @interface Country {
String name();
}
Example: Country.java
Country.java
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(value = Countries.class)
public @interface Country {
String name();
}
Example: Country.java
Country.java
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(value = Countries.class)
public @interface Country {
String name();
}
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(value = Countries.class)
public @interface Country {
String name();
}
Container Annotation: The container annotation can be declared as normal annotation and it has to have a value variable whose type is an array of above Repeatable annotation.
Example: Countries.java
Countries.java
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Countries {
Country[] value() default {};
}
Example: Countries.java
Countries.java
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Countries {
Country[] value() default {};
}
Example: Countries.java
Countries.java
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Countries {
Country[] value() default {};
}
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Countries {
Country[] value() default {};
}
Implementation: Now the products class can define the same annotation multiple times on a single product.
Example: Products.
Products.java
public class Products {
@Country(name = "India")
@Country(name = "China")
private String volleyBall;
}
Example: Products.
Products.java
public class Products {
@Country(name = "India")
@Country(name = "China")
private String volleyBall;
}
Example: Products.
Products.java
public class Products {
@Country(name = "India")
@Country(name = "China")
private String volleyBall;
}
public class Products {
@Country(name = "India")
@Country(name = "China")
private String volleyBall;
}
Retrieving Annotations: We can retrieve annotation data by using Reflection API. getAnnotationsByType() is used to retrieve the annotation values. We can also use getAnnotation() method passing the Container Annotation class as input to it to retrieve the values.
RepeatingAnnotationsTest.java
import java.lang.reflect.Field;
public class RepeatingAnnotationsTest {
public static void main(String[] args) throws NoSuchFieldException,
SecurityException {
Products products = new Products();
Class<?> c = products.getClass();
Field fd = c.getDeclaredField("volleyBall");
Country[] countries = fd.getAnnotationsByType(Country.class);
for (Country country : countries) {
System.out.println(country.name());
}
}
}
import java.lang.reflect.Field;
public class RepeatingAnnotationsTest {
public static void main(String[] args) throws NoSuchFieldException,
SecurityException {
Products products = new Products();
Class<?> c = products.getClass();
Field fd = c.getDeclaredField("volleyBall");
Country[] countries = fd.getAnnotationsByType(Country.class);
for (Country country : countries) {
System.out.println(country.name());
}
}
}
Conclusion:
Though Repeating Annotations is a small addition to Java 8, it is a very useful change released in Annotation category, when all advanced frameworks configuration is moving towards annotation-based system from XML.
Happy Learning 🙂
Importance of using Java Annotations ?
Java 8 How to Convert List to String comma separated values
Default Static methods in Interface Java 8
Java Reflection Get Method Information
@Autowired,@Qualifier,@Value annotations in Spring
How HashMap Works In Java
Lambda Expressions in Java
Hibernate Table per Class strategy Annotations Example
Hibernate One To Many Using Annotations
Hibernate 4 Example with Annotations Mysql
What are Lambda Expressions in Java 8
User defined sorting with Java 8 Comparator
ArrayList in Java
How to Convert Java String to Int
Java 8 Stream API and Parallelism
Importance of using Java Annotations ?
Java 8 How to Convert List to String comma separated values
Default Static methods in Interface Java 8
Java Reflection Get Method Information
@Autowired,@Qualifier,@Value annotations in Spring
How HashMap Works In Java
Lambda Expressions in Java
Hibernate Table per Class strategy Annotations Example
Hibernate One To Many Using Annotations
Hibernate 4 Example with Annotations Mysql
What are Lambda Expressions in Java 8
User defined sorting with Java 8 Comparator
ArrayList in Java
How to Convert Java String to Int
Java 8 Stream API and Parallelism
Δ
Install Java on Mac OS
Install AWS CLI on Windows
Install Minikube on Windows
Install Docker Toolbox on Windows
Install SOAPUI on Windows
Install Gradle on Windows
Install RabbitMQ on Windows
Install PuTTY on windows
Install Mysql on Windows
Install Hibernate Tools in Eclipse
Install Elasticsearch on Windows
Install Maven on Windows
Install Maven on Ubuntu
Install Maven on Windows Command
Add OJDBC jar to Maven Repository
Install Ant on Windows
Install RabbitMQ on Windows
Install Apache Kafka on Ubuntu
Install Apache Kafka on Windows
Java8 – Install Windows
Java8 – foreach
Java8 – forEach with index
Java8 – Stream Filter Objects
Java8 – Comparator Userdefined
Java8 – GroupingBy
Java8 – SummingInt
Java8 – walk ReadFiles
Java8 – JAVA_HOME on Windows
Howto – Install Java on Mac OS
Howto – Convert Iterable to Stream
Howto – Get common elements from two Lists
Howto – Convert List to String
Howto – Concatenate Arrays using Stream
Howto – Remove duplicates from List
Howto – Filter null values from Stream
Howto – Convert List to Map
Howto – Convert Stream to List
Howto – Sort a Map
Howto – Filter a Map
Howto – Get Current UTC Time
Howto – Verify an Array contains a specific value
Howto – Convert ArrayList to Array
Howto – Read File Line By Line
Howto – Convert Date to LocalDate
Howto – Merge Streams
Howto – Resolve NullPointerException in toMap
Howto -Get Stream count
Howto – Get Min and Max values in a Stream
Howto – Convert InputStream to String
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 570,
"s": 398,
"text": "Repeating Annotations in Java 8 are introduced for the support of having multiple same annotations to a declaration. Before Java 8 duplication annotations are not allowed."
},
{
"code": null,
"e": 954,
"s": 570,
"text": "Let’s take a use case of having a class Products which has variables with names of products and we want to attach annotations to define the names of countries where the product is manufactured. Prior to Java 8, since we don’t have support for multiple same annotations on the same declaration or type case, we create two different annotations and place on products variable as below."
},
{
"code": null,
"e": 963,
"s": 954,
"text": "Example:"
},
{
"code": null,
"e": 1289,
"s": 963,
"text": "\nCountry1.java\nCountry1.java\npublic @interface Country1 {\n String name() default \"\";\n}\n\nCountry2.java\nCountry2.java\npublic @interface Country2 {\n String name() default \"\";\n}\n\nProducts.java\nProducts.java\npublic class Products {\n @Country1(name = \"India\")\n @Country2(name = \"China\")\n private String footBall;\n}\n\n"
},
{
"code": null,
"e": 1379,
"s": 1289,
"text": "Country1.java\nCountry1.java\npublic @interface Country1 {\n String name() default \"\";\n}\n"
},
{
"code": null,
"e": 1440,
"s": 1379,
"text": "public @interface Country1 {\n String name() default \"\";\n}"
},
{
"code": null,
"e": 1530,
"s": 1440,
"text": "Country2.java\nCountry2.java\npublic @interface Country2 {\n String name() default \"\";\n}\n"
},
{
"code": null,
"e": 1591,
"s": 1530,
"text": "public @interface Country2 {\n String name() default \"\";\n}"
},
{
"code": null,
"e": 1735,
"s": 1591,
"text": "Products.java\nProducts.java\npublic class Products {\n @Country1(name = \"India\")\n @Country2(name = \"China\")\n private String footBall;\n}\n"
},
{
"code": null,
"e": 1850,
"s": 1735,
"text": "public class Products {\n @Country1(name = \"India\")\n @Country2(name = \"China\")\n private String footBall;\n}"
},
{
"code": null,
"e": 2109,
"s": 1850,
"text": "Java 8 has introduced an annotation type called java.lang.annotation.Repeatable for annotating another annotation to inform the compiler that this annotation is Repeatable. This gives the developer flexibility to have multiple same annotations on a variable."
},
{
"code": null,
"e": 2116,
"s": 2109,
"text": "Usage:"
},
{
"code": null,
"e": 4158,
"s": 2116,
"text": "\nRepeatable Annotation: The Repeating Annotation has to be annotated with @Repeatable to have the capability to repeat. We have to pass the class name as a parameter to the meta-annotation @Repeatable where the compiler can store all the multiple annotations and that acts as a container for values.\n\nExample: Country.java\nCountry.java\nimport java.lang.annotation.Repeatable;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\n\n@Retention(RetentionPolicy.RUNTIME)\n@Repeatable(value = Countries.class)\npublic @interface Country {\n String name();\n}\n\n\n\nContainer Annotation: The container annotation can be declared as normal annotation and it has to have a value variable whose type is an array of above Repeatable annotation.\n\nExample: Countries.java\nCountries.java\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\n\n@Retention(RetentionPolicy.RUNTIME)\npublic @interface Countries {\n Country[] value() default {};\n}\n\n\n\nImplementation: Now the products class can define the same annotation multiple times on a single product.\n\nExample: Products.\nProducts.java\npublic class Products {\n @Country(name = \"India\")\n @Country(name = \"China\")\n private String volleyBall;\n}\n\n\n\nRetrieving Annotations: We can retrieve annotation data by using Reflection API. getAnnotationsByType() is used to retrieve the annotation values. We can also use getAnnotation() method passing the Container Annotation class as input to it to retrieve the values.\nRepeatingAnnotationsTest.java\nimport java.lang.reflect.Field;\n\npublic class RepeatingAnnotationsTest {\n\n public static void main(String[] args) throws NoSuchFieldException,\n SecurityException {\n Products products = new Products();\n Class<?> c = products.getClass();\n Field fd = c.getDeclaredField(\"volleyBall\");\n Country[] countries = fd.getAnnotationsByType(Country.class);\n for (Country country : countries) {\n System.out.println(country.name());\n }\n }\n}\n\n"
},
{
"code": null,
"e": 4743,
"s": 4158,
"text": "Repeatable Annotation: The Repeating Annotation has to be annotated with @Repeatable to have the capability to repeat. We have to pass the class name as a parameter to the meta-annotation @Repeatable where the compiler can store all the multiple annotations and that acts as a container for values.\n\nExample: Country.java\nCountry.java\nimport java.lang.annotation.Repeatable;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\n\n@Retention(RetentionPolicy.RUNTIME)\n@Repeatable(value = Countries.class)\npublic @interface Country {\n String name();\n}\n\n\n"
},
{
"code": null,
"e": 5028,
"s": 4743,
"text": "\nExample: Country.java\nCountry.java\nimport java.lang.annotation.Repeatable;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\n\n@Retention(RetentionPolicy.RUNTIME)\n@Repeatable(value = Countries.class)\npublic @interface Country {\n String name();\n}\n\n"
},
{
"code": null,
"e": 5311,
"s": 5028,
"text": "Example: Country.java\nCountry.java\nimport java.lang.annotation.Repeatable;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\n\n@Retention(RetentionPolicy.RUNTIME)\n@Repeatable(value = Countries.class)\npublic @interface Country {\n String name();\n}\n"
},
{
"code": null,
"e": 5558,
"s": 5311,
"text": "import java.lang.annotation.Repeatable;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\n\n@Retention(RetentionPolicy.RUNTIME)\n@Repeatable(value = Countries.class)\npublic @interface Country {\n String name();\n}"
},
{
"code": null,
"e": 5963,
"s": 5558,
"text": "Container Annotation: The container annotation can be declared as normal annotation and it has to have a value variable whose type is an array of above Repeatable annotation.\n\nExample: Countries.java\nCountries.java\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\n\n@Retention(RetentionPolicy.RUNTIME)\npublic @interface Countries {\n Country[] value() default {};\n}\n\n\n"
},
{
"code": null,
"e": 6192,
"s": 5963,
"text": "\nExample: Countries.java\nCountries.java\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\n\n@Retention(RetentionPolicy.RUNTIME)\npublic @interface Countries {\n Country[] value() default {};\n}\n\n"
},
{
"code": null,
"e": 6419,
"s": 6192,
"text": "Example: Countries.java\nCountries.java\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\n\n@Retention(RetentionPolicy.RUNTIME)\npublic @interface Countries {\n Country[] value() default {};\n}\n"
},
{
"code": null,
"e": 6606,
"s": 6419,
"text": "import java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\n\n@Retention(RetentionPolicy.RUNTIME)\npublic @interface Countries {\n Country[] value() default {};\n}"
},
{
"code": null,
"e": 6864,
"s": 6606,
"text": "Implementation: Now the products class can define the same annotation multiple times on a single product.\n\nExample: Products.\nProducts.java\npublic class Products {\n @Country(name = \"India\")\n @Country(name = \"China\")\n private String volleyBall;\n}\n\n\n"
},
{
"code": null,
"e": 7015,
"s": 6864,
"text": "\nExample: Products.\nProducts.java\npublic class Products {\n @Country(name = \"India\")\n @Country(name = \"China\")\n private String volleyBall;\n}\n\n"
},
{
"code": null,
"e": 7164,
"s": 7015,
"text": "Example: Products.\nProducts.java\npublic class Products {\n @Country(name = \"India\")\n @Country(name = \"China\")\n private String volleyBall;\n}\n"
},
{
"code": null,
"e": 7279,
"s": 7164,
"text": "public class Products {\n @Country(name = \"India\")\n @Country(name = \"China\")\n private String volleyBall;\n}"
},
{
"code": null,
"e": 8071,
"s": 7279,
"text": "Retrieving Annotations: We can retrieve annotation data by using Reflection API. getAnnotationsByType() is used to retrieve the annotation values. We can also use getAnnotation() method passing the Container Annotation class as input to it to retrieve the values.\nRepeatingAnnotationsTest.java\nimport java.lang.reflect.Field;\n\npublic class RepeatingAnnotationsTest {\n\n public static void main(String[] args) throws NoSuchFieldException,\n SecurityException {\n Products products = new Products();\n Class<?> c = products.getClass();\n Field fd = c.getDeclaredField(\"volleyBall\");\n Country[] countries = fd.getAnnotationsByType(Country.class);\n for (Country country : countries) {\n System.out.println(country.name());\n }\n }\n}\n"
},
{
"code": null,
"e": 8568,
"s": 8071,
"text": "import java.lang.reflect.Field;\n\npublic class RepeatingAnnotationsTest {\n\n public static void main(String[] args) throws NoSuchFieldException,\n SecurityException {\n Products products = new Products();\n Class<?> c = products.getClass();\n Field fd = c.getDeclaredField(\"volleyBall\");\n Country[] countries = fd.getAnnotationsByType(Country.class);\n for (Country country : countries) {\n System.out.println(country.name());\n }\n }\n}"
},
{
"code": null,
"e": 8580,
"s": 8568,
"text": "Conclusion:"
},
{
"code": null,
"e": 8795,
"s": 8580,
"text": "Though Repeating Annotations is a small addition to Java 8, it is a very useful change released in Annotation category, when all advanced frameworks configuration is moving towards annotation-based system from XML."
},
{
"code": null,
"e": 8812,
"s": 8795,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 9405,
"s": 8812,
"text": "\nImportance of using Java Annotations ?\nJava 8 How to Convert List to String comma separated values\nDefault Static methods in Interface Java 8\nJava Reflection Get Method Information\n@Autowired,@Qualifier,@Value annotations in Spring\nHow HashMap Works In Java\nLambda Expressions in Java\nHibernate Table per Class strategy Annotations Example\nHibernate One To Many Using Annotations\nHibernate 4 Example with Annotations Mysql\nWhat are Lambda Expressions in Java 8\nUser defined sorting with Java 8 Comparator\nArrayList in Java\nHow to Convert Java String to Int\nJava 8 Stream API and Parallelism\n"
},
{
"code": null,
"e": 9444,
"s": 9405,
"text": "Importance of using Java Annotations ?"
},
{
"code": null,
"e": 9504,
"s": 9444,
"text": "Java 8 How to Convert List to String comma separated values"
},
{
"code": null,
"e": 9547,
"s": 9504,
"text": "Default Static methods in Interface Java 8"
},
{
"code": null,
"e": 9586,
"s": 9547,
"text": "Java Reflection Get Method Information"
},
{
"code": null,
"e": 9637,
"s": 9586,
"text": "@Autowired,@Qualifier,@Value annotations in Spring"
},
{
"code": null,
"e": 9663,
"s": 9637,
"text": "How HashMap Works In Java"
},
{
"code": null,
"e": 9690,
"s": 9663,
"text": "Lambda Expressions in Java"
},
{
"code": null,
"e": 9745,
"s": 9690,
"text": "Hibernate Table per Class strategy Annotations Example"
},
{
"code": null,
"e": 9785,
"s": 9745,
"text": "Hibernate One To Many Using Annotations"
},
{
"code": null,
"e": 9828,
"s": 9785,
"text": "Hibernate 4 Example with Annotations Mysql"
},
{
"code": null,
"e": 9866,
"s": 9828,
"text": "What are Lambda Expressions in Java 8"
},
{
"code": null,
"e": 9910,
"s": 9866,
"text": "User defined sorting with Java 8 Comparator"
},
{
"code": null,
"e": 9928,
"s": 9910,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 9962,
"s": 9928,
"text": "How to Convert Java String to Int"
},
{
"code": null,
"e": 9996,
"s": 9962,
"text": "Java 8 Stream API and Parallelism"
},
{
"code": null,
"e": 10002,
"s": 10000,
"text": "Δ"
},
{
"code": null,
"e": 10026,
"s": 10002,
"text": " Install Java on Mac OS"
},
{
"code": null,
"e": 10054,
"s": 10026,
"text": " Install AWS CLI on Windows"
},
{
"code": null,
"e": 10083,
"s": 10054,
"text": " Install Minikube on Windows"
},
{
"code": null,
"e": 10118,
"s": 10083,
"text": " Install Docker Toolbox on Windows"
},
{
"code": null,
"e": 10145,
"s": 10118,
"text": " Install SOAPUI on Windows"
},
{
"code": null,
"e": 10172,
"s": 10145,
"text": " Install Gradle on Windows"
},
{
"code": null,
"e": 10201,
"s": 10172,
"text": " Install RabbitMQ on Windows"
},
{
"code": null,
"e": 10227,
"s": 10201,
"text": " Install PuTTY on windows"
},
{
"code": null,
"e": 10253,
"s": 10227,
"text": " Install Mysql on Windows"
},
{
"code": null,
"e": 10289,
"s": 10253,
"text": " Install Hibernate Tools in Eclipse"
},
{
"code": null,
"e": 10323,
"s": 10289,
"text": " Install Elasticsearch on Windows"
},
{
"code": null,
"e": 10349,
"s": 10323,
"text": " Install Maven on Windows"
},
{
"code": null,
"e": 10374,
"s": 10349,
"text": " Install Maven on Ubuntu"
},
{
"code": null,
"e": 10408,
"s": 10374,
"text": " Install Maven on Windows Command"
},
{
"code": null,
"e": 10443,
"s": 10408,
"text": " Add OJDBC jar to Maven Repository"
},
{
"code": null,
"e": 10467,
"s": 10443,
"text": " Install Ant on Windows"
},
{
"code": null,
"e": 10496,
"s": 10467,
"text": " Install RabbitMQ on Windows"
},
{
"code": null,
"e": 10528,
"s": 10496,
"text": " Install Apache Kafka on Ubuntu"
},
{
"code": null,
"e": 10561,
"s": 10528,
"text": " Install Apache Kafka on Windows"
},
{
"code": null,
"e": 10586,
"s": 10561,
"text": " Java8 – Install Windows"
},
{
"code": null,
"e": 10603,
"s": 10586,
"text": " Java8 – foreach"
},
{
"code": null,
"e": 10631,
"s": 10603,
"text": " Java8 – forEach with index"
},
{
"code": null,
"e": 10662,
"s": 10631,
"text": " Java8 – Stream Filter Objects"
},
{
"code": null,
"e": 10694,
"s": 10662,
"text": " Java8 – Comparator Userdefined"
},
{
"code": null,
"e": 10714,
"s": 10694,
"text": " Java8 – GroupingBy"
},
{
"code": null,
"e": 10734,
"s": 10714,
"text": " Java8 – SummingInt"
},
{
"code": null,
"e": 10758,
"s": 10734,
"text": " Java8 – walk ReadFiles"
},
{
"code": null,
"e": 10788,
"s": 10758,
"text": " Java8 – JAVA_HOME on Windows"
},
{
"code": null,
"e": 10820,
"s": 10788,
"text": " Howto – Install Java on Mac OS"
},
{
"code": null,
"e": 10856,
"s": 10820,
"text": " Howto – Convert Iterable to Stream"
},
{
"code": null,
"e": 10900,
"s": 10856,
"text": " Howto – Get common elements from two Lists"
},
{
"code": null,
"e": 10932,
"s": 10900,
"text": " Howto – Convert List to String"
},
{
"code": null,
"e": 10973,
"s": 10932,
"text": " Howto – Concatenate Arrays using Stream"
},
{
"code": null,
"e": 11010,
"s": 10973,
"text": " Howto – Remove duplicates from List"
},
{
"code": null,
"e": 11050,
"s": 11010,
"text": " Howto – Filter null values from Stream"
},
{
"code": null,
"e": 11079,
"s": 11050,
"text": " Howto – Convert List to Map"
},
{
"code": null,
"e": 11111,
"s": 11079,
"text": " Howto – Convert Stream to List"
},
{
"code": null,
"e": 11131,
"s": 11111,
"text": " Howto – Sort a Map"
},
{
"code": null,
"e": 11153,
"s": 11131,
"text": " Howto – Filter a Map"
},
{
"code": null,
"e": 11183,
"s": 11153,
"text": " Howto – Get Current UTC Time"
},
{
"code": null,
"e": 11234,
"s": 11183,
"text": " Howto – Verify an Array contains a specific value"
},
{
"code": null,
"e": 11270,
"s": 11234,
"text": " Howto – Convert ArrayList to Array"
},
{
"code": null,
"e": 11302,
"s": 11270,
"text": " Howto – Read File Line By Line"
},
{
"code": null,
"e": 11337,
"s": 11302,
"text": " Howto – Convert Date to LocalDate"
},
{
"code": null,
"e": 11360,
"s": 11337,
"text": " Howto – Merge Streams"
},
{
"code": null,
"e": 11407,
"s": 11360,
"text": " Howto – Resolve NullPointerException in toMap"
},
{
"code": null,
"e": 11432,
"s": 11407,
"text": " Howto -Get Stream count"
},
{
"code": null,
"e": 11476,
"s": 11432,
"text": " Howto – Get Min and Max values in a Stream"
}
] |
How to create Python dictionary with duplicate keys?
|
Python dictionary doesn't allow key to be repeated. However, we can use defaultdict to find a workaround. This class is defined in collections module.
Use list as default factory for defaultdict object
>>> from collections import defaultdict
>>> d=defaultdict(list)
Here is a list of tuples each with two items. First item is found to be repeatedly used. This list is converted in defaultdict
>>> for k,v in l:
d[k].append(v)
Convert this defaultdict in a dictionary object using dict() function
>>> dict(d)
{1: [111, 'aaa'], 2: [222, 'bbb'], 3: [333, 'ccc']}
|
[
{
"code": null,
"e": 1213,
"s": 1062,
"text": "Python dictionary doesn't allow key to be repeated. However, we can use defaultdict to find a workaround. This class is defined in collections module."
},
{
"code": null,
"e": 1264,
"s": 1213,
"text": "Use list as default factory for defaultdict object"
},
{
"code": null,
"e": 1328,
"s": 1264,
"text": ">>> from collections import defaultdict\n>>> d=defaultdict(list)"
},
{
"code": null,
"e": 1455,
"s": 1328,
"text": "Here is a list of tuples each with two items. First item is found to be repeatedly used. This list is converted in defaultdict"
},
{
"code": null,
"e": 1494,
"s": 1455,
"text": ">>> for k,v in l:\n d[k].append(v)"
},
{
"code": null,
"e": 1564,
"s": 1494,
"text": "Convert this defaultdict in a dictionary object using dict() function"
},
{
"code": null,
"e": 1628,
"s": 1564,
"text": ">>> dict(d)\n{1: [111, 'aaa'], 2: [222, 'bbb'], 3: [333, 'ccc']}"
}
] |
Lodash _.toArray() Method - GeeksforGeeks
|
03 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 _.toArray() method is used to convert the given value to an array.
Syntax:
_.toArray( value )
Parameters: This method accepts a single parameter as mentioned above and described below:
value: This parameter holds the value to convert.
Return Value: This method returns the converted array.
Example 1:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.toArray() method console.log(_.toArray(null)); console.log(_.toArray('gfg'));
Output:
[]
['g', 'f', 'g']
Example 2:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.toArray() method console.log(_.toArray(10)); console.log(_.toArray({ 'html': 1, 'css': 2, 'javascript': 3 }));
Output:
[]
[1, 2, 3]
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24412,
"s": 24384,
"text": "\n03 Sep, 2020"
},
{
"code": null,
"e": 24552,
"s": 24412,
"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": 24623,
"s": 24552,
"text": "The _.toArray() method is used to convert the given value to an array."
},
{
"code": null,
"e": 24631,
"s": 24623,
"text": "Syntax:"
},
{
"code": null,
"e": 24651,
"s": 24631,
"text": "_.toArray( value )\n"
},
{
"code": null,
"e": 24742,
"s": 24651,
"text": "Parameters: This method accepts a single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 24792,
"s": 24742,
"text": "value: This parameter holds the value to convert."
},
{
"code": null,
"e": 24847,
"s": 24792,
"text": "Return Value: This method returns the converted array."
},
{
"code": null,
"e": 24858,
"s": 24847,
"text": "Example 1:"
},
{
"code": null,
"e": 24869,
"s": 24858,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.toArray() method console.log(_.toArray(null)); console.log(_.toArray('gfg'));",
"e": 25028,
"s": 24869,
"text": null
},
{
"code": null,
"e": 25036,
"s": 25028,
"text": "Output:"
},
{
"code": null,
"e": 25056,
"s": 25036,
"text": "[]\n['g', 'f', 'g']\n"
},
{
"code": null,
"e": 25069,
"s": 25056,
"text": "Example 2: "
},
{
"code": null,
"e": 25080,
"s": 25069,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.toArray() method console.log(_.toArray(10)); console.log(_.toArray({ 'html': 1, 'css': 2, 'javascript': 3 }));",
"e": 25276,
"s": 25080,
"text": null
},
{
"code": null,
"e": 25285,
"s": 25276,
"text": " Output:"
},
{
"code": null,
"e": 25299,
"s": 25285,
"text": "[]\n[1, 2, 3]\n"
},
{
"code": null,
"e": 25317,
"s": 25299,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 25328,
"s": 25317,
"text": "JavaScript"
},
{
"code": null,
"e": 25345,
"s": 25328,
"text": "Web Technologies"
},
{
"code": null,
"e": 25443,
"s": 25345,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25488,
"s": 25443,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 25549,
"s": 25488,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 25621,
"s": 25549,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 25673,
"s": 25621,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 25719,
"s": 25673,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 25761,
"s": 25719,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 25794,
"s": 25761,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 25837,
"s": 25794,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 25899,
"s": 25837,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
C - if...else statement
|
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
The syntax of an if...else statement in C programming language is −
if(boolean_expression) {
/* statement(s) will execute if the boolean expression is true */
} else {
/* statement(s) will execute if the boolean expression is false */
}
If the Boolean expression evaluates to true, then the if block will be executed, otherwise, the else block will be executed.
C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value.
#include <stdio.h>
int main () {
/* local variable definition */
int a = 100;
/* check the boolean condition */
if( a < 20 ) {
/* if condition is true then print the following */
printf("a is less than 20\n" );
} else {
/* if condition is false then print the following */
printf("a is not less than 20\n" );
}
printf("value of a is : %d\n", a);
return 0;
}
When the above code is compiled and executed, it produces the following result −
a is not less than 20;
value of a is : 100
An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.
When using if...else if..else statements, there are few points to keep in mind −
An if can have zero or one else's and it must come after any else if's.
An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of the remaining else if's or else's will be tested.
Once an else if succeeds, none of the remaining else if's or else's will be tested.
The syntax of an if...else if...else statement in C programming language is −
if(boolean_expression 1) {
/* Executes when the boolean expression 1 is true */
} else if( boolean_expression 2) {
/* Executes when the boolean expression 2 is true */
} else if( boolean_expression 3) {
/* Executes when the boolean expression 3 is true */
} else {
/* executes when the none of the above condition is true */
}
#include <stdio.h>
int main () {
/* local variable definition */
int a = 100;
/* check the boolean condition */
if( a == 10 ) {
/* if condition is true then print the following */
printf("Value of a is 10\n" );
} else if( a == 20 ) {
/* if else if condition is true */
printf("Value of a is 20\n" );
} else if( a == 30 ) {
/* if else if condition is true */
printf("Value of a is 30\n" );
} else {
/* if none of the conditions is true */
printf("None of the values is matching\n" );
}
printf("Exact value of a is: %d\n", a );
return 0;
}
When the above code is compiled and executed, it produces the following result −
None of the values is matching
Exact value of a is: 100
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2200,
"s": 2084,
"text": "An if statement can be followed by an optional else statement, which executes when the Boolean expression is false."
},
{
"code": null,
"e": 2268,
"s": 2200,
"text": "The syntax of an if...else statement in C programming language is −"
},
{
"code": null,
"e": 2444,
"s": 2268,
"text": "if(boolean_expression) {\n /* statement(s) will execute if the boolean expression is true */\n} else {\n /* statement(s) will execute if the boolean expression is false */\n}\n"
},
{
"code": null,
"e": 2569,
"s": 2444,
"text": "If the Boolean expression evaluates to true, then the if block will be executed, otherwise, the else block will be executed."
},
{
"code": null,
"e": 2711,
"s": 2569,
"text": "C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value."
},
{
"code": null,
"e": 3128,
"s": 2711,
"text": "#include <stdio.h>\n \nint main () {\n\n /* local variable definition */\n int a = 100;\n \n /* check the boolean condition */\n if( a < 20 ) {\n /* if condition is true then print the following */\n printf(\"a is less than 20\\n\" );\n } else {\n /* if condition is false then print the following */\n printf(\"a is not less than 20\\n\" );\n }\n \n printf(\"value of a is : %d\\n\", a);\n \n return 0;\n}"
},
{
"code": null,
"e": 3209,
"s": 3128,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3253,
"s": 3209,
"text": "a is not less than 20;\nvalue of a is : 100\n"
},
{
"code": null,
"e": 3411,
"s": 3253,
"text": "An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement."
},
{
"code": null,
"e": 3492,
"s": 3411,
"text": "When using if...else if..else statements, there are few points to keep in mind −"
},
{
"code": null,
"e": 3564,
"s": 3492,
"text": "An if can have zero or one else's and it must come after any else if's."
},
{
"code": null,
"e": 3636,
"s": 3564,
"text": "An if can have zero or one else's and it must come after any else if's."
},
{
"code": null,
"e": 3710,
"s": 3636,
"text": "An if can have zero to many else if's and they must come before the else."
},
{
"code": null,
"e": 3784,
"s": 3710,
"text": "An if can have zero to many else if's and they must come before the else."
},
{
"code": null,
"e": 3868,
"s": 3784,
"text": "Once an else if succeeds, none of the remaining else if's or else's will be tested."
},
{
"code": null,
"e": 3952,
"s": 3868,
"text": "Once an else if succeeds, none of the remaining else if's or else's will be tested."
},
{
"code": null,
"e": 4030,
"s": 3952,
"text": "The syntax of an if...else if...else statement in C programming language is −"
},
{
"code": null,
"e": 4370,
"s": 4030,
"text": "if(boolean_expression 1) {\n /* Executes when the boolean expression 1 is true */\n} else if( boolean_expression 2) {\n /* Executes when the boolean expression 2 is true */\n} else if( boolean_expression 3) {\n /* Executes when the boolean expression 3 is true */\n} else {\n /* executes when the none of the above condition is true */\n}\n"
},
{
"code": null,
"e": 4998,
"s": 4370,
"text": "#include <stdio.h>\n \nint main () {\n\n /* local variable definition */\n int a = 100;\n \n /* check the boolean condition */\n if( a == 10 ) {\n /* if condition is true then print the following */\n printf(\"Value of a is 10\\n\" );\n } else if( a == 20 ) {\n /* if else if condition is true */\n printf(\"Value of a is 20\\n\" );\n } else if( a == 30 ) {\n /* if else if condition is true */\n printf(\"Value of a is 30\\n\" );\n } else {\n /* if none of the conditions is true */\n printf(\"None of the values is matching\\n\" );\n }\n \n printf(\"Exact value of a is: %d\\n\", a );\n \n return 0;\n}"
},
{
"code": null,
"e": 5079,
"s": 4998,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5136,
"s": 5079,
"text": "None of the values is matching\nExact value of a is: 100\n"
},
{
"code": null,
"e": 5143,
"s": 5136,
"text": " Print"
},
{
"code": null,
"e": 5154,
"s": 5143,
"text": " Add Notes"
}
] |
Exercise v1.3
|
Create a variable called carName, assign the value "Volvo" to it, and display it.
Hint: Use the var keyword to create a variable.
<!DOCTYPE html>
<html>
<body>
<p id="demo">Display the result here.</p>
<script>
// Create the variable here
</script>
</body>
</html>
xxxxxxxxxx
<!DOCTYPE html>
<html>
<body>
<p id="demo">Display the result here.</p>
<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
|
[
{
"code": null,
"e": 82,
"s": 0,
"text": "Create a variable called carName, assign the value \"Volvo\" to it, and display it."
},
{
"code": null,
"e": 130,
"s": 82,
"text": "Hint: Use the var keyword to create a variable."
},
{
"code": null,
"e": 146,
"s": 130,
"text": "<!DOCTYPE html>"
},
{
"code": null,
"e": 153,
"s": 146,
"text": "<html>"
},
{
"code": null,
"e": 160,
"s": 153,
"text": "<body>"
},
{
"code": null,
"e": 162,
"s": 160,
"text": ""
},
{
"code": null,
"e": 205,
"s": 162,
"text": "<p id=\"demo\">Display the result here.</p> "
},
{
"code": null,
"e": 207,
"s": 205,
"text": ""
},
{
"code": null,
"e": 216,
"s": 207,
"text": "<script>"
},
{
"code": null,
"e": 244,
"s": 216,
"text": "// Create the variable here"
},
{
"code": null,
"e": 254,
"s": 244,
"text": "</script>"
},
{
"code": null,
"e": 256,
"s": 254,
"text": ""
},
{
"code": null,
"e": 264,
"s": 256,
"text": "</body>"
},
{
"code": null,
"e": 272,
"s": 264,
"text": "</html>"
},
{
"code": null,
"e": 274,
"s": 272,
"text": ""
},
{
"code": null,
"e": 285,
"s": 274,
"text": "xxxxxxxxxx"
},
{
"code": null,
"e": 301,
"s": 285,
"text": "<!DOCTYPE html>"
},
{
"code": null,
"e": 308,
"s": 301,
"text": "<html>"
},
{
"code": null,
"e": 315,
"s": 308,
"text": "<body>"
},
{
"code": null,
"e": 317,
"s": 315,
"text": ""
},
{
"code": null,
"e": 360,
"s": 317,
"text": "<p id=\"demo\">Display the result here.</p> "
},
{
"code": null,
"e": 362,
"s": 360,
"text": ""
},
{
"code": null,
"e": 371,
"s": 362,
"text": "<script>"
},
{
"code": null,
"e": 394,
"s": 371,
"text": "var carName = \"Volvo\";"
}
] |
PostgreSQL - Logical Operators
|
Consider the table COMPANY having records as follows −
testdb# 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)
Here are simple examples showing the usage of PostgreSQL LOGICAL Operators. The following SELECT statement lists down all the records where AGE is greater than or equal to 25 and salary is greater than or equal to 65000.00.
testdb=# SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 6500;
The above given PostgreSQL statement will produce the following result −
id | name | age | address | salary
----+-------+-----+-----------------------------------------------+--------
1 | Paul | 32 | California | 20000
2 | Allen | 25 | Texas | 15000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
(4 rows)
The following SELECT statement lists down all the records where AGE is greater than or equal to 25 OR salary is greater than or equal to 65000.00 −
testdb=# SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 6500;
The above given PostgreSQL statement will produce the following result −
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
8 | Paul | 24 | Houston | 20000
9 | James | 44 | Norway | 5000
10 | James | 45 | Texas | 5000
(10 rows)
The following SELECT statement lists down all the records where AGE is not NULL, which means all the records because none of the record is having AGE equal to NULL −
testdb=# SELECT * FROM COMPANY WHERE SALARY IS NOT NULL;
The above given PostgreSQL statement will produce the following result −
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
8 | Paul | 24 | Houston | 20000
9 | James | 44 | Norway | 5000
10 | James | 45 | Texas | 5000
(10 rows)
23 Lectures
1.5 hours
John Elder
49 Lectures
3.5 hours
Niyazi Erdogan
126 Lectures
10.5 hours
Abhishek And Pukhraj
35 Lectures
5 hours
Karthikeya T
5 Lectures
51 mins
Vinay Kumar
5 Lectures
52 mins
Vinay Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2880,
"s": 2825,
"text": "Consider the table COMPANY having records as follows −"
},
{
"code": null,
"e": 3273,
"s": 2880,
"text": "testdb# 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)\n"
},
{
"code": null,
"e": 3497,
"s": 3273,
"text": "Here are simple examples showing the usage of PostgreSQL LOGICAL Operators. The following SELECT statement lists down all the records where AGE is greater than or equal to 25 and salary is greater than or equal to 65000.00."
},
{
"code": null,
"e": 3564,
"s": 3497,
"text": "testdb=# SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 6500;"
},
{
"code": null,
"e": 3637,
"s": 3564,
"text": "The above given PostgreSQL statement will produce the following result −"
},
{
"code": null,
"e": 4098,
"s": 3637,
"text": " id | name | age | address | salary\n----+-------+-----+-----------------------------------------------+--------\n 1 | Paul | 32 | California | 20000\n 2 | Allen | 25 | Texas | 15000\n 4 | Mark | 25 | Rich-Mond | 65000\n 5 | David | 27 | Texas | 85000\n(4 rows)\n"
},
{
"code": null,
"e": 4246,
"s": 4098,
"text": "The following SELECT statement lists down all the records where AGE is greater than or equal to 25 OR salary is greater than or equal to 65000.00 −"
},
{
"code": null,
"e": 4312,
"s": 4246,
"text": "testdb=# SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 6500;"
},
{
"code": null,
"e": 4385,
"s": 4312,
"text": "The above given PostgreSQL statement will produce the following result −"
},
{
"code": null,
"e": 4889,
"s": 4385,
"text": " 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 8 | Paul | 24 | Houston | 20000\n 9 | James | 44 | Norway | 5000\n 10 | James | 45 | Texas | 5000\n(10 rows)\n"
},
{
"code": null,
"e": 5055,
"s": 4889,
"text": "The following SELECT statement lists down all the records where AGE is not NULL, which means all the records because none of the record is having AGE equal to NULL −"
},
{
"code": null,
"e": 5113,
"s": 5055,
"text": "testdb=# SELECT * FROM COMPANY WHERE SALARY IS NOT NULL;"
},
{
"code": null,
"e": 5186,
"s": 5113,
"text": "The above given PostgreSQL statement will produce the following result −"
},
{
"code": null,
"e": 5690,
"s": 5186,
"text": " 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 8 | Paul | 24 | Houston | 20000\n 9 | James | 44 | Norway | 5000\n 10 | James | 45 | Texas | 5000\n(10 rows)\n"
},
{
"code": null,
"e": 5725,
"s": 5690,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5737,
"s": 5725,
"text": " John Elder"
},
{
"code": null,
"e": 5772,
"s": 5737,
"text": "\n 49 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5788,
"s": 5772,
"text": " Niyazi Erdogan"
},
{
"code": null,
"e": 5825,
"s": 5788,
"text": "\n 126 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 5847,
"s": 5825,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 5880,
"s": 5847,
"text": "\n 35 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5894,
"s": 5880,
"text": " Karthikeya T"
},
{
"code": null,
"e": 5925,
"s": 5894,
"text": "\n 5 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 5938,
"s": 5925,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 5969,
"s": 5938,
"text": "\n 5 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 5982,
"s": 5969,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 5989,
"s": 5982,
"text": " Print"
},
{
"code": null,
"e": 6000,
"s": 5989,
"text": " Add Notes"
}
] |
Optional property in a C# class
|
A property is optional if it is possible and valid for it to have null. A property whose CLR type cannot have null cannot be configured optional.
An example optional attribute usage −
[AttributeUsage(AttributeTargets.Property,
Inherited = false,
AllowMultiple = false)]
internal sealed class OptionalAttribute : Attribute { }
public class Employee {
public string EmpName { get; set; }
[Optional]
public string AlternativeName { get; set; }
}
|
[
{
"code": null,
"e": 1208,
"s": 1062,
"text": "A property is optional if it is possible and valid for it to have null. A property whose CLR type cannot have null cannot be configured optional."
},
{
"code": null,
"e": 1246,
"s": 1208,
"text": "An example optional attribute usage −"
},
{
"code": null,
"e": 1516,
"s": 1246,
"text": "[AttributeUsage(AttributeTargets.Property,\nInherited = false,\nAllowMultiple = false)]\ninternal sealed class OptionalAttribute : Attribute { }\n\npublic class Employee {\n public string EmpName { get; set; }\n\n [Optional]\n public string AlternativeName { get; set; }\n}"
}
] |
How to check multiple columns for a single value in MySQL?
|
You can check multiple columns for one value with the help of IN operator. The syntax is as follows −
select *from yourTableName where value IN(yourColumnName1, yourColumnName2,......N);
To understand the above concept, let us create a table with some columns. The query to create a table is as follows −
mysql> create table OneValueFromAllColumns
−> (
−> StudentId int,
−> StudentFirstname varchar(200),
−> StudentLastname varchar(200),
−> StudentAge int
−> );
Query OK, 0 rows affected (1.41 sec)
Insert some records in the table with the help of select statement. The query is as follows −
mysql> insert into OneValueFromAllColumns values(1,'John','Smith',23);
Query OK, 1 row affected (0.14 sec)
mysql> insert into OneValueFromAllColumns values(2,'Carol','Taylor',22);
Query OK, 1 row affected (0.18 sec)
mysql> insert into OneValueFromAllColumns values(3,'Maria','Garcia',19);
Query OK, 1 row affected (0.16 sec)
mysql> insert into OneValueFromAllColumns values(4,'Bob','Wilson',21);
Query OK, 1 row affected (0.22 sec)
Display all records which we have inserted above. The query to display all records from the table is as follows −
mysql> select *from OneValueFromAllColumns;
The following is the output −
+-----------+------------------+-----------------+------------+
| StudentId | StudentFirstname | StudentLastname | StudentAge |
+-----------+------------------+-----------------+------------+
| 1 | John | Smith | 23 |
| 2 | Carol | Taylor | 22 |
| 3 | Maria | Garcia | 19 |
| 4 | Bob | Wilson | 21 |
+-----------+------------------+-----------------+------------+
4 rows in set (0.00 sec)
Here is the query to check multiple columns for single value. We are checking for the value “Taylor’ in multiple columns i.e. StudentId, StudentFirstname, StudentLastname and StudentAge.
The query is as follows −
mysql> select *from OneValueFromAllColumns where 'Taylor' IN(StudentId,StudentFirstname,StudentLastname,StudentAge);
The following is the output that displays the record with the value “Taylor” −
+-----------+------------------+-----------------+------------+
| StudentId | StudentFirstname | StudentLastname | StudentAge |
+-----------+------------------+-----------------+------------+
| 2 | Carol | Taylor | 22 |
+-----------+------------------+-----------------+------------+
1 row in set, 4 warnings (0.03 sec)
|
[
{
"code": null,
"e": 1164,
"s": 1062,
"text": "You can check multiple columns for one value with the help of IN operator. The syntax is as follows −"
},
{
"code": null,
"e": 1249,
"s": 1164,
"text": "select *from yourTableName where value IN(yourColumnName1, yourColumnName2,......N);"
},
{
"code": null,
"e": 1367,
"s": 1249,
"text": "To understand the above concept, let us create a table with some columns. The query to create a table is as follows −"
},
{
"code": null,
"e": 1579,
"s": 1367,
"text": "mysql> create table OneValueFromAllColumns\n −> (\n −> StudentId int,\n −> StudentFirstname varchar(200),\n −> StudentLastname varchar(200),\n −> StudentAge int\n −> );\nQuery OK, 0 rows affected (1.41 sec)"
},
{
"code": null,
"e": 1673,
"s": 1579,
"text": "Insert some records in the table with the help of select statement. The query is as follows −"
},
{
"code": null,
"e": 2108,
"s": 1673,
"text": "mysql> insert into OneValueFromAllColumns values(1,'John','Smith',23);\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into OneValueFromAllColumns values(2,'Carol','Taylor',22);\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into OneValueFromAllColumns values(3,'Maria','Garcia',19);\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into OneValueFromAllColumns values(4,'Bob','Wilson',21);\nQuery OK, 1 row affected (0.22 sec)"
},
{
"code": null,
"e": 2222,
"s": 2108,
"text": "Display all records which we have inserted above. The query to display all records from the table is as follows −"
},
{
"code": null,
"e": 2266,
"s": 2222,
"text": "mysql> select *from OneValueFromAllColumns;"
},
{
"code": null,
"e": 2296,
"s": 2266,
"text": "The following is the output −"
},
{
"code": null,
"e": 2833,
"s": 2296,
"text": "+-----------+------------------+-----------------+------------+\n| StudentId | StudentFirstname | StudentLastname | StudentAge |\n+-----------+------------------+-----------------+------------+\n| 1 | John | Smith | 23 |\n| 2 | Carol | Taylor | 22 |\n| 3 | Maria | Garcia | 19 |\n| 4 | Bob | Wilson | 21 |\n+-----------+------------------+-----------------+------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3020,
"s": 2833,
"text": "Here is the query to check multiple columns for single value. We are checking for the value “Taylor’ in multiple columns i.e. StudentId, StudentFirstname, StudentLastname and StudentAge."
},
{
"code": null,
"e": 3046,
"s": 3020,
"text": "The query is as follows −"
},
{
"code": null,
"e": 3163,
"s": 3046,
"text": "mysql> select *from OneValueFromAllColumns where 'Taylor' IN(StudentId,StudentFirstname,StudentLastname,StudentAge);"
},
{
"code": null,
"e": 3242,
"s": 3163,
"text": "The following is the output that displays the record with the value “Taylor” −"
},
{
"code": null,
"e": 3598,
"s": 3242,
"text": "+-----------+------------------+-----------------+------------+\n| StudentId | StudentFirstname | StudentLastname | StudentAge |\n+-----------+------------------+-----------------+------------+\n| 2 | Carol | Taylor | 22 |\n+-----------+------------------+-----------------+------------+\n1 row in set, 4 warnings (0.03 sec)"
}
] |
How do you create a Tkinter GUI stop button to break an infinite loop?
|
Tkinter is a Python library which is used to create GUI-based application. Let us suppose that we have to create a functional application in which a particular function is defined in a loop. The recursive function will display some text in a Label widget for infinite times.
To stop this recursive function, we can define a function which changes the condition whenever a button is clicked. The condition can be changed by declaring a global variable which can be either True or False.
# Import the required library
from tkinter import *
# Create an instance of tkinter frame
win= Tk()
# Set the size of the Tkinter window
win.geometry("700x350")
# Define a function to print something inside infinite loop
run= True
def print_hello():
if run:
Label(win, text="Hello World", font= ('Helvetica 10 bold')).pack()
# After 1 sec call the print_hello() again
win.after(1000, print_hello)
def start():
global run
run= True
def stop():
global run
run= False
# Create buttons to trigger the starting and ending of the loop
start= Button(win, text= "Start", command= start)
start.pack(padx= 10)
stop= Button(win, text= "Stop", command= stop)
stop.pack(padx= 15)
# Call the print_hello() function after 1 sec.
win.after(1000, print_hello)
win.mainloop()
Now, whenever we click the "Stop" button, it will stop calling the function.
|
[
{
"code": null,
"e": 1337,
"s": 1062,
"text": "Tkinter is a Python library which is used to create GUI-based application. Let us suppose that we have to create a functional application in which a particular function is defined in a loop. The recursive function will display some text in a Label widget for infinite times."
},
{
"code": null,
"e": 1548,
"s": 1337,
"text": "To stop this recursive function, we can define a function which changes the condition whenever a button is clicked. The condition can be changed by declaring a global variable which can be either True or False."
},
{
"code": null,
"e": 2340,
"s": 1548,
"text": "# Import the required library\nfrom tkinter import *\n\n# Create an instance of tkinter frame\nwin= Tk()\n\n# Set the size of the Tkinter window\nwin.geometry(\"700x350\")\n\n# Define a function to print something inside infinite loop\nrun= True\n\ndef print_hello():\n if run:\n Label(win, text=\"Hello World\", font= ('Helvetica 10 bold')).pack()\n # After 1 sec call the print_hello() again\n win.after(1000, print_hello)\ndef start():\n global run\n run= True\n\ndef stop():\n global run\n run= False\n\n# Create buttons to trigger the starting and ending of the loop\nstart= Button(win, text= \"Start\", command= start)\nstart.pack(padx= 10)\nstop= Button(win, text= \"Stop\", command= stop)\nstop.pack(padx= 15)\n\n# Call the print_hello() function after 1 sec.\nwin.after(1000, print_hello)\nwin.mainloop()"
},
{
"code": null,
"e": 2417,
"s": 2340,
"text": "Now, whenever we click the \"Stop\" button, it will stop calling the function."
}
] |
Python | os.DirEntry.is_dir() method
|
28 Aug, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.scandir() method of os module yields os.DirEntry objects corresponding to the entries in the directory given by specified path. os.DirEntry object has various attributes and method which is used to expose the file path and other file attributes of the directory entry.
is_dir() method on os.DirEntry object is used to check if the entry is a directory or not.
Note: os.DirEntry objects are intended to be used and thrown away after iteration as attributes and methods of the object cache their values and never refetch the values again. If the metadata of the file has been changed or if a long time has elapsed since calling os.scandir() method. we will not get up-to-date information.
Syntax: os.DirEntry.is_dir(*, follow_symlinks = True)
Parameter:follow_symlinks: A boolean value is required for this parameter. If the entry is a symbolic link and follow_symlinks is True then the method will operate on the path symbolic link point to. If the entry is a symbolic link and follow_symlinks is False then the method will operate on the symbolic link itself. If the entry is not a symbolic link then follow_symlinks parameter is ignored. The default value of this parameter is True.
Return value: This method returns True if the entry is a directory otherwise returns False.
Code #1: Use of os.DirEntry.is_dir() method
# Python program to explain os.DirEntry.is_dir() method # importing os module import os # Directory to be scanned# Pathpath = "/home / ihritik" # Using os.scandir() method# scan the specified directory# and yield os.DirEntry object# for each file and sub-directory with os.scandir(path) as itr: for entry in itr : # Check if the entry # is directory if entry.is_dir() : print("% s is a directory." % entry.name) else: print("% s is not a directory." % entry.name)
file.txt is not a directory.
Public is a directory.
Desktop is a directory.
R is a directory.
Music is a directory.
Documents is a directory.
tree.cpp is not a directory.
graph.cpp is not a directory.
Pictures is a directory.
GeeksForGeeks is a directory.
Videos is a directory.
images is a directory.
Downloads is a directory.
abc.txt is not a directory.
Code #2: Use of os.DirEntry.is_dir() method
# Python program to explain os.DirEntry.is_dir() method # importing os module import os # Directory to be scanned# Pathpath = "/home / ihritik" # Using os.scandir() method# scan the specified directory# and yield os.DirEntry object# for each file and sub-directory print("List of all directories in '% s':" % path) with os.scandir(path) as itr: for entry in itr : # Check if the entry # is directory if entry.is_dir() : # Exclude the directory name # starting with '.' if not entry.name.startswith('.') : # Print Directory name print(entry.name)
List of all directories in path '/home/ihritik':
Public
Desktop
R
Music
Documents
Pictures
GeeksForGeeks
Videos
images
Downloads
References: https://docs.python.org/3/library/os.html#os.DirEntry.is_dir
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Aug, 2019"
},
{
"code": null,
"e": 247,
"s": 28,
"text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality."
},
{
"code": null,
"e": 519,
"s": 247,
"text": "os.scandir() method of os module yields os.DirEntry objects corresponding to the entries in the directory given by specified path. os.DirEntry object has various attributes and method which is used to expose the file path and other file attributes of the directory entry."
},
{
"code": null,
"e": 610,
"s": 519,
"text": "is_dir() method on os.DirEntry object is used to check if the entry is a directory or not."
},
{
"code": null,
"e": 937,
"s": 610,
"text": "Note: os.DirEntry objects are intended to be used and thrown away after iteration as attributes and methods of the object cache their values and never refetch the values again. If the metadata of the file has been changed or if a long time has elapsed since calling os.scandir() method. we will not get up-to-date information."
},
{
"code": null,
"e": 991,
"s": 937,
"text": "Syntax: os.DirEntry.is_dir(*, follow_symlinks = True)"
},
{
"code": null,
"e": 1434,
"s": 991,
"text": "Parameter:follow_symlinks: A boolean value is required for this parameter. If the entry is a symbolic link and follow_symlinks is True then the method will operate on the path symbolic link point to. If the entry is a symbolic link and follow_symlinks is False then the method will operate on the symbolic link itself. If the entry is not a symbolic link then follow_symlinks parameter is ignored. The default value of this parameter is True."
},
{
"code": null,
"e": 1526,
"s": 1434,
"text": "Return value: This method returns True if the entry is a directory otherwise returns False."
},
{
"code": null,
"e": 1570,
"s": 1526,
"text": "Code #1: Use of os.DirEntry.is_dir() method"
},
{
"code": "# Python program to explain os.DirEntry.is_dir() method # importing os module import os # Directory to be scanned# Pathpath = \"/home / ihritik\" # Using os.scandir() method# scan the specified directory# and yield os.DirEntry object# for each file and sub-directory with os.scandir(path) as itr: for entry in itr : # Check if the entry # is directory if entry.is_dir() : print(\"% s is a directory.\" % entry.name) else: print(\"% s is not a directory.\" % entry.name)",
"e": 2094,
"s": 1570,
"text": null
},
{
"code": null,
"e": 2451,
"s": 2094,
"text": "file.txt is not a directory.\nPublic is a directory.\nDesktop is a directory.\nR is a directory.\nMusic is a directory.\nDocuments is a directory.\ntree.cpp is not a directory.\ngraph.cpp is not a directory.\nPictures is a directory.\nGeeksForGeeks is a directory.\nVideos is a directory.\nimages is a directory.\nDownloads is a directory.\nabc.txt is not a directory.\n"
},
{
"code": null,
"e": 2495,
"s": 2451,
"text": "Code #2: Use of os.DirEntry.is_dir() method"
},
{
"code": "# Python program to explain os.DirEntry.is_dir() method # importing os module import os # Directory to be scanned# Pathpath = \"/home / ihritik\" # Using os.scandir() method# scan the specified directory# and yield os.DirEntry object# for each file and sub-directory print(\"List of all directories in '% s':\" % path) with os.scandir(path) as itr: for entry in itr : # Check if the entry # is directory if entry.is_dir() : # Exclude the directory name # starting with '.' if not entry.name.startswith('.') : # Print Directory name print(entry.name)",
"e": 3145,
"s": 2495,
"text": null
},
{
"code": null,
"e": 3275,
"s": 3145,
"text": "List of all directories in path '/home/ihritik':\nPublic\nDesktop\nR\nMusic\nDocuments\nPictures\nGeeksForGeeks\nVideos\nimages\nDownloads\n"
},
{
"code": null,
"e": 3348,
"s": 3275,
"text": "References: https://docs.python.org/3/library/os.html#os.DirEntry.is_dir"
},
{
"code": null,
"e": 3365,
"s": 3348,
"text": "python-os-module"
},
{
"code": null,
"e": 3372,
"s": 3365,
"text": "Python"
}
] |
Long Division Method to find Square root with Examples
|
26 Nov, 2021
Given an integer X which is a perfect square, the task is to find the square root of it by using the long division method.
Examples:
Input: N = 484 Output: 22 222 = 484
Input: N = 144 Output: 12 122 = 144
Approach: Long division is a very common method to find the square root of a number. The following is the stepwise solution for this method:
1. Divide the digits of the number into pairs of segments starting with the digit in the units place. Let’s identify each pair and the remaining final digit(in case there is an odd count of digits in the number) as a segment. For example:
1225 is divided as (12 25)
2. After dividing the digits into segments, start from the leftmost segment. The largest number whose square is equal to or just less than the first segment is taken as the divisor and also as the quotient (so that the product is the square). For example:
9 is the closest perfect square to 12, the first segment 12
3. Subtract the square of the divisor from the first segment and bring down the next segment to the right of the remainder to get the new dividend. For example:
12 - 9 = 3 is concatenated with next segment 25.
New dividend = 325
4. Now, the new divisor is obtained by taking two times the previous quotient(which was 3 in the above example as 32 = 9) and concatenating it with a suitable digit which is also taken as the next digit of the quotient, chosen in such a way that the product of the new divisor and this digit is equal to, or just less than the new dividend. For example:
Two times quotient 3 is 6.
65 times 5 is 325 which is closest to the new dividend.
5. Repeat steps (2), (3) and (4) till all the segments have been taken up. Now, the quotient so obtained is the required square root of the given number.
Below is the implementation of the above approach:
CPP
Java
Python3
C#
Javascript
// C++ program to find the square root of a// number by using long division method #include <bits/stdc++.h>using namespace std;#define INFINITY_ 9999999 // Function to find the square root of// a number by using long division methodint sqrtByLongDivision(int n){ int i = 0, udigit, j; // Loop counters int cur_divisor = 0; int quotient_units_digit = 0; int cur_quotient = 0; int cur_dividend = 0; int cur_remainder = 0; int a[10] = { 0 }; // Dividing the number into segments while (n > 0) { a[i] = n % 100; n = n / 100; i++; } // Last index of the array of segments i--; // Start long division from the last segment(j=i) for (j = i; j >= 0; j--) { // Initialising the remainder to the maximum value cur_remainder = INFINITY_; // Including the next segment in new dividend cur_dividend = cur_dividend * 100 + a[j]; // Loop to check for the perfect square // closest to each segment for (udigit = 0; udigit <= 9; udigit++) { // This condition is to find the // divisor after adding a digit // in the range 0 to 9 if (cur_remainder >= cur_dividend - ((cur_divisor * 10 + udigit) * udigit) && cur_dividend - ((cur_divisor * 10 + udigit) * udigit) >= 0) { // Calculating the remainder cur_remainder = cur_dividend - ((cur_divisor * 10 + udigit) * udigit); // Updating the units digit of the quotient quotient_units_digit = udigit; } } // Adding units digit to the quotient cur_quotient = cur_quotient * 10 + quotient_units_digit; // New divisor is two times quotient cur_divisor = cur_quotient * 2; // Including the remainder in new dividend cur_dividend = cur_remainder; } return cur_quotient;} // Driver codeint main(){ int x = 1225; cout << sqrtByLongDivision(x) << endl; return 0;}
// Java program to find the square root of a// number by using long division methodimport java.util.*; class GFG{static final int INFINITY_ =9999999; // Function to find the square root of// a number by using long division methodstatic int sqrtByLongDivision(int n){ int i = 0, udigit, j; // Loop counters int cur_divisor = 0; int quotient_units_digit = 0; int cur_quotient = 0; int cur_dividend = 0; int cur_remainder = 0; int a[] = new int[10]; // Dividing the number into segments while (n > 0) { a[i] = n % 100; n = n / 100; i++; } // Last index of the array of segments i--; // Start long division from the last segment(j=i) for (j = i; j >= 0; j--) { // Initialising the remainder to the maximum value cur_remainder = INFINITY_; // Including the next segment in new dividend cur_dividend = cur_dividend * 100 + a[j]; // Loop to check for the perfect square // closest to each segment for (udigit = 0; udigit <= 9; udigit++) { // This condition is to find the // divisor after adding a digit // in the range 0 to 9 if (cur_remainder >= cur_dividend - ((cur_divisor * 10 + udigit) * udigit) && cur_dividend - ((cur_divisor * 10 + udigit) * udigit) >= 0) { // Calculating the remainder cur_remainder = cur_dividend - ((cur_divisor * 10 + udigit) * udigit); // Updating the units digit of the quotient quotient_units_digit = udigit; } } // Adding units digit to the quotient cur_quotient = cur_quotient * 10 + quotient_units_digit; // New divisor is two times quotient cur_divisor = cur_quotient * 2; // Including the remainder in new dividend cur_dividend = cur_remainder; } return cur_quotient;} // Driver codepublic static void main(String[] args){ int x = 1225; System.out.print(sqrtByLongDivision(x) +"\n");}} // This code is contributed by Rajput-Ji
# Python3 program to find the square root of a# number by using long division methodINFINITY_ = 9999999 # Function to find the square root of# a number by using long division methoddef sqrtByLongDivision(n): i = 0 udigit, j = 0, 0 # Loop counters cur_divisor = 0 quotient_units_digit = 0 cur_quotient = 0 cur_dividend = 0 cur_remainder = 0 a = [0]*10 # Dividing the number into segments while (n > 0): a[i] = n % 100 n = n // 100 i += 1 # Last index of the array of segments i -= 1 # Start long division from the last segment(j=i) for j in range(i, -1, -1): # Initialising the remainder to the maximum value cur_remainder = INFINITY_ # Including the next segment in new dividend cur_dividend = cur_dividend * 100 + a[j] # Loop to check for the perfect square # closest to each segment for udigit in range(10): # This condition is to find the # divisor after adding a digit # in the range 0 to 9 if (cur_remainder >= cur_dividend - ((cur_divisor * 10 + udigit) * udigit) and cur_dividend - ((cur_divisor * 10 + udigit) * udigit) >= 0): # Calculating the remainder cur_remainder = cur_dividend - ((cur_divisor * 10 + udigit) * udigit) # Updating the units digit of the quotient quotient_units_digit = udigit # Adding units digit to the quotient cur_quotient = cur_quotient * 10 + quotient_units_digit # New divisor is two times quotient cur_divisor = cur_quotient * 2 # Including the remainder in new dividend cur_dividend = cur_remainder return cur_quotient # Driver code x = 1225print(sqrtByLongDivision(x)) # This code is contributed by mohit kumar 29
// C# program to find the square root of a// number by using long division methodusing System; class GFG{static readonly int INFINITY_ =9999999; // Function to find the square root of// a number by using long division methodstatic int sqrtBylongDivision(int n){ int i = 0, udigit, j; // Loop counters int cur_divisor = 0; int quotient_units_digit = 0; int cur_quotient = 0; int cur_dividend = 0; int cur_remainder = 0; int []a = new int[10]; // Dividing the number into segments while (n > 0) { a[i] = n % 100; n = n / 100; i++; } // Last index of the array of segments i--; // Start long division from the last segment(j=i) for (j = i; j >= 0; j--) { // Initialising the remainder to the maximum value cur_remainder = INFINITY_; // Including the next segment in new dividend cur_dividend = cur_dividend * 100 + a[j]; // Loop to check for the perfect square // closest to each segment for (udigit = 0; udigit <= 9; udigit++) { // This condition is to find the // divisor after adding a digit // in the range 0 to 9 if (cur_remainder >= cur_dividend - ((cur_divisor * 10 + udigit) * udigit) && cur_dividend - ((cur_divisor * 10 + udigit) * udigit) >= 0) { // Calculating the remainder cur_remainder = cur_dividend - ((cur_divisor * 10 + udigit) * udigit); // Updating the units digit of the quotient quotient_units_digit = udigit; } } // Adding units digit to the quotient cur_quotient = cur_quotient * 10 + quotient_units_digit; // New divisor is two times quotient cur_divisor = cur_quotient * 2; // Including the remainder in new dividend cur_dividend = cur_remainder; } return cur_quotient;} // Driver codepublic static void Main(String[] args){ int x = 1225; Console.Write(sqrtBylongDivision(x) +"\n");}} // This code is contributed by Rajput-Ji
<script>// Javascript program to find the square root of a// number by using long division method let INFINITY_ =9999999; // Function to find the square root of// a number by using long division methodfunction sqrtByLongDivision(n){ let i = 0, udigit, j; // Loop counters let cur_divisor = 0; let quotient_units_digit = 0; let cur_quotient = 0; let cur_dividend = 0; let cur_remainder = 0; let a = new Array(10); // Dividing the number into segments while (n > 0) { a[i] = n % 100; n = Math.floor(n / 100); i++; } // Last index of the array of segments i--; // Start long division from the last segment(j=i) for (j = i; j >= 0; j--) { // Initialising the remainder to the maximum value cur_remainder = INFINITY_; // Including the next segment in new dividend cur_dividend = cur_dividend * 100 + a[j]; // Loop to check for the perfect square // closest to each segment for (udigit = 0; udigit <= 9; udigit++) { // This condition is to find the // divisor after adding a digit // in the range 0 to 9 if (cur_remainder >= cur_dividend - ((cur_divisor * 10 + udigit) * udigit) && cur_dividend - ((cur_divisor * 10 + udigit) * udigit) >= 0) { // Calculating the remainder cur_remainder = cur_dividend - ((cur_divisor * 10 + udigit) * udigit); // Updating the units digit of the quotient quotient_units_digit = udigit; } } // Adding units digit to the quotient cur_quotient = cur_quotient * 10 + quotient_units_digit; // New divisor is two times quotient cur_divisor = cur_quotient * 2; // Including the remainder in new dividend cur_dividend = cur_remainder; } return cur_quotient;} // Driver codelet x = 1225;document.write(sqrtByLongDivision(x) +"<br>"); // This code is contributed by unknown2108</script>
35
Time Complexity: O((log100n)2 * 10)
Auxiliary Space: O(1)
mohit kumar 29
Rajput-Ji
unknown2108
rishavmahato348
magic-square
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Check if a number is Palindrome
Count ways to reach the n'th stair
Fizz Buzz Implementation
Median of two sorted arrays of same size
Product of Array except itself
Find Union and Intersection of two unsorted arrays
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Nov, 2021"
},
{
"code": null,
"e": 151,
"s": 28,
"text": "Given an integer X which is a perfect square, the task is to find the square root of it by using the long division method."
},
{
"code": null,
"e": 163,
"s": 151,
"text": "Examples: "
},
{
"code": null,
"e": 199,
"s": 163,
"text": "Input: N = 484 Output: 22 222 = 484"
},
{
"code": null,
"e": 236,
"s": 199,
"text": "Input: N = 144 Output: 12 122 = 144 "
},
{
"code": null,
"e": 378,
"s": 236,
"text": "Approach: Long division is a very common method to find the square root of a number. The following is the stepwise solution for this method: "
},
{
"code": null,
"e": 618,
"s": 378,
"text": "1. Divide the digits of the number into pairs of segments starting with the digit in the units place. Let’s identify each pair and the remaining final digit(in case there is an odd count of digits in the number) as a segment. For example: "
},
{
"code": null,
"e": 645,
"s": 618,
"text": "1225 is divided as (12 25)"
},
{
"code": null,
"e": 902,
"s": 645,
"text": "2. After dividing the digits into segments, start from the leftmost segment. The largest number whose square is equal to or just less than the first segment is taken as the divisor and also as the quotient (so that the product is the square). For example: "
},
{
"code": null,
"e": 962,
"s": 902,
"text": "9 is the closest perfect square to 12, the first segment 12"
},
{
"code": null,
"e": 1123,
"s": 962,
"text": "3. Subtract the square of the divisor from the first segment and bring down the next segment to the right of the remainder to get the new dividend. For example:"
},
{
"code": null,
"e": 1192,
"s": 1123,
"text": "12 - 9 = 3 is concatenated with next segment 25.\nNew dividend = 325 "
},
{
"code": null,
"e": 1547,
"s": 1192,
"text": "4. Now, the new divisor is obtained by taking two times the previous quotient(which was 3 in the above example as 32 = 9) and concatenating it with a suitable digit which is also taken as the next digit of the quotient, chosen in such a way that the product of the new divisor and this digit is equal to, or just less than the new dividend. For example: "
},
{
"code": null,
"e": 1574,
"s": 1547,
"text": "Two times quotient 3 is 6."
},
{
"code": null,
"e": 1631,
"s": 1574,
"text": "65 times 5 is 325 which is closest to the new dividend. "
},
{
"code": null,
"e": 1786,
"s": 1631,
"text": "5. Repeat steps (2), (3) and (4) till all the segments have been taken up. Now, the quotient so obtained is the required square root of the given number. "
},
{
"code": null,
"e": 1838,
"s": 1786,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1842,
"s": 1838,
"text": "CPP"
},
{
"code": null,
"e": 1847,
"s": 1842,
"text": "Java"
},
{
"code": null,
"e": 1855,
"s": 1847,
"text": "Python3"
},
{
"code": null,
"e": 1858,
"s": 1855,
"text": "C#"
},
{
"code": null,
"e": 1869,
"s": 1858,
"text": "Javascript"
},
{
"code": "// C++ program to find the square root of a// number by using long division method #include <bits/stdc++.h>using namespace std;#define INFINITY_ 9999999 // Function to find the square root of// a number by using long division methodint sqrtByLongDivision(int n){ int i = 0, udigit, j; // Loop counters int cur_divisor = 0; int quotient_units_digit = 0; int cur_quotient = 0; int cur_dividend = 0; int cur_remainder = 0; int a[10] = { 0 }; // Dividing the number into segments while (n > 0) { a[i] = n % 100; n = n / 100; i++; } // Last index of the array of segments i--; // Start long division from the last segment(j=i) for (j = i; j >= 0; j--) { // Initialising the remainder to the maximum value cur_remainder = INFINITY_; // Including the next segment in new dividend cur_dividend = cur_dividend * 100 + a[j]; // Loop to check for the perfect square // closest to each segment for (udigit = 0; udigit <= 9; udigit++) { // This condition is to find the // divisor after adding a digit // in the range 0 to 9 if (cur_remainder >= cur_dividend - ((cur_divisor * 10 + udigit) * udigit) && cur_dividend - ((cur_divisor * 10 + udigit) * udigit) >= 0) { // Calculating the remainder cur_remainder = cur_dividend - ((cur_divisor * 10 + udigit) * udigit); // Updating the units digit of the quotient quotient_units_digit = udigit; } } // Adding units digit to the quotient cur_quotient = cur_quotient * 10 + quotient_units_digit; // New divisor is two times quotient cur_divisor = cur_quotient * 2; // Including the remainder in new dividend cur_dividend = cur_remainder; } return cur_quotient;} // Driver codeint main(){ int x = 1225; cout << sqrtByLongDivision(x) << endl; return 0;}",
"e": 4109,
"s": 1869,
"text": null
},
{
"code": "// Java program to find the square root of a// number by using long division methodimport java.util.*; class GFG{static final int INFINITY_ =9999999; // Function to find the square root of// a number by using long division methodstatic int sqrtByLongDivision(int n){ int i = 0, udigit, j; // Loop counters int cur_divisor = 0; int quotient_units_digit = 0; int cur_quotient = 0; int cur_dividend = 0; int cur_remainder = 0; int a[] = new int[10]; // Dividing the number into segments while (n > 0) { a[i] = n % 100; n = n / 100; i++; } // Last index of the array of segments i--; // Start long division from the last segment(j=i) for (j = i; j >= 0; j--) { // Initialising the remainder to the maximum value cur_remainder = INFINITY_; // Including the next segment in new dividend cur_dividend = cur_dividend * 100 + a[j]; // Loop to check for the perfect square // closest to each segment for (udigit = 0; udigit <= 9; udigit++) { // This condition is to find the // divisor after adding a digit // in the range 0 to 9 if (cur_remainder >= cur_dividend - ((cur_divisor * 10 + udigit) * udigit) && cur_dividend - ((cur_divisor * 10 + udigit) * udigit) >= 0) { // Calculating the remainder cur_remainder = cur_dividend - ((cur_divisor * 10 + udigit) * udigit); // Updating the units digit of the quotient quotient_units_digit = udigit; } } // Adding units digit to the quotient cur_quotient = cur_quotient * 10 + quotient_units_digit; // New divisor is two times quotient cur_divisor = cur_quotient * 2; // Including the remainder in new dividend cur_dividend = cur_remainder; } return cur_quotient;} // Driver codepublic static void main(String[] args){ int x = 1225; System.out.print(sqrtByLongDivision(x) +\"\\n\");}} // This code is contributed by Rajput-Ji",
"e": 6436,
"s": 4109,
"text": null
},
{
"code": "# Python3 program to find the square root of a# number by using long division methodINFINITY_ = 9999999 # Function to find the square root of# a number by using long division methoddef sqrtByLongDivision(n): i = 0 udigit, j = 0, 0 # Loop counters cur_divisor = 0 quotient_units_digit = 0 cur_quotient = 0 cur_dividend = 0 cur_remainder = 0 a = [0]*10 # Dividing the number into segments while (n > 0): a[i] = n % 100 n = n // 100 i += 1 # Last index of the array of segments i -= 1 # Start long division from the last segment(j=i) for j in range(i, -1, -1): # Initialising the remainder to the maximum value cur_remainder = INFINITY_ # Including the next segment in new dividend cur_dividend = cur_dividend * 100 + a[j] # Loop to check for the perfect square # closest to each segment for udigit in range(10): # This condition is to find the # divisor after adding a digit # in the range 0 to 9 if (cur_remainder >= cur_dividend - ((cur_divisor * 10 + udigit) * udigit) and cur_dividend - ((cur_divisor * 10 + udigit) * udigit) >= 0): # Calculating the remainder cur_remainder = cur_dividend - ((cur_divisor * 10 + udigit) * udigit) # Updating the units digit of the quotient quotient_units_digit = udigit # Adding units digit to the quotient cur_quotient = cur_quotient * 10 + quotient_units_digit # New divisor is two times quotient cur_divisor = cur_quotient * 2 # Including the remainder in new dividend cur_dividend = cur_remainder return cur_quotient # Driver code x = 1225print(sqrtByLongDivision(x)) # This code is contributed by mohit kumar 29 ",
"e": 8524,
"s": 6436,
"text": null
},
{
"code": "// C# program to find the square root of a// number by using long division methodusing System; class GFG{static readonly int INFINITY_ =9999999; // Function to find the square root of// a number by using long division methodstatic int sqrtBylongDivision(int n){ int i = 0, udigit, j; // Loop counters int cur_divisor = 0; int quotient_units_digit = 0; int cur_quotient = 0; int cur_dividend = 0; int cur_remainder = 0; int []a = new int[10]; // Dividing the number into segments while (n > 0) { a[i] = n % 100; n = n / 100; i++; } // Last index of the array of segments i--; // Start long division from the last segment(j=i) for (j = i; j >= 0; j--) { // Initialising the remainder to the maximum value cur_remainder = INFINITY_; // Including the next segment in new dividend cur_dividend = cur_dividend * 100 + a[j]; // Loop to check for the perfect square // closest to each segment for (udigit = 0; udigit <= 9; udigit++) { // This condition is to find the // divisor after adding a digit // in the range 0 to 9 if (cur_remainder >= cur_dividend - ((cur_divisor * 10 + udigit) * udigit) && cur_dividend - ((cur_divisor * 10 + udigit) * udigit) >= 0) { // Calculating the remainder cur_remainder = cur_dividend - ((cur_divisor * 10 + udigit) * udigit); // Updating the units digit of the quotient quotient_units_digit = udigit; } } // Adding units digit to the quotient cur_quotient = cur_quotient * 10 + quotient_units_digit; // New divisor is two times quotient cur_divisor = cur_quotient * 2; // Including the remainder in new dividend cur_dividend = cur_remainder; } return cur_quotient;} // Driver codepublic static void Main(String[] args){ int x = 1225; Console.Write(sqrtBylongDivision(x) +\"\\n\");}} // This code is contributed by Rajput-Ji",
"e": 10829,
"s": 8524,
"text": null
},
{
"code": "<script>// Javascript program to find the square root of a// number by using long division method let INFINITY_ =9999999; // Function to find the square root of// a number by using long division methodfunction sqrtByLongDivision(n){ let i = 0, udigit, j; // Loop counters let cur_divisor = 0; let quotient_units_digit = 0; let cur_quotient = 0; let cur_dividend = 0; let cur_remainder = 0; let a = new Array(10); // Dividing the number into segments while (n > 0) { a[i] = n % 100; n = Math.floor(n / 100); i++; } // Last index of the array of segments i--; // Start long division from the last segment(j=i) for (j = i; j >= 0; j--) { // Initialising the remainder to the maximum value cur_remainder = INFINITY_; // Including the next segment in new dividend cur_dividend = cur_dividend * 100 + a[j]; // Loop to check for the perfect square // closest to each segment for (udigit = 0; udigit <= 9; udigit++) { // This condition is to find the // divisor after adding a digit // in the range 0 to 9 if (cur_remainder >= cur_dividend - ((cur_divisor * 10 + udigit) * udigit) && cur_dividend - ((cur_divisor * 10 + udigit) * udigit) >= 0) { // Calculating the remainder cur_remainder = cur_dividend - ((cur_divisor * 10 + udigit) * udigit); // Updating the units digit of the quotient quotient_units_digit = udigit; } } // Adding units digit to the quotient cur_quotient = cur_quotient * 10 + quotient_units_digit; // New divisor is two times quotient cur_divisor = cur_quotient * 2; // Including the remainder in new dividend cur_dividend = cur_remainder; } return cur_quotient;} // Driver codelet x = 1225;document.write(sqrtByLongDivision(x) +\"<br>\"); // This code is contributed by unknown2108</script>",
"e": 13120,
"s": 10829,
"text": null
},
{
"code": null,
"e": 13123,
"s": 13120,
"text": "35"
},
{
"code": null,
"e": 13161,
"s": 13125,
"text": "Time Complexity: O((log100n)2 * 10)"
},
{
"code": null,
"e": 13183,
"s": 13161,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 13198,
"s": 13183,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 13208,
"s": 13198,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 13220,
"s": 13208,
"text": "unknown2108"
},
{
"code": null,
"e": 13236,
"s": 13220,
"text": "rishavmahato348"
},
{
"code": null,
"e": 13249,
"s": 13236,
"text": "magic-square"
},
{
"code": null,
"e": 13262,
"s": 13249,
"text": "Mathematical"
},
{
"code": null,
"e": 13275,
"s": 13262,
"text": "Mathematical"
},
{
"code": null,
"e": 13373,
"s": 13275,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13405,
"s": 13373,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 13451,
"s": 13405,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 13495,
"s": 13451,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 13537,
"s": 13495,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 13569,
"s": 13537,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 13604,
"s": 13569,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 13629,
"s": 13604,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 13670,
"s": 13629,
"text": "Median of two sorted arrays of same size"
},
{
"code": null,
"e": 13701,
"s": 13670,
"text": "Product of Array except itself"
}
] |
Program to print characters present at prime indexes in a given string
|
01 May, 2021
Given a string, our task is to print the characters present at prime index.
Examples :
Input : I love programming
Output : lv gan
Explanation :
prime index characters in a string are : lv gan
Input : Happy coding everyone
Output : apycn ro
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Approach :
Use two loops to divide the numbers upto the value of length of string.Increment variable result when the remainder is 0.If the variable result = 1, then print the corresponding character.
Use two loops to divide the numbers upto the value of length of string.
Increment variable result when the remainder is 0.
If the variable result = 1, then print the corresponding character.
Below is the implementation of above approach :
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to print Characters at// Prime index in a given String#include <bits/stdc++.h>using namespace std; bool isPrime(int n){ // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i < n; i++) if (n % i == 0) return false; return true;} // Function to print// character at prime indexvoid prime_index(string input){ int n = input.length(); // Loop to check if // index prime or not for (int i = 2; i <= n; i++) if (isPrime(i)) cout << input[i - 1]; } // Driver Codeint main(){ string input = "GeeksforGeeks"; prime_index(input); return 0;}
// Java Program to print// Characters at Prime index// in a given Stringclass GFG{ static boolean isPrime(int n) { // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i < n; i++) if (n % i == 0) return false; return true; } // Function to print // character at prime index static void prime_index(String input) { int n = input.length(); // Loop to check if // index prime or not for (int i = 2; i <= n; i++) if (isPrime(i)) System.out.print (input.charAt(i - 1)); } // Driver code public static void main (String[] args) { String input = "GeeksforGeeks"; prime_index(input); }} // This code is contributed by Anant Agarwal.
# Python3 program to print# Characters at Prime index# in a given String def isPrime(n): # Corner case if n <= 1: return False # Check from 2 to n-1 for i in range(2, n): if n % i == 0: return False; return True # Function to print# character at prime indexdef prime_index (input): p = list(input) s = "" # Loop to check if # index prime or not for i in range (2, len(p) + 1): if isPrime(i): s = s + input[i-1] print (s) # Driver Codeinput = "GeeksforGeeks"prime_index(input)
// C# Program to print Characters// at Prime index in a given Stringusing System; class GFG{ static bool isPrime(int n) { // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i < n; i++) if (n % i == 0) return false; return true; } // Function to print character // at prime index static void prime_index(string input) { int n = input.Length; // Loop to check if // index prime or not for (int i = 2; i <= n; i++) if (isPrime(i)) Console.Write(input[i - 1]); } // Driver code public static void Main () { string input = "GeeksforGeeks"; prime_index(input); }} // This code is contributed by Vt_m.
<?php// PHP Program to print// Characters at Prime// index in a given String function isPrime($n){ // Corner case if ($n <= 1) return false; // Check from 2 to n-1 for ($i = 2; $i < $n; $i++) if ($n % $i == 0) return false; return true;} // Function to print// character at prime indexfunction prime_index($input){ $n = strlen($input); // Loop to check if // index prime or not for ($i = 2; $i <= $n; $i++) if (isPrime($i)) echo $input[$i - 1]; } // Driver Code$input = "GeeksforGeeks";prime_index($input); // This code is contributed by ajit.?>
<script> // Javascript program to print characters// at Prime index in a given Stringfunction isPrime(n){ // Corner case if (n <= 1) return false; // Check from 2 to n-1 for(let i = 2; i < n; i++) if (n % i == 0) return false; return true;} // Function to print character// at prime indexfunction prime_index(input){ let n = input.length; // Loop to check if // index prime or not for(let i = 2; i <= n; i++) if (isPrime(i)) document.write(input[i - 1]); } // Driver codelet input = "GeeksforGeeks"; prime_index(input); // This code is contributed by suresh07 </script>
Output :
eesoes
Optimizations : For large strings, we can use Sieve of Eratosthenes to efficiently find all prime numbers smaller than or equal to length of string.
Program to print characters present at prime indexes in a given string | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersProgram to print characters present at prime indexes in a given string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:18•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=luBTP8zRqMo" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
jit_t
suresh07
Prime Number
Strings
Strings
Prime Number
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Longest Palindromic Substring | Set 1
Length of the longest substring without repeating characters
Top 50 String Coding Problems for Interviews
What is Data Structure: Types, Classifications and Applications
Convert string to char array in C++
Check whether two strings are anagram of each other
Reverse words in a given string
Print all the duplicates in the input string
Reverse string in Python (6 different ways)
Remove duplicates from a given string
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 May, 2021"
},
{
"code": null,
"e": 104,
"s": 28,
"text": "Given a string, our task is to print the characters present at prime index."
},
{
"code": null,
"e": 116,
"s": 104,
"text": "Examples : "
},
{
"code": null,
"e": 282,
"s": 116,
"text": "Input : I love programming \nOutput : lv gan\nExplanation :\nprime index characters in a string are : lv gan\n \n\nInput : Happy coding everyone\nOutput : apycn ro"
},
{
"code": null,
"e": 295,
"s": 286,
"text": "Chapters"
},
{
"code": null,
"e": 322,
"s": 295,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 372,
"s": 322,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 395,
"s": 372,
"text": "captions off, selected"
},
{
"code": null,
"e": 403,
"s": 395,
"text": "English"
},
{
"code": null,
"e": 427,
"s": 403,
"text": "This is a modal window."
},
{
"code": null,
"e": 496,
"s": 427,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 518,
"s": 496,
"text": "End of dialog window."
},
{
"code": null,
"e": 530,
"s": 518,
"text": "Approach : "
},
{
"code": null,
"e": 719,
"s": 530,
"text": "Use two loops to divide the numbers upto the value of length of string.Increment variable result when the remainder is 0.If the variable result = 1, then print the corresponding character."
},
{
"code": null,
"e": 791,
"s": 719,
"text": "Use two loops to divide the numbers upto the value of length of string."
},
{
"code": null,
"e": 842,
"s": 791,
"text": "Increment variable result when the remainder is 0."
},
{
"code": null,
"e": 910,
"s": 842,
"text": "If the variable result = 1, then print the corresponding character."
},
{
"code": null,
"e": 959,
"s": 910,
"text": "Below is the implementation of above approach : "
},
{
"code": null,
"e": 963,
"s": 959,
"text": "C++"
},
{
"code": null,
"e": 968,
"s": 963,
"text": "Java"
},
{
"code": null,
"e": 976,
"s": 968,
"text": "Python3"
},
{
"code": null,
"e": 979,
"s": 976,
"text": "C#"
},
{
"code": null,
"e": 983,
"s": 979,
"text": "PHP"
},
{
"code": null,
"e": 994,
"s": 983,
"text": "Javascript"
},
{
"code": "// C++ Program to print Characters at// Prime index in a given String#include <bits/stdc++.h>using namespace std; bool isPrime(int n){ // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i < n; i++) if (n % i == 0) return false; return true;} // Function to print// character at prime indexvoid prime_index(string input){ int n = input.length(); // Loop to check if // index prime or not for (int i = 2; i <= n; i++) if (isPrime(i)) cout << input[i - 1]; } // Driver Codeint main(){ string input = \"GeeksforGeeks\"; prime_index(input); return 0;}",
"e": 1650,
"s": 994,
"text": null
},
{
"code": "// Java Program to print// Characters at Prime index// in a given Stringclass GFG{ static boolean isPrime(int n) { // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i < n; i++) if (n % i == 0) return false; return true; } // Function to print // character at prime index static void prime_index(String input) { int n = input.length(); // Loop to check if // index prime or not for (int i = 2; i <= n; i++) if (isPrime(i)) System.out.print (input.charAt(i - 1)); } // Driver code public static void main (String[] args) { String input = \"GeeksforGeeks\"; prime_index(input); }} // This code is contributed by Anant Agarwal.",
"e": 2525,
"s": 1650,
"text": null
},
{
"code": "# Python3 program to print# Characters at Prime index# in a given String def isPrime(n): # Corner case if n <= 1: return False # Check from 2 to n-1 for i in range(2, n): if n % i == 0: return False; return True # Function to print# character at prime indexdef prime_index (input): p = list(input) s = \"\" # Loop to check if # index prime or not for i in range (2, len(p) + 1): if isPrime(i): s = s + input[i-1] print (s) # Driver Codeinput = \"GeeksforGeeks\"prime_index(input)",
"e": 3093,
"s": 2525,
"text": null
},
{
"code": "// C# Program to print Characters// at Prime index in a given Stringusing System; class GFG{ static bool isPrime(int n) { // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i < n; i++) if (n % i == 0) return false; return true; } // Function to print character // at prime index static void prime_index(string input) { int n = input.Length; // Loop to check if // index prime or not for (int i = 2; i <= n; i++) if (isPrime(i)) Console.Write(input[i - 1]); } // Driver code public static void Main () { string input = \"GeeksforGeeks\"; prime_index(input); }} // This code is contributed by Vt_m.",
"e": 3942,
"s": 3093,
"text": null
},
{
"code": "<?php// PHP Program to print// Characters at Prime// index in a given String function isPrime($n){ // Corner case if ($n <= 1) return false; // Check from 2 to n-1 for ($i = 2; $i < $n; $i++) if ($n % $i == 0) return false; return true;} // Function to print// character at prime indexfunction prime_index($input){ $n = strlen($input); // Loop to check if // index prime or not for ($i = 2; $i <= $n; $i++) if (isPrime($i)) echo $input[$i - 1]; } // Driver Code$input = \"GeeksforGeeks\";prime_index($input); // This code is contributed by ajit.?>",
"e": 4557,
"s": 3942,
"text": null
},
{
"code": "<script> // Javascript program to print characters// at Prime index in a given Stringfunction isPrime(n){ // Corner case if (n <= 1) return false; // Check from 2 to n-1 for(let i = 2; i < n; i++) if (n % i == 0) return false; return true;} // Function to print character// at prime indexfunction prime_index(input){ let n = input.length; // Loop to check if // index prime or not for(let i = 2; i <= n; i++) if (isPrime(i)) document.write(input[i - 1]); } // Driver codelet input = \"GeeksforGeeks\"; prime_index(input); // This code is contributed by suresh07 </script>",
"e": 5220,
"s": 4557,
"text": null
},
{
"code": null,
"e": 5230,
"s": 5220,
"text": "Output : "
},
{
"code": null,
"e": 5237,
"s": 5230,
"text": "eesoes"
},
{
"code": null,
"e": 5388,
"s": 5237,
"text": "Optimizations : For large strings, we can use Sieve of Eratosthenes to efficiently find all prime numbers smaller than or equal to length of string. "
},
{
"code": null,
"e": 6346,
"s": 5388,
"text": "Program to print characters present at prime indexes in a given string | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersProgram to print characters present at prime indexes in a given string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:18•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=luBTP8zRqMo\" 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": 6354,
"s": 6348,
"text": "jit_t"
},
{
"code": null,
"e": 6363,
"s": 6354,
"text": "suresh07"
},
{
"code": null,
"e": 6376,
"s": 6363,
"text": "Prime Number"
},
{
"code": null,
"e": 6384,
"s": 6376,
"text": "Strings"
},
{
"code": null,
"e": 6392,
"s": 6384,
"text": "Strings"
},
{
"code": null,
"e": 6405,
"s": 6392,
"text": "Prime Number"
},
{
"code": null,
"e": 6503,
"s": 6405,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6541,
"s": 6503,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 6602,
"s": 6541,
"text": "Length of the longest substring without repeating characters"
},
{
"code": null,
"e": 6647,
"s": 6602,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 6711,
"s": 6647,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 6747,
"s": 6711,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 6799,
"s": 6747,
"text": "Check whether two strings are anagram of each other"
},
{
"code": null,
"e": 6831,
"s": 6799,
"text": "Reverse words in a given string"
},
{
"code": null,
"e": 6876,
"s": 6831,
"text": "Print all the duplicates in the input string"
},
{
"code": null,
"e": 6920,
"s": 6876,
"text": "Reverse string in Python (6 different ways)"
}
] |
Matplotlib.axes.Axes.set_position() in Python
|
19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.set_position() function in axes module of matplotlib library is used to set the axes position.
Syntax: Axes.set_position(self)
Parameters: This method accepts the following parameters.
pos : This parameter is the new position of the in Figure coordinates.
which : This parameter is used to determines which position variables to change.
Return value: This method does not return any value.
Below examples illustrate the matplotlib.axes.Axes.set_position() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np x = np.arange(10)y = [2, 4, 6, 14, 15, 16, 17, 16, 18, 20]y2 = [10, 11, 12, 13, 8, 10, 12, 14, 18, 19] fig, ax = plt.subplots() ax.plot(x, y, "go-", label ='Line 1', )ax.plot(x, y2, "o-", label ='Line 2') chartBox = ax.get_position()ax.set_position([chartBox.x0, chartBox.y0, chartBox.width, chartBox.height * 0.6]) ax.legend(loc ='upper center', bbox_to_anchor =(0.5, 1.45), shadow = True, ncol = 1) fig.suptitle('matplotlib.axes.Axes.set_position()\function Example', fontweight ="bold")plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm Z = np.random.rand(6, 30) fig, (ax, ax1) = plt.subplots(1, 2) ax.pcolor(Z)ax1.pcolor(Z) chartBox = ax1.get_position()ax1.set_position([chartBox.x0, chartBox.y0, chartBox.width, chartBox.height * 0.6]) ax.set_title("Original Window")ax1.set_title("Modified Window") fig.suptitle('matplotlib.axes.Axes.set_position()\function Example', fontweight ="bold")plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Apr, 2020"
},
{
"code": null,
"e": 328,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute."
},
{
"code": null,
"e": 432,
"s": 328,
"text": "The Axes.set_position() function in axes module of matplotlib library is used to set the axes position."
},
{
"code": null,
"e": 464,
"s": 432,
"text": "Syntax: Axes.set_position(self)"
},
{
"code": null,
"e": 522,
"s": 464,
"text": "Parameters: This method accepts the following parameters."
},
{
"code": null,
"e": 593,
"s": 522,
"text": "pos : This parameter is the new position of the in Figure coordinates."
},
{
"code": null,
"e": 674,
"s": 593,
"text": "which : This parameter is used to determines which position variables to change."
},
{
"code": null,
"e": 727,
"s": 674,
"text": "Return value: This method does not return any value."
},
{
"code": null,
"e": 822,
"s": 727,
"text": "Below examples illustrate the matplotlib.axes.Axes.set_position() function in matplotlib.axes:"
},
{
"code": null,
"e": 833,
"s": 822,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np x = np.arange(10)y = [2, 4, 6, 14, 15, 16, 17, 16, 18, 20]y2 = [10, 11, 12, 13, 8, 10, 12, 14, 18, 19] fig, ax = plt.subplots() ax.plot(x, y, \"go-\", label ='Line 1', )ax.plot(x, y2, \"o-\", label ='Line 2') chartBox = ax.get_position()ax.set_position([chartBox.x0, chartBox.y0, chartBox.width, chartBox.height * 0.6]) ax.legend(loc ='upper center', bbox_to_anchor =(0.5, 1.45), shadow = True, ncol = 1) fig.suptitle('matplotlib.axes.Axes.set_position()\\function Example', fontweight =\"bold\")plt.show()",
"e": 1489,
"s": 833,
"text": null
},
{
"code": null,
"e": 1497,
"s": 1489,
"text": "Output:"
},
{
"code": null,
"e": 1508,
"s": 1497,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm Z = np.random.rand(6, 30) fig, (ax, ax1) = plt.subplots(1, 2) ax.pcolor(Z)ax1.pcolor(Z) chartBox = ax1.get_position()ax1.set_position([chartBox.x0, chartBox.y0, chartBox.width, chartBox.height * 0.6]) ax.set_title(\"Original Window\")ax1.set_title(\"Modified Window\") fig.suptitle('matplotlib.axes.Axes.set_position()\\function Example', fontweight =\"bold\")plt.show()",
"e": 2061,
"s": 1508,
"text": null
},
{
"code": null,
"e": 2069,
"s": 2061,
"text": "Output:"
},
{
"code": null,
"e": 2087,
"s": 2069,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2094,
"s": 2087,
"text": "Python"
},
{
"code": null,
"e": 2192,
"s": 2094,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2210,
"s": 2192,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2252,
"s": 2210,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2274,
"s": 2252,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2309,
"s": 2274,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2335,
"s": 2309,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2367,
"s": 2335,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2396,
"s": 2367,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2423,
"s": 2396,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2453,
"s": 2423,
"text": "Iterate over a list in Python"
}
] |
Introduction to Webpack Module Bundler
|
14 Dec, 2020
Webpack: Webpack is a static module bundler used for JavaScript applications. Since webpack understands only JavaScript and JSON files, It transforms front-end assets such as HTML, CSS, and images into valid modules if the corresponding loaders are included. While Processing your application webpack internally builds a dependency graph that maps every module your project needs and produces one or more output bundles.
Some core concepts of webpack are:
EntryOutputLoadersPluginsMode
Entry
Output
Loaders
Plugins
Mode
Entry: An entry point defines which module webpack should use to start building out its internal dependency graph. The entry point’s default value is ./src/index.js, but in the webpack configuration., you can specify a different or multiple entry points by setting an entry property within this file.
Let us consider an example in which file.js inside the GeeksForGeeks directory is the entry point. Then the webpack.config.js file should be as follows:
Filename: webpack.config.js
module.exports = {
entry: './GeeksForGeeks/file.js'
};
Output: The output property indicates webpack where to emit the bundles it creates and tells the way to name these files. By default, its value is ./dist/main.js for the main output file and it is ./dist folder for any other generated file, but we can change this part of the process by specifying an output field in our configuration.
Filename: webpack.config.js
const path = require('path');
module.exports = {
entry: './GeeksForGeeks/file.js',
output: {
path: path.resolve(__dirname, 'gfg'),
filename: 'GeeksForGeeks-webpack.bundle.js'
}
};
Loaders: Since webpack only understands JavaScript and JSON files. Loaders process other types of files and after that, it converts them into the valid modules which can be consumed by our application, and add them to the dependency graph.
Loaders preprocess the other type of files and them to the bundle, Loaders have two properties in webpack configuration through which they achieve this:
The test propertyThe use property
The test property
The use property
The test property: It is used to identify which file or files should be transformed by the respective loader. Usually, a regular expression is used to identify the file or files which should be transformed.
The use property: It is used to indicate which loader should be used to do the transforming.
Filename: webpack.config.js
const path = require('path');
module.exports = {
output: {
filename: 'GeeksForGeeks-webpack.bundle.js'
},
module: {
rules: [
{ test: /\.txt$/, use: 'raw-loader' }
]
}
};
The above webpack configuration above has defined a rules property for one module with two required properties which are test and use. When webpack compiler encounters a path that resolves to a ‘.txt’ file inside a require()/import statement, it will use the raw-loader to transform it before adding it to the bundle.
Plugins: While loaders are used to preprocess certain types of modules, plugins can be used to carry out a wider range of tasks like an injection of environment variables, asset management, and bundle optimization.
In order to use a plugin, we have to require() it and add it to the plugins array. Plugins can be customized through options. Since a plugin can be used multiple times in a configuration for different purposes, we need to create an instance of it by calling it with the new operator.
Filename: webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
module.exports = {
module: {
rules: [
{ test: /\.txt$/, use: 'raw-loader' }
]
},
plugins: [
new HtmlWebpackPlugin({template: './src/GeeksForGeeks.html'})
]
};
In the example above, the html-webpack-plugin is used to generate an HTML file for our application by injecting all our generated bundles automatically.
Mode: We can enable webpack’s built-in optimizations that correspond to each environment by setting the mode parameter to either development, production, or none. Its default value is production.
Filename: webpack.config.js
module.exports = {
mode: 'development'
}
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
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 ?
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Dec, 2020"
},
{
"code": null,
"e": 449,
"s": 28,
"text": "Webpack: Webpack is a static module bundler used for JavaScript applications. Since webpack understands only JavaScript and JSON files, It transforms front-end assets such as HTML, CSS, and images into valid modules if the corresponding loaders are included. While Processing your application webpack internally builds a dependency graph that maps every module your project needs and produces one or more output bundles."
},
{
"code": null,
"e": 484,
"s": 449,
"text": "Some core concepts of webpack are:"
},
{
"code": null,
"e": 514,
"s": 484,
"text": "EntryOutputLoadersPluginsMode"
},
{
"code": null,
"e": 520,
"s": 514,
"text": "Entry"
},
{
"code": null,
"e": 527,
"s": 520,
"text": "Output"
},
{
"code": null,
"e": 535,
"s": 527,
"text": "Loaders"
},
{
"code": null,
"e": 543,
"s": 535,
"text": "Plugins"
},
{
"code": null,
"e": 548,
"s": 543,
"text": "Mode"
},
{
"code": null,
"e": 849,
"s": 548,
"text": "Entry: An entry point defines which module webpack should use to start building out its internal dependency graph. The entry point’s default value is ./src/index.js, but in the webpack configuration., you can specify a different or multiple entry points by setting an entry property within this file."
},
{
"code": null,
"e": 1002,
"s": 849,
"text": "Let us consider an example in which file.js inside the GeeksForGeeks directory is the entry point. Then the webpack.config.js file should be as follows:"
},
{
"code": null,
"e": 1030,
"s": 1002,
"text": "Filename: webpack.config.js"
},
{
"code": null,
"e": 1086,
"s": 1030,
"text": "module.exports = {\n entry: './GeeksForGeeks/file.js'\n};"
},
{
"code": null,
"e": 1422,
"s": 1086,
"text": "Output: The output property indicates webpack where to emit the bundles it creates and tells the way to name these files. By default, its value is ./dist/main.js for the main output file and it is ./dist folder for any other generated file, but we can change this part of the process by specifying an output field in our configuration."
},
{
"code": null,
"e": 1450,
"s": 1422,
"text": "Filename: webpack.config.js"
},
{
"code": null,
"e": 1639,
"s": 1450,
"text": "const path = require('path');\nmodule.exports = {\n entry: './GeeksForGeeks/file.js',\n output: {\n path: path.resolve(__dirname, 'gfg'),\n filename: 'GeeksForGeeks-webpack.bundle.js'\n }\n};"
},
{
"code": null,
"e": 1879,
"s": 1639,
"text": "Loaders: Since webpack only understands JavaScript and JSON files. Loaders process other types of files and after that, it converts them into the valid modules which can be consumed by our application, and add them to the dependency graph."
},
{
"code": null,
"e": 2032,
"s": 1879,
"text": "Loaders preprocess the other type of files and them to the bundle, Loaders have two properties in webpack configuration through which they achieve this:"
},
{
"code": null,
"e": 2066,
"s": 2032,
"text": "The test propertyThe use property"
},
{
"code": null,
"e": 2084,
"s": 2066,
"text": "The test property"
},
{
"code": null,
"e": 2101,
"s": 2084,
"text": "The use property"
},
{
"code": null,
"e": 2308,
"s": 2101,
"text": "The test property: It is used to identify which file or files should be transformed by the respective loader. Usually, a regular expression is used to identify the file or files which should be transformed."
},
{
"code": null,
"e": 2401,
"s": 2308,
"text": "The use property: It is used to indicate which loader should be used to do the transforming."
},
{
"code": null,
"e": 2429,
"s": 2401,
"text": "Filename: webpack.config.js"
},
{
"code": null,
"e": 2617,
"s": 2429,
"text": "const path = require('path');\nmodule.exports = {\n output: {\n filename: 'GeeksForGeeks-webpack.bundle.js'\n },\n module: {\n rules: [\n { test: /\\.txt$/, use: 'raw-loader' }\n ]\n }\n};"
},
{
"code": null,
"e": 2935,
"s": 2617,
"text": "The above webpack configuration above has defined a rules property for one module with two required properties which are test and use. When webpack compiler encounters a path that resolves to a ‘.txt’ file inside a require()/import statement, it will use the raw-loader to transform it before adding it to the bundle."
},
{
"code": null,
"e": 3150,
"s": 2935,
"text": "Plugins: While loaders are used to preprocess certain types of modules, plugins can be used to carry out a wider range of tasks like an injection of environment variables, asset management, and bundle optimization."
},
{
"code": null,
"e": 3434,
"s": 3150,
"text": "In order to use a plugin, we have to require() it and add it to the plugins array. Plugins can be customized through options. Since a plugin can be used multiple times in a configuration for different purposes, we need to create an instance of it by calling it with the new operator."
},
{
"code": null,
"e": 3462,
"s": 3434,
"text": "Filename: webpack.config.js"
},
{
"code": null,
"e": 3733,
"s": 3462,
"text": "const HtmlWebpackPlugin = require('html-webpack-plugin');\nconst webpack = require('webpack');\nmodule.exports = {\n module: {\n rules: [\n { test: /\\.txt$/, use: 'raw-loader' }\n ]\n },\n plugins: [\n new HtmlWebpackPlugin({template: './src/GeeksForGeeks.html'})\n ]\n};"
},
{
"code": null,
"e": 3886,
"s": 3733,
"text": "In the example above, the html-webpack-plugin is used to generate an HTML file for our application by injecting all our generated bundles automatically."
},
{
"code": null,
"e": 4082,
"s": 3886,
"text": "Mode: We can enable webpack’s built-in optimizations that correspond to each environment by setting the mode parameter to either development, production, or none. Its default value is production."
},
{
"code": null,
"e": 4110,
"s": 4082,
"text": "Filename: webpack.config.js"
},
{
"code": null,
"e": 4152,
"s": 4110,
"text": "module.exports = {\n mode: 'development'\n}"
},
{
"code": null,
"e": 4165,
"s": 4152,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 4173,
"s": 4165,
"text": "Node.js"
},
{
"code": null,
"e": 4190,
"s": 4173,
"text": "Web Technologies"
},
{
"code": null,
"e": 4288,
"s": 4190,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4320,
"s": 4288,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 4355,
"s": 4320,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 4425,
"s": 4355,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 4452,
"s": 4425,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 4477,
"s": 4452,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 4539,
"s": 4477,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4600,
"s": 4539,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4650,
"s": 4600,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 4693,
"s": 4650,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Difference Between Single and Double Quotes in Shell Script and Linux
|
17 Nov, 2020
Single quotes and double quotes are both functional in Linux while working with shell scripts or executing commands directly in the terminal but there is a difference between the way the bash shell interprets them.
Single quotes:
Enclosing characters in single quotation marks (‘) holds onto the literal value of each character within the quotes. In simpler words, the shell will interpret the enclosed text within single quotes literally and will not interpolate anything including variables, backticks, certain \ escapes, etc. No character in the single quote has special meaning. This is convenient when you do not want to use the escape characters to change the way the bash interprets the input string.
Double quotes:
Double quotes are similar to single quotes except that it allows the shell to interpret dollar sign ($), backtick(`), backslash(\) and exclamation mark(!). The characters have special meaning when used with double quotes, and before display, they are evaluated. A double quote may be used within double quotes by preceding it with a backslash.
1. In the below-mentioned case, the test is a variable that is initialized with 10. The dollar sign ($) indicates that the characters following are a variable name and should be replaced with the value of that variable which in this case is 10. When the $test is enclosed within single quotes, then the text inside is retained and the value does not get displayed. The $test does not get interpolated. But when it is closed within double quotes, then the $test is evaluated and the value of the variable which is 10 is printed.
test=10
echo "$test"
echo 'test'
2. In the below-mentioned case, when \n is used within double quotes, it gets interpreted as a newline but when it is used within single quotes, \n is displayed along with other text in the same line.
printf "k\\nk"
printf 'k\\nk'
3. In the below-mentioned case, when ${array[0]} is enclosed within single quotes, it gets evaluated and 10 is printed, as it is the 0th element of the array but when enclosed within single quotes, the literal identity of $ is retained and it does not get evaluated.
array=(10) #an array with a single element at index 0
echo "${array[0]}"
echo '${array[0]}'
4. In the below-mentioned case, Single quotes have no special meaning when it is enclosed within double quotes, and hence $a gets evaluated even when it is within single quotes. But when double quotes are enclosed within single quotes, then it is treated literally and $a does not get evaluated even when it is inside double-quotes.
a=10
echo "'$a'"
echo '"$a"'
Difference Between
Linux-Unix
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
Difference Between Method Overloading and Method Overriding in Java
Similarities and Difference between Java and C++
Difference between Internal and External fragmentation
Difference between Compile-time and Run-time Polymorphism in Java
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
cp command in Linux with examples
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Nov, 2020"
},
{
"code": null,
"e": 244,
"s": 28,
"text": "Single quotes and double quotes are both functional in Linux while working with shell scripts or executing commands directly in the terminal but there is a difference between the way the bash shell interprets them. "
},
{
"code": null,
"e": 259,
"s": 244,
"text": "Single quotes:"
},
{
"code": null,
"e": 738,
"s": 259,
"text": "Enclosing characters in single quotation marks (‘) holds onto the literal value of each character within the quotes. In simpler words, the shell will interpret the enclosed text within single quotes literally and will not interpolate anything including variables, backticks, certain \\ escapes, etc. No character in the single quote has special meaning. This is convenient when you do not want to use the escape characters to change the way the bash interprets the input string."
},
{
"code": null,
"e": 753,
"s": 738,
"text": "Double quotes:"
},
{
"code": null,
"e": 1097,
"s": 753,
"text": "Double quotes are similar to single quotes except that it allows the shell to interpret dollar sign ($), backtick(`), backslash(\\) and exclamation mark(!). The characters have special meaning when used with double quotes, and before display, they are evaluated. A double quote may be used within double quotes by preceding it with a backslash."
},
{
"code": null,
"e": 1625,
"s": 1097,
"text": "1. In the below-mentioned case, the test is a variable that is initialized with 10. The dollar sign ($) indicates that the characters following are a variable name and should be replaced with the value of that variable which in this case is 10. When the $test is enclosed within single quotes, then the text inside is retained and the value does not get displayed. The $test does not get interpolated. But when it is closed within double quotes, then the $test is evaluated and the value of the variable which is 10 is printed."
},
{
"code": null,
"e": 1659,
"s": 1625,
"text": "test=10\necho \"$test\"\necho 'test'\n"
},
{
"code": null,
"e": 1860,
"s": 1659,
"text": "2. In the below-mentioned case, when \\n is used within double quotes, it gets interpreted as a newline but when it is used within single quotes, \\n is displayed along with other text in the same line."
},
{
"code": null,
"e": 1891,
"s": 1860,
"text": "printf \"k\\\\nk\"\nprintf 'k\\\\nk'\n"
},
{
"code": null,
"e": 2158,
"s": 1891,
"text": "3. In the below-mentioned case, when ${array[0]} is enclosed within single quotes, it gets evaluated and 10 is printed, as it is the 0th element of the array but when enclosed within single quotes, the literal identity of $ is retained and it does not get evaluated."
},
{
"code": null,
"e": 2251,
"s": 2158,
"text": "array=(10) #an array with a single element at index 0\necho \"${array[0]}\"\necho '${array[0]}'\n"
},
{
"code": null,
"e": 2584,
"s": 2251,
"text": "4. In the below-mentioned case, Single quotes have no special meaning when it is enclosed within double quotes, and hence $a gets evaluated even when it is within single quotes. But when double quotes are enclosed within single quotes, then it is treated literally and $a does not get evaluated even when it is inside double-quotes."
},
{
"code": null,
"e": 2614,
"s": 2584,
"text": "a=10\necho \"'$a'\"\necho '\"$a\"'\n"
},
{
"code": null,
"e": 2633,
"s": 2614,
"text": "Difference Between"
},
{
"code": null,
"e": 2644,
"s": 2633,
"text": "Linux-Unix"
},
{
"code": null,
"e": 2742,
"s": 2644,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2803,
"s": 2742,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2871,
"s": 2803,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 2920,
"s": 2871,
"text": "Similarities and Difference between Java and C++"
},
{
"code": null,
"e": 2975,
"s": 2920,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 3041,
"s": 2975,
"text": "Difference between Compile-time and Run-time Polymorphism in Java"
},
{
"code": null,
"e": 3081,
"s": 3041,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 3121,
"s": 3081,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 3148,
"s": 3121,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 3183,
"s": 3148,
"text": "cut command in Linux with examples"
}
] |
Flutter – Stack Widget
|
21 Feb, 2022
Stack widget is a built-in widget in flutter SDK which allows us to make a layer of widgets by putting them on top of each other. Many of the times a simple row and column layout is not enough, we need a way to overlay one widget on top of the other, for example, we might want to show some text over an image, so to tackle such a situation we have Stack widget. The Stack widget has two types of child one is positioned which are wrapped in the Positioned widget and the other one is non–positioned which is not wrapped in the Positioned widget. For all the non-positioned widgets the alignment property is set to the top-left corner. The positioned child widgets are positioned through the top, right, left, and bottom properties. The child widgets are of Stack are printed in order the top-most widget becomes the bottom-most on the screen and vice-versa. We can use the key property of the Stack widget to change that order or to assign a different order.
Stack(
{Key key,
AlignmentGeometry alignment: AlignmentDirectional.topStart,
TextDirection textDirection,
StackFit fit: StackFit.loose,
Overflow overflow: Overflow.clip,
Clip clipBehavior: Clip.hardEdge,
List<Widget> children: const <Widget>[]}
)
alignment: This property takes a parameter of Alignment Geometry, and controls how a child widget which is non-positioned or partially-positioned will be aligned in the Stack.
clipBehaviour: This property decided whether the content will be clipped or not.
fit: This property decided how the non-positioned children in the Stack will fill the space available to it.
overflow: This property controls whether the overflow part of the content will be visible or not,
textDirection: With this property, we can choose the text direction from right to left. or left to right.
Example 1:
Dart
import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], ), //AppBar body: Center( child: SizedBox( width: 300, height: 300, child: Center( child: Stack( children: <Widget>[ Container( width: 300, height: 300, color: Colors.red, ), //Container Container( width: 250, height: 250, color: Colors.black, ), //Container Container( height: 200, width: 200, color: Colors.purple, ), //Container ], //<Widget>[] ), //Stack ), //Center ), //SizedBox ) //Center ) //Scaffold ) //MaterialApp );}
Output:
Explanation: Taking a look at the code of this flutter app, we can see that the parent widget for this app is Scaffold. On the top of the widget tree, we have AppBar widget with title Text widget reading ‘GeeksforGeeks‘ and the background color of the app bar is greenAccent[400]. In the body of the app, the parent widget is Center followed by the SizedBox of height 300 and width 300. SizedBox is also having a child Center which in turn is holding the Stack widget. In the Stack widget, we have a list of children widgets holding three Container widgets. The first Container widget is having a height and width of 300, the same as the SizedBox, with a red color. The Second Container is having a width and height of 250 with black color. The third Container is having a width and height of 200 with a purple color. Now, looking at the app we can see that all three containers that are children to Stack are stacked on top of each other with the red containers at the bottom of the purple at the top, and the black in the middle. All these three containers are non-positioned widget in Stack so the alignment property for them is set to Alignment.topRight, therefore we can see all of them aligned to the top right corner.
Example 2:
Dart
import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], ), //AppBar body: Center( child: SizedBox( width: 300, height: 300, child: Center( child: Stack( children: <Widget>[ Container( width: 300, height: 300, color: Colors.red, padding: EdgeInsets.all(15.0), alignment: Alignment.topRight, child: Text( 'One', style: TextStyle(color: Colors.white), ), //Text ), //Container Container( width: 250, height: 250, color: Colors.black, padding: EdgeInsets.all(15.0), alignment: Alignment.bottomLeft, child: Text( 'Two', style: TextStyle(color: Colors.white), ), //Text ), //Container Container( height: 200, width: 200, padding: EdgeInsets.all(15.0), alignment: Alignment.bottomCenter, decoration: BoxDecoration( image: DecorationImage( image: NetworkImage( "https://pbs.twimg.com/profile_images/1304985167476523008/QNHrwL2q_400x400.jpg") //NetworkImage ), //DecorationImage ), //BoxDecoration child: Text( "GeeksforGeeks", style: TextStyle(color: Colors.white, fontSize: 20.0), ), //Text ), //Container ], //<Widget>[] ), //Stack ), //Center ), //SizedBox ) //Center ) //Scaffold ) //MaterialApp );}
Output:
Explanation: In this app, we have added padding and a child Text widget is each of the containers with the text color being white. In the first Container, the text is ‘One’, and the alignment is set to Alignment.topRight, which puts the Text widget in the top-right corner. In the second Container, the text is ‘Two’, and the alignment is set to Alignment.bottom left, which put the child which is the Text in the bottom-left corner. In the third Container, we have added a background image showing the GeeksforGeeks logo by using the decoration property in the container. The text in this container is ‘GeeksforGeeks’ and the alignment is set to bottom-center, which puts the test above the image in the bottom Centre part of the container.
This is how we can use the Stack widget to show the text (or any other widget) on top of another widget.
Example 3:
Dart
import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], ), //AppBar body: Center( child: SizedBox( width: 300, height: 300, child: Center( child: Stack( fit: StackFit.expand, clipBehavior: Clip.antiAliasWithSaveLayer, overflow: Overflow.visible, children: <Widget>[ Container( width: 300, height: 300, color: Colors.red, ), //Container Positioned( top: 80, left: 80, child: Container( width: 250, height: 250, color: Colors.black, ), ), //Container Positioned( left: 20, top: 20, child: Container( height: 200, width: 200, color: Colors.purple, ), ), //Container ], //<Widget>[] ), //Stack ), //Center ), //SizedBox ) //Center ) //Scaffold ) //MaterialApp );}
Output:
Explanation: In this app, we have wrapped the purple and the black Container with a Positioned widget, so these children widgets are now positioned widgets. In the Stack widget, the fit property is set to StackFit.expand which will force all its children widgets to take maximum space available to them. The clip property is set to antiAliasWithSaveLayer, which avoid any bleeding edges. And the overflow is set to visible, to make the overflowing parts visible. Now, that we have wrapped containers with the Positioned widget we need to specify their position. For the black Container, the top and the left properties are set to 80 each, which makes it overflow out of the SizedBox and the red Container. But as the overflow is set to visible, so we are able to see the overflowing portion of the black Container. And for the purple Container, the top and left are set to 20 each, which makes it a bit offset when compared to the first example.
So, this is how the Stack widget can be used. But we can also achieve a similar or same result with CustomSingleChildLayout widget and CustomMultiChildLayout widget.
sagar0719kumar
simranarora5sos
android
Flutter
Flutter-widgets
Android
Dart
Flutter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
Flutter - DropDownButton Widget
Listview.builder in Flutter
Flutter - Custom Bottom Navigation Bar
Splash Screen in Flutter
Flutter - Asset Image
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Feb, 2022"
},
{
"code": null,
"e": 1013,
"s": 52,
"text": "Stack widget is a built-in widget in flutter SDK which allows us to make a layer of widgets by putting them on top of each other. Many of the times a simple row and column layout is not enough, we need a way to overlay one widget on top of the other, for example, we might want to show some text over an image, so to tackle such a situation we have Stack widget. The Stack widget has two types of child one is positioned which are wrapped in the Positioned widget and the other one is non–positioned which is not wrapped in the Positioned widget. For all the non-positioned widgets the alignment property is set to the top-left corner. The positioned child widgets are positioned through the top, right, left, and bottom properties. The child widgets are of Stack are printed in order the top-most widget becomes the bottom-most on the screen and vice-versa. We can use the key property of the Stack widget to change that order or to assign a different order. "
},
{
"code": null,
"e": 1260,
"s": 1013,
"text": "Stack(\n{Key key,\nAlignmentGeometry alignment: AlignmentDirectional.topStart,\nTextDirection textDirection,\nStackFit fit: StackFit.loose,\nOverflow overflow: Overflow.clip,\nClip clipBehavior: Clip.hardEdge,\nList<Widget> children: const <Widget>[]}\n)"
},
{
"code": null,
"e": 1436,
"s": 1260,
"text": "alignment: This property takes a parameter of Alignment Geometry, and controls how a child widget which is non-positioned or partially-positioned will be aligned in the Stack."
},
{
"code": null,
"e": 1517,
"s": 1436,
"text": "clipBehaviour: This property decided whether the content will be clipped or not."
},
{
"code": null,
"e": 1626,
"s": 1517,
"text": "fit: This property decided how the non-positioned children in the Stack will fill the space available to it."
},
{
"code": null,
"e": 1724,
"s": 1626,
"text": "overflow: This property controls whether the overflow part of the content will be visible or not,"
},
{
"code": null,
"e": 1830,
"s": 1724,
"text": "textDirection: With this property, we can choose the text direction from right to left. or left to right."
},
{
"code": null,
"e": 1841,
"s": 1830,
"text": "Example 1:"
},
{
"code": null,
"e": 1846,
"s": 1841,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], ), //AppBar body: Center( child: SizedBox( width: 300, height: 300, child: Center( child: Stack( children: <Widget>[ Container( width: 300, height: 300, color: Colors.red, ), //Container Container( width: 250, height: 250, color: Colors.black, ), //Container Container( height: 200, width: 200, color: Colors.purple, ), //Container ], //<Widget>[] ), //Stack ), //Center ), //SizedBox ) //Center ) //Scaffold ) //MaterialApp );}",
"e": 3113,
"s": 1846,
"text": null
},
{
"code": null,
"e": 3121,
"s": 3113,
"text": "Output:"
},
{
"code": null,
"e": 4346,
"s": 3121,
"text": "Explanation: Taking a look at the code of this flutter app, we can see that the parent widget for this app is Scaffold. On the top of the widget tree, we have AppBar widget with title Text widget reading ‘GeeksforGeeks‘ and the background color of the app bar is greenAccent[400]. In the body of the app, the parent widget is Center followed by the SizedBox of height 300 and width 300. SizedBox is also having a child Center which in turn is holding the Stack widget. In the Stack widget, we have a list of children widgets holding three Container widgets. The first Container widget is having a height and width of 300, the same as the SizedBox, with a red color. The Second Container is having a width and height of 250 with black color. The third Container is having a width and height of 200 with a purple color. Now, looking at the app we can see that all three containers that are children to Stack are stacked on top of each other with the red containers at the bottom of the purple at the top, and the black in the middle. All these three containers are non-positioned widget in Stack so the alignment property for them is set to Alignment.topRight, therefore we can see all of them aligned to the top right corner."
},
{
"code": null,
"e": 4357,
"s": 4346,
"text": "Example 2:"
},
{
"code": null,
"e": 4362,
"s": 4357,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], ), //AppBar body: Center( child: SizedBox( width: 300, height: 300, child: Center( child: Stack( children: <Widget>[ Container( width: 300, height: 300, color: Colors.red, padding: EdgeInsets.all(15.0), alignment: Alignment.topRight, child: Text( 'One', style: TextStyle(color: Colors.white), ), //Text ), //Container Container( width: 250, height: 250, color: Colors.black, padding: EdgeInsets.all(15.0), alignment: Alignment.bottomLeft, child: Text( 'Two', style: TextStyle(color: Colors.white), ), //Text ), //Container Container( height: 200, width: 200, padding: EdgeInsets.all(15.0), alignment: Alignment.bottomCenter, decoration: BoxDecoration( image: DecorationImage( image: NetworkImage( \"https://pbs.twimg.com/profile_images/1304985167476523008/QNHrwL2q_400x400.jpg\") //NetworkImage ), //DecorationImage ), //BoxDecoration child: Text( \"GeeksforGeeks\", style: TextStyle(color: Colors.white, fontSize: 20.0), ), //Text ), //Container ], //<Widget>[] ), //Stack ), //Center ), //SizedBox ) //Center ) //Scaffold ) //MaterialApp );}",
"e": 6882,
"s": 4362,
"text": null
},
{
"code": null,
"e": 6890,
"s": 6882,
"text": "Output:"
},
{
"code": null,
"e": 7633,
"s": 6890,
"text": "Explanation: In this app, we have added padding and a child Text widget is each of the containers with the text color being white. In the first Container, the text is ‘One’, and the alignment is set to Alignment.topRight, which puts the Text widget in the top-right corner. In the second Container, the text is ‘Two’, and the alignment is set to Alignment.bottom left, which put the child which is the Text in the bottom-left corner. In the third Container, we have added a background image showing the GeeksforGeeks logo by using the decoration property in the container. The text in this container is ‘GeeksforGeeks’ and the alignment is set to bottom-center, which puts the test above the image in the bottom Centre part of the container. "
},
{
"code": null,
"e": 7738,
"s": 7633,
"text": "This is how we can use the Stack widget to show the text (or any other widget) on top of another widget."
},
{
"code": null,
"e": 7749,
"s": 7738,
"text": "Example 3:"
},
{
"code": null,
"e": 7754,
"s": 7749,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], ), //AppBar body: Center( child: SizedBox( width: 300, height: 300, child: Center( child: Stack( fit: StackFit.expand, clipBehavior: Clip.antiAliasWithSaveLayer, overflow: Overflow.visible, children: <Widget>[ Container( width: 300, height: 300, color: Colors.red, ), //Container Positioned( top: 80, left: 80, child: Container( width: 250, height: 250, color: Colors.black, ), ), //Container Positioned( left: 20, top: 20, child: Container( height: 200, width: 200, color: Colors.purple, ), ), //Container ], //<Widget>[] ), //Stack ), //Center ), //SizedBox ) //Center ) //Scaffold ) //MaterialApp );}",
"e": 9471,
"s": 7754,
"text": null
},
{
"code": null,
"e": 9479,
"s": 9471,
"text": "Output:"
},
{
"code": null,
"e": 10425,
"s": 9479,
"text": "Explanation: In this app, we have wrapped the purple and the black Container with a Positioned widget, so these children widgets are now positioned widgets. In the Stack widget, the fit property is set to StackFit.expand which will force all its children widgets to take maximum space available to them. The clip property is set to antiAliasWithSaveLayer, which avoid any bleeding edges. And the overflow is set to visible, to make the overflowing parts visible. Now, that we have wrapped containers with the Positioned widget we need to specify their position. For the black Container, the top and the left properties are set to 80 each, which makes it overflow out of the SizedBox and the red Container. But as the overflow is set to visible, so we are able to see the overflowing portion of the black Container. And for the purple Container, the top and left are set to 20 each, which makes it a bit offset when compared to the first example."
},
{
"code": null,
"e": 10591,
"s": 10425,
"text": "So, this is how the Stack widget can be used. But we can also achieve a similar or same result with CustomSingleChildLayout widget and CustomMultiChildLayout widget."
},
{
"code": null,
"e": 10606,
"s": 10591,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 10622,
"s": 10606,
"text": "simranarora5sos"
},
{
"code": null,
"e": 10630,
"s": 10622,
"text": "android"
},
{
"code": null,
"e": 10638,
"s": 10630,
"text": "Flutter"
},
{
"code": null,
"e": 10654,
"s": 10638,
"text": "Flutter-widgets"
},
{
"code": null,
"e": 10662,
"s": 10654,
"text": "Android"
},
{
"code": null,
"e": 10667,
"s": 10662,
"text": "Dart"
},
{
"code": null,
"e": 10675,
"s": 10667,
"text": "Flutter"
},
{
"code": null,
"e": 10683,
"s": 10675,
"text": "Android"
},
{
"code": null,
"e": 10781,
"s": 10683,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10850,
"s": 10781,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 10882,
"s": 10850,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 10921,
"s": 10882,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 10970,
"s": 10921,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 11012,
"s": 10970,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 11044,
"s": 11012,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 11072,
"s": 11044,
"text": "Listview.builder in Flutter"
},
{
"code": null,
"e": 11111,
"s": 11072,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 11136,
"s": 11111,
"text": "Splash Screen in Flutter"
}
] |
Quadratic equation whose roots are reciprocal to the roots of given equation
|
22 Apr, 2021
Given three integers A, B, and C representing the coefficients of a quadratic equation Ax2 + Bx + C = 0, the task is to find the quadratic equation whose roots are reciprocal to the roots of the given equation.
Examples:
Input: A = 1, B = -5, C = 6 Output: (6)x^2 +(-5)x + (1) = 0Explanation: The given quadratic equation x2 – 5x + 6 = 0.Roots of the above equation are 2, 3.Reciprocal of these roots are 1/2, 1/3.Therefore, the quadratic equation with these reciprocal roots is 6x2 – 5x + 1 = 0.
Input: A = 1, B = -7, C = 12Output: (12)x^2 +(-7)x + (1) = 0
Approach: The idea is to use the concept of quadratic roots to solve the problem. Follow the steps below to solve the problem:
Consider the roots of the equation Ax2 + Bx + C = 0 to be p, q.
The product of the roots of the above equation is given by p * q = C / A.
The sum of the roots of the above equation is given by p + q = -B / A.
Therefore, the reciprocals of the roots are 1/p, 1/q.
The product of these reciprocal roots is 1/p * 1/q = A / C.
The sum of these reciprocal roots is 1/p + 1/q = -B / C.
If the sum and product of roots is known, the quadratic equation can be x2 – (Sum of the roots)x + (Product of the roots) = 0.
On solving the above equation, quadratic equation becomes Cx2 + Bx + A = 0.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the quadratic// equation having reciprocal rootsvoid findEquation(int A, int B, int C){ // Print quadratic equation cout << "(" << C << ")" << "x^2 +(" << B << ")x + (" << A << ") = 0";} // Driver Codeint main(){ // Given coefficients int A = 1, B = -5, C = 6; // Function call to find the quadratic // equation having reciprocal roots findEquation(A, B, C); return 0;}
// Java program for the above approachclass GFG{ // Function to find the quadratic// equation having reciprocal rootsstatic void findEquation(int A, int B, int C){ // Print quadratic equation System.out.print("(" + C + ")" + "x^2 +(" + B + ")x + (" + A + ") = 0");} // Driver Codepublic static void main(String args[]){ // Given coefficients int A = 1, B = -5, C = 6; // Function call to find the quadratic // equation having reciprocal roots findEquation(A, B, C);}} // This code is contributed by AnkThon
# Python3 program for the above approach # Function to find the quadratic# equation having reciprocal rootsdef findEquation(A, B, C): # Print quadratic equation print("(" + str(C) + ")" + "x^2 +(" + str(B) + ")x + (" + str(A) + ") = 0") # Driver Codeif __name__ == "__main__": # Given coefficients A = 1 B = -5 C = 6 # Function call to find the quadratic # equation having reciprocal roots findEquation(A, B, C) # This code is contributed by AnkThon
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the quadratic// equation having reciprocal rootsstatic void findEquation(int A, int B, int C){ // Print quadratic equation Console.Write("(" + C + ")" + "x^2 +(" + B + ")x + (" + A + ") = 0");} // Driver Codepublic static void Main(){ // Given coefficients int A = 1, B = -5, C = 6; // Function call to find the quadratic // equation having reciprocal roots findEquation(A, B, C);}} // This code is contributed by bgangwar59
<script> // Javascript program for the above approach // Function to find the quadratic // equation having reciprocal roots function findEquation(A, B, C) { // Print quadratic equation document.write("(" + C + ")" + "x^2 +(" + B + ")x + (" + A + ") = 0") } // Driver Code // Given coefficients let A = 1, B = -5, C = 6; // Function call to find the quadratic // equation having reciprocal roots findEquation(A, B, C); // This code is contributed by Hritik </script>
(6)x^2 +(-5)x + (1) = 0
Time Complexity: O(1)Auxiliary Space: O(1)
bgangwar59
ankthon
hritikrommie
root
Mathematical
Pattern Searching
Mathematical
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Sieve of Eratosthenes
Program to find GCD or HCF of two numbers
KMP Algorithm for Pattern Searching
Rabin-Karp Algorithm for Pattern Searching
Check if an URL is valid or not using Regular Expression
Check if a string is substring of another
Boyer Moore Algorithm for Pattern Searching
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n22 Apr, 2021"
},
{
"code": null,
"e": 264,
"s": 53,
"text": "Given three integers A, B, and C representing the coefficients of a quadratic equation Ax2 + Bx + C = 0, the task is to find the quadratic equation whose roots are reciprocal to the roots of the given equation."
},
{
"code": null,
"e": 274,
"s": 264,
"text": "Examples:"
},
{
"code": null,
"e": 550,
"s": 274,
"text": "Input: A = 1, B = -5, C = 6 Output: (6)x^2 +(-5)x + (1) = 0Explanation: The given quadratic equation x2 – 5x + 6 = 0.Roots of the above equation are 2, 3.Reciprocal of these roots are 1/2, 1/3.Therefore, the quadratic equation with these reciprocal roots is 6x2 – 5x + 1 = 0."
},
{
"code": null,
"e": 611,
"s": 550,
"text": "Input: A = 1, B = -7, C = 12Output: (12)x^2 +(-7)x + (1) = 0"
},
{
"code": null,
"e": 738,
"s": 611,
"text": "Approach: The idea is to use the concept of quadratic roots to solve the problem. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 802,
"s": 738,
"text": "Consider the roots of the equation Ax2 + Bx + C = 0 to be p, q."
},
{
"code": null,
"e": 876,
"s": 802,
"text": "The product of the roots of the above equation is given by p * q = C / A."
},
{
"code": null,
"e": 947,
"s": 876,
"text": "The sum of the roots of the above equation is given by p + q = -B / A."
},
{
"code": null,
"e": 1001,
"s": 947,
"text": "Therefore, the reciprocals of the roots are 1/p, 1/q."
},
{
"code": null,
"e": 1061,
"s": 1001,
"text": "The product of these reciprocal roots is 1/p * 1/q = A / C."
},
{
"code": null,
"e": 1118,
"s": 1061,
"text": "The sum of these reciprocal roots is 1/p + 1/q = -B / C."
},
{
"code": null,
"e": 1245,
"s": 1118,
"text": "If the sum and product of roots is known, the quadratic equation can be x2 – (Sum of the roots)x + (Product of the roots) = 0."
},
{
"code": null,
"e": 1321,
"s": 1245,
"text": "On solving the above equation, quadratic equation becomes Cx2 + Bx + A = 0."
},
{
"code": null,
"e": 1373,
"s": 1321,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1377,
"s": 1373,
"text": "C++"
},
{
"code": null,
"e": 1382,
"s": 1377,
"text": "Java"
},
{
"code": null,
"e": 1390,
"s": 1382,
"text": "Python3"
},
{
"code": null,
"e": 1393,
"s": 1390,
"text": "C#"
},
{
"code": null,
"e": 1404,
"s": 1393,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the quadratic// equation having reciprocal rootsvoid findEquation(int A, int B, int C){ // Print quadratic equation cout << \"(\" << C << \")\" << \"x^2 +(\" << B << \")x + (\" << A << \") = 0\";} // Driver Codeint main(){ // Given coefficients int A = 1, B = -5, C = 6; // Function call to find the quadratic // equation having reciprocal roots findEquation(A, B, C); return 0;}",
"e": 1919,
"s": 1404,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ // Function to find the quadratic// equation having reciprocal rootsstatic void findEquation(int A, int B, int C){ // Print quadratic equation System.out.print(\"(\" + C + \")\" + \"x^2 +(\" + B + \")x + (\" + A + \") = 0\");} // Driver Codepublic static void main(String args[]){ // Given coefficients int A = 1, B = -5, C = 6; // Function call to find the quadratic // equation having reciprocal roots findEquation(A, B, C);}} // This code is contributed by AnkThon",
"e": 2501,
"s": 1919,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the quadratic# equation having reciprocal rootsdef findEquation(A, B, C): # Print quadratic equation print(\"(\" + str(C) + \")\" + \"x^2 +(\" + str(B) + \")x + (\" + str(A) + \") = 0\") # Driver Codeif __name__ == \"__main__\": # Given coefficients A = 1 B = -5 C = 6 # Function call to find the quadratic # equation having reciprocal roots findEquation(A, B, C) # This code is contributed by AnkThon",
"e": 3009,
"s": 2501,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the quadratic// equation having reciprocal rootsstatic void findEquation(int A, int B, int C){ // Print quadratic equation Console.Write(\"(\" + C + \")\" + \"x^2 +(\" + B + \")x + (\" + A + \") = 0\");} // Driver Codepublic static void Main(){ // Given coefficients int A = 1, B = -5, C = 6; // Function call to find the quadratic // equation having reciprocal roots findEquation(A, B, C);}} // This code is contributed by bgangwar59",
"e": 3612,
"s": 3009,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to find the quadratic // equation having reciprocal roots function findEquation(A, B, C) { // Print quadratic equation document.write(\"(\" + C + \")\" + \"x^2 +(\" + B + \")x + (\" + A + \") = 0\") } // Driver Code // Given coefficients let A = 1, B = -5, C = 6; // Function call to find the quadratic // equation having reciprocal roots findEquation(A, B, C); // This code is contributed by Hritik </script>",
"e": 4240,
"s": 3612,
"text": null
},
{
"code": null,
"e": 4264,
"s": 4240,
"text": "(6)x^2 +(-5)x + (1) = 0"
},
{
"code": null,
"e": 4309,
"s": 4266,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 4322,
"s": 4311,
"text": "bgangwar59"
},
{
"code": null,
"e": 4330,
"s": 4322,
"text": "ankthon"
},
{
"code": null,
"e": 4343,
"s": 4330,
"text": "hritikrommie"
},
{
"code": null,
"e": 4348,
"s": 4343,
"text": "root"
},
{
"code": null,
"e": 4361,
"s": 4348,
"text": "Mathematical"
},
{
"code": null,
"e": 4379,
"s": 4361,
"text": "Pattern Searching"
},
{
"code": null,
"e": 4392,
"s": 4379,
"text": "Mathematical"
},
{
"code": null,
"e": 4410,
"s": 4392,
"text": "Pattern Searching"
},
{
"code": null,
"e": 4508,
"s": 4410,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4532,
"s": 4508,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 4553,
"s": 4532,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 4567,
"s": 4553,
"text": "Prime Numbers"
},
{
"code": null,
"e": 4589,
"s": 4567,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 4631,
"s": 4589,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 4667,
"s": 4631,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 4710,
"s": 4667,
"text": "Rabin-Karp Algorithm for Pattern Searching"
},
{
"code": null,
"e": 4767,
"s": 4710,
"text": "Check if an URL is valid or not using Regular Expression"
},
{
"code": null,
"e": 4809,
"s": 4767,
"text": "Check if a string is substring of another"
}
] |
Python | Pandas dataframe.count()
|
20 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.count() is used to count the no. of non-NA/null observations across the given axis. It works with non-floating type data as well.
Syntax: DataFrame.count(axis=0, level=None, numeric_only=False)
Parameters:axis : 0 or ‘index’ for row-wise, 1 or ‘columns’ for column-wiselevel : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a DataFramenumeric_only : Include only float, int, boolean data
Returns: count : Series (or DataFrame if level specified)
Example #1: Use count() function to find the number of non-NA/null value across the row axis.
# importing pandas as pdimport pandas as pd # Creating a dataframe using dictionarydf = pd.DataFrame({"A":[-5, 8, 12, None, 5, 3], "B":[-1, None, 6, 4, None, 3], "C:["sam", "haris", "alex", np.nan, "peter", "nathan"]}) # Printing the dataframedf
Now find the count of non-NA value across the row axis
# axis = 0 indicates rowdf.count(axis = 0)
Output : Example #2: Use count() function to find the number of non-NA/null value across the column.
# importing pandas as pdimport pandas as pd # Creating a dataframe using dictionarydf = pd.DataFrame({"A":[-5, 8, 12, None, 5, 3], "B":[-1, None, 6, 4, None, 3], "C:["sam", "haris", "alex", np.nan, "peter", "nathan"]}) # Find count of non-NA across the columnsdf.count(axis = 1)
Output :
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n20 Nov, 2018"
},
{
"code": null,
"e": 266,
"s": 52,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 413,
"s": 266,
"text": "Pandas dataframe.count() is used to count the no. of non-NA/null observations across the given axis. It works with non-floating type data as well."
},
{
"code": null,
"e": 477,
"s": 413,
"text": "Syntax: DataFrame.count(axis=0, level=None, numeric_only=False)"
},
{
"code": null,
"e": 716,
"s": 477,
"text": "Parameters:axis : 0 or ‘index’ for row-wise, 1 or ‘columns’ for column-wiselevel : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a DataFramenumeric_only : Include only float, int, boolean data"
},
{
"code": null,
"e": 774,
"s": 716,
"text": "Returns: count : Series (or DataFrame if level specified)"
},
{
"code": null,
"e": 868,
"s": 774,
"text": "Example #1: Use count() function to find the number of non-NA/null value across the row axis."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating a dataframe using dictionarydf = pd.DataFrame({\"A\":[-5, 8, 12, None, 5, 3], \"B\":[-1, None, 6, 4, None, 3], \"C:[\"sam\", \"haris\", \"alex\", np.nan, \"peter\", \"nathan\"]}) # Printing the dataframedf",
"e": 1153,
"s": 868,
"text": null
},
{
"code": null,
"e": 1208,
"s": 1153,
"text": "Now find the count of non-NA value across the row axis"
},
{
"code": "# axis = 0 indicates rowdf.count(axis = 0)",
"e": 1251,
"s": 1208,
"text": null
},
{
"code": null,
"e": 1352,
"s": 1251,
"text": "Output : Example #2: Use count() function to find the number of non-NA/null value across the column."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating a dataframe using dictionarydf = pd.DataFrame({\"A\":[-5, 8, 12, None, 5, 3], \"B\":[-1, None, 6, 4, None, 3], \"C:[\"sam\", \"haris\", \"alex\", np.nan, \"peter\", \"nathan\"]}) # Find count of non-NA across the columnsdf.count(axis = 1)",
"e": 1670,
"s": 1352,
"text": null
},
{
"code": null,
"e": 1679,
"s": 1670,
"text": "Output :"
},
{
"code": null,
"e": 1703,
"s": 1679,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 1735,
"s": 1703,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 1749,
"s": 1735,
"text": "Python-pandas"
},
{
"code": null,
"e": 1756,
"s": 1749,
"text": "Python"
}
] |
Upload and Retrieve Images on MongoDB using Dart in Flutter
|
16 Oct, 2020
To upload files from a local system to the dedicated server is called file uploading and retrieval files from the dedicated server to a local system is called file retrieving. It works exactly the same as the definition when we select a file from the Android device and click the submit button, the Android device takes the file from the local storage and sends it to the server with the help of an Http request and the server does its job to save the file to the defined location. In this article, we are demonstrating how image files are stored and retrieved into the MongoDB Atlas cluster database along with compressing the size of images form Megabytes(MBs) to Kilobytes(KB) with the help of the flutter_image_compress plugin.
Prerequisite: For getting started with this an individual needs to be familiar with the following
Flutter
Dart
MongoDB
Mongo Dart
Here, We are creating an Android application to demonstrate the use of MongoDB in the Flutter application. To get started we need to install certain Flutter packages & plugins and Android Studio must be installed in the local system.
Before getting started Flutter development toolkit in the local system and Flutter plugin in Android Studio IDE must be installed.
Open Android Studio and create a new flutter application project with a name called ‘geeksforgeeks’.
Once the project is created and sync successfully, connect your Android device to Android Studio, and make sure Developer options and USB debugging are On.
Run the project by clicking on the first green icon at the center top to cross-check the project is built and running successfully(first time Android Studio takes a little more time as usual).
Now, It’s time to install the necessary packages & plugins, open the ‘pubspec.yaml’ file from geeksforgeeks -> pubspec.yaml project structure and copy-paste three dependencies that are image_picker, flutter_image_compress, and mongo_dart as follows.
dependencies:
image_picker: ^0.6.7+7
flutter_image_compress: ^0.7.0
mongo_dart:
git:
url: https://github.com/mongo-dart/mongo_dart.git
Once, you have done the above steps then click on ‘Packages get’ flutter command appearing at the center top to get install all necessary packages and plugins.
To upload and retrieve an image on MongoDB using Dart in flutter lets begin, follow each and every step below one by one.
Step 1:
Since this entire application is built on the top of the Android smartphone hence it won’t be possible to connect with the local MongoDB database that’s why here, we will be using the MongoDB cluster database, and to connect with cluster database all we need replicas’ URIs.
Signup or Login to MongoDB account and create a database with any custom name.
To get these replicas from Atlas, got to ‘Connect’ -> ‘Connect with Shell’ -> ‘I have the Mongo Shell installed’ -> set your version to 3.4 or earlier.
If you have 3 replicas, you will have 3 URLs split up with commas like below.
Dart
final url = [ "mongodb://<username>:<password>@<hostname1>:27017/<DBName>?ssl=true& replicaSet=<MySet>&authSource=admin&retryWrites=true&w=majority", "mongodb://<username>:<password>@<hostname2>:27017/<DBName>?ssl=true& replicaSet=<MySet>&authSource=admin&retryWrites=true&w=majority", "mongodb://<username>:<password>@<hostname3>:27017/<DBName>?ssl=true& replicaSet=<MySet>&authSource=admin&retryWrites=true&w=majority"];
Step 2:
To begins with the database connection, Since Atlas now only allows SSL connections, we will need the source from TLS/SSL to open a secure connection. To the Db.pool() instruction we will have to pass in each of these URLs prefaced with mongodb://, followed by /test?authSource=[auth db (probably ‘admin’)] we can see an example of replicas’ URIs in the above step.
Dart
Future connection () async{ Db _db = new Db.pool(url); await _db.open(secure: true); GridFS bucket = GridFS(_db,"image");}
Step 3:
Once we have established a connection to the MongoDB cluster database, we can now begin defining our back-end logic. Since uploading and retrieving long size image is very time-consuming and sometimes it leads with a bunch of problems like for example acquire more space, more costly, access time more, and more data overload therefore In this, the step we are compressing the size of an image from MB’s to KB’s with maintaining aspect ratio.
Dart
final pickedFile = await picker.getImage(source: ImageSource.gallery);if(pickedFile!=null){ var _cmpressed_image; try { _cmpressed_image = await FlutterImageCompress.compressWithFile( pickedFile.path, format: CompressFormat.heic, quality: 70 ); } catch (e) { _cmpressed_image = await FlutterImageCompress.compressWithFile( pickedFile.path, format: CompressFormat.jpeg, quality: 70 ); }}
Step 4:
Now, this is the fourth and final step here, we will be building queries to upload and retrieve images to MongoDB, therefore, cluster database. Since MongoDB supports JSON like(i.e key-value pair) data format therefore we will have to create a Hashmap with two key-value pairs that are ‘_id’ and ‘data’ to store image unique id and image pixel data respectively.
Dart
Map<String,dynamic> image = { "_id" : pickedFile.path.split("/").last, "data": base64Encode(_cmpressed_image)}; var res = await bucket.chunks.insert(image);var img = await bucket.chunks.findOne({ "_id": pickedFile.path.split("/").last});
Now, It is time to show the full approach, open ‘main.dart’ file from geeksforgeeks -> lib -> main.dart project directory structure and copy-paste following the entire code.
Dart
import 'dart:convert';import 'dart:io'; import 'package:flutter/material.dart';import 'package:image_picker/image_picker.dart';import 'package:flutter_image_compress/flutter_image_compress.dart';import 'package:mongo_dart/mongo_dart.dart' show Db, GridFS; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Geeks Demo', debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.green, ), home: MyHomePage(title: 'GeeksforGeeks'), ); }} class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin{ final url = [ "mongodb://<username>:<password>@<hostname1>:27017/<DBName>?ssl=true& replicaSet=<MySet>&authSource=admin&retryWrites=true&w=majority", "mongodb://<username>:<password>@<hostname2>:27017/<DBName>?ssl=true& replicaSet=<MySet>&authSource=admin&retryWrites=true&w=majority", "mongodb://<username>:<password>@<hostname3>:27017/<DBName>?ssl=true& replicaSet=<MySet>&authSource=admin&retryWrites=true&w=majority" ]; final picker = ImagePicker(); File _image; GridFS bucket; AnimationController _animationController; Animation<Color> _colorTween; ImageProvider provider; var flag = false; @override void initState() { _animationController = AnimationController( duration: Duration(milliseconds: 1800), vsync: this, ); _colorTween = _animationController.drive(ColorTween(begin: Colors.green, end: Colors.deepOrange)); _animationController.repeat(); super.initState(); connection(); } Future getImage() async{ final pickedFile = await picker.getImage(source: ImageSource.gallery); if(pickedFile!=null){ var _cmpressed_image; try { _cmpressed_image = await FlutterImageCompress.compressWithFile( pickedFile.path, format: CompressFormat.heic, quality: 70 ); } catch (e) { _cmpressed_image = await FlutterImageCompress.compressWithFile( pickedFile.path, format: CompressFormat.jpeg, quality: 70 ); } setState(() { flag = true; }); Map<String,dynamic> image = { "_id" : pickedFile.path.split("/").last, "data": base64Encode(_cmpressed_image) }; var res = await bucket.chunks.insert(image); var img = await bucket.chunks.findOne({ "_id": pickedFile.path.split("/").last }); setState(() { provider = MemoryImage(base64Decode(img["data"])); flag = false; }); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), backgroundColor: Colors.green, ), body: SingleChildScrollView( child: Center( child: Column( children: [ SizedBox( height: 20, ), provider == null ? Text('No image selected.') : Image(image: provider,), SizedBox(height: 10,), if(flag==true) CircularProgressIndicator(valueColor: _colorTween), SizedBox(height: 20,), RaisedButton( onPressed: getImage, textColor: Colors.white, padding: const EdgeInsets.all(0.0), child: Container( decoration: BoxDecoration( gradient: LinearGradient( colors: <Color>[ Colors.green, Colors.green[200], Colors.green[900], ], ), ), padding: const EdgeInsets.all(10.0), child: const Text( 'Select Image', style: TextStyle(fontSize: 20) ), ), ), ], ), ) ) ); } Future connection () async{ Db _db = new Db.pool(url); await _db.open(secure: true); bucket = GridFS(_db,"image"); }}
Finally, Run the project by clicking on the first green icon at the center top to see the output, and your job gets done.
Output:
Flutter
Dart
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Oct, 2020"
},
{
"code": null,
"e": 787,
"s": 54,
"text": "To upload files from a local system to the dedicated server is called file uploading and retrieval files from the dedicated server to a local system is called file retrieving. It works exactly the same as the definition when we select a file from the Android device and click the submit button, the Android device takes the file from the local storage and sends it to the server with the help of an Http request and the server does its job to save the file to the defined location. In this article, we are demonstrating how image files are stored and retrieved into the MongoDB Atlas cluster database along with compressing the size of images form Megabytes(MBs) to Kilobytes(KB) with the help of the flutter_image_compress plugin."
},
{
"code": null,
"e": 885,
"s": 787,
"text": "Prerequisite: For getting started with this an individual needs to be familiar with the following"
},
{
"code": null,
"e": 893,
"s": 885,
"text": "Flutter"
},
{
"code": null,
"e": 898,
"s": 893,
"text": "Dart"
},
{
"code": null,
"e": 906,
"s": 898,
"text": "MongoDB"
},
{
"code": null,
"e": 917,
"s": 906,
"text": "Mongo Dart"
},
{
"code": null,
"e": 1151,
"s": 917,
"text": "Here, We are creating an Android application to demonstrate the use of MongoDB in the Flutter application. To get started we need to install certain Flutter packages & plugins and Android Studio must be installed in the local system."
},
{
"code": null,
"e": 1283,
"s": 1151,
"text": "Before getting started Flutter development toolkit in the local system and Flutter plugin in Android Studio IDE must be installed."
},
{
"code": null,
"e": 1384,
"s": 1283,
"text": "Open Android Studio and create a new flutter application project with a name called ‘geeksforgeeks’."
},
{
"code": null,
"e": 1540,
"s": 1384,
"text": "Once the project is created and sync successfully, connect your Android device to Android Studio, and make sure Developer options and USB debugging are On."
},
{
"code": null,
"e": 1733,
"s": 1540,
"text": "Run the project by clicking on the first green icon at the center top to cross-check the project is built and running successfully(first time Android Studio takes a little more time as usual)."
},
{
"code": null,
"e": 1983,
"s": 1733,
"text": "Now, It’s time to install the necessary packages & plugins, open the ‘pubspec.yaml’ file from geeksforgeeks -> pubspec.yaml project structure and copy-paste three dependencies that are image_picker, flutter_image_compress, and mongo_dart as follows."
},
{
"code": null,
"e": 2135,
"s": 1983,
"text": "dependencies:\n image_picker: ^0.6.7+7\n flutter_image_compress: ^0.7.0\n mongo_dart:\n git:\n url: https://github.com/mongo-dart/mongo_dart.git\n"
},
{
"code": null,
"e": 2295,
"s": 2135,
"text": "Once, you have done the above steps then click on ‘Packages get’ flutter command appearing at the center top to get install all necessary packages and plugins."
},
{
"code": null,
"e": 2417,
"s": 2295,
"text": "To upload and retrieve an image on MongoDB using Dart in flutter lets begin, follow each and every step below one by one."
},
{
"code": null,
"e": 2425,
"s": 2417,
"text": "Step 1:"
},
{
"code": null,
"e": 2700,
"s": 2425,
"text": "Since this entire application is built on the top of the Android smartphone hence it won’t be possible to connect with the local MongoDB database that’s why here, we will be using the MongoDB cluster database, and to connect with cluster database all we need replicas’ URIs."
},
{
"code": null,
"e": 2779,
"s": 2700,
"text": "Signup or Login to MongoDB account and create a database with any custom name."
},
{
"code": null,
"e": 2931,
"s": 2779,
"text": "To get these replicas from Atlas, got to ‘Connect’ -> ‘Connect with Shell’ -> ‘I have the Mongo Shell installed’ -> set your version to 3.4 or earlier."
},
{
"code": null,
"e": 3009,
"s": 2931,
"text": "If you have 3 replicas, you will have 3 URLs split up with commas like below."
},
{
"code": null,
"e": 3014,
"s": 3009,
"text": "Dart"
},
{
"code": "final url = [ \"mongodb://<username>:<password>@<hostname1>:27017/<DBName>?ssl=true& replicaSet=<MySet>&authSource=admin&retryWrites=true&w=majority\", \"mongodb://<username>:<password>@<hostname2>:27017/<DBName>?ssl=true& replicaSet=<MySet>&authSource=admin&retryWrites=true&w=majority\", \"mongodb://<username>:<password>@<hostname3>:27017/<DBName>?ssl=true& replicaSet=<MySet>&authSource=admin&retryWrites=true&w=majority\"];",
"e": 3467,
"s": 3014,
"text": null
},
{
"code": null,
"e": 3476,
"s": 3467,
"text": "Step 2: "
},
{
"code": null,
"e": 3842,
"s": 3476,
"text": "To begins with the database connection, Since Atlas now only allows SSL connections, we will need the source from TLS/SSL to open a secure connection. To the Db.pool() instruction we will have to pass in each of these URLs prefaced with mongodb://, followed by /test?authSource=[auth db (probably ‘admin’)] we can see an example of replicas’ URIs in the above step."
},
{
"code": null,
"e": 3847,
"s": 3842,
"text": "Dart"
},
{
"code": "Future connection () async{ Db _db = new Db.pool(url); await _db.open(secure: true); GridFS bucket = GridFS(_db,\"image\");}",
"e": 3979,
"s": 3847,
"text": null
},
{
"code": null,
"e": 3988,
"s": 3979,
"text": "Step 3: "
},
{
"code": null,
"e": 4431,
"s": 3988,
"text": "Once we have established a connection to the MongoDB cluster database, we can now begin defining our back-end logic. Since uploading and retrieving long size image is very time-consuming and sometimes it leads with a bunch of problems like for example acquire more space, more costly, access time more, and more data overload therefore In this, the step we are compressing the size of an image from MB’s to KB’s with maintaining aspect ratio."
},
{
"code": null,
"e": 4436,
"s": 4431,
"text": "Dart"
},
{
"code": "final pickedFile = await picker.getImage(source: ImageSource.gallery);if(pickedFile!=null){ var _cmpressed_image; try { _cmpressed_image = await FlutterImageCompress.compressWithFile( pickedFile.path, format: CompressFormat.heic, quality: 70 ); } catch (e) { _cmpressed_image = await FlutterImageCompress.compressWithFile( pickedFile.path, format: CompressFormat.jpeg, quality: 70 ); }}",
"e": 4911,
"s": 4436,
"text": null
},
{
"code": null,
"e": 4920,
"s": 4911,
"text": "Step 4: "
},
{
"code": null,
"e": 5283,
"s": 4920,
"text": "Now, this is the fourth and final step here, we will be building queries to upload and retrieve images to MongoDB, therefore, cluster database. Since MongoDB supports JSON like(i.e key-value pair) data format therefore we will have to create a Hashmap with two key-value pairs that are ‘_id’ and ‘data’ to store image unique id and image pixel data respectively."
},
{
"code": null,
"e": 5288,
"s": 5283,
"text": "Dart"
},
{
"code": "Map<String,dynamic> image = { \"_id\" : pickedFile.path.split(\"/\").last, \"data\": base64Encode(_cmpressed_image)}; var res = await bucket.chunks.insert(image);var img = await bucket.chunks.findOne({ \"_id\": pickedFile.path.split(\"/\").last});",
"e": 5542,
"s": 5288,
"text": null
},
{
"code": null,
"e": 5716,
"s": 5542,
"text": "Now, It is time to show the full approach, open ‘main.dart’ file from geeksforgeeks -> lib -> main.dart project directory structure and copy-paste following the entire code."
},
{
"code": null,
"e": 5721,
"s": 5716,
"text": "Dart"
},
{
"code": "import 'dart:convert';import 'dart:io'; import 'package:flutter/material.dart';import 'package:image_picker/image_picker.dart';import 'package:flutter_image_compress/flutter_image_compress.dart';import 'package:mongo_dart/mongo_dart.dart' show Db, GridFS; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Geeks Demo', debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.green, ), home: MyHomePage(title: 'GeeksforGeeks'), ); }} class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin{ final url = [ \"mongodb://<username>:<password>@<hostname1>:27017/<DBName>?ssl=true& replicaSet=<MySet>&authSource=admin&retryWrites=true&w=majority\", \"mongodb://<username>:<password>@<hostname2>:27017/<DBName>?ssl=true& replicaSet=<MySet>&authSource=admin&retryWrites=true&w=majority\", \"mongodb://<username>:<password>@<hostname3>:27017/<DBName>?ssl=true& replicaSet=<MySet>&authSource=admin&retryWrites=true&w=majority\" ]; final picker = ImagePicker(); File _image; GridFS bucket; AnimationController _animationController; Animation<Color> _colorTween; ImageProvider provider; var flag = false; @override void initState() { _animationController = AnimationController( duration: Duration(milliseconds: 1800), vsync: this, ); _colorTween = _animationController.drive(ColorTween(begin: Colors.green, end: Colors.deepOrange)); _animationController.repeat(); super.initState(); connection(); } Future getImage() async{ final pickedFile = await picker.getImage(source: ImageSource.gallery); if(pickedFile!=null){ var _cmpressed_image; try { _cmpressed_image = await FlutterImageCompress.compressWithFile( pickedFile.path, format: CompressFormat.heic, quality: 70 ); } catch (e) { _cmpressed_image = await FlutterImageCompress.compressWithFile( pickedFile.path, format: CompressFormat.jpeg, quality: 70 ); } setState(() { flag = true; }); Map<String,dynamic> image = { \"_id\" : pickedFile.path.split(\"/\").last, \"data\": base64Encode(_cmpressed_image) }; var res = await bucket.chunks.insert(image); var img = await bucket.chunks.findOne({ \"_id\": pickedFile.path.split(\"/\").last }); setState(() { provider = MemoryImage(base64Decode(img[\"data\"])); flag = false; }); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), backgroundColor: Colors.green, ), body: SingleChildScrollView( child: Center( child: Column( children: [ SizedBox( height: 20, ), provider == null ? Text('No image selected.') : Image(image: provider,), SizedBox(height: 10,), if(flag==true) CircularProgressIndicator(valueColor: _colorTween), SizedBox(height: 20,), RaisedButton( onPressed: getImage, textColor: Colors.white, padding: const EdgeInsets.all(0.0), child: Container( decoration: BoxDecoration( gradient: LinearGradient( colors: <Color>[ Colors.green, Colors.green[200], Colors.green[900], ], ), ), padding: const EdgeInsets.all(10.0), child: const Text( 'Select Image', style: TextStyle(fontSize: 20) ), ), ), ], ), ) ) ); } Future connection () async{ Db _db = new Db.pool(url); await _db.open(secure: true); bucket = GridFS(_db,\"image\"); }}",
"e": 10078,
"s": 5721,
"text": null
},
{
"code": null,
"e": 10200,
"s": 10078,
"text": "Finally, Run the project by clicking on the first green icon at the center top to see the output, and your job gets done."
},
{
"code": null,
"e": 10208,
"s": 10200,
"text": "Output:"
},
{
"code": null,
"e": 10216,
"s": 10208,
"text": "Flutter"
},
{
"code": null,
"e": 10221,
"s": 10216,
"text": "Dart"
},
{
"code": null,
"e": 10229,
"s": 10221,
"text": "MongoDB"
}
] |
java.net.URLConnection Class in Java
|
26 Aug, 2021
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL class. Secondly, with a URLConnection we can check the header sent by the server and respond accordingly, we can configure header fields used in client requests. We can also download binary files by using URLConnection.
Let us do discuss out major methods of this class
Implementation:
Example
Java
// Java Program to demonstrate URLConnection class // Importing input output classesimport java.io.*;// Importing java.net package// consisting of all network classesimport java.net.*; // Main class// URLConnectionExamplepublic class GFG { // Main driver method public static void main(String[] args) throws Exception { // Try block to check for exceptions try { // Creating an object of URL class // Custom input URL is passed as an argument URL u = new URL("www.geeksforgeeks.com"); // Creating an object of URLConnection class to // communicate between application and URL URLConnection urlconnect = u.openConnection(); // Creating an object of InputStream class // for our application streams to be read InputStream stream = urlconnect.getInputStream(); // Declaring an integer variable int i; // Till the time URL is being read while ((i = stream.read()) != -1) { // Continue printing the stream System.out.print((char)i); } } // Catch block to handle the exception catch (Exception e) { // Print the exception on the console System.out.println(e); } }}
java.net.MalformedURLException: no protocol: www.geeksforgeeks.com
anikaseth98
adnanirshad158
sooda367
Java-Classes
Java-net-package
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Aug, 2021"
},
{
"code": null,
"e": 596,
"s": 28,
"text": "URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL class. Secondly, with a URLConnection we can check the header sent by the server and respond accordingly, we can configure header fields used in client requests. We can also download binary files by using URLConnection."
},
{
"code": null,
"e": 646,
"s": 596,
"text": "Let us do discuss out major methods of this class"
},
{
"code": null,
"e": 662,
"s": 646,
"text": "Implementation:"
},
{
"code": null,
"e": 670,
"s": 662,
"text": "Example"
},
{
"code": null,
"e": 675,
"s": 670,
"text": "Java"
},
{
"code": "// Java Program to demonstrate URLConnection class // Importing input output classesimport java.io.*;// Importing java.net package// consisting of all network classesimport java.net.*; // Main class// URLConnectionExamplepublic class GFG { // Main driver method public static void main(String[] args) throws Exception { // Try block to check for exceptions try { // Creating an object of URL class // Custom input URL is passed as an argument URL u = new URL(\"www.geeksforgeeks.com\"); // Creating an object of URLConnection class to // communicate between application and URL URLConnection urlconnect = u.openConnection(); // Creating an object of InputStream class // for our application streams to be read InputStream stream = urlconnect.getInputStream(); // Declaring an integer variable int i; // Till the time URL is being read while ((i = stream.read()) != -1) { // Continue printing the stream System.out.print((char)i); } } // Catch block to handle the exception catch (Exception e) { // Print the exception on the console System.out.println(e); } }}",
"e": 2019,
"s": 675,
"text": null
},
{
"code": null,
"e": 2086,
"s": 2019,
"text": "java.net.MalformedURLException: no protocol: www.geeksforgeeks.com"
},
{
"code": null,
"e": 2100,
"s": 2088,
"text": "anikaseth98"
},
{
"code": null,
"e": 2115,
"s": 2100,
"text": "adnanirshad158"
},
{
"code": null,
"e": 2124,
"s": 2115,
"text": "sooda367"
},
{
"code": null,
"e": 2137,
"s": 2124,
"text": "Java-Classes"
},
{
"code": null,
"e": 2154,
"s": 2137,
"text": "Java-net-package"
},
{
"code": null,
"e": 2161,
"s": 2154,
"text": "Picked"
},
{
"code": null,
"e": 2166,
"s": 2161,
"text": "Java"
},
{
"code": null,
"e": 2171,
"s": 2166,
"text": "Java"
}
] |
Python | Decimal conjugate() method
|
05 Sep, 2019
Decimal#conjugate() : conjugate() is a Decimal class method which returns the self, this method is only to comply with the Decimal Specification
Syntax:
Decimal.conjugate()
Parameter:
Decimal values
Return:
the self Decimal value
Code #1 : Example for conjugate() method
# Python Program explaining # conjugate() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal(-1) b = Decimal('0.142857') # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b) # Using Decimal.conjugate() methodprint ("\n\nDecimal a with conjugate() method : ", a.conjugate()) print ("Decimal b with conjugate() method : ", b.conjugate())
Output :
Decimal value a : -1
Decimal value b : 0.142857
Decimal a with conjugate() method : -1
Decimal b with conjugate() method : 0.142857
Code #2 : Example for conjugate() method
# Python Program explaining # conjugate() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal('-3.14') b = Decimal('321e + 5') # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b) # Using Decimal.conjugate() methodprint ("\n\nDecimal a with conjugate() method : ", a.conjugate()) print ("Decimal b with conjugate() method : ", b.conjugate())
Output :
Decimal value a : -3.14
Decimal value b : 3.21E+7
Decimal a with conjugate() method : -3.14
Decimal b with conjugate() method : 3.21E+7
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python OOPs Concepts
Python Classes and Objects
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python - Pandas dataframe.append()
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Sep, 2019"
},
{
"code": null,
"e": 173,
"s": 28,
"text": "Decimal#conjugate() : conjugate() is a Decimal class method which returns the self, this method is only to comply with the Decimal Specification"
},
{
"code": null,
"e": 265,
"s": 173,
"text": "Syntax: \nDecimal.conjugate()\n\nParameter: \nDecimal values\n\nReturn: \nthe self Decimal value\n\n"
},
{
"code": null,
"e": 306,
"s": 265,
"text": "Code #1 : Example for conjugate() method"
},
{
"code": "# Python Program explaining # conjugate() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal(-1) b = Decimal('0.142857') # printing Decimal valuesprint (\"Decimal value a : \", a)print (\"Decimal value b : \", b) # Using Decimal.conjugate() methodprint (\"\\n\\nDecimal a with conjugate() method : \", a.conjugate()) print (\"Decimal b with conjugate() method : \", b.conjugate())",
"e": 732,
"s": 306,
"text": null
},
{
"code": null,
"e": 741,
"s": 732,
"text": "Output :"
},
{
"code": null,
"e": 881,
"s": 741,
"text": "Decimal value a : -1\nDecimal value b : 0.142857\n\n\nDecimal a with conjugate() method : -1\nDecimal b with conjugate() method : 0.142857\n\n"
},
{
"code": null,
"e": 922,
"s": 881,
"text": "Code #2 : Example for conjugate() method"
},
{
"code": "# Python Program explaining # conjugate() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal('-3.14') b = Decimal('321e + 5') # printing Decimal valuesprint (\"Decimal value a : \", a)print (\"Decimal value b : \", b) # Using Decimal.conjugate() methodprint (\"\\n\\nDecimal a with conjugate() method : \", a.conjugate()) print (\"Decimal b with conjugate() method : \", b.conjugate())",
"e": 1353,
"s": 922,
"text": null
},
{
"code": null,
"e": 1362,
"s": 1353,
"text": "Output :"
},
{
"code": null,
"e": 1505,
"s": 1362,
"text": "Decimal value a : -3.14\nDecimal value b : 3.21E+7\n\n\nDecimal a with conjugate() method : -3.14\nDecimal b with conjugate() method : 3.21E+7\n"
},
{
"code": null,
"e": 1512,
"s": 1505,
"text": "Python"
},
{
"code": null,
"e": 1610,
"s": 1512,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1642,
"s": 1610,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1663,
"s": 1642,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1690,
"s": 1663,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1713,
"s": 1690,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1744,
"s": 1713,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1800,
"s": 1744,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1842,
"s": 1800,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1884,
"s": 1842,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1919,
"s": 1884,
"text": "Python - Pandas dataframe.append()"
}
] |
ML | Spectral Clustering
|
19 Jul, 2019
Prerequisites: K-Means Clustering
Spectral Clustering is a growing clustering algorithm which has performed better than many traditional clustering algorithms in many cases. It treats each data point as a graph-node and thus transforms the clustering problem into a graph-partitioning problem. A typical implementation consists of three fundamental steps:-
Building the Similarity Graph: This step builds the Similarity Graph in the form of an adjacency matrix which is represented by A. The adjacency matrix can be built in the following manners:-Epsilon-neighbourhood Graph: A parameter epsilon is fixed beforehand. Then, each point is connected to all the points which lie in it’s epsilon-radius. If all the distances between any two points are similar in scale then typically the weights of the edges ie the distance between the two points are not stored since they do not provide any additional information. Thus, in this case, the graph built is an undirected and unweighted graph.K-Nearest Neighbours A parameter k is fixed beforehand. Then, for two vertices u and v, an edge is directed from u to v only if v is among the k-nearest neighbours of u. Note that this leads to the formation of a weighted and directed graph because it is not always the case that for each u having v as one of the k-nearest neighbours, it will be the same case for v having u among its k-nearest neighbours. To make this graph undirected, one of the following approaches are followed:-Direct an edge from u to v and from v to u if either v is among the k-nearest neighbours of u OR u is among the k-nearest neighbours of v.Direct an edge from u to v and from v to u if v is among the k-nearest neighbours of u AND u is among the k-nearest neighbours of v.Fully-Connected Graph: To build this graph, each point is connected with an undirected edge-weighted by the distance between the two points to every other point. Since this approach is used to model the local neighbourhood relationships thus typically the Gaussian similarity metric is used to calculate the distance.Projecting the data onto a lower Dimensional Space: This step is done to account for the possibility that members of the same cluster may be far away in the given dimensional space. Thus the dimensional space is reduced so that those points are closer in the reduced dimensional space and thus can be clustered together by a traditional clustering algorithm. It is done by computing the Graph Laplacian Matrix . To compute it though first, the degree of a node needs to be defined. The degree of the ith node is given byNote that is the edge between the nodes i and j as defined in the adjacency matrix above.The degree matrix is defined as follows:-Thus the Graph Laplacian Matrix is defined as:-This Matrix is then normalized for mathematical efficiency. To reduce the dimensions, first, the eigenvalues and the respective eigenvectors are calculated. If the number of clusters is k then the first eigenvalues and their eigen-vectors are taken and stacked into a matrix such that the eigen-vectors are the columns.Clustering the Data: This process mainly involves clustering the reduced data by using any traditional clustering technique – typically K-Means Clustering. First, each node is assigned a row of the normalized of the Graph Laplacian Matrix. Then this data is clustered using any traditional technique. To transform the clustering result, the node identifier is retained.Properties:Assumption-Less: This clustering technique, unlike other traditional techniques do not assume the data to follow some property. Thus this makes this technique to answer a more-generic class of clustering problems.Ease of implementation and Speed: This algorithm is easier to implement than other clustering algorithms and is also very fast as it mainly consists of mathematical computations.Not-Scalable: Since it involves the building of matrices and computation of eigenvalues and eigenvectors it is time-consuming for dense datasets.
Building the Similarity Graph: This step builds the Similarity Graph in the form of an adjacency matrix which is represented by A. The adjacency matrix can be built in the following manners:-Epsilon-neighbourhood Graph: A parameter epsilon is fixed beforehand. Then, each point is connected to all the points which lie in it’s epsilon-radius. If all the distances between any two points are similar in scale then typically the weights of the edges ie the distance between the two points are not stored since they do not provide any additional information. Thus, in this case, the graph built is an undirected and unweighted graph.K-Nearest Neighbours A parameter k is fixed beforehand. Then, for two vertices u and v, an edge is directed from u to v only if v is among the k-nearest neighbours of u. Note that this leads to the formation of a weighted and directed graph because it is not always the case that for each u having v as one of the k-nearest neighbours, it will be the same case for v having u among its k-nearest neighbours. To make this graph undirected, one of the following approaches are followed:-Direct an edge from u to v and from v to u if either v is among the k-nearest neighbours of u OR u is among the k-nearest neighbours of v.Direct an edge from u to v and from v to u if v is among the k-nearest neighbours of u AND u is among the k-nearest neighbours of v.Fully-Connected Graph: To build this graph, each point is connected with an undirected edge-weighted by the distance between the two points to every other point. Since this approach is used to model the local neighbourhood relationships thus typically the Gaussian similarity metric is used to calculate the distance.
Epsilon-neighbourhood Graph: A parameter epsilon is fixed beforehand. Then, each point is connected to all the points which lie in it’s epsilon-radius. If all the distances between any two points are similar in scale then typically the weights of the edges ie the distance between the two points are not stored since they do not provide any additional information. Thus, in this case, the graph built is an undirected and unweighted graph.
K-Nearest Neighbours A parameter k is fixed beforehand. Then, for two vertices u and v, an edge is directed from u to v only if v is among the k-nearest neighbours of u. Note that this leads to the formation of a weighted and directed graph because it is not always the case that for each u having v as one of the k-nearest neighbours, it will be the same case for v having u among its k-nearest neighbours. To make this graph undirected, one of the following approaches are followed:-Direct an edge from u to v and from v to u if either v is among the k-nearest neighbours of u OR u is among the k-nearest neighbours of v.Direct an edge from u to v and from v to u if v is among the k-nearest neighbours of u AND u is among the k-nearest neighbours of v.
Direct an edge from u to v and from v to u if either v is among the k-nearest neighbours of u OR u is among the k-nearest neighbours of v.Direct an edge from u to v and from v to u if v is among the k-nearest neighbours of u AND u is among the k-nearest neighbours of v.
Direct an edge from u to v and from v to u if either v is among the k-nearest neighbours of u OR u is among the k-nearest neighbours of v.
Direct an edge from u to v and from v to u if v is among the k-nearest neighbours of u AND u is among the k-nearest neighbours of v.
Fully-Connected Graph: To build this graph, each point is connected with an undirected edge-weighted by the distance between the two points to every other point. Since this approach is used to model the local neighbourhood relationships thus typically the Gaussian similarity metric is used to calculate the distance.
Projecting the data onto a lower Dimensional Space: This step is done to account for the possibility that members of the same cluster may be far away in the given dimensional space. Thus the dimensional space is reduced so that those points are closer in the reduced dimensional space and thus can be clustered together by a traditional clustering algorithm. It is done by computing the Graph Laplacian Matrix . To compute it though first, the degree of a node needs to be defined. The degree of the ith node is given byNote that is the edge between the nodes i and j as defined in the adjacency matrix above.The degree matrix is defined as follows:-Thus the Graph Laplacian Matrix is defined as:-This Matrix is then normalized for mathematical efficiency. To reduce the dimensions, first, the eigenvalues and the respective eigenvectors are calculated. If the number of clusters is k then the first eigenvalues and their eigen-vectors are taken and stacked into a matrix such that the eigen-vectors are the columns.
Note that is the edge between the nodes i and j as defined in the adjacency matrix above.
The degree matrix is defined as follows:-
Thus the Graph Laplacian Matrix is defined as:-
This Matrix is then normalized for mathematical efficiency. To reduce the dimensions, first, the eigenvalues and the respective eigenvectors are calculated. If the number of clusters is k then the first eigenvalues and their eigen-vectors are taken and stacked into a matrix such that the eigen-vectors are the columns.
Clustering the Data: This process mainly involves clustering the reduced data by using any traditional clustering technique – typically K-Means Clustering. First, each node is assigned a row of the normalized of the Graph Laplacian Matrix. Then this data is clustered using any traditional technique. To transform the clustering result, the node identifier is retained.Properties:Assumption-Less: This clustering technique, unlike other traditional techniques do not assume the data to follow some property. Thus this makes this technique to answer a more-generic class of clustering problems.Ease of implementation and Speed: This algorithm is easier to implement than other clustering algorithms and is also very fast as it mainly consists of mathematical computations.Not-Scalable: Since it involves the building of matrices and computation of eigenvalues and eigenvectors it is time-consuming for dense datasets.
Properties:
Assumption-Less: This clustering technique, unlike other traditional techniques do not assume the data to follow some property. Thus this makes this technique to answer a more-generic class of clustering problems.Ease of implementation and Speed: This algorithm is easier to implement than other clustering algorithms and is also very fast as it mainly consists of mathematical computations.Not-Scalable: Since it involves the building of matrices and computation of eigenvalues and eigenvectors it is time-consuming for dense datasets.
Assumption-Less: This clustering technique, unlike other traditional techniques do not assume the data to follow some property. Thus this makes this technique to answer a more-generic class of clustering problems.
Ease of implementation and Speed: This algorithm is easier to implement than other clustering algorithms and is also very fast as it mainly consists of mathematical computations.
Not-Scalable: Since it involves the building of matrices and computation of eigenvalues and eigenvectors it is time-consuming for dense datasets.
The below steps demonstrate how to implement Spectral Clustering using Sklearn. The data for the following steps is the Credit Card Data which can be downloaded from Kaggle.
Step 1: Importing the required libraries
import pandas as pdimport matplotlib.pyplot as pltfrom sklearn.cluster import SpectralClusteringfrom sklearn.preprocessing import StandardScaler, normalizefrom sklearn.decomposition import PCAfrom sklearn.metrics import silhouette_score
Step 2: Loading and Cleaning the Data
# Changing the working location to the location of the datacd "C:\Users\Dev\Desktop\Kaggle\Credit_Card" # Loading the dataX = pd.read_csv('CC_GENERAL.csv') # Dropping the CUST_ID column from the dataX = X.drop('CUST_ID', axis = 1) # Handling the missing values if anyX.fillna(method ='ffill', inplace = True) X.head()
Step 3: Preprocessing the data to make the data visualizable
# Preprocessing the data to make it visualizable # Scaling the Datascaler = StandardScaler()X_scaled = scaler.fit_transform(X) # Normalizing the DataX_normalized = normalize(X_scaled) # Converting the numpy array into a pandas DataFrameX_normalized = pd.DataFrame(X_normalized) # Reducing the dimensions of the datapca = PCA(n_components = 2)X_principal = pca.fit_transform(X_normalized)X_principal = pd.DataFrame(X_principal)X_principal.columns = ['P1', 'P2'] X_principal.head()
Step 4: Building the Clustering models and Visualizing the clustering
In the below steps, two different Spectral Clustering models with different values for the parameter ‘affinity’. You can read about the documentation of the Spectral Clustering class here.
a) affinity = ‘rbf’
# Building the clustering modelspectral_model_rbf = SpectralClustering(n_clusters = 2, affinity ='rbf') # Training the model and Storing the predicted cluster labelslabels_rbf = spectral_model_rbf.fit_predict(X_principal)
# Building the label to colour mappingcolours = {}colours[0] = 'b'colours[1] = 'y' # Building the colour vector for each data pointcvec = [colours[label] for label in labels_rbf] # Plotting the clustered scatter plot b = plt.scatter(X_principal['P1'], X_principal['P2'], color ='b');y = plt.scatter(X_principal['P1'], X_principal['P2'], color ='y'); plt.figure(figsize =(9, 9))plt.scatter(X_principal['P1'], X_principal['P2'], c = cvec)plt.legend((b, y), ('Label 0', 'Label 1'))plt.show()
b) affinity = ‘nearest_neighbors’
# Building the clustering modelspectral_model_nn = SpectralClustering(n_clusters = 2, affinity ='nearest_neighbors') # Training the model and Storing the predicted cluster labelslabels_nn = spectral_model_nn.fit_predict(X_principal)
Step 5: Evaluating the performances
# List of different values of affinityaffinity = ['rbf', 'nearest-neighbours'] # List of Silhouette Scoress_scores = [] # Evaluating the performances_scores.append(silhouette_score(X, labels_rbf))s_scores.append(silhouette_score(X, labels_nn)) print(s_scores)
Step 6: Comparing the performances
# Plotting a Bar Graph to compare the modelsplt.bar(affinity, s_scores)plt.xlabel('Affinity')plt.ylabel('Silhouette Score')plt.title('Comparison of different Clustering Models')plt.show()
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Jul, 2019"
},
{
"code": null,
"e": 86,
"s": 52,
"text": "Prerequisites: K-Means Clustering"
},
{
"code": null,
"e": 409,
"s": 86,
"text": "Spectral Clustering is a growing clustering algorithm which has performed better than many traditional clustering algorithms in many cases. It treats each data point as a graph-node and thus transforms the clustering problem into a graph-partitioning problem. A typical implementation consists of three fundamental steps:-"
},
{
"code": null,
"e": 4045,
"s": 409,
"text": "Building the Similarity Graph: This step builds the Similarity Graph in the form of an adjacency matrix which is represented by A. The adjacency matrix can be built in the following manners:-Epsilon-neighbourhood Graph: A parameter epsilon is fixed beforehand. Then, each point is connected to all the points which lie in it’s epsilon-radius. If all the distances between any two points are similar in scale then typically the weights of the edges ie the distance between the two points are not stored since they do not provide any additional information. Thus, in this case, the graph built is an undirected and unweighted graph.K-Nearest Neighbours A parameter k is fixed beforehand. Then, for two vertices u and v, an edge is directed from u to v only if v is among the k-nearest neighbours of u. Note that this leads to the formation of a weighted and directed graph because it is not always the case that for each u having v as one of the k-nearest neighbours, it will be the same case for v having u among its k-nearest neighbours. To make this graph undirected, one of the following approaches are followed:-Direct an edge from u to v and from v to u if either v is among the k-nearest neighbours of u OR u is among the k-nearest neighbours of v.Direct an edge from u to v and from v to u if v is among the k-nearest neighbours of u AND u is among the k-nearest neighbours of v.Fully-Connected Graph: To build this graph, each point is connected with an undirected edge-weighted by the distance between the two points to every other point. Since this approach is used to model the local neighbourhood relationships thus typically the Gaussian similarity metric is used to calculate the distance.Projecting the data onto a lower Dimensional Space: This step is done to account for the possibility that members of the same cluster may be far away in the given dimensional space. Thus the dimensional space is reduced so that those points are closer in the reduced dimensional space and thus can be clustered together by a traditional clustering algorithm. It is done by computing the Graph Laplacian Matrix . To compute it though first, the degree of a node needs to be defined. The degree of the ith node is given byNote that is the edge between the nodes i and j as defined in the adjacency matrix above.The degree matrix is defined as follows:-Thus the Graph Laplacian Matrix is defined as:-This Matrix is then normalized for mathematical efficiency. To reduce the dimensions, first, the eigenvalues and the respective eigenvectors are calculated. If the number of clusters is k then the first eigenvalues and their eigen-vectors are taken and stacked into a matrix such that the eigen-vectors are the columns.Clustering the Data: This process mainly involves clustering the reduced data by using any traditional clustering technique – typically K-Means Clustering. First, each node is assigned a row of the normalized of the Graph Laplacian Matrix. Then this data is clustered using any traditional technique. To transform the clustering result, the node identifier is retained.Properties:Assumption-Less: This clustering technique, unlike other traditional techniques do not assume the data to follow some property. Thus this makes this technique to answer a more-generic class of clustering problems.Ease of implementation and Speed: This algorithm is easier to implement than other clustering algorithms and is also very fast as it mainly consists of mathematical computations.Not-Scalable: Since it involves the building of matrices and computation of eigenvalues and eigenvectors it is time-consuming for dense datasets."
},
{
"code": null,
"e": 5748,
"s": 4045,
"text": "Building the Similarity Graph: This step builds the Similarity Graph in the form of an adjacency matrix which is represented by A. The adjacency matrix can be built in the following manners:-Epsilon-neighbourhood Graph: A parameter epsilon is fixed beforehand. Then, each point is connected to all the points which lie in it’s epsilon-radius. If all the distances between any two points are similar in scale then typically the weights of the edges ie the distance between the two points are not stored since they do not provide any additional information. Thus, in this case, the graph built is an undirected and unweighted graph.K-Nearest Neighbours A parameter k is fixed beforehand. Then, for two vertices u and v, an edge is directed from u to v only if v is among the k-nearest neighbours of u. Note that this leads to the formation of a weighted and directed graph because it is not always the case that for each u having v as one of the k-nearest neighbours, it will be the same case for v having u among its k-nearest neighbours. To make this graph undirected, one of the following approaches are followed:-Direct an edge from u to v and from v to u if either v is among the k-nearest neighbours of u OR u is among the k-nearest neighbours of v.Direct an edge from u to v and from v to u if v is among the k-nearest neighbours of u AND u is among the k-nearest neighbours of v.Fully-Connected Graph: To build this graph, each point is connected with an undirected edge-weighted by the distance between the two points to every other point. Since this approach is used to model the local neighbourhood relationships thus typically the Gaussian similarity metric is used to calculate the distance."
},
{
"code": null,
"e": 6188,
"s": 5748,
"text": "Epsilon-neighbourhood Graph: A parameter epsilon is fixed beforehand. Then, each point is connected to all the points which lie in it’s epsilon-radius. If all the distances between any two points are similar in scale then typically the weights of the edges ie the distance between the two points are not stored since they do not provide any additional information. Thus, in this case, the graph built is an undirected and unweighted graph."
},
{
"code": null,
"e": 6944,
"s": 6188,
"text": "K-Nearest Neighbours A parameter k is fixed beforehand. Then, for two vertices u and v, an edge is directed from u to v only if v is among the k-nearest neighbours of u. Note that this leads to the formation of a weighted and directed graph because it is not always the case that for each u having v as one of the k-nearest neighbours, it will be the same case for v having u among its k-nearest neighbours. To make this graph undirected, one of the following approaches are followed:-Direct an edge from u to v and from v to u if either v is among the k-nearest neighbours of u OR u is among the k-nearest neighbours of v.Direct an edge from u to v and from v to u if v is among the k-nearest neighbours of u AND u is among the k-nearest neighbours of v."
},
{
"code": null,
"e": 7215,
"s": 6944,
"text": "Direct an edge from u to v and from v to u if either v is among the k-nearest neighbours of u OR u is among the k-nearest neighbours of v.Direct an edge from u to v and from v to u if v is among the k-nearest neighbours of u AND u is among the k-nearest neighbours of v."
},
{
"code": null,
"e": 7354,
"s": 7215,
"text": "Direct an edge from u to v and from v to u if either v is among the k-nearest neighbours of u OR u is among the k-nearest neighbours of v."
},
{
"code": null,
"e": 7487,
"s": 7354,
"text": "Direct an edge from u to v and from v to u if v is among the k-nearest neighbours of u AND u is among the k-nearest neighbours of v."
},
{
"code": null,
"e": 7805,
"s": 7487,
"text": "Fully-Connected Graph: To build this graph, each point is connected with an undirected edge-weighted by the distance between the two points to every other point. Since this approach is used to model the local neighbourhood relationships thus typically the Gaussian similarity metric is used to calculate the distance."
},
{
"code": null,
"e": 8823,
"s": 7805,
"text": "Projecting the data onto a lower Dimensional Space: This step is done to account for the possibility that members of the same cluster may be far away in the given dimensional space. Thus the dimensional space is reduced so that those points are closer in the reduced dimensional space and thus can be clustered together by a traditional clustering algorithm. It is done by computing the Graph Laplacian Matrix . To compute it though first, the degree of a node needs to be defined. The degree of the ith node is given byNote that is the edge between the nodes i and j as defined in the adjacency matrix above.The degree matrix is defined as follows:-Thus the Graph Laplacian Matrix is defined as:-This Matrix is then normalized for mathematical efficiency. To reduce the dimensions, first, the eigenvalues and the respective eigenvectors are calculated. If the number of clusters is k then the first eigenvalues and their eigen-vectors are taken and stacked into a matrix such that the eigen-vectors are the columns."
},
{
"code": null,
"e": 8914,
"s": 8823,
"text": "Note that is the edge between the nodes i and j as defined in the adjacency matrix above."
},
{
"code": null,
"e": 8956,
"s": 8914,
"text": "The degree matrix is defined as follows:-"
},
{
"code": null,
"e": 9004,
"s": 8956,
"text": "Thus the Graph Laplacian Matrix is defined as:-"
},
{
"code": null,
"e": 9324,
"s": 9004,
"text": "This Matrix is then normalized for mathematical efficiency. To reduce the dimensions, first, the eigenvalues and the respective eigenvectors are calculated. If the number of clusters is k then the first eigenvalues and their eigen-vectors are taken and stacked into a matrix such that the eigen-vectors are the columns."
},
{
"code": null,
"e": 10241,
"s": 9324,
"text": "Clustering the Data: This process mainly involves clustering the reduced data by using any traditional clustering technique – typically K-Means Clustering. First, each node is assigned a row of the normalized of the Graph Laplacian Matrix. Then this data is clustered using any traditional technique. To transform the clustering result, the node identifier is retained.Properties:Assumption-Less: This clustering technique, unlike other traditional techniques do not assume the data to follow some property. Thus this makes this technique to answer a more-generic class of clustering problems.Ease of implementation and Speed: This algorithm is easier to implement than other clustering algorithms and is also very fast as it mainly consists of mathematical computations.Not-Scalable: Since it involves the building of matrices and computation of eigenvalues and eigenvectors it is time-consuming for dense datasets."
},
{
"code": null,
"e": 10253,
"s": 10241,
"text": "Properties:"
},
{
"code": null,
"e": 10790,
"s": 10253,
"text": "Assumption-Less: This clustering technique, unlike other traditional techniques do not assume the data to follow some property. Thus this makes this technique to answer a more-generic class of clustering problems.Ease of implementation and Speed: This algorithm is easier to implement than other clustering algorithms and is also very fast as it mainly consists of mathematical computations.Not-Scalable: Since it involves the building of matrices and computation of eigenvalues and eigenvectors it is time-consuming for dense datasets."
},
{
"code": null,
"e": 11004,
"s": 10790,
"text": "Assumption-Less: This clustering technique, unlike other traditional techniques do not assume the data to follow some property. Thus this makes this technique to answer a more-generic class of clustering problems."
},
{
"code": null,
"e": 11183,
"s": 11004,
"text": "Ease of implementation and Speed: This algorithm is easier to implement than other clustering algorithms and is also very fast as it mainly consists of mathematical computations."
},
{
"code": null,
"e": 11329,
"s": 11183,
"text": "Not-Scalable: Since it involves the building of matrices and computation of eigenvalues and eigenvectors it is time-consuming for dense datasets."
},
{
"code": null,
"e": 11503,
"s": 11329,
"text": "The below steps demonstrate how to implement Spectral Clustering using Sklearn. The data for the following steps is the Credit Card Data which can be downloaded from Kaggle."
},
{
"code": null,
"e": 11544,
"s": 11503,
"text": "Step 1: Importing the required libraries"
},
{
"code": "import pandas as pdimport matplotlib.pyplot as pltfrom sklearn.cluster import SpectralClusteringfrom sklearn.preprocessing import StandardScaler, normalizefrom sklearn.decomposition import PCAfrom sklearn.metrics import silhouette_score",
"e": 11781,
"s": 11544,
"text": null
},
{
"code": null,
"e": 11819,
"s": 11781,
"text": "Step 2: Loading and Cleaning the Data"
},
{
"code": "# Changing the working location to the location of the datacd \"C:\\Users\\Dev\\Desktop\\Kaggle\\Credit_Card\" # Loading the dataX = pd.read_csv('CC_GENERAL.csv') # Dropping the CUST_ID column from the dataX = X.drop('CUST_ID', axis = 1) # Handling the missing values if anyX.fillna(method ='ffill', inplace = True) X.head()",
"e": 12141,
"s": 11819,
"text": null
},
{
"code": null,
"e": 12202,
"s": 12141,
"text": "Step 3: Preprocessing the data to make the data visualizable"
},
{
"code": "# Preprocessing the data to make it visualizable # Scaling the Datascaler = StandardScaler()X_scaled = scaler.fit_transform(X) # Normalizing the DataX_normalized = normalize(X_scaled) # Converting the numpy array into a pandas DataFrameX_normalized = pd.DataFrame(X_normalized) # Reducing the dimensions of the datapca = PCA(n_components = 2)X_principal = pca.fit_transform(X_normalized)X_principal = pd.DataFrame(X_principal)X_principal.columns = ['P1', 'P2'] X_principal.head()",
"e": 12687,
"s": 12202,
"text": null
},
{
"code": null,
"e": 12757,
"s": 12687,
"text": "Step 4: Building the Clustering models and Visualizing the clustering"
},
{
"code": null,
"e": 12946,
"s": 12757,
"text": "In the below steps, two different Spectral Clustering models with different values for the parameter ‘affinity’. You can read about the documentation of the Spectral Clustering class here."
},
{
"code": null,
"e": 12966,
"s": 12946,
"text": "a) affinity = ‘rbf’"
},
{
"code": "# Building the clustering modelspectral_model_rbf = SpectralClustering(n_clusters = 2, affinity ='rbf') # Training the model and Storing the predicted cluster labelslabels_rbf = spectral_model_rbf.fit_predict(X_principal)",
"e": 13189,
"s": 12966,
"text": null
},
{
"code": "# Building the label to colour mappingcolours = {}colours[0] = 'b'colours[1] = 'y' # Building the colour vector for each data pointcvec = [colours[label] for label in labels_rbf] # Plotting the clustered scatter plot b = plt.scatter(X_principal['P1'], X_principal['P2'], color ='b');y = plt.scatter(X_principal['P1'], X_principal['P2'], color ='y'); plt.figure(figsize =(9, 9))plt.scatter(X_principal['P1'], X_principal['P2'], c = cvec)plt.legend((b, y), ('Label 0', 'Label 1'))plt.show()",
"e": 13682,
"s": 13189,
"text": null
},
{
"code": null,
"e": 13716,
"s": 13682,
"text": "b) affinity = ‘nearest_neighbors’"
},
{
"code": "# Building the clustering modelspectral_model_nn = SpectralClustering(n_clusters = 2, affinity ='nearest_neighbors') # Training the model and Storing the predicted cluster labelslabels_nn = spectral_model_nn.fit_predict(X_principal)",
"e": 13950,
"s": 13716,
"text": null
},
{
"code": null,
"e": 13986,
"s": 13950,
"text": "Step 5: Evaluating the performances"
},
{
"code": "# List of different values of affinityaffinity = ['rbf', 'nearest-neighbours'] # List of Silhouette Scoress_scores = [] # Evaluating the performances_scores.append(silhouette_score(X, labels_rbf))s_scores.append(silhouette_score(X, labels_nn)) print(s_scores)",
"e": 14249,
"s": 13986,
"text": null
},
{
"code": null,
"e": 14284,
"s": 14249,
"text": "Step 6: Comparing the performances"
},
{
"code": "# Plotting a Bar Graph to compare the modelsplt.bar(affinity, s_scores)plt.xlabel('Affinity')plt.ylabel('Silhouette Score')plt.title('Comparison of different Clustering Models')plt.show()",
"e": 14472,
"s": 14284,
"text": null
},
{
"code": null,
"e": 14489,
"s": 14472,
"text": "Machine Learning"
},
{
"code": null,
"e": 14496,
"s": 14489,
"text": "Python"
},
{
"code": null,
"e": 14513,
"s": 14496,
"text": "Machine Learning"
}
] |
PyQt5 – Change size of Push Button
|
22 Apr, 2020
In this article we will see how to change the size of push button. There are basically two ways in order to change the size of button i.e using resize method and setGeometry method.The main difference between them is resize method will only resize the push button. on the other hand setGeometry method will change the size and also set the position of the push button.
Method #1:
Syntax : button.setGeometry(left, top, width, height)
Argument : It takes four integer as argument, first two are the position and second two are the size.
Action performed : It sets the position and the size of push button.
Code :
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a push button button = QPushButton("CLICK", self) # setting geometry of button button.setGeometry(200, 150, 100, 40) # adding action to a button button.clicked.connect(self.clickme) # action method def clickme(self): # printing pressed print("pressed") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Method #2:
Syntax : button.resize(width, height)
Argument : It takes two integer as argument i.e width and height.
Action performed : It sets the size of push button
Code :
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a push button button = QPushButton("CLICK", self) # setting size of button button.resize(150, 50) # adding action to a button button.clicked.connect(self.clickme) # action method def clickme(self): # printing pressed print("pressed") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Introduction To PYTHON
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 397,
"s": 28,
"text": "In this article we will see how to change the size of push button. There are basically two ways in order to change the size of button i.e using resize method and setGeometry method.The main difference between them is resize method will only resize the push button. on the other hand setGeometry method will change the size and also set the position of the push button."
},
{
"code": null,
"e": 408,
"s": 397,
"text": "Method #1:"
},
{
"code": null,
"e": 462,
"s": 408,
"text": "Syntax : button.setGeometry(left, top, width, height)"
},
{
"code": null,
"e": 564,
"s": 462,
"text": "Argument : It takes four integer as argument, first two are the position and second two are the size."
},
{
"code": null,
"e": 633,
"s": 564,
"text": "Action performed : It sets the position and the size of push button."
},
{
"code": null,
"e": 640,
"s": 633,
"text": "Code :"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a push button button = QPushButton(\"CLICK\", self) # setting geometry of button button.setGeometry(200, 150, 100, 40) # adding action to a button button.clicked.connect(self.clickme) # action method def clickme(self): # printing pressed print(\"pressed\") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 1608,
"s": 640,
"text": null
},
{
"code": null,
"e": 1618,
"s": 1608,
"text": "Output : "
},
{
"code": null,
"e": 1629,
"s": 1618,
"text": "Method #2:"
},
{
"code": null,
"e": 1667,
"s": 1629,
"text": "Syntax : button.resize(width, height)"
},
{
"code": null,
"e": 1733,
"s": 1667,
"text": "Argument : It takes two integer as argument i.e width and height."
},
{
"code": null,
"e": 1784,
"s": 1733,
"text": "Action performed : It sets the size of push button"
},
{
"code": null,
"e": 1791,
"s": 1784,
"text": "Code :"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a push button button = QPushButton(\"CLICK\", self) # setting size of button button.resize(150, 50) # adding action to a button button.clicked.connect(self.clickme) # action method def clickme(self): # printing pressed print(\"pressed\") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 2740,
"s": 1791,
"text": null
},
{
"code": null,
"e": 2749,
"s": 2740,
"text": "Output :"
},
{
"code": null,
"e": 2760,
"s": 2749,
"text": "Python-gui"
},
{
"code": null,
"e": 2772,
"s": 2760,
"text": "Python-PyQt"
},
{
"code": null,
"e": 2779,
"s": 2772,
"text": "Python"
},
{
"code": null,
"e": 2877,
"s": 2779,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2895,
"s": 2877,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2937,
"s": 2895,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2959,
"s": 2937,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2994,
"s": 2959,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3020,
"s": 2994,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3052,
"s": 3020,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3081,
"s": 3052,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3108,
"s": 3081,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3138,
"s": 3108,
"text": "Iterate over a list in Python"
}
] |
Deque in Python
|
09 May, 2022
Deque (Doubly Ended Queue) in Python is implemented using the module “collections“. Deque is preferred over a list in the cases where we need quicker append and pop operations from both the ends of the container, as deque provides an O(1) time complexity for append and pop operations as compared to list which provides O(n) time complexity.
Example:
Python3
# Python code to demonstrate deque from collections import deque # Declaring deque queue = deque(['name','age','DOB']) print(queue)
Output:
deque(['name', 'age', 'DOB'])
Let’s see various Operations on deque :
append():- This function is used to insert the value in its argument to the right end of the deque.
appendleft():- This function is used to insert the value in its argument to the left end of the deque.
pop():- This function is used to delete an argument from the right end of the deque.
popleft():- This function is used to delete an argument from the left end of the deque.
Python3
# Python code to demonstrate working of # append(), appendleft(), pop(), and popleft() # importing "collections" for deque operationsimport collections # initializing dequede = collections.deque([1,2,3]) # using append() to insert element at right end # inserts 4 at the end of dequede.append(4) # printing modified dequeprint ("The deque after appending at right is : ")print (de) # using appendleft() to insert element at left end # inserts 6 at the beginning of dequede.appendleft(6) # printing modified dequeprint ("The deque after appending at left is : ")print (de) # using pop() to delete element from right end # deletes 4 from the right end of dequede.pop() # printing modified dequeprint ("The deque after deleting from right is : ")print (de) # using popleft() to delete element from left end # deletes 6 from the left end of dequede.popleft() # printing modified dequeprint ("The deque after deleting from left is : ")print (de)
Output:
The deque after appending at right is :
deque([1, 2, 3, 4])
The deque after appending at left is :
deque([6, 1, 2, 3, 4])
The deque after deleting from right is :
deque([6, 1, 2, 3])
The deque after deleting from left is :
deque([1, 2, 3])
index(ele, beg, end):- This function returns the first index of the value mentioned in arguments, starting searching from beg till end index.
insert(i, a) :- This function inserts the value mentioned in arguments(a) at index(i) specified in arguments.
remove():- This function removes the first occurrence of value mentioned in arguments.
count():- This function counts the number of occurrences of value mentioned in arguments.
Python3
# Python code to demonstrate working of # insert(), index(), remove(), count() # importing "collections" for deque operationsimport collections # initializing dequede = collections.deque([1, 2, 3, 3, 4, 2, 4]) # using index() to print the first occurrence of 4print ("The number 4 first occurs at a position : ")print (de.index(4,2,5)) # using insert() to insert the value 3 at 5th positionde.insert(4,3) # printing modified dequeprint ("The deque after inserting 3 at 5th position is : ")print (de) # using count() to count the occurrences of 3print ("The count of 3 in deque is : ")print (de.count(3)) # using remove() to remove the first occurrence of 3de.remove(3) # printing modified dequeprint ("The deque after deleting first occurrence of 3 is : ")print (de)
Output:
The number 4 first occurs at a position :
4
The deque after inserting 3 at 5th position is :
deque([1, 2, 3, 3, 3, 4, 2, 4])
The count of 3 in deque is :
3
The deque after deleting first occurrence of 3 is :
deque([1, 2, 3, 3, 4, 2, 4])
extend(iterable):- This function is used to add multiple values at the right end of the deque. The argument passed is iterable.
extendleft(iterable):- This function is used to add multiple values at the left end of the deque. The argument passed is iterable. Order is reversed as a result of left appends.
reverse():- This function is used to reverse the order of deque elements.
rotate():- This function rotates the deque by the number specified in arguments. If the number specified is negative, rotation occurs to the left. Else rotation is to right.
Python3
# Python code to demonstrate working of # extend(), extendleft(), rotate(), reverse() # importing "collections" for deque operationsimport collections # initializing dequede = collections.deque([1, 2, 3,]) # using extend() to add numbers to right end # adds 4,5,6 to right endde.extend([4,5,6]) # printing modified dequeprint ("The deque after extending deque at end is : ")print (de) # using extendleft() to add numbers to left end # adds 7,8,9 to left endde.extendleft([7,8,9]) # printing modified dequeprint ("The deque after extending deque at beginning is : ")print (de) # using rotate() to rotate the deque# rotates by 3 to leftde.rotate(-3) # printing modified dequeprint ("The deque after rotating deque is : ")print (de) # using reverse() to reverse the dequede.reverse() # printing modified dequeprint ("The deque after reversing deque is : ")print (de)
Output :
The deque after extending deque at end is :
deque([1, 2, 3, 4, 5, 6])
The deque after extending deque at beginning is :
deque([9, 8, 7, 1, 2, 3, 4, 5, 6])
The deque after rotating deque is :
deque([1, 2, 3, 4, 5, 6, 9, 8, 7])
The deque after reversing deque is :
deque([7, 8, 9, 6, 5, 4, 3, 2, 1])
Python Programming Tutorial | Deque in Python | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPython Programming Tutorial | Deque in Python | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:58•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=P6nskYVnQOE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Manjeet Singh. 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.
eddywade
punamsingh628700
hariaditya
deque
Python collections-module
Python-Data-Structures
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
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 ?
Iterate over a list in Python
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 May, 2022"
},
{
"code": null,
"e": 394,
"s": 52,
"text": "Deque (Doubly Ended Queue) in Python is implemented using the module “collections“. Deque is preferred over a list in the cases where we need quicker append and pop operations from both the ends of the container, as deque provides an O(1) time complexity for append and pop operations as compared to list which provides O(n) time complexity."
},
{
"code": null,
"e": 403,
"s": 394,
"text": "Example:"
},
{
"code": null,
"e": 411,
"s": 403,
"text": "Python3"
},
{
"code": "# Python code to demonstrate deque from collections import deque # Declaring deque queue = deque(['name','age','DOB']) print(queue)",
"e": 566,
"s": 411,
"text": null
},
{
"code": null,
"e": 575,
"s": 566,
"text": "Output: "
},
{
"code": null,
"e": 605,
"s": 575,
"text": "deque(['name', 'age', 'DOB'])"
},
{
"code": null,
"e": 646,
"s": 605,
"text": "Let’s see various Operations on deque : "
},
{
"code": null,
"e": 746,
"s": 646,
"text": "append():- This function is used to insert the value in its argument to the right end of the deque."
},
{
"code": null,
"e": 849,
"s": 746,
"text": "appendleft():- This function is used to insert the value in its argument to the left end of the deque."
},
{
"code": null,
"e": 934,
"s": 849,
"text": "pop():- This function is used to delete an argument from the right end of the deque."
},
{
"code": null,
"e": 1022,
"s": 934,
"text": "popleft():- This function is used to delete an argument from the left end of the deque."
},
{
"code": null,
"e": 1030,
"s": 1022,
"text": "Python3"
},
{
"code": "# Python code to demonstrate working of # append(), appendleft(), pop(), and popleft() # importing \"collections\" for deque operationsimport collections # initializing dequede = collections.deque([1,2,3]) # using append() to insert element at right end # inserts 4 at the end of dequede.append(4) # printing modified dequeprint (\"The deque after appending at right is : \")print (de) # using appendleft() to insert element at left end # inserts 6 at the beginning of dequede.appendleft(6) # printing modified dequeprint (\"The deque after appending at left is : \")print (de) # using pop() to delete element from right end # deletes 4 from the right end of dequede.pop() # printing modified dequeprint (\"The deque after deleting from right is : \")print (de) # using popleft() to delete element from left end # deletes 6 from the left end of dequede.popleft() # printing modified dequeprint (\"The deque after deleting from left is : \")print (de)",
"e": 1981,
"s": 1030,
"text": null
},
{
"code": null,
"e": 1990,
"s": 1981,
"text": "Output: "
},
{
"code": null,
"e": 2234,
"s": 1990,
"text": "The deque after appending at right is : \ndeque([1, 2, 3, 4])\nThe deque after appending at left is : \ndeque([6, 1, 2, 3, 4])\nThe deque after deleting from right is : \ndeque([6, 1, 2, 3])\nThe deque after deleting from left is : \ndeque([1, 2, 3])"
},
{
"code": null,
"e": 2376,
"s": 2234,
"text": "index(ele, beg, end):- This function returns the first index of the value mentioned in arguments, starting searching from beg till end index."
},
{
"code": null,
"e": 2486,
"s": 2376,
"text": "insert(i, a) :- This function inserts the value mentioned in arguments(a) at index(i) specified in arguments."
},
{
"code": null,
"e": 2573,
"s": 2486,
"text": "remove():- This function removes the first occurrence of value mentioned in arguments."
},
{
"code": null,
"e": 2663,
"s": 2573,
"text": "count():- This function counts the number of occurrences of value mentioned in arguments."
},
{
"code": null,
"e": 2671,
"s": 2663,
"text": "Python3"
},
{
"code": "# Python code to demonstrate working of # insert(), index(), remove(), count() # importing \"collections\" for deque operationsimport collections # initializing dequede = collections.deque([1, 2, 3, 3, 4, 2, 4]) # using index() to print the first occurrence of 4print (\"The number 4 first occurs at a position : \")print (de.index(4,2,5)) # using insert() to insert the value 3 at 5th positionde.insert(4,3) # printing modified dequeprint (\"The deque after inserting 3 at 5th position is : \")print (de) # using count() to count the occurrences of 3print (\"The count of 3 in deque is : \")print (de.count(3)) # using remove() to remove the first occurrence of 3de.remove(3) # printing modified dequeprint (\"The deque after deleting first occurrence of 3 is : \")print (de)",
"e": 3446,
"s": 2671,
"text": null
},
{
"code": null,
"e": 3456,
"s": 3446,
"text": "Output: "
},
{
"code": null,
"e": 3697,
"s": 3456,
"text": "The number 4 first occurs at a position : \n4\nThe deque after inserting 3 at 5th position is : \ndeque([1, 2, 3, 3, 3, 4, 2, 4])\nThe count of 3 in deque is : \n3\nThe deque after deleting first occurrence of 3 is : \ndeque([1, 2, 3, 3, 4, 2, 4])"
},
{
"code": null,
"e": 3825,
"s": 3697,
"text": "extend(iterable):- This function is used to add multiple values at the right end of the deque. The argument passed is iterable."
},
{
"code": null,
"e": 4003,
"s": 3825,
"text": "extendleft(iterable):- This function is used to add multiple values at the left end of the deque. The argument passed is iterable. Order is reversed as a result of left appends."
},
{
"code": null,
"e": 4077,
"s": 4003,
"text": "reverse():- This function is used to reverse the order of deque elements."
},
{
"code": null,
"e": 4251,
"s": 4077,
"text": "rotate():- This function rotates the deque by the number specified in arguments. If the number specified is negative, rotation occurs to the left. Else rotation is to right."
},
{
"code": null,
"e": 4259,
"s": 4251,
"text": "Python3"
},
{
"code": "# Python code to demonstrate working of # extend(), extendleft(), rotate(), reverse() # importing \"collections\" for deque operationsimport collections # initializing dequede = collections.deque([1, 2, 3,]) # using extend() to add numbers to right end # adds 4,5,6 to right endde.extend([4,5,6]) # printing modified dequeprint (\"The deque after extending deque at end is : \")print (de) # using extendleft() to add numbers to left end # adds 7,8,9 to left endde.extendleft([7,8,9]) # printing modified dequeprint (\"The deque after extending deque at beginning is : \")print (de) # using rotate() to rotate the deque# rotates by 3 to leftde.rotate(-3) # printing modified dequeprint (\"The deque after rotating deque is : \")print (de) # using reverse() to reverse the dequede.reverse() # printing modified dequeprint (\"The deque after reversing deque is : \")print (de)",
"e": 5133,
"s": 4259,
"text": null
},
{
"code": null,
"e": 5143,
"s": 5133,
"text": "Output : "
},
{
"code": null,
"e": 5446,
"s": 5143,
"text": "The deque after extending deque at end is : \ndeque([1, 2, 3, 4, 5, 6])\nThe deque after extending deque at beginning is : \ndeque([9, 8, 7, 1, 2, 3, 4, 5, 6])\nThe deque after rotating deque is : \ndeque([1, 2, 3, 4, 5, 6, 9, 8, 7])\nThe deque after reversing deque is : \ndeque([7, 8, 9, 6, 5, 4, 3, 2, 1]) "
},
{
"code": null,
"e": 6354,
"s": 5446,
"text": "Python Programming Tutorial | Deque in Python | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPython Programming Tutorial | Deque in Python | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:58•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=P6nskYVnQOE\" 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": 6775,
"s": 6354,
"text": "This article is contributed by Manjeet Singh. 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": 6784,
"s": 6775,
"text": "eddywade"
},
{
"code": null,
"e": 6801,
"s": 6784,
"text": "punamsingh628700"
},
{
"code": null,
"e": 6812,
"s": 6801,
"text": "hariaditya"
},
{
"code": null,
"e": 6818,
"s": 6812,
"text": "deque"
},
{
"code": null,
"e": 6844,
"s": 6818,
"text": "Python collections-module"
},
{
"code": null,
"e": 6867,
"s": 6844,
"text": "Python-Data-Structures"
},
{
"code": null,
"e": 6874,
"s": 6867,
"text": "Python"
},
{
"code": null,
"e": 6972,
"s": 6874,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7000,
"s": 6972,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 7050,
"s": 7000,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 7072,
"s": 7050,
"text": "Python map() function"
},
{
"code": null,
"e": 7116,
"s": 7072,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 7158,
"s": 7116,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 7180,
"s": 7158,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 7215,
"s": 7180,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 7241,
"s": 7215,
"text": "Python String | replace()"
},
{
"code": null,
"e": 7273,
"s": 7241,
"text": "How to Install PIP on Windows ?"
}
] |
std::advance in C++
|
26 Apr, 2022
std::advance advances the iterator ‘it’ by n element positions. Syntax :
template
void advance (InputIterator& it, Distance n);
it : Iterator to be advanced
n : Number of element positions to advance.
This shall only be negative for random-access and bidirectional iterators.
Return type :
None.
Motivation problem : A vector container is given. Task is to print alternate elements. Examples :
Input : 10 40 20 50 80 70
Output : 10 20 80
CPP
// C++ program to illustrate// using std::advance#include <bits/stdc++.h> // Driver codeint main(){ // Vector container std::vector<int> vec; // Initialising vector for (int i = 0; i < 10; i++) vec.push_back(i * 10); // Printing the vector elements for (int i = 0; i < 10; i++) { std::cout << vec[i] << " "; } std::cout << std::endl; // Declaring the vector iterator std::vector<int>::iterator it = vec.begin(); // Printing alternate elements while (it < vec.end()) { std::cout << *it << " "; std::advance(it, 2); }}
Output:
0 10 20 30 40 50 60 70 80 90
0 20 40 60 80
C++
#include <iostream>#include<bits/stdc++.h>using namespace std; int main() { vector<int >vect(10); //insert the ten element in the vector for(int i=1;i<=10;i++) { vect[i-1]=i; } //iterator pointing to first element. vector<int >::iterator it=vect.begin(); for(int i=1;i<=10;i++) { cout<<*it<<" "; it++; } vector<int >::iterator it1=vect.begin(); //here it is pointing to the 3rd element. advance(it1,2);//here second argument is the index base. cout<<endl; cout<<*it1; //print it1 pointing to the 3rd position. return 0;}/* This code is contributed by Sameer Hake/*
1 2 3 4 5 6 7 8 9 10
3
This article is contributed by Rohit Thapliyal , Sameer Hake. 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.
sameerhakeentc2019
cpp-iterator
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
std::find in C++
List in C++ Standard Template Library (STL)
Inline Functions in C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Apr, 2022"
},
{
"code": null,
"e": 125,
"s": 52,
"text": "std::advance advances the iterator ‘it’ by n element positions. Syntax :"
},
{
"code": null,
"e": 355,
"s": 125,
"text": "template \n void advance (InputIterator& it, Distance n);\n\nit : Iterator to be advanced\nn : Number of element positions to advance.\nThis shall only be negative for random-access and bidirectional iterators.\n\nReturn type :\nNone."
},
{
"code": null,
"e": 453,
"s": 355,
"text": "Motivation problem : A vector container is given. Task is to print alternate elements. Examples :"
},
{
"code": null,
"e": 497,
"s": 453,
"text": "Input : 10 40 20 50 80 70\nOutput : 10 20 80"
},
{
"code": null,
"e": 501,
"s": 497,
"text": "CPP"
},
{
"code": "// C++ program to illustrate// using std::advance#include <bits/stdc++.h> // Driver codeint main(){ // Vector container std::vector<int> vec; // Initialising vector for (int i = 0; i < 10; i++) vec.push_back(i * 10); // Printing the vector elements for (int i = 0; i < 10; i++) { std::cout << vec[i] << \" \"; } std::cout << std::endl; // Declaring the vector iterator std::vector<int>::iterator it = vec.begin(); // Printing alternate elements while (it < vec.end()) { std::cout << *it << \" \"; std::advance(it, 2); }}",
"e": 1090,
"s": 501,
"text": null
},
{
"code": null,
"e": 1098,
"s": 1090,
"text": "Output:"
},
{
"code": null,
"e": 1142,
"s": 1098,
"text": "0 10 20 30 40 50 60 70 80 90 \n0 20 40 60 80"
},
{
"code": null,
"e": 1146,
"s": 1142,
"text": "C++"
},
{
"code": "#include <iostream>#include<bits/stdc++.h>using namespace std; int main() { vector<int >vect(10); //insert the ten element in the vector for(int i=1;i<=10;i++) { vect[i-1]=i; } //iterator pointing to first element. vector<int >::iterator it=vect.begin(); for(int i=1;i<=10;i++) { cout<<*it<<\" \"; it++; } vector<int >::iterator it1=vect.begin(); //here it is pointing to the 3rd element. advance(it1,2);//here second argument is the index base. cout<<endl; cout<<*it1; //print it1 pointing to the 3rd position. return 0;}/* This code is contributed by Sameer Hake/*",
"e": 1793,
"s": 1146,
"text": null
},
{
"code": null,
"e": 1817,
"s": 1793,
"text": "1 2 3 4 5 6 7 8 9 10 \n3"
},
{
"code": null,
"e": 2255,
"s": 1817,
"text": "This article is contributed by Rohit Thapliyal , Sameer Hake. 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": 2274,
"s": 2255,
"text": "sameerhakeentc2019"
},
{
"code": null,
"e": 2287,
"s": 2274,
"text": "cpp-iterator"
},
{
"code": null,
"e": 2291,
"s": 2287,
"text": "STL"
},
{
"code": null,
"e": 2295,
"s": 2291,
"text": "C++"
},
{
"code": null,
"e": 2299,
"s": 2295,
"text": "STL"
},
{
"code": null,
"e": 2303,
"s": 2299,
"text": "CPP"
},
{
"code": null,
"e": 2401,
"s": 2303,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2425,
"s": 2401,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 2445,
"s": 2425,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 2478,
"s": 2445,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 2522,
"s": 2478,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2547,
"s": 2522,
"text": "std::string class in C++"
},
{
"code": null,
"e": 2592,
"s": 2547,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2640,
"s": 2592,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 2657,
"s": 2640,
"text": "std::find in C++"
},
{
"code": null,
"e": 2701,
"s": 2657,
"text": "List in C++ Standard Template Library (STL)"
}
] |
req.cookies and req.signedCookies in Express.js
|
26 Nov, 2021
req.cookies: Request.Cookies are supposed to be cookies that come from client (browser) and Response.Cookies are cookies that will send back to client (browser). Cookies are small files/data that are sent to the client with a server request and stored on the client side. This helps us to keep track of the user’s actions.
Cookie-parser is a middleware that parses cookies attached to the client request object. When we use cookie-parser middleware then this property is an object that contains cookies sent by the request. If the request contains no cookies, it defaults to { }.
Example:
Javascript
var cookieParser = require('cookie-parser');var express = require('express');var app = express();var PORT = 3000; app.use(cookieParser()); app.get('/user', function (req, res) { req.cookies.name='Gourav'; req.cookies.age=12; console.log(req.cookies); res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Output: Now open your browser and make GET request to http://localhost:3000/user, now you can see the following output on your console:
Server listening on PORT 3000
[Object: null prototype] { name: 'Gourav', age: 12 }
req.signedCookies: The req.signedCookies property contains signed cookies sent by the request, unsigned, and ready for use when using cookie-parser middleware. Signing a cookie does not make it hidden or encrypted but simply prevents tampering with the cookie. It works by creating a HMAC of the value (current cookie), and base64 encoded it. When the cookie gets read, it recalculates the signature and makes sure that it matches the signature attached to it.If it does not match, then it gives an error. If no signed cookies are sent then the property defaults to { }.
Example:
Javascript
var cookieParser = require('cookie-parser');var express = require('express');var app = express();var PORT = 3000; app.use(cookieParser()); app.get('/user', function (req, res) { // Setting multiple cookies req.signedCookies.title='Gourav'; req.signedCookies.age=12; console.log(req.signedCookies); res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Output: Now open your browser and make GET request to http://localhost:3000/user, now you can see the following output on your console:
Server listening on PORT 3000
[Object: null prototype] { title: 'Gourav', age: 12 }
Difference between req.cookies and req.signedCookies –
minhazrabbi93041
Express.js
Node.js-Misc
Technical Scripter 2020
Difference Between
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference Between Method Overloading and Method Overriding in Java
Difference between var, let and const keywords in JavaScript
Difference between Compile-time and Run-time Polymorphism in Java
Differences and Applications of List, Tuple, Set and Dictionary in Python
Similarities and Difference between Java and C++
How to update Node.js and NPM to next version ?
Installation of Node.js on Linux
Node.js fs.readFileSync() Method
How to use an ES6 import in Node.js?
Difference between promise and async await in Node.js
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n26 Nov, 2021"
},
{
"code": null,
"e": 377,
"s": 54,
"text": "req.cookies: Request.Cookies are supposed to be cookies that come from client (browser) and Response.Cookies are cookies that will send back to client (browser). Cookies are small files/data that are sent to the client with a server request and stored on the client side. This helps us to keep track of the user’s actions."
},
{
"code": null,
"e": 634,
"s": 377,
"text": "Cookie-parser is a middleware that parses cookies attached to the client request object. When we use cookie-parser middleware then this property is an object that contains cookies sent by the request. If the request contains no cookies, it defaults to { }."
},
{
"code": null,
"e": 643,
"s": 634,
"text": "Example:"
},
{
"code": null,
"e": 654,
"s": 643,
"text": "Javascript"
},
{
"code": "var cookieParser = require('cookie-parser');var express = require('express');var app = express();var PORT = 3000; app.use(cookieParser()); app.get('/user', function (req, res) { req.cookies.name='Gourav'; req.cookies.age=12; console.log(req.cookies); res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});",
"e": 1048,
"s": 654,
"text": null
},
{
"code": null,
"e": 1184,
"s": 1048,
"text": "Output: Now open your browser and make GET request to http://localhost:3000/user, now you can see the following output on your console:"
},
{
"code": null,
"e": 1267,
"s": 1184,
"text": "Server listening on PORT 3000\n[Object: null prototype] { name: 'Gourav', age: 12 }"
},
{
"code": null,
"e": 1838,
"s": 1267,
"text": "req.signedCookies: The req.signedCookies property contains signed cookies sent by the request, unsigned, and ready for use when using cookie-parser middleware. Signing a cookie does not make it hidden or encrypted but simply prevents tampering with the cookie. It works by creating a HMAC of the value (current cookie), and base64 encoded it. When the cookie gets read, it recalculates the signature and makes sure that it matches the signature attached to it.If it does not match, then it gives an error. If no signed cookies are sent then the property defaults to { }."
},
{
"code": null,
"e": 1847,
"s": 1838,
"text": "Example:"
},
{
"code": null,
"e": 1858,
"s": 1847,
"text": "Javascript"
},
{
"code": "var cookieParser = require('cookie-parser');var express = require('express');var app = express();var PORT = 3000; app.use(cookieParser()); app.get('/user', function (req, res) { // Setting multiple cookies req.signedCookies.title='Gourav'; req.signedCookies.age=12; console.log(req.signedCookies); res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});",
"e": 2303,
"s": 1858,
"text": null
},
{
"code": null,
"e": 2439,
"s": 2303,
"text": "Output: Now open your browser and make GET request to http://localhost:3000/user, now you can see the following output on your console:"
},
{
"code": null,
"e": 2523,
"s": 2439,
"text": "Server listening on PORT 3000\n[Object: null prototype] { title: 'Gourav', age: 12 }"
},
{
"code": null,
"e": 2579,
"s": 2523,
"text": "Difference between req.cookies and req.signedCookies – "
},
{
"code": null,
"e": 2596,
"s": 2579,
"text": "minhazrabbi93041"
},
{
"code": null,
"e": 2607,
"s": 2596,
"text": "Express.js"
},
{
"code": null,
"e": 2620,
"s": 2607,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 2644,
"s": 2620,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2663,
"s": 2644,
"text": "Difference Between"
},
{
"code": null,
"e": 2671,
"s": 2663,
"text": "Node.js"
},
{
"code": null,
"e": 2690,
"s": 2671,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2707,
"s": 2690,
"text": "Web Technologies"
},
{
"code": null,
"e": 2805,
"s": 2707,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2873,
"s": 2805,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 2934,
"s": 2873,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3000,
"s": 2934,
"text": "Difference between Compile-time and Run-time Polymorphism in Java"
},
{
"code": null,
"e": 3074,
"s": 3000,
"text": "Differences and Applications of List, Tuple, Set and Dictionary in Python"
},
{
"code": null,
"e": 3123,
"s": 3074,
"text": "Similarities and Difference between Java and C++"
},
{
"code": null,
"e": 3171,
"s": 3123,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 3204,
"s": 3171,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3237,
"s": 3204,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 3274,
"s": 3237,
"text": "How to use an ES6 import in Node.js?"
}
] |
Socket Programming in Python
|
10 Nov, 2021
Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while the other socket reaches out to the other to form a connection. The server forms the listener socket while the client reaches out to the server. They are the real backbones behind web browsing. In simpler terms, there is a server and a client. Socket programming is started by importing the socket library and making a simple socket.
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Here we made a socket instance and passed it two parameters. The first parameter is AF_INET and the second one is SOCK_STREAM. AF_INET refers to the address-family ipv4. The SOCK_STREAM means connection-oriented TCP protocol. Now we can connect to a server using this socket.3
Note that if any error occurs during the creation of a socket then a socket. error is thrown and we can only connect to a server by knowing its IP. You can find the IP of the server by using this :
$ ping www.google.com
You can also find the IP using python:
import socket
ip = socket.gethostbyname('www.google.com')
print ip
Here is an example of a script for connecting to Google.
Python3
# An example script to connect to Google using socket# programming in Pythonimport socket # for socketimport sys try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print ("Socket successfully created")except socket.error as err: print ("socket creation failed with error %s" %(err)) # default port for socketport = 80 try: host_ip = socket.gethostbyname('www.google.com')except socket.gaierror: # this means could not resolve the host print ("there was an error resolving the host") sys.exit() # connecting to the servers.connect((host_ip, port)) print ("the socket has successfully connected to google")
Output :
Socket successfully created
the socket has successfully connected to google
on port == 173.194.40.19
First of all, we made a socket.
Then we resolved google’s IP and lastly, we connected to google.
Now we need to know how can we send some data through a socket.
For sending data the socket library has a sendall function. This function allows you to send data to a server to which the socket is connected and the server can also send data to the client using this function.
Server :
A server has a bind() method which binds it to a specific IP and port so that it can listen to incoming requests on that IP and port. A server has a listen() method which puts the server into listening mode. This allows the server to listen to incoming connections. And last a server has an accept() and close() method. The accept method initiates a connection with the client and the close method closes the connection with the client.
Python3
# first of all import the socket libraryimport socket # next create a socket objects = socket.socket() print ("Socket successfully created") # reserve a port on your computer in our# case it is 12345 but it can be anythingport = 12345 # Next bind to the port# we have not typed any ip in the ip field# instead we have inputted an empty string# this makes the server listen to requests# coming from other computers on the networks.bind(('', port)) print ("socket binded to %s" %(port)) # put the socket into listening modes.listen(5) print ("socket is listening") # a forever loop until we interrupt it or# an error occurswhile True: # Establish connection with client. c, addr = s.accept() print ('Got connection from', addr ) # send a thank you message to the client. encoding to send byte type. c.send('Thank you for connecting'.encode()) # Close the connection with the client c.close() # Breaking once connection closed break
First of all, we import socket which is necessary.
Then we made a socket object and reserved a port on our pc.
After that, we bound our server to the specified port. Passing an empty string means that the server can listen to incoming connections from other computers as well. If we would have passed 127.0.0.1 then it would have listened to only those calls made within the local computer.
After that we put the server into listening mode.5 here means that 5 connections are kept waiting if the server is busy and if a 6th socket tries to connect then the connection is refused.
At last, we make a while loop and start to accept all incoming connections and close those connections after a thank you message to all connected sockets.
Client : Now we need something with which a server can interact. We could tenet to the server like this just to know that our server is working. Type these commands in the terminal:
# start the server
$ python server.py
# keep the above terminal open
# now open another terminal and type:
$ telnet localhost 12345
If ‘telnet’ is not recognized. On windows search windows features and turn on the “telnet client” feature.
Output :
# in the server.py terminal you will see
# this output:
Socket successfully created
socket binded to 12345
socket is listening
Got connection from ('127.0.0.1', 52617)
# In the telnet terminal you will get this:
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Thank you for connectingConnection closed by foreign host.
This output shows that our server is working.Now for the client-side:
Python3
# Import socket moduleimport socket # Create a socket objects = socket.socket() # Define the port on which you want to connectport = 12345 # connect to the server on local computers.connect(('127.0.0.1', port)) # receive data from the server and decoding to get the string.print (s.recv(1024).decode())# close the connections.close()
First of all, we make a socket object.
Then we connect to localhost on port 12345 (the port on which our server runs) and lastly, we receive data from the server and close the connection.
Now save this file as client.py and run it from the terminal after starting the server script.
# start the server:
$ python server.py
Socket successfully created
socket binded to 12345
socket is listening
Got connection from ('127.0.0.1', 52617)
# start the client:
$ python client.py
Thank you for connecting
Reference: Python Socket ProgrammingThis article is contributed by Kishlay Verma. 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.
pall58183
rupeshdharme200001
marcosarcticseal
Computer Networks
Python
Technical Scripter
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 Nov, 2021"
},
{
"code": null,
"e": 548,
"s": 54,
"text": "Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while the other socket reaches out to the other to form a connection. The server forms the listener socket while the client reaches out to the server. They are the real backbones behind web browsing. In simpler terms, there is a server and a client. Socket programming is started by importing the socket library and making a simple socket. "
},
{
"code": null,
"e": 616,
"s": 548,
"text": "import socket\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)"
},
{
"code": null,
"e": 893,
"s": 616,
"text": "Here we made a socket instance and passed it two parameters. The first parameter is AF_INET and the second one is SOCK_STREAM. AF_INET refers to the address-family ipv4. The SOCK_STREAM means connection-oriented TCP protocol. Now we can connect to a server using this socket.3"
},
{
"code": null,
"e": 1092,
"s": 893,
"text": "Note that if any error occurs during the creation of a socket then a socket. error is thrown and we can only connect to a server by knowing its IP. You can find the IP of the server by using this : "
},
{
"code": null,
"e": 1114,
"s": 1092,
"text": "$ ping www.google.com"
},
{
"code": null,
"e": 1154,
"s": 1114,
"text": "You can also find the IP using python: "
},
{
"code": null,
"e": 1223,
"s": 1154,
"text": "import socket \n\nip = socket.gethostbyname('www.google.com')\nprint ip"
},
{
"code": null,
"e": 1280,
"s": 1223,
"text": "Here is an example of a script for connecting to Google."
},
{
"code": null,
"e": 1288,
"s": 1280,
"text": "Python3"
},
{
"code": "# An example script to connect to Google using socket# programming in Pythonimport socket # for socketimport sys try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print (\"Socket successfully created\")except socket.error as err: print (\"socket creation failed with error %s\" %(err)) # default port for socketport = 80 try: host_ip = socket.gethostbyname('www.google.com')except socket.gaierror: # this means could not resolve the host print (\"there was an error resolving the host\") sys.exit() # connecting to the servers.connect((host_ip, port)) print (\"the socket has successfully connected to google\")",
"e": 1923,
"s": 1288,
"text": null
},
{
"code": null,
"e": 1933,
"s": 1923,
"text": "Output : "
},
{
"code": null,
"e": 2035,
"s": 1933,
"text": "Socket successfully created\nthe socket has successfully connected to google \non port == 173.194.40.19"
},
{
"code": null,
"e": 2067,
"s": 2035,
"text": "First of all, we made a socket."
},
{
"code": null,
"e": 2132,
"s": 2067,
"text": "Then we resolved google’s IP and lastly, we connected to google."
},
{
"code": null,
"e": 2196,
"s": 2132,
"text": "Now we need to know how can we send some data through a socket."
},
{
"code": null,
"e": 2408,
"s": 2196,
"text": "For sending data the socket library has a sendall function. This function allows you to send data to a server to which the socket is connected and the server can also send data to the client using this function."
},
{
"code": null,
"e": 2418,
"s": 2408,
"text": "Server : "
},
{
"code": null,
"e": 2856,
"s": 2418,
"text": "A server has a bind() method which binds it to a specific IP and port so that it can listen to incoming requests on that IP and port. A server has a listen() method which puts the server into listening mode. This allows the server to listen to incoming connections. And last a server has an accept() and close() method. The accept method initiates a connection with the client and the close method closes the connection with the client. "
},
{
"code": null,
"e": 2864,
"s": 2856,
"text": "Python3"
},
{
"code": "# first of all import the socket libraryimport socket # next create a socket objects = socket.socket() print (\"Socket successfully created\") # reserve a port on your computer in our# case it is 12345 but it can be anythingport = 12345 # Next bind to the port# we have not typed any ip in the ip field# instead we have inputted an empty string# this makes the server listen to requests# coming from other computers on the networks.bind(('', port)) print (\"socket binded to %s\" %(port)) # put the socket into listening modes.listen(5) print (\"socket is listening\") # a forever loop until we interrupt it or# an error occurswhile True: # Establish connection with client. c, addr = s.accept() print ('Got connection from', addr ) # send a thank you message to the client. encoding to send byte type. c.send('Thank you for connecting'.encode()) # Close the connection with the client c.close() # Breaking once connection closed break",
"e": 3866,
"s": 2864,
"text": null
},
{
"code": null,
"e": 3917,
"s": 3866,
"text": "First of all, we import socket which is necessary."
},
{
"code": null,
"e": 3977,
"s": 3917,
"text": "Then we made a socket object and reserved a port on our pc."
},
{
"code": null,
"e": 4257,
"s": 3977,
"text": "After that, we bound our server to the specified port. Passing an empty string means that the server can listen to incoming connections from other computers as well. If we would have passed 127.0.0.1 then it would have listened to only those calls made within the local computer."
},
{
"code": null,
"e": 4446,
"s": 4257,
"text": "After that we put the server into listening mode.5 here means that 5 connections are kept waiting if the server is busy and if a 6th socket tries to connect then the connection is refused."
},
{
"code": null,
"e": 4601,
"s": 4446,
"text": "At last, we make a while loop and start to accept all incoming connections and close those connections after a thank you message to all connected sockets."
},
{
"code": null,
"e": 4784,
"s": 4601,
"text": "Client : Now we need something with which a server can interact. We could tenet to the server like this just to know that our server is working. Type these commands in the terminal: "
},
{
"code": null,
"e": 4921,
"s": 4784,
"text": "# start the server\n$ python server.py\n\n# keep the above terminal open \n# now open another terminal and type: \n \n$ telnet localhost 12345"
},
{
"code": null,
"e": 5028,
"s": 4921,
"text": "If ‘telnet’ is not recognized. On windows search windows features and turn on the “telnet client” feature."
},
{
"code": null,
"e": 5038,
"s": 5028,
"text": "Output : "
},
{
"code": null,
"e": 5206,
"s": 5038,
"text": "# in the server.py terminal you will see\n# this output:\nSocket successfully created\nsocket binded to 12345\nsocket is listening\nGot connection from ('127.0.0.1', 52617)"
},
{
"code": null,
"e": 5393,
"s": 5206,
"text": "# In the telnet terminal you will get this:\nTrying ::1...\nTrying 127.0.0.1...\nConnected to localhost.\nEscape character is '^]'.\nThank you for connectingConnection closed by foreign host."
},
{
"code": null,
"e": 5464,
"s": 5393,
"text": "This output shows that our server is working.Now for the client-side: "
},
{
"code": null,
"e": 5472,
"s": 5464,
"text": "Python3"
},
{
"code": "# Import socket moduleimport socket # Create a socket objects = socket.socket() # Define the port on which you want to connectport = 12345 # connect to the server on local computers.connect(('127.0.0.1', port)) # receive data from the server and decoding to get the string.print (s.recv(1024).decode())# close the connections.close() ",
"e": 5850,
"s": 5472,
"text": null
},
{
"code": null,
"e": 5889,
"s": 5850,
"text": "First of all, we make a socket object."
},
{
"code": null,
"e": 6038,
"s": 5889,
"text": "Then we connect to localhost on port 12345 (the port on which our server runs) and lastly, we receive data from the server and close the connection."
},
{
"code": null,
"e": 6133,
"s": 6038,
"text": "Now save this file as client.py and run it from the terminal after starting the server script."
},
{
"code": null,
"e": 6284,
"s": 6133,
"text": "# start the server:\n$ python server.py\nSocket successfully created\nsocket binded to 12345\nsocket is listening\nGot connection from ('127.0.0.1', 52617)"
},
{
"code": null,
"e": 6348,
"s": 6284,
"text": "# start the client:\n$ python client.py\nThank you for connecting"
},
{
"code": null,
"e": 6810,
"s": 6348,
"text": "Reference: Python Socket ProgrammingThis article is contributed by Kishlay Verma. 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. "
},
{
"code": null,
"e": 6820,
"s": 6810,
"text": "pall58183"
},
{
"code": null,
"e": 6839,
"s": 6820,
"text": "rupeshdharme200001"
},
{
"code": null,
"e": 6856,
"s": 6839,
"text": "marcosarcticseal"
},
{
"code": null,
"e": 6874,
"s": 6856,
"text": "Computer Networks"
},
{
"code": null,
"e": 6881,
"s": 6874,
"text": "Python"
},
{
"code": null,
"e": 6900,
"s": 6881,
"text": "Technical Scripter"
},
{
"code": null,
"e": 6918,
"s": 6900,
"text": "Computer Networks"
}
] |
Addition in Nested Tuples in Python
|
When it is required to perform addition in nested tuples, the 'zip' method and the generator expression can be used.
Generator is a simple way of creating iterators. It automatically implements a class with '__iter__()' and '__next__()' methods and keeps track of the internal states, as well as raises 'StopIteration' exception when no values are present that could be returned.
The zip method takes iterables, aggregates them into a tuple, and returns it as the result.
Below is a demonstration of the same −
Live Demo
my_tuple_1 = ((7, 8), (3, 4), (3, 2))
my_tuple_2 = ((9, 6), (8, 2), (1, 4))
print ("The first tuple is : " )
print(my_tuple_1)
print ("The second tuple is : " )
print(my_tuple_2)
my_result = tuple(tuple(a + b for a, b in zip(tup_1, tup_2))
for tup_1, tup_2 in zip(my_tuple_1, my_tuple_2))
print("The tuple after summation is : ")
print(my_result)
The first tuple is :
((7, 8), (3, 4), (3, 2))
The second tuple is :
((9, 6), (8, 2), (1, 4))
The tuple after summation is :
((16, 14), (11, 6), (4, 6))
Two nested tuples/tuple of tuples are defined and are displayed on the console.
They are zipped, and iterated over, and every element in each of the nested tuple is added, and a new tuple of tuples is created.
This result is assigned to a variable.
It is displayed as output on the console.
|
[
{
"code": null,
"e": 1179,
"s": 1062,
"text": "When it is required to perform addition in nested tuples, the 'zip' method and the generator expression can be used."
},
{
"code": null,
"e": 1442,
"s": 1179,
"text": "Generator is a simple way of creating iterators. It automatically implements a class with '__iter__()' and '__next__()' methods and keeps track of the internal states, as well as raises 'StopIteration' exception when no values are present that could be returned."
},
{
"code": null,
"e": 1534,
"s": 1442,
"text": "The zip method takes iterables, aggregates them into a tuple, and returns it as the result."
},
{
"code": null,
"e": 1573,
"s": 1534,
"text": "Below is a demonstration of the same −"
},
{
"code": null,
"e": 1583,
"s": 1573,
"text": "Live Demo"
},
{
"code": null,
"e": 1935,
"s": 1583,
"text": "my_tuple_1 = ((7, 8), (3, 4), (3, 2))\nmy_tuple_2 = ((9, 6), (8, 2), (1, 4))\n\nprint (\"The first tuple is : \" )\nprint(my_tuple_1)\nprint (\"The second tuple is : \" )\nprint(my_tuple_2)\n\nmy_result = tuple(tuple(a + b for a, b in zip(tup_1, tup_2))\n for tup_1, tup_2 in zip(my_tuple_1, my_tuple_2))\nprint(\"The tuple after summation is : \")\nprint(my_result)"
},
{
"code": null,
"e": 2087,
"s": 1935,
"text": "The first tuple is :\n((7, 8), (3, 4), (3, 2))\nThe second tuple is :\n((9, 6), (8, 2), (1, 4))\nThe tuple after summation is :\n((16, 14), (11, 6), (4, 6))"
},
{
"code": null,
"e": 2167,
"s": 2087,
"text": "Two nested tuples/tuple of tuples are defined and are displayed on the console."
},
{
"code": null,
"e": 2297,
"s": 2167,
"text": "They are zipped, and iterated over, and every element in each of the nested tuple is added, and a new tuple of tuples is created."
},
{
"code": null,
"e": 2336,
"s": 2297,
"text": "This result is assigned to a variable."
},
{
"code": null,
"e": 2378,
"s": 2336,
"text": "It is displayed as output on the console."
}
] |
How to Create a Docker Image with Jupyter Notebook and Kotlin | by Miguel Doctor Yuste | Towards Data Science
|
Computational Notebooks or simply Notebooks are a flexible and interactive tool that allows scientists to combine software code, computational output and explanatory resources (like text, charts and any other media content) within the same document. Notebooks are used for a wide variety of purposes, including data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning and much more.
Computational notebooks are not something new and they have been around for quite some time. However, the rise of web based development environments as well as the growing interest on data science disciplines (like exploratory data analysis, machine learning or deep learning among others), has appointed, notebooks in general and Jupyter notebooks in particular, as the preferred tool for scientists and researchers all around the world. There are plenty of ways to install Jupyter on your local environment (pip, Anaconda,...) or even working directly on cloud powered notebook environments (like Google Colab). Nevertheless, most of these approaches are Python oriented, which means that if you want to use Jupyter with any other language (like Kotlin, Scala or Java) you will have to install additional “kernels”. In this post we are going to explain an extremely simple approach to set up your own Jupyter environment compatible with Kotlin language without having to install anything but only one tool on your laptop: Docker.
This article is written based on the following platform:
Operating System: MacOS Catalina 10.15.7
Docker Community: v.20.10.2 for Mac (how to install docker)
This article aims to illustrate in detail the steps to follow in order to create a custom docker image with the following components: Jupyter Notebook and Kotlin kernel. Once the environment is set up, we will show how to access it and how to work with it. Finally, after confirming that everything works fine we will upload our image to a container images repository like Docker Hub, so it can be easily accessed by the community.
Let’s briefly discuss about the technologies and products we are going to use:
Docker is a software platform designed to make it easier to create, deploy, and run applications by using containers. Docker grants developers to package up applications along with all their dependencies in a container, and then ship it out as one package. This technology allows to stop worrying about installing components and libraries, just focus on working.
Jupyter is a web-based interactive development environment that allows to manage Jupyter notebooks. Jupyter Notebook is an interactive open document format based on JSON, which is used to combine software source code, narrative text, media content and computational outputs in one single document.
Kotlin is a general purpose, free, open source, statically typed “pragmatic” programming language created by JetBrains. Kotlin combines object-oriented and functional programming features and it is designed to interoperate fully with Java, and the JVM version of Kotlin’s standard library depends on the Java Class Library.
It’s out of the scope of this post to discuss about the reasons to use Kotlin on your data science projects, but if you want to read about the topic I would recommend to check the following resource from JetBrains (here).
A Dockerfile is a text document that contains the instructions a user can execute on the command line to build and assemble a docker image. Since we aim to create a docker image, our first step consist of creating a docker file. So go to your project directory and create a new file named Dockerfile. Once created we can edit it by adding the content as follows:
Let’s explain the content of the file:
FROM jupyter/base-notebook: This is the first line for our Dockerfile. Usually a Dockerfile begins with the FROM command. The FROM instruction receives as argument a pre-existent docker image. The idea is to use the services provided by this image and extends it by adding new layers on top of. The base image passed as argument is jupyter/base-notebook. This image contains a basic version of Jupyter already installed.
LABEL Miguel Doctor <[email protected]>: LABEL command is optional. It is used to identify the maintainer of the image. If included, you allow people interested on your image to contact you in case they need to ask you something or report a problem with the image.
The ENV defines an environmental variable. On this case we indicate that we want to use the full Jupyter Lab solution, which allows us to handle several notebooks and use a nice browser web interface.
As mentioned earlier, the default configuration for Jupyter is Python oriented, therefore in order to use a different language like Kotlin, we need to install and configure a specific Kernel. Since Kotlin is a JVM language, the first thing to install is the Java Runtime Environment (JRE).
So, let us update our Dockerfile by including the openjdk-8-jre installation on it. Once the JRE is installed, we need to add the Kotlin kernel so it can be connected to Jupyter. To achive this we just need to open the Dockerfile and edit its content as indicated in the script below:
As you can see we have added several lines to our file, and these lines make use of new Dockerfile keywords like USER and RUN. So le us explain what are these commands used for.
The USER command allows to change the user account in charge of executing the following instructions within the Dockerfile. Since installing the JDK 8 on the container is something only available for the root user, we need to indicate so in the file.
The RUN keyword is in charge of executing actions at build time. By using RUN you can customize the underlying image updating software packages, adding new applications to the image or arranging security rules among others. In our case, we call the RUN instruction twice in the file. First to run apt package management utility so the open-jdk (version 8) can be installed on the container. The second RUN instruction executes conda command line tool to install kotlin-jupyter-kernel.
So that is pretty much all as regards the Dockerfile! Now, we need to use docker to take the just created docker file and build the docker image so it can be run as a container. In order to do so, just go to the terminal, navigate to your project folder (where the Dockerfile is located) and create a new text file named Makefile. Then you need to add the following:
Let us explain what we have just added to the file:
1) run keyword defines a section with instructions to be executed when running the Makefile.
2) docker build -t <name of the image> <path or the dockerfile>:It creates the docker image by passing as argument a name for the image and the path where the Dockerfile is located.
Important: The label “migueldoctor/docker-jupyter-kotlin-notebook” is the identifier we have assigned to the image. This is an arbitrary parameter so you can modify as you wish.
3) docker run: This command actually starts up the docker container. It requires some parameters that we are explained as follows:
The argument --name is used to assign a specific name to the container.
The option -v is used to establish a mapping between a folder (you have to create the folder whether it does not exist yet) located on the host (/Users/mdoctor/Documents/dockerVolumes/kotlin-jupyter) and a specific path within the container (/home/jovyan/work). This is what Docker define as Volume and it allows to share information between the host and the container. Both paths need to be separated by colon (:) symbol when passing as argument to the docker run command. If you want to know more about volumes, you can check a post about the topic here.
The option -p allows us to map the host ports and the container ports. The -p parameter is followed by the port number of the host (8888) that will be redirected to the port number of the container (8888).
Finally, we need to pass as argument the image migueldoctor/docker-jupyter-kotlin-notebook created in the previous docker build command.
Once explained the Makefile, we just need to save the file and type the following command when located into the folder of the project.
$ make
For a while, the terminal will display the list of instructions under execution (building the image, starting up the container...) and eventually you will see something like the following log trace:
That means the Jupyter server is up and running and you can access it by opening your web browser and typing the last URL displayed on the logs:(http://127.0.0.1:8888/lab?token=de4d7f250f18430848ad1b40bb84a127d558968907cb10a6).
Congratulations if you can see what is indicated in the picture! That means the container is running with Jupyter and the Kotlin kernel. Now you just need to click on the Kotlin icon within the Notebook section to create your notebook and start working with it. As follows you can see how a simple notebook should look like with some kotlin code.
Important: Note that running make command will build the docker image every time you execute it, which means that it will waste time and resources if you haven’t made any modifications in the Dockerfile. Therefore, unless you edit the Dockerfile you should run the container using the following command (already included in the makefile and explained above).
$ docker run --name my-jupyter-kotlin -v /Users/mdoctor/Documents/dockerVolumes/kotlin-jupyter/:/home/jovyan/work -p 8888:8888 migueldoctor/docker-jupyter-kotlin-notebook
In some situations we might be interested on releasing our docker image to the community, so everybody can benefit from our work. For our particular case, we have decided to use Docker Hub as our central registry. As follows, we describe the approach to upload our just created image to Docker Hub:
Docker Hub allows users to create an account as requirement to upload images, so you need to register on the web if you have not done it yet.
Once registered, you need to open a terminal and connect to the Docker registry using the docker login command. You will be prompted asking for you username and password.
$ docker loginLogin with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one.Username:
Finally you need to use docker push followed by the name of image to upload. Since we have used our docker ID username (migueldoctor) as prefix for building the image, we can push it directly with the command below. If you have not used your docker ID as prefix you would need to tag it as indicated in the step 5 of the following post:
$ docker push migueldoctor/docker-jupyter-kotlin-notebook
Once the image is successfully pushed into Docker Hub, a new url is created to provide public access to the image. This url will contain the current version of the image as well as any new version/tag we might want to push in the future. For our example the url is the following:
https://hub.docker.com/r/migueldoctor/docker-jupyter-kotlin-notebook
In this post we have described how to create your own custom docker image including a fully functional Jupyter Notebook server compatible with Kotlin Kernel. Also, we explained all parameters so you can customize the image by adding/removing kernels. Finally we explained how to run the image and the steps to push your docker image to Docker Hub registry.
Please feel free to leave any comment, insight, or error you might have detected in the article. Your feedback is very welcomed and it will always help in improving the quality of the article. As always, thank you for reading. I strongly hope this tutorial helps you get started on data science projects using Jupyter, Kotlin and Docker.
|
[
{
"code": null,
"e": 613,
"s": 172,
"text": "Computational Notebooks or simply Notebooks are a flexible and interactive tool that allows scientists to combine software code, computational output and explanatory resources (like text, charts and any other media content) within the same document. Notebooks are used for a wide variety of purposes, including data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning and much more."
},
{
"code": null,
"e": 1645,
"s": 613,
"text": "Computational notebooks are not something new and they have been around for quite some time. However, the rise of web based development environments as well as the growing interest on data science disciplines (like exploratory data analysis, machine learning or deep learning among others), has appointed, notebooks in general and Jupyter notebooks in particular, as the preferred tool for scientists and researchers all around the world. There are plenty of ways to install Jupyter on your local environment (pip, Anaconda,...) or even working directly on cloud powered notebook environments (like Google Colab). Nevertheless, most of these approaches are Python oriented, which means that if you want to use Jupyter with any other language (like Kotlin, Scala or Java) you will have to install additional “kernels”. In this post we are going to explain an extremely simple approach to set up your own Jupyter environment compatible with Kotlin language without having to install anything but only one tool on your laptop: Docker."
},
{
"code": null,
"e": 1702,
"s": 1645,
"text": "This article is written based on the following platform:"
},
{
"code": null,
"e": 1743,
"s": 1702,
"text": "Operating System: MacOS Catalina 10.15.7"
},
{
"code": null,
"e": 1803,
"s": 1743,
"text": "Docker Community: v.20.10.2 for Mac (how to install docker)"
},
{
"code": null,
"e": 2235,
"s": 1803,
"text": "This article aims to illustrate in detail the steps to follow in order to create a custom docker image with the following components: Jupyter Notebook and Kotlin kernel. Once the environment is set up, we will show how to access it and how to work with it. Finally, after confirming that everything works fine we will upload our image to a container images repository like Docker Hub, so it can be easily accessed by the community."
},
{
"code": null,
"e": 2314,
"s": 2235,
"text": "Let’s briefly discuss about the technologies and products we are going to use:"
},
{
"code": null,
"e": 2677,
"s": 2314,
"text": "Docker is a software platform designed to make it easier to create, deploy, and run applications by using containers. Docker grants developers to package up applications along with all their dependencies in a container, and then ship it out as one package. This technology allows to stop worrying about installing components and libraries, just focus on working."
},
{
"code": null,
"e": 2975,
"s": 2677,
"text": "Jupyter is a web-based interactive development environment that allows to manage Jupyter notebooks. Jupyter Notebook is an interactive open document format based on JSON, which is used to combine software source code, narrative text, media content and computational outputs in one single document."
},
{
"code": null,
"e": 3299,
"s": 2975,
"text": "Kotlin is a general purpose, free, open source, statically typed “pragmatic” programming language created by JetBrains. Kotlin combines object-oriented and functional programming features and it is designed to interoperate fully with Java, and the JVM version of Kotlin’s standard library depends on the Java Class Library."
},
{
"code": null,
"e": 3521,
"s": 3299,
"text": "It’s out of the scope of this post to discuss about the reasons to use Kotlin on your data science projects, but if you want to read about the topic I would recommend to check the following resource from JetBrains (here)."
},
{
"code": null,
"e": 3884,
"s": 3521,
"text": "A Dockerfile is a text document that contains the instructions a user can execute on the command line to build and assemble a docker image. Since we aim to create a docker image, our first step consist of creating a docker file. So go to your project directory and create a new file named Dockerfile. Once created we can edit it by adding the content as follows:"
},
{
"code": null,
"e": 3923,
"s": 3884,
"text": "Let’s explain the content of the file:"
},
{
"code": null,
"e": 4344,
"s": 3923,
"text": "FROM jupyter/base-notebook: This is the first line for our Dockerfile. Usually a Dockerfile begins with the FROM command. The FROM instruction receives as argument a pre-existent docker image. The idea is to use the services provided by this image and extends it by adding new layers on top of. The base image passed as argument is jupyter/base-notebook. This image contains a basic version of Jupyter already installed."
},
{
"code": null,
"e": 4614,
"s": 4344,
"text": "LABEL Miguel Doctor <[email protected]>: LABEL command is optional. It is used to identify the maintainer of the image. If included, you allow people interested on your image to contact you in case they need to ask you something or report a problem with the image."
},
{
"code": null,
"e": 4815,
"s": 4614,
"text": "The ENV defines an environmental variable. On this case we indicate that we want to use the full Jupyter Lab solution, which allows us to handle several notebooks and use a nice browser web interface."
},
{
"code": null,
"e": 5105,
"s": 4815,
"text": "As mentioned earlier, the default configuration for Jupyter is Python oriented, therefore in order to use a different language like Kotlin, we need to install and configure a specific Kernel. Since Kotlin is a JVM language, the first thing to install is the Java Runtime Environment (JRE)."
},
{
"code": null,
"e": 5390,
"s": 5105,
"text": "So, let us update our Dockerfile by including the openjdk-8-jre installation on it. Once the JRE is installed, we need to add the Kotlin kernel so it can be connected to Jupyter. To achive this we just need to open the Dockerfile and edit its content as indicated in the script below:"
},
{
"code": null,
"e": 5568,
"s": 5390,
"text": "As you can see we have added several lines to our file, and these lines make use of new Dockerfile keywords like USER and RUN. So le us explain what are these commands used for."
},
{
"code": null,
"e": 5819,
"s": 5568,
"text": "The USER command allows to change the user account in charge of executing the following instructions within the Dockerfile. Since installing the JDK 8 on the container is something only available for the root user, we need to indicate so in the file."
},
{
"code": null,
"e": 6304,
"s": 5819,
"text": "The RUN keyword is in charge of executing actions at build time. By using RUN you can customize the underlying image updating software packages, adding new applications to the image or arranging security rules among others. In our case, we call the RUN instruction twice in the file. First to run apt package management utility so the open-jdk (version 8) can be installed on the container. The second RUN instruction executes conda command line tool to install kotlin-jupyter-kernel."
},
{
"code": null,
"e": 6671,
"s": 6304,
"text": "So that is pretty much all as regards the Dockerfile! Now, we need to use docker to take the just created docker file and build the docker image so it can be run as a container. In order to do so, just go to the terminal, navigate to your project folder (where the Dockerfile is located) and create a new text file named Makefile. Then you need to add the following:"
},
{
"code": null,
"e": 6723,
"s": 6671,
"text": "Let us explain what we have just added to the file:"
},
{
"code": null,
"e": 6816,
"s": 6723,
"text": "1) run keyword defines a section with instructions to be executed when running the Makefile."
},
{
"code": null,
"e": 6998,
"s": 6816,
"text": "2) docker build -t <name of the image> <path or the dockerfile>:It creates the docker image by passing as argument a name for the image and the path where the Dockerfile is located."
},
{
"code": null,
"e": 7176,
"s": 6998,
"text": "Important: The label “migueldoctor/docker-jupyter-kotlin-notebook” is the identifier we have assigned to the image. This is an arbitrary parameter so you can modify as you wish."
},
{
"code": null,
"e": 7307,
"s": 7176,
"text": "3) docker run: This command actually starts up the docker container. It requires some parameters that we are explained as follows:"
},
{
"code": null,
"e": 7379,
"s": 7307,
"text": "The argument --name is used to assign a specific name to the container."
},
{
"code": null,
"e": 7936,
"s": 7379,
"text": "The option -v is used to establish a mapping between a folder (you have to create the folder whether it does not exist yet) located on the host (/Users/mdoctor/Documents/dockerVolumes/kotlin-jupyter) and a specific path within the container (/home/jovyan/work). This is what Docker define as Volume and it allows to share information between the host and the container. Both paths need to be separated by colon (:) symbol when passing as argument to the docker run command. If you want to know more about volumes, you can check a post about the topic here."
},
{
"code": null,
"e": 8142,
"s": 7936,
"text": "The option -p allows us to map the host ports and the container ports. The -p parameter is followed by the port number of the host (8888) that will be redirected to the port number of the container (8888)."
},
{
"code": null,
"e": 8279,
"s": 8142,
"text": "Finally, we need to pass as argument the image migueldoctor/docker-jupyter-kotlin-notebook created in the previous docker build command."
},
{
"code": null,
"e": 8414,
"s": 8279,
"text": "Once explained the Makefile, we just need to save the file and type the following command when located into the folder of the project."
},
{
"code": null,
"e": 8421,
"s": 8414,
"text": "$ make"
},
{
"code": null,
"e": 8620,
"s": 8421,
"text": "For a while, the terminal will display the list of instructions under execution (building the image, starting up the container...) and eventually you will see something like the following log trace:"
},
{
"code": null,
"e": 8848,
"s": 8620,
"text": "That means the Jupyter server is up and running and you can access it by opening your web browser and typing the last URL displayed on the logs:(http://127.0.0.1:8888/lab?token=de4d7f250f18430848ad1b40bb84a127d558968907cb10a6)."
},
{
"code": null,
"e": 9195,
"s": 8848,
"text": "Congratulations if you can see what is indicated in the picture! That means the container is running with Jupyter and the Kotlin kernel. Now you just need to click on the Kotlin icon within the Notebook section to create your notebook and start working with it. As follows you can see how a simple notebook should look like with some kotlin code."
},
{
"code": null,
"e": 9554,
"s": 9195,
"text": "Important: Note that running make command will build the docker image every time you execute it, which means that it will waste time and resources if you haven’t made any modifications in the Dockerfile. Therefore, unless you edit the Dockerfile you should run the container using the following command (already included in the makefile and explained above)."
},
{
"code": null,
"e": 9725,
"s": 9554,
"text": "$ docker run --name my-jupyter-kotlin -v /Users/mdoctor/Documents/dockerVolumes/kotlin-jupyter/:/home/jovyan/work -p 8888:8888 migueldoctor/docker-jupyter-kotlin-notebook"
},
{
"code": null,
"e": 10024,
"s": 9725,
"text": "In some situations we might be interested on releasing our docker image to the community, so everybody can benefit from our work. For our particular case, we have decided to use Docker Hub as our central registry. As follows, we describe the approach to upload our just created image to Docker Hub:"
},
{
"code": null,
"e": 10166,
"s": 10024,
"text": "Docker Hub allows users to create an account as requirement to upload images, so you need to register on the web if you have not done it yet."
},
{
"code": null,
"e": 10337,
"s": 10166,
"text": "Once registered, you need to open a terminal and connect to the Docker registry using the docker login command. You will be prompted asking for you username and password."
},
{
"code": null,
"e": 10509,
"s": 10337,
"text": "$ docker loginLogin with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one.Username:"
},
{
"code": null,
"e": 10846,
"s": 10509,
"text": "Finally you need to use docker push followed by the name of image to upload. Since we have used our docker ID username (migueldoctor) as prefix for building the image, we can push it directly with the command below. If you have not used your docker ID as prefix you would need to tag it as indicated in the step 5 of the following post:"
},
{
"code": null,
"e": 10904,
"s": 10846,
"text": "$ docker push migueldoctor/docker-jupyter-kotlin-notebook"
},
{
"code": null,
"e": 11184,
"s": 10904,
"text": "Once the image is successfully pushed into Docker Hub, a new url is created to provide public access to the image. This url will contain the current version of the image as well as any new version/tag we might want to push in the future. For our example the url is the following:"
},
{
"code": null,
"e": 11253,
"s": 11184,
"text": "https://hub.docker.com/r/migueldoctor/docker-jupyter-kotlin-notebook"
},
{
"code": null,
"e": 11610,
"s": 11253,
"text": "In this post we have described how to create your own custom docker image including a fully functional Jupyter Notebook server compatible with Kotlin Kernel. Also, we explained all parameters so you can customize the image by adding/removing kernels. Finally we explained how to run the image and the steps to push your docker image to Docker Hub registry."
}
] |
Count characters with same neighbors - GeeksforGeeks
|
28 Jun, 2021
Given a string, the task is to find the number of characters with the same adjacent characters. Note: First and last character will always be counted as they will have only one adjacent character.Examples:
Input: str = “egeeksk” Output: 4 Characters with same adjacent characters are e, g, s, kInput: str = “eeeeeeee” Output: 8 Characters with same adjacent characters are e, e, e, e, e, e, e, e
Approach:
If the length of the string is less than 3 then return the length of the string.Initialize the count with 2 as first and last will always be counted.Start traversing the string.Check if the previous and next characters of the current character are the same.Increment count, if yes.Return count.
If the length of the string is less than 3 then return the length of the string.
Initialize the count with 2 as first and last will always be counted.
Start traversing the string.Check if the previous and next characters of the current character are the same.Increment count, if yes.
Check if the previous and next characters of the current character are the same.
Increment count, if yes.
Return count.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to count the characters// with same adjacent charactersint countChar(string str){ int n = str.length(); // if length is less than 3 // then return length as there // will be only two characters if (n <= 2) return n; int count = 2; // Traverse the string for (int i = 1; i < n - 1; i++) // Increment the count if the previous // and next character is same if (str[i - 1] == str[i + 1]) count++; // Return count return count;} // Driver codeint main(){ string str = "egeeksk"; cout << countChar(str); return 0;}
// Java implementation of the above approach class GFG{ // Function to count the characters // with same adjacent characters static int countChar(String str) { int n = str.length(); // if length is less than 3 // then return length as there // will be only two characters if (n <= 2) return n; int count = 2; // Traverse the string for (int i = 1; i < n - 1; i++) // Increment the count if the previous // and next character is same if (str.charAt(i - 1) == str.charAt(i + 1)) count++; // Return count return count; } // Driver code public static void main(String []args) { String str = "egeeksk"; System.out.println(countChar(str)); }} // This code is contributed// by ihritik
# Python 3 implementation of above approach # Function to count the characters# with same adjacent charactersdef countChar(str): n = len(str) # if length is less than 3 # then return length as there # will be only two characters if (n <= 2): return n count = 2 # Traverse the string for i in range(1, n - 1): # Increment the count if the previous # and next character is same if (str[i - 1] == str[i + 1]): count += 1 # Return count return count # Driver codeif __name__ == '__main__': str = "egeeksk" print(countChar(str)) # This code is contributed by# Surendra_Gangwar
// C# implementation of above approachusing System; class GFG{ // Function to count the characters// with same adjacent charactersstatic int countChar(String str){ int n = str.Length; // if length is less than 3 // then return length as there // will be only two characters if (n <= 2) return n; int count = 2; // Traverse the string for (int i = 1; i < n - 1; i++) // Increment the count if the previous // and next character is same if (str[i - 1] == str[i + 1]) count++; // Return count return count;} // Driver codepublic static void Main(){ String str = "egeeksk"; Console.WriteLine(countChar(str));}} // This code is contributed// by Subhadeep
<?php// PHP implementation of above approach // Function to count the characters// with same adjacent charactersfunction countChar($str){ $n = strlen($str); // if length is less than 3 // then return length as there // will be only two characters if ($n <= 2) return $n; $count = 2; // Traverse the string for ($i = 1; $i < $n - 1; $i++) // Increment the count if the previous // and next character is same if ($str[$i - 1] == $str[$i + 1]) $count++; // Return count return $count;} // Driver code$str = "egeeksk";echo countChar($str); // This code is contributed by Sach?>
<script> // Javascript implementation of above approach // Function to count the characters// with same adjacent charactersfunction countChar(str){ var n = str.length; // if length is less than 3 // then return length as there // will be only two characters if (n <= 2) return n; var count = 2; // Traverse the string for (var i = 1; i < n - 1; i++) // Increment the count if the previous // and next character is same if (str[i - 1] == str[i + 1]) count++; // Return count return count;} // Driver codevar str = "egeeksk";document.write( countChar(str)); </script>
4
ihritik
tufan_gupta2000
Sach_Code
SURENDRA_GANGWAR
ManasChhabra2
rrrtnx
as5853535
ruhelaa48
Searching
Strings
Searching
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Best First Search (Informed Search)
Program to remove vowels from a String
3 Different ways to print Fibonacci series in Java
Recursive Programs to find Minimum and Maximum elements of array
Interpolation search vs Binary search
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
C++ Data Types
Write a program to print all permutations of a given string
|
[
{
"code": null,
"e": 24902,
"s": 24874,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25109,
"s": 24902,
"text": "Given a string, the task is to find the number of characters with the same adjacent characters. Note: First and last character will always be counted as they will have only one adjacent character.Examples: "
},
{
"code": null,
"e": 25299,
"s": 25109,
"text": "Input: str = “egeeksk” Output: 4 Characters with same adjacent characters are e, g, s, kInput: str = “eeeeeeee” Output: 8 Characters with same adjacent characters are e, e, e, e, e, e, e, e"
},
{
"code": null,
"e": 25313,
"s": 25301,
"text": "Approach: "
},
{
"code": null,
"e": 25608,
"s": 25313,
"text": "If the length of the string is less than 3 then return the length of the string.Initialize the count with 2 as first and last will always be counted.Start traversing the string.Check if the previous and next characters of the current character are the same.Increment count, if yes.Return count."
},
{
"code": null,
"e": 25689,
"s": 25608,
"text": "If the length of the string is less than 3 then return the length of the string."
},
{
"code": null,
"e": 25759,
"s": 25689,
"text": "Initialize the count with 2 as first and last will always be counted."
},
{
"code": null,
"e": 25892,
"s": 25759,
"text": "Start traversing the string.Check if the previous and next characters of the current character are the same.Increment count, if yes."
},
{
"code": null,
"e": 25973,
"s": 25892,
"text": "Check if the previous and next characters of the current character are the same."
},
{
"code": null,
"e": 25998,
"s": 25973,
"text": "Increment count, if yes."
},
{
"code": null,
"e": 26012,
"s": 25998,
"text": "Return count."
},
{
"code": null,
"e": 26064,
"s": 26012,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26068,
"s": 26064,
"text": "C++"
},
{
"code": null,
"e": 26073,
"s": 26068,
"text": "Java"
},
{
"code": null,
"e": 26081,
"s": 26073,
"text": "Python3"
},
{
"code": null,
"e": 26084,
"s": 26081,
"text": "C#"
},
{
"code": null,
"e": 26088,
"s": 26084,
"text": "PHP"
},
{
"code": null,
"e": 26099,
"s": 26088,
"text": "Javascript"
},
{
"code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to count the characters// with same adjacent charactersint countChar(string str){ int n = str.length(); // if length is less than 3 // then return length as there // will be only two characters if (n <= 2) return n; int count = 2; // Traverse the string for (int i = 1; i < n - 1; i++) // Increment the count if the previous // and next character is same if (str[i - 1] == str[i + 1]) count++; // Return count return count;} // Driver codeint main(){ string str = \"egeeksk\"; cout << countChar(str); return 0;}",
"e": 26788,
"s": 26099,
"text": null
},
{
"code": "// Java implementation of the above approach class GFG{ // Function to count the characters // with same adjacent characters static int countChar(String str) { int n = str.length(); // if length is less than 3 // then return length as there // will be only two characters if (n <= 2) return n; int count = 2; // Traverse the string for (int i = 1; i < n - 1; i++) // Increment the count if the previous // and next character is same if (str.charAt(i - 1) == str.charAt(i + 1)) count++; // Return count return count; } // Driver code public static void main(String []args) { String str = \"egeeksk\"; System.out.println(countChar(str)); }} // This code is contributed// by ihritik",
"e": 27828,
"s": 26788,
"text": null
},
{
"code": "# Python 3 implementation of above approach # Function to count the characters# with same adjacent charactersdef countChar(str): n = len(str) # if length is less than 3 # then return length as there # will be only two characters if (n <= 2): return n count = 2 # Traverse the string for i in range(1, n - 1): # Increment the count if the previous # and next character is same if (str[i - 1] == str[i + 1]): count += 1 # Return count return count # Driver codeif __name__ == '__main__': str = \"egeeksk\" print(countChar(str)) # This code is contributed by# Surendra_Gangwar",
"e": 28491,
"s": 27828,
"text": null
},
{
"code": "// C# implementation of above approachusing System; class GFG{ // Function to count the characters// with same adjacent charactersstatic int countChar(String str){ int n = str.Length; // if length is less than 3 // then return length as there // will be only two characters if (n <= 2) return n; int count = 2; // Traverse the string for (int i = 1; i < n - 1; i++) // Increment the count if the previous // and next character is same if (str[i - 1] == str[i + 1]) count++; // Return count return count;} // Driver codepublic static void Main(){ String str = \"egeeksk\"; Console.WriteLine(countChar(str));}} // This code is contributed// by Subhadeep",
"e": 29220,
"s": 28491,
"text": null
},
{
"code": "<?php// PHP implementation of above approach // Function to count the characters// with same adjacent charactersfunction countChar($str){ $n = strlen($str); // if length is less than 3 // then return length as there // will be only two characters if ($n <= 2) return $n; $count = 2; // Traverse the string for ($i = 1; $i < $n - 1; $i++) // Increment the count if the previous // and next character is same if ($str[$i - 1] == $str[$i + 1]) $count++; // Return count return $count;} // Driver code$str = \"egeeksk\";echo countChar($str); // This code is contributed by Sach?>",
"e": 29871,
"s": 29220,
"text": null
},
{
"code": "<script> // Javascript implementation of above approach // Function to count the characters// with same adjacent charactersfunction countChar(str){ var n = str.length; // if length is less than 3 // then return length as there // will be only two characters if (n <= 2) return n; var count = 2; // Traverse the string for (var i = 1; i < n - 1; i++) // Increment the count if the previous // and next character is same if (str[i - 1] == str[i + 1]) count++; // Return count return count;} // Driver codevar str = \"egeeksk\";document.write( countChar(str)); </script>",
"e": 30510,
"s": 29871,
"text": null
},
{
"code": null,
"e": 30512,
"s": 30510,
"text": "4"
},
{
"code": null,
"e": 30522,
"s": 30514,
"text": "ihritik"
},
{
"code": null,
"e": 30538,
"s": 30522,
"text": "tufan_gupta2000"
},
{
"code": null,
"e": 30548,
"s": 30538,
"text": "Sach_Code"
},
{
"code": null,
"e": 30565,
"s": 30548,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 30579,
"s": 30565,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 30586,
"s": 30579,
"text": "rrrtnx"
},
{
"code": null,
"e": 30596,
"s": 30586,
"text": "as5853535"
},
{
"code": null,
"e": 30606,
"s": 30596,
"text": "ruhelaa48"
},
{
"code": null,
"e": 30616,
"s": 30606,
"text": "Searching"
},
{
"code": null,
"e": 30624,
"s": 30616,
"text": "Strings"
},
{
"code": null,
"e": 30634,
"s": 30624,
"text": "Searching"
},
{
"code": null,
"e": 30642,
"s": 30634,
"text": "Strings"
},
{
"code": null,
"e": 30740,
"s": 30642,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30749,
"s": 30740,
"text": "Comments"
},
{
"code": null,
"e": 30762,
"s": 30749,
"text": "Old Comments"
},
{
"code": null,
"e": 30798,
"s": 30762,
"text": "Best First Search (Informed Search)"
},
{
"code": null,
"e": 30837,
"s": 30798,
"text": "Program to remove vowels from a String"
},
{
"code": null,
"e": 30888,
"s": 30837,
"text": "3 Different ways to print Fibonacci series in Java"
},
{
"code": null,
"e": 30953,
"s": 30888,
"text": "Recursive Programs to find Minimum and Maximum elements of array"
},
{
"code": null,
"e": 30991,
"s": 30953,
"text": "Interpolation search vs Binary search"
},
{
"code": null,
"e": 31016,
"s": 30991,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 31062,
"s": 31016,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 31096,
"s": 31062,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 31111,
"s": 31096,
"text": "C++ Data Types"
}
] |
Dart Programming - List.single Method
|
Checks if the list has only one element and returns it.
List.single
void main() {
var lst = new List();
lst.add(12);
print("The list has only one element: ${lst.single}");
}
It will produce the following output −
The list values in reverse order: (13, 12)
It will produce the following output −
The list has only one element: 12
This property throws an exception if the List has more than one element in it. The following example illustrates the same −
void main() {
var lst = new List();
lst.add(12);
lst.add(10);
print(lst.single);
}
If the list has more than one element, then the same code will throw the following exception −
Unhandled exception:
Bad state: Too many elements
#0 List.single (dart:core-patch/growable_array.dart:234)
#1 main (file:///D:/Demos/Boolean.dart:6:13)
#2 _startIsolate.<anonymous closure> (dart:isolatepatch/isolate_patch.dart:261)
#3 _RawReceivePortImpl._handleMessage (dart:isolatepatch/isolate_patch.dart:148)
44 Lectures
4.5 hours
Sriyank Siddhartha
34 Lectures
4 hours
Sriyank Siddhartha
69 Lectures
4 hours
Frahaan Hussain
117 Lectures
10 hours
Frahaan Hussain
22 Lectures
1.5 hours
Pranjal Srivastava
34 Lectures
3 hours
Pranjal Srivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2581,
"s": 2525,
"text": "Checks if the list has only one element and returns it."
},
{
"code": null,
"e": 2595,
"s": 2581,
"text": "List.single \n"
},
{
"code": null,
"e": 2715,
"s": 2595,
"text": "void main() { \n var lst = new List(); \n lst.add(12);\n print(\"The list has only one element: ${lst.single}\"); \n} "
},
{
"code": null,
"e": 2754,
"s": 2715,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 2799,
"s": 2754,
"text": "The list values in reverse order: (13, 12) \n"
},
{
"code": null,
"e": 2838,
"s": 2799,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 2874,
"s": 2838,
"text": "The list has only one element: 12 \n"
},
{
"code": null,
"e": 2998,
"s": 2874,
"text": "This property throws an exception if the List has more than one element in it. The following example illustrates the same −"
},
{
"code": null,
"e": 3098,
"s": 2998,
"text": "void main() { \n var lst = new List(); \n lst.add(12); \n lst.add(10); \n print(lst.single); \n}"
},
{
"code": null,
"e": 3193,
"s": 3098,
"text": "If the list has more than one element, then the same code will throw the following exception −"
},
{
"code": null,
"e": 3512,
"s": 3193,
"text": "Unhandled exception: \nBad state: Too many elements \n#0 List.single (dart:core-patch/growable_array.dart:234) \n#1 main (file:///D:/Demos/Boolean.dart:6:13) \n#2 _startIsolate.<anonymous closure> (dart:isolatepatch/isolate_patch.dart:261) \n#3 _RawReceivePortImpl._handleMessage (dart:isolatepatch/isolate_patch.dart:148)\n"
},
{
"code": null,
"e": 3547,
"s": 3512,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3567,
"s": 3547,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 3600,
"s": 3567,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3620,
"s": 3600,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 3653,
"s": 3620,
"text": "\n 69 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3670,
"s": 3653,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3705,
"s": 3670,
"text": "\n 117 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3722,
"s": 3705,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3757,
"s": 3722,
"text": "\n 22 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3777,
"s": 3757,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 3810,
"s": 3777,
"text": "\n 34 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3830,
"s": 3810,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 3837,
"s": 3830,
"text": " Print"
},
{
"code": null,
"e": 3848,
"s": 3837,
"text": " Add Notes"
}
] |
Dictionary Methods in Python | Set 1 (cmp(), len(), items()...) - GeeksforGeeks
|
28 Jun, 2021
Python Dictionary Basics have been discussed in the article below
Dictionary
Some dictionary methods are discussed in this article.
1. str(dic) :- This method is used to return the string, denoting all the dictionary keys with their values.
2. items() :- This method is used to return the list with all dictionary keys with values.
# Python code to demonstrate working of# str() and items() # Initializing dictionarydic = { 'Name' : 'Nandini', 'Age' : 19 } # using str() to display dic as stringprint ("The constituents of dictionary as string are : ")print (str(dic)) # using str() to display dic as listprint ("The constituents of dictionary as list are : ")print (dic.items())
Output:
The constituents of dictionary as string are :
{'Name': 'Nandini', 'Age': 19}
The constituents of dictionary as list are :
dict_items([('Name', 'Nandini'), ('Age', 19)])
3. len() :- It returns the count of key entities of the dictionary elements.
4. type() :- This function returns the data type of the argument.
# Python code to demonstrate working of# len() and type() # Initializing dictionarydic = { 'Name' : 'Nandini', 'Age' : 19, 'ID' : 2541997 } # Initializing listli = [ 1, 3, 5, 6 ] # using len() to display dic sizeprint ("The size of dic is : ",end="")print (len(dic)) # using type() to display data typeprint ("The data type of dic is : ",end="")print (type(dic)) # using type() to display data typeprint ("The data type of li is : ",end="")print (type(li))
Output:
The size of dic is : 3
The data type of dic is :
The data type of li is :
5. copy() :- This function creates the shallow copy of the dictionary into other dictionary.
6. clear() :- This function is used to clear the dictionary contents.
# Python code to demonstrate working of# clear() and copy() # Initializing dictionarydic1 = { 'Name' : 'Nandini', 'Age' : 19 } # Initializing dictionary dic3 = {} # using copy() to make shallow copy of dictionarydic3 = dic1.copy() # printing new dictionaryprint ("The new copied dictionary is : ")print (dic3.items()) # clearing the dictionarydic1.clear() # printing cleared dictionaryprint ("The contents of deleted dictionary is : ",end="")print (dic1.items())
Output:
The new copied dictionary is :
dict_items([('Age', 19), ('Name', 'Nandini')])
The contents of deleted dictionary is : dict_items([])
This article is contributed by Manjeet Singh. 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.
python-dict
Python
School Programming
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java
C++ Classes and Objects
|
[
{
"code": null,
"e": 24396,
"s": 24368,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24462,
"s": 24396,
"text": "Python Dictionary Basics have been discussed in the article below"
},
{
"code": null,
"e": 24473,
"s": 24462,
"text": "Dictionary"
},
{
"code": null,
"e": 24528,
"s": 24473,
"text": "Some dictionary methods are discussed in this article."
},
{
"code": null,
"e": 24637,
"s": 24528,
"text": "1. str(dic) :- This method is used to return the string, denoting all the dictionary keys with their values."
},
{
"code": null,
"e": 24728,
"s": 24637,
"text": "2. items() :- This method is used to return the list with all dictionary keys with values."
},
{
"code": "# Python code to demonstrate working of# str() and items() # Initializing dictionarydic = { 'Name' : 'Nandini', 'Age' : 19 } # using str() to display dic as stringprint (\"The constituents of dictionary as string are : \")print (str(dic)) # using str() to display dic as listprint (\"The constituents of dictionary as list are : \")print (dic.items())",
"e": 25079,
"s": 24728,
"text": null
},
{
"code": null,
"e": 25087,
"s": 25079,
"text": "Output:"
},
{
"code": null,
"e": 25260,
"s": 25087,
"text": "The constituents of dictionary as string are : \n{'Name': 'Nandini', 'Age': 19}\nThe constituents of dictionary as list are : \ndict_items([('Name', 'Nandini'), ('Age', 19)])\n"
},
{
"code": null,
"e": 25337,
"s": 25260,
"text": "3. len() :- It returns the count of key entities of the dictionary elements."
},
{
"code": null,
"e": 25403,
"s": 25337,
"text": "4. type() :- This function returns the data type of the argument."
},
{
"code": "# Python code to demonstrate working of# len() and type() # Initializing dictionarydic = { 'Name' : 'Nandini', 'Age' : 19, 'ID' : 2541997 } # Initializing listli = [ 1, 3, 5, 6 ] # using len() to display dic sizeprint (\"The size of dic is : \",end=\"\")print (len(dic)) # using type() to display data typeprint (\"The data type of dic is : \",end=\"\")print (type(dic)) # using type() to display data typeprint (\"The data type of li is : \",end=\"\")print (type(li))",
"e": 25865,
"s": 25403,
"text": null
},
{
"code": null,
"e": 25873,
"s": 25865,
"text": "Output:"
},
{
"code": null,
"e": 25950,
"s": 25873,
"text": "The size of dic is : 3\nThe data type of dic is : \nThe data type of li is : \n"
},
{
"code": null,
"e": 26043,
"s": 25950,
"text": "5. copy() :- This function creates the shallow copy of the dictionary into other dictionary."
},
{
"code": null,
"e": 26113,
"s": 26043,
"text": "6. clear() :- This function is used to clear the dictionary contents."
},
{
"code": "# Python code to demonstrate working of# clear() and copy() # Initializing dictionarydic1 = { 'Name' : 'Nandini', 'Age' : 19 } # Initializing dictionary dic3 = {} # using copy() to make shallow copy of dictionarydic3 = dic1.copy() # printing new dictionaryprint (\"The new copied dictionary is : \")print (dic3.items()) # clearing the dictionarydic1.clear() # printing cleared dictionaryprint (\"The contents of deleted dictionary is : \",end=\"\")print (dic1.items())",
"e": 26582,
"s": 26113,
"text": null
},
{
"code": null,
"e": 26590,
"s": 26582,
"text": "Output:"
},
{
"code": null,
"e": 26725,
"s": 26590,
"text": "The new copied dictionary is : \ndict_items([('Age', 19), ('Name', 'Nandini')])\nThe contents of deleted dictionary is : dict_items([])\n"
},
{
"code": null,
"e": 27022,
"s": 26725,
"text": "This article is contributed by Manjeet Singh. 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": 27147,
"s": 27022,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27159,
"s": 27147,
"text": "python-dict"
},
{
"code": null,
"e": 27166,
"s": 27159,
"text": "Python"
},
{
"code": null,
"e": 27185,
"s": 27166,
"text": "School Programming"
},
{
"code": null,
"e": 27197,
"s": 27185,
"text": "python-dict"
},
{
"code": null,
"e": 27295,
"s": 27197,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27317,
"s": 27295,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27349,
"s": 27317,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27391,
"s": 27349,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27417,
"s": 27391,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27454,
"s": 27417,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27470,
"s": 27454,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 27489,
"s": 27470,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 27514,
"s": 27489,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 27533,
"s": 27514,
"text": "Interfaces in Java"
}
] |
How to exit a Kivy application using a button ? - GeeksforGeeks
|
15 Mar, 2021
Kivy is a graphical user interface open-source Python library that allows you to develop multi-platform applications on Windows, macOS, Android, iOS, Linux, and Raspberry-Pi. In addition to the regular mouse and keyboard inputs, it also supports multitouch events. The applications made using Kivy will similar across all the platforms, but it also means that the application’s feel or look will differ from any native application.
In this article, we will develop a GUI window using kivy framework of python, and we will add a single button on the window which will close kivy application on click
Import kivy button
Import kivy app
Import kivy builder
Create App class
Return builder string
Run an instance of the class
Below is the implementation.
Python3
# importing button widget from kivy frameworkfrom kivy.uix.button import Buttonfrom kivy.app import Appfrom kivy.core.window import Window # importing builder from kivyfrom kivy.lang import Builder # this is the main class which # will render the whole applicationclass uiApp(App): # method which will render our application def close_application(self): # closing application App.get_running_app().stop() # removing window Window.close() def build(self): return Builder.load_string(""" #:import C kivy.utils.get_color_from_hexButton: # text which will appear on first button text:"Close App" on_release: app.close_application() """) # running the applicationuiApp().run()
Output:
Python-kivy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Defaultdict in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24316,
"s": 24288,
"text": "\n15 Mar, 2021"
},
{
"code": null,
"e": 24748,
"s": 24316,
"text": "Kivy is a graphical user interface open-source Python library that allows you to develop multi-platform applications on Windows, macOS, Android, iOS, Linux, and Raspberry-Pi. In addition to the regular mouse and keyboard inputs, it also supports multitouch events. The applications made using Kivy will similar across all the platforms, but it also means that the application’s feel or look will differ from any native application."
},
{
"code": null,
"e": 24915,
"s": 24748,
"text": "In this article, we will develop a GUI window using kivy framework of python, and we will add a single button on the window which will close kivy application on click"
},
{
"code": null,
"e": 24934,
"s": 24915,
"text": "Import kivy button"
},
{
"code": null,
"e": 24950,
"s": 24934,
"text": "Import kivy app"
},
{
"code": null,
"e": 24970,
"s": 24950,
"text": "Import kivy builder"
},
{
"code": null,
"e": 24987,
"s": 24970,
"text": "Create App class"
},
{
"code": null,
"e": 25009,
"s": 24987,
"text": "Return builder string"
},
{
"code": null,
"e": 25038,
"s": 25009,
"text": "Run an instance of the class"
},
{
"code": null,
"e": 25067,
"s": 25038,
"text": "Below is the implementation."
},
{
"code": null,
"e": 25075,
"s": 25067,
"text": "Python3"
},
{
"code": "# importing button widget from kivy frameworkfrom kivy.uix.button import Buttonfrom kivy.app import Appfrom kivy.core.window import Window # importing builder from kivyfrom kivy.lang import Builder # this is the main class which # will render the whole applicationclass uiApp(App): # method which will render our application def close_application(self): # closing application App.get_running_app().stop() # removing window Window.close() def build(self): return Builder.load_string(\"\"\" #:import C kivy.utils.get_color_from_hexButton: # text which will appear on first button text:\"Close App\" on_release: app.close_application() \"\"\") # running the applicationuiApp().run()",
"e": 25852,
"s": 25075,
"text": null
},
{
"code": null,
"e": 25860,
"s": 25852,
"text": "Output:"
},
{
"code": null,
"e": 25872,
"s": 25860,
"text": "Python-kivy"
},
{
"code": null,
"e": 25879,
"s": 25872,
"text": "Python"
},
{
"code": null,
"e": 25977,
"s": 25879,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26009,
"s": 25977,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26051,
"s": 26009,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26107,
"s": 26051,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26149,
"s": 26107,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26171,
"s": 26149,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26202,
"s": 26171,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26257,
"s": 26202,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26296,
"s": 26257,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26325,
"s": 26296,
"text": "Create a directory in Python"
}
] |
Difference between Selection and Projection in DBMS - GeeksforGeeks
|
12 Jun, 2020
Prerequisite – Relational Algebra1. Selection :This operation chooses the subset of tuples from the relation that satisfies the given condition mentioned in the syntax of selection.
Notation –
σc (R)
Here, ‘c’ is selection condition and ‘σ (sigma)’ is used to denote Select Operator.
2. Projection :This operation selects certain required attributes, while discarding other attributes.
Notation –
πA (R)
where ‘A’ is the attribute list, it is the desired set of attributes from the attributes of relation(R),symbol ‘π(pi)’ is used to denote the Project operator,R is generally a relational algebra expression, which results in a relation.
Difference between Selection and Projection in DBMS
DBMS-Relational Algebra
DBMS
Difference Between
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
Introduction of Relational Algebra in DBMS
What is Temporary Table in SQL?
Two Phase Locking Protocol
KDD Process in Data Mining
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Difference between Process and Thread
|
[
{
"code": null,
"e": 24304,
"s": 24276,
"text": "\n12 Jun, 2020"
},
{
"code": null,
"e": 24486,
"s": 24304,
"text": "Prerequisite – Relational Algebra1. Selection :This operation chooses the subset of tuples from the relation that satisfies the given condition mentioned in the syntax of selection."
},
{
"code": null,
"e": 24497,
"s": 24486,
"text": "Notation –"
},
{
"code": null,
"e": 24504,
"s": 24497,
"text": "σc (R)"
},
{
"code": null,
"e": 24588,
"s": 24504,
"text": "Here, ‘c’ is selection condition and ‘σ (sigma)’ is used to denote Select Operator."
},
{
"code": null,
"e": 24690,
"s": 24588,
"text": "2. Projection :This operation selects certain required attributes, while discarding other attributes."
},
{
"code": null,
"e": 24701,
"s": 24690,
"text": "Notation –"
},
{
"code": null,
"e": 24708,
"s": 24701,
"text": "πA (R)"
},
{
"code": null,
"e": 24944,
"s": 24708,
"text": "where ‘A’ is the attribute list, it is the desired set of attributes from the attributes of relation(R),symbol ‘π(pi)’ is used to denote the Project operator,R is generally a relational algebra expression, which results in a relation."
},
{
"code": null,
"e": 24996,
"s": 24944,
"text": "Difference between Selection and Projection in DBMS"
},
{
"code": null,
"e": 25020,
"s": 24996,
"text": "DBMS-Relational Algebra"
},
{
"code": null,
"e": 25025,
"s": 25020,
"text": "DBMS"
},
{
"code": null,
"e": 25044,
"s": 25025,
"text": "Difference Between"
},
{
"code": null,
"e": 25052,
"s": 25044,
"text": "GATE CS"
},
{
"code": null,
"e": 25057,
"s": 25052,
"text": "DBMS"
},
{
"code": null,
"e": 25155,
"s": 25057,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25196,
"s": 25155,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 25239,
"s": 25196,
"text": "Introduction of Relational Algebra in DBMS"
},
{
"code": null,
"e": 25271,
"s": 25239,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 25298,
"s": 25271,
"text": "Two Phase Locking Protocol"
},
{
"code": null,
"e": 25325,
"s": 25298,
"text": "KDD Process in Data Mining"
},
{
"code": null,
"e": 25356,
"s": 25325,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 25396,
"s": 25356,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 25428,
"s": 25396,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 25489,
"s": 25428,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
Raspberry Pi: Dummy Tutorial on hosting a Jupyter Notebook that you can access anywhere | by JimSpark | Towards Data Science
|
This series is mainly about setting up your Raspberry Pi with a Jupyter Notebook server that you can access anywhere with open internet. And we are at the final chapter.
In the previous sessions, we have covered how to set up port forwarding or a cloud proxy server in order for you to connect to Raspberry Pi via SSH securely. And in my first article, I have also covered how TCP/IP handles different incoming traffic. Now that we know how to open up our Pi and access it via SSH, we could actually replicate the same idea. In a simple one-liner, Jupyter Notebook runs on HTTP (Which seems apparent since we all use our web browser to use Jupyter Notebook). Therefore, what we need to do is to simply open up a port for HTTP traffic from the Pi, and hook it up with the Jupyter Notebook application.
For the necessary prerequisite, go check out the article below that introduce cloud proxy server setup. I will assume that you already have a cloud proxy server registered at remote.in and are able to connect to your Pi via SSH. I want to highlight that many cloud proxy server providers offer free service for you to access your Raspberry Pi. Since you don’t really rent any server but hosting your own, the services from many providers in general are quite generous. So do check out other providers by yourself!
medium.com
And we want to do this in the most secure way. That’s why this chapter will combine all the things we have learnt so far. Not only are we gonna expose a port on our Raspberry Pi, we are also going to connect the port/Jupyter Notebook app to the cloud proxy server. From the user point of view, nothing is different, they just need to visit another URL instead of the original IP address. But from the server point of view, this gives you great security. And it really matters, since I assume most of you set up your Pi at home, which means your home network will be exposed to attack if anything goes wrong.
Again, this is just for fun. Raspberry Pi doesn’t offer a lot of computing power. But imagine you got a NVIDIA computing box, then it might actually be a good idea to set up remote access. Besides, on the data science industry, using a linux server to do ML stuff is a norm right now. And learning how to set up one just gives your lot of edge and convenience over others.
You could definitely open up the public access to your notebook app via port forwarding. But its really dangerous to do so. Since jupyter notebook generally enables “jupyter magic”, which could create, alter and delete any file on your running os, anyone intentionally visit your jupyter notebook will impose great risk equal to a SSH access.
With all the BS cover, here is the list of steps. Let's do this.
Install Jupyter Notebook on raspberry pi.
Add configuration and set up a password.
Set up an application on cloud proxy server so that you could expose your Jupyter Notebook to open internet.
The current Raspberry Pi release does not include python3-pip. So first we will need to install pip3, then jupyter. SSH into your Raspberry Pi, then run
# install pipsudo apt -y install python3-pip# install jupyterpip3 install jupyter# running pip freeze should show jupyter in the list of packages your installedpip freeze
Jupyter provides a lot of handy tools for us to deal with the setup process. It includes these 3 steps.
1. Create a password and hash it.
A good practice to host a public notebook server is to require a password every time a user visits the notebook. To do that, first, we will need to create a password, and store it securely in the web server (hence the hash part).
To create a password, please run jupyter notebook password,
$ jupyter notebook passwordEnter password: ****Verify password: ****[NotebookPasswordApp] Wrote hashed password to /Users/you/.jupyter/ jupyter_notebook_config.json
Then, use any editor to open the json, and you should see there is a hash password (start with sha1, see the picture below), please copy it now as we will need to paste it in the configuration file later.
2. Create a configuration file.
Run jupyter notebook --generate-config, a jupyter_notebook_config.py should be generated under /home/USERNAME/.jupyter/jupyter_notebook_config.py.
Use any editor to open the .py file, you should see all setting are commented, so we could simply add in any configuration we needed without conflicting any setting.
3. Add in configuration parameter.
In any line, add in the following configuration.
c.NotebookApp.allow_password_change = Truec.NotebookApp.password = u'your_copied_hash_password'c.NotebookApp.open_browser = Falsec.NotebookApp.port = 8888c.NotebookApp.allow_remote_access = True
allow_password_change: Allows you to change the password once you successfully use the password to login to your notebook server.
password: Copy the password you have just generated, remember to paste the sha hashed password, but not the literal password!
open_browser: Set it to false to prevent web server opening a browser like we normally do in our local machine.
port: The port number notebook server use. You need to remember this as we will need to expose this to the cloud proxy server.
Once done, save the file and the setup is finished! Let’s run jupyter notebook to host a notebook on the Raspberry Pi!
Most of the content covered here are on the official documentation.
In a nutshell, what a cloud proxy server does is to listen to the port you pointed to, and host a public server that you could access anywhere from open internet. Whenever you access that public server, the only thing it does is to forward your request to the application of the open port. In this case, jupyter notebook is running on port 8888 with HTTP protocol. Which means when a user visits the public cloud proxy server, the HTTP get request will be forward to your Pi at port 8888, which return the notebook website to the user.
Assuming you have a remote server set up at remote.in, we can add an HTTP application by visiting http://find.remote.it/. Select your Raspberry Pi device and you should be in the dashboard, go to setting and select your Pi there.
If you need some quick help to set up the cloud proxy server in your Raspberry Pi, the best resource is the quickstart guide from the official gitbook, or my last article that cover the setup.
Then, click Add Manually >, and fill in the new service. You could fill in any name you prefer, with a Type set to HTTP, port set to 8888 (or any port that you choose to use in your jupyter config).
Then the setup is finally finished! Now visit https://app.remote.it/, and select your Pi device, click on the service you just created.
And it should return a public URL where you can access.
Visit this website and you will access your jupyter notebook! This is not limited to the same LAN, you could literally access it anywhere from open internet now!
And this wraps up the whole series. We covered how to install a Raspberry Pi OS, setting up SSH, cloud proxy server and finally a Jupyter Notebook server. The same methodology also stands for setting up a website and other IDEs like visual studio code (technically there is a compiling issue when setting up a visual studio code as of today, which we can't really resolve by ourselves. But this is definitely possible in the future!). So do try different things out, google it and test your skills.
If you have any other side projects you would like some help on, let me know in the comment session. Thank you for reading this series.
|
[
{
"code": null,
"e": 216,
"s": 46,
"text": "This series is mainly about setting up your Raspberry Pi with a Jupyter Notebook server that you can access anywhere with open internet. And we are at the final chapter."
},
{
"code": null,
"e": 847,
"s": 216,
"text": "In the previous sessions, we have covered how to set up port forwarding or a cloud proxy server in order for you to connect to Raspberry Pi via SSH securely. And in my first article, I have also covered how TCP/IP handles different incoming traffic. Now that we know how to open up our Pi and access it via SSH, we could actually replicate the same idea. In a simple one-liner, Jupyter Notebook runs on HTTP (Which seems apparent since we all use our web browser to use Jupyter Notebook). Therefore, what we need to do is to simply open up a port for HTTP traffic from the Pi, and hook it up with the Jupyter Notebook application."
},
{
"code": null,
"e": 1361,
"s": 847,
"text": "For the necessary prerequisite, go check out the article below that introduce cloud proxy server setup. I will assume that you already have a cloud proxy server registered at remote.in and are able to connect to your Pi via SSH. I want to highlight that many cloud proxy server providers offer free service for you to access your Raspberry Pi. Since you don’t really rent any server but hosting your own, the services from many providers in general are quite generous. So do check out other providers by yourself!"
},
{
"code": null,
"e": 1372,
"s": 1361,
"text": "medium.com"
},
{
"code": null,
"e": 1980,
"s": 1372,
"text": "And we want to do this in the most secure way. That’s why this chapter will combine all the things we have learnt so far. Not only are we gonna expose a port on our Raspberry Pi, we are also going to connect the port/Jupyter Notebook app to the cloud proxy server. From the user point of view, nothing is different, they just need to visit another URL instead of the original IP address. But from the server point of view, this gives you great security. And it really matters, since I assume most of you set up your Pi at home, which means your home network will be exposed to attack if anything goes wrong."
},
{
"code": null,
"e": 2353,
"s": 1980,
"text": "Again, this is just for fun. Raspberry Pi doesn’t offer a lot of computing power. But imagine you got a NVIDIA computing box, then it might actually be a good idea to set up remote access. Besides, on the data science industry, using a linux server to do ML stuff is a norm right now. And learning how to set up one just gives your lot of edge and convenience over others."
},
{
"code": null,
"e": 2696,
"s": 2353,
"text": "You could definitely open up the public access to your notebook app via port forwarding. But its really dangerous to do so. Since jupyter notebook generally enables “jupyter magic”, which could create, alter and delete any file on your running os, anyone intentionally visit your jupyter notebook will impose great risk equal to a SSH access."
},
{
"code": null,
"e": 2761,
"s": 2696,
"text": "With all the BS cover, here is the list of steps. Let's do this."
},
{
"code": null,
"e": 2803,
"s": 2761,
"text": "Install Jupyter Notebook on raspberry pi."
},
{
"code": null,
"e": 2844,
"s": 2803,
"text": "Add configuration and set up a password."
},
{
"code": null,
"e": 2953,
"s": 2844,
"text": "Set up an application on cloud proxy server so that you could expose your Jupyter Notebook to open internet."
},
{
"code": null,
"e": 3106,
"s": 2953,
"text": "The current Raspberry Pi release does not include python3-pip. So first we will need to install pip3, then jupyter. SSH into your Raspberry Pi, then run"
},
{
"code": null,
"e": 3277,
"s": 3106,
"text": "# install pipsudo apt -y install python3-pip# install jupyterpip3 install jupyter# running pip freeze should show jupyter in the list of packages your installedpip freeze"
},
{
"code": null,
"e": 3381,
"s": 3277,
"text": "Jupyter provides a lot of handy tools for us to deal with the setup process. It includes these 3 steps."
},
{
"code": null,
"e": 3415,
"s": 3381,
"text": "1. Create a password and hash it."
},
{
"code": null,
"e": 3645,
"s": 3415,
"text": "A good practice to host a public notebook server is to require a password every time a user visits the notebook. To do that, first, we will need to create a password, and store it securely in the web server (hence the hash part)."
},
{
"code": null,
"e": 3705,
"s": 3645,
"text": "To create a password, please run jupyter notebook password,"
},
{
"code": null,
"e": 3871,
"s": 3705,
"text": "$ jupyter notebook passwordEnter password: ****Verify password: ****[NotebookPasswordApp] Wrote hashed password to /Users/you/.jupyter/ jupyter_notebook_config.json"
},
{
"code": null,
"e": 4076,
"s": 3871,
"text": "Then, use any editor to open the json, and you should see there is a hash password (start with sha1, see the picture below), please copy it now as we will need to paste it in the configuration file later."
},
{
"code": null,
"e": 4108,
"s": 4076,
"text": "2. Create a configuration file."
},
{
"code": null,
"e": 4255,
"s": 4108,
"text": "Run jupyter notebook --generate-config, a jupyter_notebook_config.py should be generated under /home/USERNAME/.jupyter/jupyter_notebook_config.py."
},
{
"code": null,
"e": 4421,
"s": 4255,
"text": "Use any editor to open the .py file, you should see all setting are commented, so we could simply add in any configuration we needed without conflicting any setting."
},
{
"code": null,
"e": 4456,
"s": 4421,
"text": "3. Add in configuration parameter."
},
{
"code": null,
"e": 4505,
"s": 4456,
"text": "In any line, add in the following configuration."
},
{
"code": null,
"e": 4700,
"s": 4505,
"text": "c.NotebookApp.allow_password_change = Truec.NotebookApp.password = u'your_copied_hash_password'c.NotebookApp.open_browser = Falsec.NotebookApp.port = 8888c.NotebookApp.allow_remote_access = True"
},
{
"code": null,
"e": 4830,
"s": 4700,
"text": "allow_password_change: Allows you to change the password once you successfully use the password to login to your notebook server."
},
{
"code": null,
"e": 4956,
"s": 4830,
"text": "password: Copy the password you have just generated, remember to paste the sha hashed password, but not the literal password!"
},
{
"code": null,
"e": 5068,
"s": 4956,
"text": "open_browser: Set it to false to prevent web server opening a browser like we normally do in our local machine."
},
{
"code": null,
"e": 5195,
"s": 5068,
"text": "port: The port number notebook server use. You need to remember this as we will need to expose this to the cloud proxy server."
},
{
"code": null,
"e": 5314,
"s": 5195,
"text": "Once done, save the file and the setup is finished! Let’s run jupyter notebook to host a notebook on the Raspberry Pi!"
},
{
"code": null,
"e": 5382,
"s": 5314,
"text": "Most of the content covered here are on the official documentation."
},
{
"code": null,
"e": 5918,
"s": 5382,
"text": "In a nutshell, what a cloud proxy server does is to listen to the port you pointed to, and host a public server that you could access anywhere from open internet. Whenever you access that public server, the only thing it does is to forward your request to the application of the open port. In this case, jupyter notebook is running on port 8888 with HTTP protocol. Which means when a user visits the public cloud proxy server, the HTTP get request will be forward to your Pi at port 8888, which return the notebook website to the user."
},
{
"code": null,
"e": 6148,
"s": 5918,
"text": "Assuming you have a remote server set up at remote.in, we can add an HTTP application by visiting http://find.remote.it/. Select your Raspberry Pi device and you should be in the dashboard, go to setting and select your Pi there."
},
{
"code": null,
"e": 6341,
"s": 6148,
"text": "If you need some quick help to set up the cloud proxy server in your Raspberry Pi, the best resource is the quickstart guide from the official gitbook, or my last article that cover the setup."
},
{
"code": null,
"e": 6540,
"s": 6341,
"text": "Then, click Add Manually >, and fill in the new service. You could fill in any name you prefer, with a Type set to HTTP, port set to 8888 (or any port that you choose to use in your jupyter config)."
},
{
"code": null,
"e": 6676,
"s": 6540,
"text": "Then the setup is finally finished! Now visit https://app.remote.it/, and select your Pi device, click on the service you just created."
},
{
"code": null,
"e": 6732,
"s": 6676,
"text": "And it should return a public URL where you can access."
},
{
"code": null,
"e": 6894,
"s": 6732,
"text": "Visit this website and you will access your jupyter notebook! This is not limited to the same LAN, you could literally access it anywhere from open internet now!"
},
{
"code": null,
"e": 7393,
"s": 6894,
"text": "And this wraps up the whole series. We covered how to install a Raspberry Pi OS, setting up SSH, cloud proxy server and finally a Jupyter Notebook server. The same methodology also stands for setting up a website and other IDEs like visual studio code (technically there is a compiling issue when setting up a visual studio code as of today, which we can't really resolve by ourselves. But this is definitely possible in the future!). So do try different things out, google it and test your skills."
}
] |
Seaborn - Histogram
|
Histograms represent the data distribution by forming bins along the range of the data and then drawing bars to show the number of observations that fall in each bin.
Seaborn comes with some datasets and we have used few datasets in our previous chapters. We have learnt how to load the dataset and how to lookup the list of available datasets.
Seaborn comes with some datasets and we have used few datasets in our previous chapters. We have learnt how to load the dataset and how to lookup the list of available datasets.
import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt
df = sb.load_dataset('iris')
sb.distplot(df['petal_length'],kde = False)
plt.show()
Here, kde flag is set to False. As a result, the representation of the kernel estimation plot will be removed and only histogram is plotted.
11 Lectures
4 hours
DATAhill Solutions Srinivas Reddy
11 Lectures
2.5 hours
DATAhill Solutions Srinivas Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2206,
"s": 2039,
"text": "Histograms represent the data distribution by forming bins along the range of the data and then drawing bars to show the number of observations that fall in each bin."
},
{
"code": null,
"e": 2384,
"s": 2206,
"text": "Seaborn comes with some datasets and we have used few datasets in our previous chapters. We have learnt how to load the dataset and how to lookup the list of available datasets."
},
{
"code": null,
"e": 2562,
"s": 2384,
"text": "Seaborn comes with some datasets and we have used few datasets in our previous chapters. We have learnt how to load the dataset and how to lookup the list of available datasets."
},
{
"code": null,
"e": 2725,
"s": 2562,
"text": "import pandas as pd\nimport seaborn as sb\nfrom matplotlib import pyplot as plt\ndf = sb.load_dataset('iris')\nsb.distplot(df['petal_length'],kde = False)\nplt.show()\n"
},
{
"code": null,
"e": 2866,
"s": 2725,
"text": "Here, kde flag is set to False. As a result, the representation of the kernel estimation plot will be removed and only histogram is plotted."
},
{
"code": null,
"e": 2899,
"s": 2866,
"text": "\n 11 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2934,
"s": 2899,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 2969,
"s": 2934,
"text": "\n 11 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3004,
"s": 2969,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 3011,
"s": 3004,
"text": " Print"
},
{
"code": null,
"e": 3022,
"s": 3011,
"text": " Add Notes"
}
] |
Pascal - Bit Operators
|
The Bitwise operators supported by Pascal are listed in the following table. Assume variable A holds 60 and variable B holds 13, then −
Please note that different implementations of Pascal differ in bitwise operators. Free Pascal, the compiler we used here, however, supports the following bitwise operators −
The following example illustrates the concept −
program beBitwise;
var
a, b, c: integer;
begin
a := 60; (* 60 = 0011 1100 *)
b := 13; (* 13 = 0000 1101 *)
c := 0;
c := a and b; (* 12 = 0000 1100 *)
writeln('Line 1 - Value of c is ', c );
c := a or b; (* 61 = 0011 1101 *)
writeln('Line 2 - Value of c is ', c );
c := not a; (* -61 = 1100 0011 *)
writeln('Line 3 - Value of c is ', c );
c := a << 2; (* 240 = 1111 0000 *)
writeln('Line 4 - Value of c is ', c );
c := a >> 2; (* 15 = 0000 1111 *)
writeln('Line 5 - Value of c is ', c );
end.
When the above code is compiled and executed, it produces the following result −
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is -61
Line 4 - Value of c is 240
Line 5 - Value of c is 15
94 Lectures
8.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2219,
"s": 2083,
"text": "The Bitwise operators supported by Pascal are listed in the following table. Assume variable A holds 60 and variable B holds 13, then −"
},
{
"code": null,
"e": 2393,
"s": 2219,
"text": "Please note that different implementations of Pascal differ in bitwise operators. Free Pascal, the compiler we used here, however, supports the following bitwise operators −"
},
{
"code": null,
"e": 2441,
"s": 2393,
"text": "The following example illustrates the concept −"
},
{
"code": null,
"e": 3025,
"s": 2441,
"text": "program beBitwise;\nvar\na, b, c: integer;\n\nbegin\n a := 60;\t(* 60 = 0011 1100 *) \n b := 13;\t(* 13 = 0000 1101 *)\n c := 0; \n\n c := a and b; (* 12 = 0000 1100 *)\n writeln('Line 1 - Value of c is ', c );\n\n c := a or b; (* 61 = 0011 1101 *)\n writeln('Line 2 - Value of c is ', c );\n\n c := not a; (* -61 = 1100 0011 *)\n writeln('Line 3 - Value of c is ', c );\n\n c := a << 2; (* 240 = 1111 0000 *)\n writeln('Line 4 - Value of c is ', c );\n\n c := a >> 2; (* 15 = 0000 1111 *)\n writeln('Line 5 - Value of c is ', c );\nend."
},
{
"code": null,
"e": 3106,
"s": 3025,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3239,
"s": 3106,
"text": "Line 1 - Value of c is 12\nLine 2 - Value of c is 61\nLine 3 - Value of c is -61\nLine 4 - Value of c is 240\nLine 5 - Value of c is 15\n"
},
{
"code": null,
"e": 3274,
"s": 3239,
"text": "\n 94 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3297,
"s": 3274,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3304,
"s": 3297,
"text": " Print"
},
{
"code": null,
"e": 3315,
"s": 3304,
"text": " Add Notes"
}
] |
power query functions, power query functions list,power query functions table, power bi functions, power query functions custom, functions apply | Towards Data Science
|
Cleaning, wrangling and summarizing. I don’t know about you but I enjoy this process of data analysis. Power Query is the main tool I use for this. I’ll be writing more about Power Query in the future.
I clean because the data is dirty. I clean because I want good data for analysis. I wrangle to get the right “shape” for joins to work. It’s dreadful if you have to clean data manually and it’s prone to cleaning errors. Imagine error on top of errors? What will you really be analyzing?
Don’t worry. Functions — much like those cute little robots on top can come to the rescue.
What exactly is a function anyways? A quick google search gives this definition.
“A function is a block of organized, reusable code that is used to perform a single, related action. ... Different programming languages name them differently, for example, functions, methods, sub-routines, procedures, etc.”
The keyword here is reusable. It has to be reusable for it to be a function. That means you can use this code and apply it to not just one file but other files as well. I think of a function as something that takes inputs, performs a custom set of procedures, and gives an output.
A lot of what you use today, for example, the sum function in Power BI to the joins are functions.
For example — take a look at this function in M (Power Query Language)
The problem is...sometimes we don’t have functions that are available to us that quite meet our needs. We want to apply a custom set of procedures to various files. This is why and when we have to use it.
Let’s go through how to create functions in Power BI in Power Query. With all the cleaning and wrangling in life, I’m sure this will be very useful to us.
As the stick figure mentioned, We have several different files across the years. we need to perform these same actions across all the files.
We don’t want to do this procedure to each one of the files but we want the function to do this for us.
To get started, let’s load in all our files in a folder.
After you’ve loaded all your files, you should see them displayed as below.
Let’s start by creating a “Duplicate” of the main file — we want to build a function from this duplicate.
Now that there is a duplicate, we keep only the first row to build the function.
Power BI keeps only the first row. Nice.
Here is a neat and important trick — you can type in [Content] which refers to the column and {0} which refers to the actual “cell” itself. If you have more of a technical understanding, I am referring to the column and returning a list, then referring to the list value 0 to return the binary file.
If you don’t like typing, you can also click on “drill down” on the binary file itself.
Power BI neatly loads the file without those automatic transformations.
Now let’s do our quick summary using group by. You can find “Group By” under the Transform Ribbon on the top of the pane.
Here is our result for one of the files.
This is exactly what we need.
Hmm... stick figures.
Not done yet, let’s make it into an actual function.
You can do this by going to the Advance Editor option under the Transform Ribbon.
Power BI records all the steps and turns it into an M script for us. If you are familiar with Excel, it’s like a recorded macro. we just need to change the reference so that it can be applied to other files.
You don’t need to know how to type out all the M code below. The beauty of Power BI is that it records all these steps for you. I will be writing a bit more about how to read M scripts in the near future.
This is the current script.
let Source = Folder.Files("MY_DRIVE"), #"Removed Top Rows" = Table.Skip(Source,1), #"Removed Other Columns" = Table.SelectColumns(#"Removed Top Rows",{"Name", "Content"}), #"Kept First Rows" = Table.FirstN(#"Removed Other Columns",1)[Content]{0}, #"Imported CSV" = Csv.Document(#"Kept First Rows",[Delimiter=",", Columns=5, Encoding=65001, QuoteStyle=QuoteStyle.None]), #"Promoted Headers" = Table.PromoteHeaders(#"Imported CSV", [PromoteAllScalars=true]), #"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",{{"Year", Int64.Type}, {"Sex", type text}, {"Name", type text}, {"Job Title", type text}, {"Salary", Int64.Type}}), #"Grouped Rows" = Table.Group(#"Changed Type", {"Year", "Sex"}, {{"Average Salary", each List.Average([Salary]), type nullable number}}), #"Rounded Off" = Table.TransformColumns(#"Grouped Rows",{{"Average Salary", each Number.Round(_, 0), type number}})in #"Rounded Off"
Don’t let this overwhelm you, the only thing we care about is the Csv.Document part.
Let’s remove everything above the Csv.Document part and declare our variable. I chose (X as binary) because we want this function to have a binary input.
Remember all those csv files on the folder? They are binary files.
This is our function!
Now let’s apply this to our files. Let’s “invoke” our custom function. You can find “invoke” under the “add column” ribbon.
Sounds like something out of Harry Potter right?
Here it is!
Let’s hit expand for our final table.
Ta-da!
Male and Female by average salary by year.
Now, this is a simple data set but you can also build in joins and other much more complex transformations into a function and apply it to all the files.
TL:DR? I built this for you.
Hope you’ve enjoyed this article.
If you’d like to watch a video instead — Curbal is a channel that has really taught me a lot about functions and of course Power BI.
Stay safe and hope this helps you with your journey with data!
|
[
{
"code": null,
"e": 374,
"s": 172,
"text": "Cleaning, wrangling and summarizing. I don’t know about you but I enjoy this process of data analysis. Power Query is the main tool I use for this. I’ll be writing more about Power Query in the future."
},
{
"code": null,
"e": 661,
"s": 374,
"text": "I clean because the data is dirty. I clean because I want good data for analysis. I wrangle to get the right “shape” for joins to work. It’s dreadful if you have to clean data manually and it’s prone to cleaning errors. Imagine error on top of errors? What will you really be analyzing?"
},
{
"code": null,
"e": 752,
"s": 661,
"text": "Don’t worry. Functions — much like those cute little robots on top can come to the rescue."
},
{
"code": null,
"e": 833,
"s": 752,
"text": "What exactly is a function anyways? A quick google search gives this definition."
},
{
"code": null,
"e": 1058,
"s": 833,
"text": "“A function is a block of organized, reusable code that is used to perform a single, related action. ... Different programming languages name them differently, for example, functions, methods, sub-routines, procedures, etc.”"
},
{
"code": null,
"e": 1339,
"s": 1058,
"text": "The keyword here is reusable. It has to be reusable for it to be a function. That means you can use this code and apply it to not just one file but other files as well. I think of a function as something that takes inputs, performs a custom set of procedures, and gives an output."
},
{
"code": null,
"e": 1438,
"s": 1339,
"text": "A lot of what you use today, for example, the sum function in Power BI to the joins are functions."
},
{
"code": null,
"e": 1509,
"s": 1438,
"text": "For example — take a look at this function in M (Power Query Language)"
},
{
"code": null,
"e": 1714,
"s": 1509,
"text": "The problem is...sometimes we don’t have functions that are available to us that quite meet our needs. We want to apply a custom set of procedures to various files. This is why and when we have to use it."
},
{
"code": null,
"e": 1869,
"s": 1714,
"text": "Let’s go through how to create functions in Power BI in Power Query. With all the cleaning and wrangling in life, I’m sure this will be very useful to us."
},
{
"code": null,
"e": 2010,
"s": 1869,
"text": "As the stick figure mentioned, We have several different files across the years. we need to perform these same actions across all the files."
},
{
"code": null,
"e": 2114,
"s": 2010,
"text": "We don’t want to do this procedure to each one of the files but we want the function to do this for us."
},
{
"code": null,
"e": 2171,
"s": 2114,
"text": "To get started, let’s load in all our files in a folder."
},
{
"code": null,
"e": 2247,
"s": 2171,
"text": "After you’ve loaded all your files, you should see them displayed as below."
},
{
"code": null,
"e": 2353,
"s": 2247,
"text": "Let’s start by creating a “Duplicate” of the main file — we want to build a function from this duplicate."
},
{
"code": null,
"e": 2434,
"s": 2353,
"text": "Now that there is a duplicate, we keep only the first row to build the function."
},
{
"code": null,
"e": 2475,
"s": 2434,
"text": "Power BI keeps only the first row. Nice."
},
{
"code": null,
"e": 2775,
"s": 2475,
"text": "Here is a neat and important trick — you can type in [Content] which refers to the column and {0} which refers to the actual “cell” itself. If you have more of a technical understanding, I am referring to the column and returning a list, then referring to the list value 0 to return the binary file."
},
{
"code": null,
"e": 2863,
"s": 2775,
"text": "If you don’t like typing, you can also click on “drill down” on the binary file itself."
},
{
"code": null,
"e": 2935,
"s": 2863,
"text": "Power BI neatly loads the file without those automatic transformations."
},
{
"code": null,
"e": 3057,
"s": 2935,
"text": "Now let’s do our quick summary using group by. You can find “Group By” under the Transform Ribbon on the top of the pane."
},
{
"code": null,
"e": 3098,
"s": 3057,
"text": "Here is our result for one of the files."
},
{
"code": null,
"e": 3128,
"s": 3098,
"text": "This is exactly what we need."
},
{
"code": null,
"e": 3150,
"s": 3128,
"text": "Hmm... stick figures."
},
{
"code": null,
"e": 3203,
"s": 3150,
"text": "Not done yet, let’s make it into an actual function."
},
{
"code": null,
"e": 3285,
"s": 3203,
"text": "You can do this by going to the Advance Editor option under the Transform Ribbon."
},
{
"code": null,
"e": 3493,
"s": 3285,
"text": "Power BI records all the steps and turns it into an M script for us. If you are familiar with Excel, it’s like a recorded macro. we just need to change the reference so that it can be applied to other files."
},
{
"code": null,
"e": 3698,
"s": 3493,
"text": "You don’t need to know how to type out all the M code below. The beauty of Power BI is that it records all these steps for you. I will be writing a bit more about how to read M scripts in the near future."
},
{
"code": null,
"e": 3726,
"s": 3698,
"text": "This is the current script."
},
{
"code": null,
"e": 4665,
"s": 3726,
"text": "let Source = Folder.Files(\"MY_DRIVE\"), #\"Removed Top Rows\" = Table.Skip(Source,1), #\"Removed Other Columns\" = Table.SelectColumns(#\"Removed Top Rows\",{\"Name\", \"Content\"}), #\"Kept First Rows\" = Table.FirstN(#\"Removed Other Columns\",1)[Content]{0}, #\"Imported CSV\" = Csv.Document(#\"Kept First Rows\",[Delimiter=\",\", Columns=5, Encoding=65001, QuoteStyle=QuoteStyle.None]), #\"Promoted Headers\" = Table.PromoteHeaders(#\"Imported CSV\", [PromoteAllScalars=true]), #\"Changed Type\" = Table.TransformColumnTypes(#\"Promoted Headers\",{{\"Year\", Int64.Type}, {\"Sex\", type text}, {\"Name\", type text}, {\"Job Title\", type text}, {\"Salary\", Int64.Type}}), #\"Grouped Rows\" = Table.Group(#\"Changed Type\", {\"Year\", \"Sex\"}, {{\"Average Salary\", each List.Average([Salary]), type nullable number}}), #\"Rounded Off\" = Table.TransformColumns(#\"Grouped Rows\",{{\"Average Salary\", each Number.Round(_, 0), type number}})in #\"Rounded Off\""
},
{
"code": null,
"e": 4750,
"s": 4665,
"text": "Don’t let this overwhelm you, the only thing we care about is the Csv.Document part."
},
{
"code": null,
"e": 4904,
"s": 4750,
"text": "Let’s remove everything above the Csv.Document part and declare our variable. I chose (X as binary) because we want this function to have a binary input."
},
{
"code": null,
"e": 4971,
"s": 4904,
"text": "Remember all those csv files on the folder? They are binary files."
},
{
"code": null,
"e": 4993,
"s": 4971,
"text": "This is our function!"
},
{
"code": null,
"e": 5117,
"s": 4993,
"text": "Now let’s apply this to our files. Let’s “invoke” our custom function. You can find “invoke” under the “add column” ribbon."
},
{
"code": null,
"e": 5166,
"s": 5117,
"text": "Sounds like something out of Harry Potter right?"
},
{
"code": null,
"e": 5178,
"s": 5166,
"text": "Here it is!"
},
{
"code": null,
"e": 5216,
"s": 5178,
"text": "Let’s hit expand for our final table."
},
{
"code": null,
"e": 5223,
"s": 5216,
"text": "Ta-da!"
},
{
"code": null,
"e": 5266,
"s": 5223,
"text": "Male and Female by average salary by year."
},
{
"code": null,
"e": 5420,
"s": 5266,
"text": "Now, this is a simple data set but you can also build in joins and other much more complex transformations into a function and apply it to all the files."
},
{
"code": null,
"e": 5449,
"s": 5420,
"text": "TL:DR? I built this for you."
},
{
"code": null,
"e": 5483,
"s": 5449,
"text": "Hope you’ve enjoyed this article."
},
{
"code": null,
"e": 5616,
"s": 5483,
"text": "If you’d like to watch a video instead — Curbal is a channel that has really taught me a lot about functions and of course Power BI."
}
] |
PyQt5 - QDock Widget
|
A dockable window is a subwindow that can remain in floating state or can be attached to the main window at a specified position. Main window object of QMainWindow class has an area reserved for dockable windows. This area is around the central widget.
A dock window can be moved inside the main window, or they can be undocked to be moved into a new area by the user. These properties are controlled by the following QDockWidget class methods −
setWidget()
Sets any QWidget in the dock window’s area
setFloating()
If set to true, the dock window can float
setAllowedAreas()
Sets the areas to which the window can be docked
setFeatures()
Sets the features of dock window
In the following example, top level window is a QMainWindow object. A QTextEdit object is its central widget.
self.setCentralWidget(QTextEdit())
A dockable window is first created.
self.items = QDockWidget("Dockable", self)
A QListWidget object is added as a dock window.
self.listWidget = QListWidget()
self.listWidget.addItem("item1")
self.listWidget.addItem("item2")
self.listWidget.addItem("item3")
self.items.setWidget(self.listWidget)
Dockable object is placed towards the right side of the central widget.
self.addDockWidget(Qt.RightDockWidgetArea, self.items)
The complete code is as follows −
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class dockdemo(QMainWindow):
def __init__(self, parent = None):
super(dockdemo, self).__init__(parent)
layout = QHBoxLayout()
bar = self.menuBar()
file = bar.addMenu("File")
file.addAction("New")
file.addAction("save")
file.addAction("quit")
self.items = QDockWidget("Dockable", self)
self.listWidget = QListWidget()
self.listWidget.addItem("item1")
self.listWidget.addItem("item2")
self.listWidget.addItem("item3")
self.items.setWidget(self.listWidget)
self.items.setFloating(False)
self.setCentralWidget(QTextEdit())
self.addDockWidget(Qt.RightDockWidgetArea, self.items)
self.setLayout(layout)
self.setWindowTitle("Dock demo")
def main():
app = QApplication(sys.argv)
ex = dockdemo()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
The above code produces the following output. Click on Dock icon to undock the ListWidget window. Double click to dock again −
146 Lectures
22.5 hours
ALAA EID
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2216,
"s": 1963,
"text": "A dockable window is a subwindow that can remain in floating state or can be attached to the main window at a specified position. Main window object of QMainWindow class has an area reserved for dockable windows. This area is around the central widget."
},
{
"code": null,
"e": 2409,
"s": 2216,
"text": "A dock window can be moved inside the main window, or they can be undocked to be moved into a new area by the user. These properties are controlled by the following QDockWidget class methods −"
},
{
"code": null,
"e": 2421,
"s": 2409,
"text": "setWidget()"
},
{
"code": null,
"e": 2464,
"s": 2421,
"text": "Sets any QWidget in the dock window’s area"
},
{
"code": null,
"e": 2478,
"s": 2464,
"text": "setFloating()"
},
{
"code": null,
"e": 2520,
"s": 2478,
"text": "If set to true, the dock window can float"
},
{
"code": null,
"e": 2538,
"s": 2520,
"text": "setAllowedAreas()"
},
{
"code": null,
"e": 2587,
"s": 2538,
"text": "Sets the areas to which the window can be docked"
},
{
"code": null,
"e": 2601,
"s": 2587,
"text": "setFeatures()"
},
{
"code": null,
"e": 2634,
"s": 2601,
"text": "Sets the features of dock window"
},
{
"code": null,
"e": 2744,
"s": 2634,
"text": "In the following example, top level window is a QMainWindow object. A QTextEdit object is its central widget."
},
{
"code": null,
"e": 2780,
"s": 2744,
"text": "self.setCentralWidget(QTextEdit())\n"
},
{
"code": null,
"e": 2816,
"s": 2780,
"text": "A dockable window is first created."
},
{
"code": null,
"e": 2860,
"s": 2816,
"text": "self.items = QDockWidget(\"Dockable\", self)\n"
},
{
"code": null,
"e": 2908,
"s": 2860,
"text": "A QListWidget object is added as a dock window."
},
{
"code": null,
"e": 3078,
"s": 2908,
"text": "self.listWidget = QListWidget()\nself.listWidget.addItem(\"item1\")\nself.listWidget.addItem(\"item2\")\nself.listWidget.addItem(\"item3\")\nself.items.setWidget(self.listWidget)\n"
},
{
"code": null,
"e": 3150,
"s": 3078,
"text": "Dockable object is placed towards the right side of the central widget."
},
{
"code": null,
"e": 3206,
"s": 3150,
"text": "self.addDockWidget(Qt.RightDockWidgetArea, self.items)\n"
},
{
"code": null,
"e": 3240,
"s": 3206,
"text": "The complete code is as follows −"
},
{
"code": null,
"e": 4228,
"s": 3240,
"text": "import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\nclass dockdemo(QMainWindow):\n def __init__(self, parent = None):\n super(dockdemo, self).__init__(parent)\n\t\t\n layout = QHBoxLayout()\n bar = self.menuBar()\n file = bar.addMenu(\"File\")\n file.addAction(\"New\")\n file.addAction(\"save\")\n file.addAction(\"quit\")\n\t\t\n self.items = QDockWidget(\"Dockable\", self)\n self.listWidget = QListWidget()\n self.listWidget.addItem(\"item1\")\n self.listWidget.addItem(\"item2\")\n self.listWidget.addItem(\"item3\")\n\t\t\n self.items.setWidget(self.listWidget)\n self.items.setFloating(False)\n self.setCentralWidget(QTextEdit())\n self.addDockWidget(Qt.RightDockWidgetArea, self.items)\n self.setLayout(layout)\n self.setWindowTitle(\"Dock demo\")\n\t\t\ndef main():\n app = QApplication(sys.argv)\n ex = dockdemo()\n ex.show()\n sys.exit(app.exec_())\n\t\nif __name__ == '__main__':\n main()"
},
{
"code": null,
"e": 4355,
"s": 4228,
"text": "The above code produces the following output. Click on Dock icon to undock the ListWidget window. Double click to dock again −"
},
{
"code": null,
"e": 4392,
"s": 4355,
"text": "\n 146 Lectures \n 22.5 hours \n"
},
{
"code": null,
"e": 4402,
"s": 4392,
"text": " ALAA EID"
},
{
"code": null,
"e": 4409,
"s": 4402,
"text": " Print"
},
{
"code": null,
"e": 4420,
"s": 4409,
"text": " Add Notes"
}
] |
How to remove onClickListener for a view in android?
|
In some situations, We should not allow onClickListener for a view. This example demonstrates how to remove onClickListener for a view in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/acitivity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:id = "@+id/parent"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:gravity = "center"
android:orientation = "vertical">
<TextView
android:id = "@+id/text"
android:textSize = "28sp"
android:textAlignment = "center"
android:layout_width = "match_parent"
android:layout_height = "wrap_content" />
</LinearLayout>
In the above code, we have taken a text view, In this example, we should remove onClickListner for this text view.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int view = R.layout.activity_main;
TextView textview;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(view);
textview = findViewById(R.id.text);
textview.setText("There is no Click listner for text view");
textview.setOnClickListener(null);
}
}
In the above example, we are passing a null value to setOnClickListener(), so it will don't perform any action when a user clicks on the text view.
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 −
In the above screen click on text view, it will show nothing because we have sent a null value for setOnClickListener().
|
[
{
"code": null,
"e": 1209,
"s": 1062,
"text": "In some situations, We should not allow onClickListener for a view. This example demonstrates how to remove onClickListener for a view in android."
},
{
"code": null,
"e": 1338,
"s": 1209,
"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": 1404,
"s": 1338,
"text": "Step 2 − Add the following code to res/layout/acitivity_main.xml."
},
{
"code": null,
"e": 2012,
"s": 1404,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n android:id = \"@+id/parent\"\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:gravity = \"center\"\n android:orientation = \"vertical\">\n <TextView\n android:id = \"@+id/text\"\n android:textSize = \"28sp\"\n android:textAlignment = \"center\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2127,
"s": 2012,
"text": "In the above code, we have taken a text view, In this example, we should remove onClickListner for this text view."
},
{
"code": null,
"e": 2184,
"s": 2127,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2909,
"s": 2184,
"text": "package com.example.andy.myapplication;\nimport android.content.res.Configuration;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n int view = R.layout.activity_main;\n TextView textview;\n @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(view);\n textview = findViewById(R.id.text);\n textview.setText(\"There is no Click listner for text view\");\n textview.setOnClickListener(null);\n }\n}"
},
{
"code": null,
"e": 3057,
"s": 2909,
"text": "In the above example, we are passing a null value to setOnClickListener(), so it will don't perform any action when a user clicks on the text view."
},
{
"code": null,
"e": 3404,
"s": 3057,
"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": 3525,
"s": 3404,
"text": "In the above screen click on text view, it will show nothing because we have sent a null value for setOnClickListener()."
}
] |
Avoid duplicate entries in MongoDB?
|
To avoid duplicate entries in MongoDB, you can use createIndex(). The syntax is as follows −
db.yourCollectionName.createIndex({"yourFieldName":1},{unique:true});
Let us implement the above syntax. The query to avoid duplicate entries in MongoDB is a follows −
> db.avoidDuplicateEntriesDemo.createIndex({"UserName":1},{unique:true});
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
Now insert some records in the above collection. The query to insert record is as follows −
> db.avoidDuplicateEntriesDemo.insertOne({"UserName":"John"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90e1824afe5c1d2279d697")
}
Here is the error whenever you try to insert the same record once again −
> db.avoidDuplicateEntriesDemo.insertOne({"UserName":"John"});
2019-03-19T18:03:08.465+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: test.avoidDuplicateEntriesDemo index: UserName_1 dup key: { : "John" } :
WriteError({
"index" : 0,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: test.avoidDuplicateEntriesDemo index: UserName_1 dup key: { : \"John\" }",
"op" : {
"_id" : ObjectId("5c90e1844afe5c1d2279d698"),
"UserName" : "John"
}
})
WriteError@src/mongo/shell/bulk_api.js:461:48
Bulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49
Bulk/executeBatch@src/mongo/shell/bulk_api.js:906:13
Bulk/this.execute@src/mongo/shell/bulk_api.js:1150:21
DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:252:9
@(shell):1:1
Let us insert another record. The query is as follows −
> db.avoidDuplicateEntriesDemo.insertOne({"UserName":"Carol"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90e18d4afe5c1d2279d699")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.avoidDuplicateEntriesDemo.find();
The following is the output −
{ "_id" : ObjectId("5c90e1824afe5c1d2279d697"), "UserName" : "John" }
{ "_id" : ObjectId("5c90e18d4afe5c1d2279d699"), "UserName" : "Carol" }
|
[
{
"code": null,
"e": 1155,
"s": 1062,
"text": "To avoid duplicate entries in MongoDB, you can use createIndex(). The syntax is as follows −"
},
{
"code": null,
"e": 1225,
"s": 1155,
"text": "db.yourCollectionName.createIndex({\"yourFieldName\":1},{unique:true});"
},
{
"code": null,
"e": 1323,
"s": 1225,
"text": "Let us implement the above syntax. The query to avoid duplicate entries in MongoDB is a follows −"
},
{
"code": null,
"e": 1510,
"s": 1323,
"text": "> db.avoidDuplicateEntriesDemo.createIndex({\"UserName\":1},{unique:true});\n{\n \"createdCollectionAutomatically\" : true,\n \"numIndexesBefore\" : 1,\n \"numIndexesAfter\" : 2,\n \"ok\" : 1\n}"
},
{
"code": null,
"e": 1602,
"s": 1510,
"text": "Now insert some records in the above collection. The query to insert record is as follows −"
},
{
"code": null,
"e": 1750,
"s": 1602,
"text": "> db.avoidDuplicateEntriesDemo.insertOne({\"UserName\":\"John\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c90e1824afe5c1d2279d697\")\n}"
},
{
"code": null,
"e": 1824,
"s": 1750,
"text": "Here is the error whenever you try to insert the same record once again −"
},
{
"code": null,
"e": 2619,
"s": 1824,
"text": "> db.avoidDuplicateEntriesDemo.insertOne({\"UserName\":\"John\"});\n2019-03-19T18:03:08.465+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: test.avoidDuplicateEntriesDemo index: UserName_1 dup key: { : \"John\" } :\nWriteError({\n \"index\" : 0,\n \"code\" : 11000,\n \"errmsg\" : \"E11000 duplicate key error collection: test.avoidDuplicateEntriesDemo index: UserName_1 dup key: { : \\\"John\\\" }\",\n \"op\" : {\n \"_id\" : ObjectId(\"5c90e1844afe5c1d2279d698\"),\n \"UserName\" : \"John\"\n }\n})\nWriteError@src/mongo/shell/bulk_api.js:461:48\nBulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49\nBulk/executeBatch@src/mongo/shell/bulk_api.js:906:13\nBulk/this.execute@src/mongo/shell/bulk_api.js:1150:21\nDBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:252:9\n@(shell):1:1"
},
{
"code": null,
"e": 2675,
"s": 2619,
"text": "Let us insert another record. The query is as follows −"
},
{
"code": null,
"e": 2824,
"s": 2675,
"text": "> db.avoidDuplicateEntriesDemo.insertOne({\"UserName\":\"Carol\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c90e18d4afe5c1d2279d699\")\n}"
},
{
"code": null,
"e": 2922,
"s": 2824,
"text": "Display all documents from a collection with the help of find() method. The query is as follows −"
},
{
"code": null,
"e": 2961,
"s": 2922,
"text": "> db.avoidDuplicateEntriesDemo.find();"
},
{
"code": null,
"e": 2991,
"s": 2961,
"text": "The following is the output −"
},
{
"code": null,
"e": 3132,
"s": 2991,
"text": "{ \"_id\" : ObjectId(\"5c90e1824afe5c1d2279d697\"), \"UserName\" : \"John\" }\n{ \"_id\" : ObjectId(\"5c90e18d4afe5c1d2279d699\"), \"UserName\" : \"Carol\" }"
}
] |
Visualizing Tiff File Using Matplotlib and GDAL using Python - GeeksforGeeks
|
12 Nov, 2020
Tiff file formats are used for storing raster images. A library called GDAL- Geospatial Data Abstraction Library is specially used for the purpose of reading such raster files along with other file formats like vector formats. The gdal module belongs to Open Source Geospatial Foundation
To install this module run this command into your terminal.
pip install GDAL
To visualize a tiff file we need matplotlib and GDAL modules in python.
Import the moduleCount the number of bands.Fetch all the raster bands from the tiff file.Read the bands into NumPy arrays.Pass the arrays into Matplotlib’s imshow() to visualize.
Import the module
Count the number of bands.
Fetch all the raster bands from the tiff file.
Read the bands into NumPy arrays.
Pass the arrays into Matplotlib’s imshow() to visualize.
The tiff file can be downloaded from here.
Step 1: Import the modules and open the file.
Python3
from osgeo import gdalimport matplotlib.pyplot as plt dataset = gdal.Open(r'land_shallow_topo_2048.tif')
Step 2: Count the number of bands.
Python3
print(dataset.RasterCount)
Output:
3
Step 3: Fetch the bands,
To fetch the bands we use GDAL’s GetRasterBand(int). Note that the value of int we pass will always start from 1 (indexing of bands starts from 1),
Python3
# since there are 3 bands# we store in 3 different variablesband1 = dataset.GetRasterBand(1) # Red channelband2 = dataset.GetRasterBand(2) # Green channelband3 = dataset.GetRasterBand(3) # Blue channel
Step 4: Read the bands as Numpy arrays.
GDAL provides ReadAsArray() method that converts the bands into numpy arrays and returns them.
Python3
b1 = band1.ReadAsArray()b2 = band2.ReadAsArray()b3 = band3.ReadAsArray()
Step 5: Plotting the arrays using imshow().
To plot the three arrays we will stack them in sequence.
Python3
img = np.dstack((b1, b2, b3))f = plt.figure()plt.imshow(img)plt.savefig('Tiff.png')plt.show()
Output:
Data Visualization
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n12 Nov, 2020"
},
{
"code": null,
"e": 25825,
"s": 25537,
"text": "Tiff file formats are used for storing raster images. A library called GDAL- Geospatial Data Abstraction Library is specially used for the purpose of reading such raster files along with other file formats like vector formats. The gdal module belongs to Open Source Geospatial Foundation"
},
{
"code": null,
"e": 25886,
"s": 25825,
"text": "To install this module run this command into your terminal. "
},
{
"code": null,
"e": 25904,
"s": 25886,
"text": "pip install GDAL\n"
},
{
"code": null,
"e": 25977,
"s": 25904,
"text": "To visualize a tiff file we need matplotlib and GDAL modules in python. "
},
{
"code": null,
"e": 26156,
"s": 25977,
"text": "Import the moduleCount the number of bands.Fetch all the raster bands from the tiff file.Read the bands into NumPy arrays.Pass the arrays into Matplotlib’s imshow() to visualize."
},
{
"code": null,
"e": 26174,
"s": 26156,
"text": "Import the module"
},
{
"code": null,
"e": 26201,
"s": 26174,
"text": "Count the number of bands."
},
{
"code": null,
"e": 26248,
"s": 26201,
"text": "Fetch all the raster bands from the tiff file."
},
{
"code": null,
"e": 26282,
"s": 26248,
"text": "Read the bands into NumPy arrays."
},
{
"code": null,
"e": 26339,
"s": 26282,
"text": "Pass the arrays into Matplotlib’s imshow() to visualize."
},
{
"code": null,
"e": 26382,
"s": 26339,
"text": "The tiff file can be downloaded from here."
},
{
"code": null,
"e": 26428,
"s": 26382,
"text": "Step 1: Import the modules and open the file."
},
{
"code": null,
"e": 26436,
"s": 26428,
"text": "Python3"
},
{
"code": "from osgeo import gdalimport matplotlib.pyplot as plt dataset = gdal.Open(r'land_shallow_topo_2048.tif')",
"e": 26544,
"s": 26436,
"text": null
},
{
"code": null,
"e": 26579,
"s": 26544,
"text": "Step 2: Count the number of bands."
},
{
"code": null,
"e": 26587,
"s": 26579,
"text": "Python3"
},
{
"code": "print(dataset.RasterCount)",
"e": 26614,
"s": 26587,
"text": null
},
{
"code": null,
"e": 26622,
"s": 26614,
"text": "Output:"
},
{
"code": null,
"e": 26625,
"s": 26622,
"text": "3\n"
},
{
"code": null,
"e": 26650,
"s": 26625,
"text": "Step 3: Fetch the bands,"
},
{
"code": null,
"e": 26799,
"s": 26650,
"text": "To fetch the bands we use GDAL’s GetRasterBand(int). Note that the value of int we pass will always start from 1 (indexing of bands starts from 1), "
},
{
"code": null,
"e": 26807,
"s": 26799,
"text": "Python3"
},
{
"code": "# since there are 3 bands# we store in 3 different variablesband1 = dataset.GetRasterBand(1) # Red channelband2 = dataset.GetRasterBand(2) # Green channelband3 = dataset.GetRasterBand(3) # Blue channel",
"e": 27009,
"s": 26807,
"text": null
},
{
"code": null,
"e": 27049,
"s": 27009,
"text": "Step 4: Read the bands as Numpy arrays."
},
{
"code": null,
"e": 27146,
"s": 27049,
"text": " GDAL provides ReadAsArray() method that converts the bands into numpy arrays and returns them. "
},
{
"code": null,
"e": 27154,
"s": 27146,
"text": "Python3"
},
{
"code": "b1 = band1.ReadAsArray()b2 = band2.ReadAsArray()b3 = band3.ReadAsArray()",
"e": 27227,
"s": 27154,
"text": null
},
{
"code": null,
"e": 27271,
"s": 27227,
"text": "Step 5: Plotting the arrays using imshow()."
},
{
"code": null,
"e": 27329,
"s": 27271,
"text": "To plot the three arrays we will stack them in sequence. "
},
{
"code": null,
"e": 27337,
"s": 27329,
"text": "Python3"
},
{
"code": "img = np.dstack((b1, b2, b3))f = plt.figure()plt.imshow(img)plt.savefig('Tiff.png')plt.show()",
"e": 27431,
"s": 27337,
"text": null
},
{
"code": null,
"e": 27439,
"s": 27431,
"text": "Output:"
},
{
"code": null,
"e": 27458,
"s": 27439,
"text": "Data Visualization"
},
{
"code": null,
"e": 27476,
"s": 27458,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 27483,
"s": 27476,
"text": "Python"
},
{
"code": null,
"e": 27581,
"s": 27483,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27613,
"s": 27581,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27655,
"s": 27613,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27697,
"s": 27655,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27724,
"s": 27697,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27780,
"s": 27724,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27802,
"s": 27780,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27841,
"s": 27802,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27872,
"s": 27841,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27901,
"s": 27872,
"text": "Create a directory in Python"
}
] |
ByteArrayOutputStream toByteArray() method in Java with Examples - GeeksforGeeks
|
28 May, 2020
The toByteArray() method of ByteArrayOutputStream class in Java is used to create a newly allocated byte array. The size of the newly allocated byte array is equal to the current size of this output stream. This method copies valid contents of the buffer into it.
Syntax:
public byte[] toByteArray()
Parameters: This method does not accept any parameter.
Return value: The method returns newly allocated byte array which has the valid contents of this output stream.
Exceptions: This method does not throw any exception.
Below programs illustrate toByteArray() method in ByteArrayOutputStream class in IO package:
Program 1:
// Java program to illustrate// ByteArrayOutputStream toByteArray() method import java.io.*; public class GFG { public static void main(String[] args) throws Exception { // Create byteArrayOutputStream ByteArrayOutputStream byteArrayOutStr = new ByteArrayOutputStream(); // Create byte array byte[] buf = { 71, 69, 69, 75, 83 }; // Write byte array // to byteArrayOutputStream byteArrayOutStr.write(buf); for (byte b : byteArrayOutStr .toByteArray()) { // Print the byte System.out.println((char)b); } }}
G
E
E
K
S
Program 2:
// Java program to illustrate// ByteArrayOutputStream toByteArray() method import java.io.*; public class GFG { public static void main(String[] args) throws Exception { // Create byteArrayOutputStream ByteArrayOutputStream byteArrayOutStr = new ByteArrayOutputStream(); // Create byte array byte[] buf = { 71, 69, 69, 75, 83, 70, 79, 82, 71, 69, 69, 75, 83 }; // Write byte array // to byteArrayOutputStream byteArrayOutStr.write(buf); for (byte b : byteArrayOutStr .toByteArray()) { // Print the byte System.out.println((char)b); } }}
G
E
E
K
S
F
O
R
G
E
E
K
S
References:https://docs.oracle.com/javase/10/docs/api/java/io/ByteArrayOutputStream.html#toByteArray()
Java-Functions
Java-IO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n28 May, 2020"
},
{
"code": null,
"e": 25489,
"s": 25225,
"text": "The toByteArray() method of ByteArrayOutputStream class in Java is used to create a newly allocated byte array. The size of the newly allocated byte array is equal to the current size of this output stream. This method copies valid contents of the buffer into it."
},
{
"code": null,
"e": 25497,
"s": 25489,
"text": "Syntax:"
},
{
"code": null,
"e": 25526,
"s": 25497,
"text": "public byte[] toByteArray()\n"
},
{
"code": null,
"e": 25581,
"s": 25526,
"text": "Parameters: This method does not accept any parameter."
},
{
"code": null,
"e": 25693,
"s": 25581,
"text": "Return value: The method returns newly allocated byte array which has the valid contents of this output stream."
},
{
"code": null,
"e": 25747,
"s": 25693,
"text": "Exceptions: This method does not throw any exception."
},
{
"code": null,
"e": 25840,
"s": 25747,
"text": "Below programs illustrate toByteArray() method in ByteArrayOutputStream class in IO package:"
},
{
"code": null,
"e": 25851,
"s": 25840,
"text": "Program 1:"
},
{
"code": "// Java program to illustrate// ByteArrayOutputStream toByteArray() method import java.io.*; public class GFG { public static void main(String[] args) throws Exception { // Create byteArrayOutputStream ByteArrayOutputStream byteArrayOutStr = new ByteArrayOutputStream(); // Create byte array byte[] buf = { 71, 69, 69, 75, 83 }; // Write byte array // to byteArrayOutputStream byteArrayOutStr.write(buf); for (byte b : byteArrayOutStr .toByteArray()) { // Print the byte System.out.println((char)b); } }}",
"e": 26505,
"s": 25851,
"text": null
},
{
"code": null,
"e": 26516,
"s": 26505,
"text": "G\nE\nE\nK\nS\n"
},
{
"code": null,
"e": 26527,
"s": 26516,
"text": "Program 2:"
},
{
"code": "// Java program to illustrate// ByteArrayOutputStream toByteArray() method import java.io.*; public class GFG { public static void main(String[] args) throws Exception { // Create byteArrayOutputStream ByteArrayOutputStream byteArrayOutStr = new ByteArrayOutputStream(); // Create byte array byte[] buf = { 71, 69, 69, 75, 83, 70, 79, 82, 71, 69, 69, 75, 83 }; // Write byte array // to byteArrayOutputStream byteArrayOutStr.write(buf); for (byte b : byteArrayOutStr .toByteArray()) { // Print the byte System.out.println((char)b); } }}",
"e": 27257,
"s": 26527,
"text": null
},
{
"code": null,
"e": 27284,
"s": 27257,
"text": "G\nE\nE\nK\nS\nF\nO\nR\nG\nE\nE\nK\nS\n"
},
{
"code": null,
"e": 27387,
"s": 27284,
"text": "References:https://docs.oracle.com/javase/10/docs/api/java/io/ByteArrayOutputStream.html#toByteArray()"
},
{
"code": null,
"e": 27402,
"s": 27387,
"text": "Java-Functions"
},
{
"code": null,
"e": 27418,
"s": 27402,
"text": "Java-IO package"
},
{
"code": null,
"e": 27423,
"s": 27418,
"text": "Java"
},
{
"code": null,
"e": 27428,
"s": 27423,
"text": "Java"
},
{
"code": null,
"e": 27526,
"s": 27428,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27541,
"s": 27526,
"text": "Stream In Java"
},
{
"code": null,
"e": 27562,
"s": 27541,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27581,
"s": 27562,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27611,
"s": 27581,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27657,
"s": 27611,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27674,
"s": 27657,
"text": "Generics in Java"
},
{
"code": null,
"e": 27695,
"s": 27674,
"text": "Introduction to Java"
},
{
"code": null,
"e": 27738,
"s": 27695,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27774,
"s": 27738,
"text": "Internal Working of HashMap in Java"
}
] |
How to Request Permissions in Android Application? - GeeksforGeeks
|
30 Apr, 2021
Starting from Android 6.0 (API 23), users are not asked for permissions at the time of installation rather developers need to request the permissions at the run time. Only the permissions that are defined in the manifest file can be requested at run time.
1. Install-Time Permissions: If the Android 5.1.1 (API 22) or lower, the permission is requested at the installation time at the Google Play Store.
If the user Accepts the permissions, the app is installed. Else the app installation is canceled.
2. Run-Time Permissions: If the Android 6 (API 23) or higher, the permission is requested at the run time during the running of the app.
If the user Accepts the permissions, then that feature of the app can be used. Else to use the feature, the app requests permission again.
So, now the permissions are requested at runtime. In this article, we will discuss how to request permissions in an Android Application at run time.
Step 1: Declare the permission in the Android Manifest file: In Android, permissions are declared in the AndroidManifest.xml file using the uses-permission tag.
<uses-permission android:name=”android.permission.PERMISSION_NAME”/>
Here we are declaring storage and camera permission.
XML
<!--Declaring the required permissions--><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.CAMERA" />
Step 2: Modify activity_main.xml file to Add two buttons to request permission on button click: Permission will be checked and requested on button click. Open the activity_main.xml file and add two buttons to it.
XML
<!--Button to request storage permission--><Button android:id="@+id/storage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Storage" android:layout_marginTop="16dp" android:padding="8dp" android:layout_below="@id/toolbar" android:layout_centerHorizontal="true"/> <!--Button to request camera permission--><Button android:id="@+id/camera" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Camera" android:layout_marginTop="16dp" android:padding="8dp" android:layout_below="@id/storage" android:layout_centerHorizontal="true"/>
Step 3: Check whether permission is already granted or not. If permission isn’t already granted, request the user for the permission: In order to use any service or feature, the permissions are required. Hence we have to ensure that the permissions are given for that. If not, then the permissions are requested.
Check for permissions: Beginning with Android 6.0 (API level 23), the user has the right to revoke permissions from any app at any time, even if the app targets a lower API level. So to use the service, the app needs to check for permissions every time.
Syntax:
if(ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.WRITE_CALENDAR)
!= PackageManager.PERMISSION_GRANTED)
{
// Permission is not granted
}
Request Permissions: When PERMISSION_DENIED is returned from the checkSelfPermission() method in the above syntax, we need to prompt the user for that permission. Android provides several methods that can be used to request permission, such as requestPermissions().
Syntax:
ActivityCompat.requestPermissions(MainActivity.this,
permissionArray,
requestCode);
Here permissionArray is an array of type String.
Example:
Java
Kotlin
// Function to check and request permissionpublic void checkPermission(String permission, int requestCode){ // Checking if permission is not granted if (ContextCompat.checkSelfPermission(MainActivity.this, permission) == PackageManager.PERMISSION_DENIED) { ActivityCompat.requestPermissions(MainActivity.this, new String[] { permission }, requestCode); } else { Toast.makeText(MainActivity.this, "Permission already granted", Toast.LENGTH_SHORT).show(); }}
// Function to check and request permission.private fun checkPermission(permission: String, requestCode: Int) { if (ContextCompat.checkSelfPermission(this@MainActivity, permission) == PackageManager.PERMISSION_DENIED) { // Requesting the permission ActivityCompat.requestPermissions(this@MainActivity, arrayOf(permission), requestCode) } else { Toast.makeText(this@MainActivity, "Permission already granted", Toast.LENGTH_SHORT).show() } }
This function will show a Toast message if permission is already granted otherwise prompt the user for permission.
Step 4: Override onRequestPermissionsResult() method: onRequestPermissionsResult() is called when user grant or decline the permission. RequestCode is one of the parameters of this function which is used to check user action for the corresponding requests. Here a toast message is shown indicating the permission and user action.
Example:
Java
Kotlin
// This function is called when user accept or decline the permission.// Request Code is used to check which permission called this function.// This request code is provided when user is prompt for permission.@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults){ super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == CAMERA_PERMISSION_CODE) { // Checking whether user granted the permission or not. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Showing the toast message Toast.makeText(MainActivity.this, "Camera Permission Granted", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Camera Permission Denied", Toast.LENGTH_SHORT).show(); } } else if (requestCode == STORAGE_PERMISSION_CODE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(MainActivity.this, "Storage Permission Granted", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Storage Permission Denied", Toast.LENGTH_SHORT).show(); } }}
// This function is called when the user accepts or decline the permission.// Request Code is used to check which permission called this function.// This request code is provided when the user is prompt for permission.override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == CAMERA_PERMISSION_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this@MainActivity, "Camera Permission Granted", Toast.LENGTH_SHORT).show() } else { Toast.makeText(this@MainActivity, "Camera Permission Denied", Toast.LENGTH_SHORT).show() } } else if (requestCode == STORAGE_PERMISSION_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this@MainActivity, "Storage Permission Granted", Toast.LENGTH_SHORT).show() } else { Toast.makeText(this@MainActivity, "Storage Permission Denied", Toast.LENGTH_SHORT).show() } }}
Below is the complete code of this application:
Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- To show toolbar--> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:background="@color/colorPrimary" app:title="GFG | Permission Example" app:titleTextColor="@android:color/white" android:layout_height="?android:attr/actionBarSize"/> <!--Button to request storage permission--> <Button android:id="@+id/storage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Storage" android:layout_marginTop="16dp" android:padding="8dp" android:layout_below="@id/toolbar" android:layout_centerHorizontal="true"/> <!--Button to request camera permission--> <Button android:id="@+id/camera" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Camera" android:layout_marginTop="16dp" android:padding="8dp" android:layout_below="@id/storage" android:layout_centerHorizontal="true"/> </RelativeLayout>
Below is the code for the AndroidManifest.xml file.
XML
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.geeksforgeeks.requestPermission"> <!--Declaring the required permissions--> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.CAMERA" /> <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>
Below is the code for the MainActivity file.
Kotlin
Java
import android.Manifestimport android.content.pm.PackageManagerimport android.os.Bundleimport android.widget.Buttonimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport androidx.core.app.ActivityCompatimport androidx.core.content.ContextCompat class MainActivity : AppCompatActivity() { companion object { private const val CAMERA_PERMISSION_CODE = 100 private const val STORAGE_PERMISSION_CODE = 101 } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Defining Buttons val storage: Button? = findViewById(R.id.storage) val camera: Button? = findViewById(R.id.camera) // Set Buttons on Click Listeners storage?.setOnClickListener {checkPermission( Manifest.permission.WRITE_EXTERNAL_STORAGE, STORAGE_PERMISSION_CODE) } camera?.setOnClickListener { checkPermission(Manifest.permission.CAMERA, CAMERA_PERMISSION_CODE) } } // Function to check and request permission. private fun checkPermission(permission: String, requestCode: Int) { if (ContextCompat.checkSelfPermission(this@MainActivity, permission) == PackageManager.PERMISSION_DENIED) { // Requesting the permission ActivityCompat.requestPermissions(this@MainActivity, arrayOf(permission), requestCode) } else { Toast.makeText(this@MainActivity, "Permission already granted", Toast.LENGTH_SHORT).show() } } // This function is called when the user accepts or decline the permission. // Request Code is used to check which permission called this function. // This request code is provided when the user is prompt for permission. override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == CAMERA_PERMISSION_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this@MainActivity, "Camera Permission Granted", Toast.LENGTH_SHORT).show() } else { Toast.makeText(this@MainActivity, "Camera Permission Denied", Toast.LENGTH_SHORT).show() } } else if (requestCode == STORAGE_PERMISSION_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this@MainActivity, "Storage Permission Granted", Toast.LENGTH_SHORT).show() } else { Toast.makeText(this@MainActivity, "Storage Permission Denied", Toast.LENGTH_SHORT).show() } } }}
import android.Manifest;import android.content.pm.PackageManager;import android.support.annotation.NonNull;import android.support.v4.app.ActivityCompat;import android.support.v4.content.ContextCompat;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast; public class MainActivity extends AppCompatActivity { // Defining Buttons private Button storage, camera; // Defining Permission codes. // We can give any value // but unique for each permission. private static final int CAMERA_PERMISSION_CODE = 100; private static final int STORAGE_PERMISSION_CODE = 101; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); storage = findViewById(R.id.storage); camera = findViewById(R.id.camera); // Set Buttons on Click Listeners storage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, STORAGE_PERMISSION_CODE); } }); camera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { checkPermission(Manifest.permission.CAMERA, CAMERA_PERMISSION_CODE); } }); } // Function to check and request permission. public void checkPermission(String permission, int requestCode) { if (ContextCompat.checkSelfPermission(MainActivity.this, permission) == PackageManager.PERMISSION_DENIED) { // Requesting the permission ActivityCompat.requestPermissions(MainActivity.this, new String[] { permission }, requestCode); } else { Toast.makeText(MainActivity.this, "Permission already granted", Toast.LENGTH_SHORT).show(); } } // This function is called when the user accepts or decline the permission. // Request Code is used to check which permission called this function. // This request code is provided when the user is prompt for permission. @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == CAMERA_PERMISSION_CODE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(MainActivity.this, "Camera Permission Granted", Toast.LENGTH_SHORT) .show(); } else { Toast.makeText(MainActivity.this, "Camera Permission Denied", Toast.LENGTH_SHORT) .show(); } } else if (requestCode == STORAGE_PERMISSION_CODE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(MainActivity.this, "Storage Permission Granted", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Storage Permission Denied", Toast.LENGTH_SHORT).show(); } } }}
Output:
On starting the application:
On clicking the camera button for the first time:
On Granting the permission:
On clicking the camera button again:
aashaypawar
android
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": 25876,
"s": 25848,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 26132,
"s": 25876,
"text": "Starting from Android 6.0 (API 23), users are not asked for permissions at the time of installation rather developers need to request the permissions at the run time. Only the permissions that are defined in the manifest file can be requested at run time."
},
{
"code": null,
"e": 26280,
"s": 26132,
"text": "1. Install-Time Permissions: If the Android 5.1.1 (API 22) or lower, the permission is requested at the installation time at the Google Play Store."
},
{
"code": null,
"e": 26378,
"s": 26280,
"text": "If the user Accepts the permissions, the app is installed. Else the app installation is canceled."
},
{
"code": null,
"e": 26515,
"s": 26378,
"text": "2. Run-Time Permissions: If the Android 6 (API 23) or higher, the permission is requested at the run time during the running of the app."
},
{
"code": null,
"e": 26654,
"s": 26515,
"text": "If the user Accepts the permissions, then that feature of the app can be used. Else to use the feature, the app requests permission again."
},
{
"code": null,
"e": 26804,
"s": 26654,
"text": "So, now the permissions are requested at runtime. In this article, we will discuss how to request permissions in an Android Application at run time. "
},
{
"code": null,
"e": 26966,
"s": 26804,
"text": "Step 1: Declare the permission in the Android Manifest file: In Android, permissions are declared in the AndroidManifest.xml file using the uses-permission tag. "
},
{
"code": null,
"e": 27035,
"s": 26966,
"text": "<uses-permission android:name=”android.permission.PERMISSION_NAME”/>"
},
{
"code": null,
"e": 27088,
"s": 27035,
"text": "Here we are declaring storage and camera permission."
},
{
"code": null,
"e": 27092,
"s": 27088,
"text": "XML"
},
{
"code": "<!--Declaring the required permissions--><uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\" /><uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" /><uses-permission android:name=\"android.permission.CAMERA\" />",
"e": 27345,
"s": 27092,
"text": null
},
{
"code": null,
"e": 27558,
"s": 27345,
"text": "Step 2: Modify activity_main.xml file to Add two buttons to request permission on button click: Permission will be checked and requested on button click. Open the activity_main.xml file and add two buttons to it."
},
{
"code": null,
"e": 27562,
"s": 27558,
"text": "XML"
},
{
"code": "<!--Button to request storage permission--><Button android:id=\"@+id/storage\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Storage\" android:layout_marginTop=\"16dp\" android:padding=\"8dp\" android:layout_below=\"@id/toolbar\" android:layout_centerHorizontal=\"true\"/> <!--Button to request camera permission--><Button android:id=\"@+id/camera\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Camera\" android:layout_marginTop=\"16dp\" android:padding=\"8dp\" android:layout_below=\"@id/storage\" android:layout_centerHorizontal=\"true\"/>",
"e": 28213,
"s": 27562,
"text": null
},
{
"code": null,
"e": 28526,
"s": 28213,
"text": "Step 3: Check whether permission is already granted or not. If permission isn’t already granted, request the user for the permission: In order to use any service or feature, the permissions are required. Hence we have to ensure that the permissions are given for that. If not, then the permissions are requested."
},
{
"code": null,
"e": 28780,
"s": 28526,
"text": "Check for permissions: Beginning with Android 6.0 (API level 23), the user has the right to revoke permissions from any app at any time, even if the app targets a lower API level. So to use the service, the app needs to check for permissions every time."
},
{
"code": null,
"e": 28789,
"s": 28780,
"text": "Syntax: "
},
{
"code": null,
"e": 28955,
"s": 28789,
"text": "if(ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.WRITE_CALENDAR)\n != PackageManager.PERMISSION_GRANTED) \n{\n // Permission is not granted\n}"
},
{
"code": null,
"e": 29221,
"s": 28955,
"text": "Request Permissions: When PERMISSION_DENIED is returned from the checkSelfPermission() method in the above syntax, we need to prompt the user for that permission. Android provides several methods that can be used to request permission, such as requestPermissions()."
},
{
"code": null,
"e": 29230,
"s": 29221,
"text": "Syntax: "
},
{
"code": null,
"e": 29434,
"s": 29230,
"text": "ActivityCompat.requestPermissions(MainActivity.this, \n permissionArray, \n requestCode);\n\nHere permissionArray is an array of type String."
},
{
"code": null,
"e": 29443,
"s": 29434,
"text": "Example:"
},
{
"code": null,
"e": 29448,
"s": 29443,
"text": "Java"
},
{
"code": null,
"e": 29455,
"s": 29448,
"text": "Kotlin"
},
{
"code": "// Function to check and request permissionpublic void checkPermission(String permission, int requestCode){ // Checking if permission is not granted if (ContextCompat.checkSelfPermission(MainActivity.this, permission) == PackageManager.PERMISSION_DENIED) { ActivityCompat.requestPermissions(MainActivity.this, new String[] { permission }, requestCode); } else { Toast.makeText(MainActivity.this, \"Permission already granted\", Toast.LENGTH_SHORT).show(); }}",
"e": 29941,
"s": 29455,
"text": null
},
{
"code": "// Function to check and request permission.private fun checkPermission(permission: String, requestCode: Int) { if (ContextCompat.checkSelfPermission(this@MainActivity, permission) == PackageManager.PERMISSION_DENIED) { // Requesting the permission ActivityCompat.requestPermissions(this@MainActivity, arrayOf(permission), requestCode) } else { Toast.makeText(this@MainActivity, \"Permission already granted\", Toast.LENGTH_SHORT).show() } }",
"e": 30437,
"s": 29941,
"text": null
},
{
"code": null,
"e": 30552,
"s": 30437,
"text": "This function will show a Toast message if permission is already granted otherwise prompt the user for permission."
},
{
"code": null,
"e": 30883,
"s": 30552,
"text": "Step 4: Override onRequestPermissionsResult() method: onRequestPermissionsResult() is called when user grant or decline the permission. RequestCode is one of the parameters of this function which is used to check user action for the corresponding requests. Here a toast message is shown indicating the permission and user action. "
},
{
"code": null,
"e": 30892,
"s": 30883,
"text": "Example:"
},
{
"code": null,
"e": 30897,
"s": 30892,
"text": "Java"
},
{
"code": null,
"e": 30904,
"s": 30897,
"text": "Kotlin"
},
{
"code": "// This function is called when user accept or decline the permission.// Request Code is used to check which permission called this function.// This request code is provided when user is prompt for permission.@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults){ super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == CAMERA_PERMISSION_CODE) { // Checking whether user granted the permission or not. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Showing the toast message Toast.makeText(MainActivity.this, \"Camera Permission Granted\", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, \"Camera Permission Denied\", Toast.LENGTH_SHORT).show(); } } else if (requestCode == STORAGE_PERMISSION_CODE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(MainActivity.this, \"Storage Permission Granted\", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, \"Storage Permission Denied\", Toast.LENGTH_SHORT).show(); } }}",
"e": 32284,
"s": 30904,
"text": null
},
{
"code": "// This function is called when the user accepts or decline the permission.// Request Code is used to check which permission called this function.// This request code is provided when the user is prompt for permission.override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == CAMERA_PERMISSION_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this@MainActivity, \"Camera Permission Granted\", Toast.LENGTH_SHORT).show() } else { Toast.makeText(this@MainActivity, \"Camera Permission Denied\", Toast.LENGTH_SHORT).show() } } else if (requestCode == STORAGE_PERMISSION_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this@MainActivity, \"Storage Permission Granted\", Toast.LENGTH_SHORT).show() } else { Toast.makeText(this@MainActivity, \"Storage Permission Denied\", Toast.LENGTH_SHORT).show() } }}",
"e": 33577,
"s": 32284,
"text": null
},
{
"code": null,
"e": 33625,
"s": 33577,
"text": "Below is the complete code of this application:"
},
{
"code": null,
"e": 33676,
"s": 33625,
"text": "Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 33680,
"s": 33676,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- To show toolbar--> <android.support.v7.widget.Toolbar android:id=\"@+id/toolbar\" android:layout_width=\"match_parent\" android:background=\"@color/colorPrimary\" app:title=\"GFG | Permission Example\" app:titleTextColor=\"@android:color/white\" android:layout_height=\"?android:attr/actionBarSize\"/> <!--Button to request storage permission--> <Button android:id=\"@+id/storage\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Storage\" android:layout_marginTop=\"16dp\" android:padding=\"8dp\" android:layout_below=\"@id/toolbar\" android:layout_centerHorizontal=\"true\"/> <!--Button to request camera permission--> <Button android:id=\"@+id/camera\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Camera\" android:layout_marginTop=\"16dp\" android:padding=\"8dp\" android:layout_below=\"@id/storage\" android:layout_centerHorizontal=\"true\"/> </RelativeLayout>",
"e": 35111,
"s": 33680,
"text": null
},
{
"code": null,
"e": 35164,
"s": 35111,
"text": "Below is the code for the AndroidManifest.xml file. "
},
{
"code": null,
"e": 35168,
"s": 35164,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"org.geeksforgeeks.requestPermission\"> <!--Declaring the required permissions--> <uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\" /> <uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" /> <uses-permission android:name=\"android.permission.CAMERA\" /> <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>",
"e": 36330,
"s": 35168,
"text": null
},
{
"code": null,
"e": 36375,
"s": 36330,
"text": "Below is the code for the MainActivity file."
},
{
"code": null,
"e": 36382,
"s": 36375,
"text": "Kotlin"
},
{
"code": null,
"e": 36387,
"s": 36382,
"text": "Java"
},
{
"code": "import android.Manifestimport android.content.pm.PackageManagerimport android.os.Bundleimport android.widget.Buttonimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport androidx.core.app.ActivityCompatimport androidx.core.content.ContextCompat class MainActivity : AppCompatActivity() { companion object { private const val CAMERA_PERMISSION_CODE = 100 private const val STORAGE_PERMISSION_CODE = 101 } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Defining Buttons val storage: Button? = findViewById(R.id.storage) val camera: Button? = findViewById(R.id.camera) // Set Buttons on Click Listeners storage?.setOnClickListener {checkPermission( Manifest.permission.WRITE_EXTERNAL_STORAGE, STORAGE_PERMISSION_CODE) } camera?.setOnClickListener { checkPermission(Manifest.permission.CAMERA, CAMERA_PERMISSION_CODE) } } // Function to check and request permission. private fun checkPermission(permission: String, requestCode: Int) { if (ContextCompat.checkSelfPermission(this@MainActivity, permission) == PackageManager.PERMISSION_DENIED) { // Requesting the permission ActivityCompat.requestPermissions(this@MainActivity, arrayOf(permission), requestCode) } else { Toast.makeText(this@MainActivity, \"Permission already granted\", Toast.LENGTH_SHORT).show() } } // This function is called when the user accepts or decline the permission. // Request Code is used to check which permission called this function. // This request code is provided when the user is prompt for permission. override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == CAMERA_PERMISSION_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this@MainActivity, \"Camera Permission Granted\", Toast.LENGTH_SHORT).show() } else { Toast.makeText(this@MainActivity, \"Camera Permission Denied\", Toast.LENGTH_SHORT).show() } } else if (requestCode == STORAGE_PERMISSION_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this@MainActivity, \"Storage Permission Granted\", Toast.LENGTH_SHORT).show() } else { Toast.makeText(this@MainActivity, \"Storage Permission Denied\", Toast.LENGTH_SHORT).show() } } }}",
"e": 39313,
"s": 36387,
"text": null
},
{
"code": "import android.Manifest;import android.content.pm.PackageManager;import android.support.annotation.NonNull;import android.support.v4.app.ActivityCompat;import android.support.v4.content.ContextCompat;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast; public class MainActivity extends AppCompatActivity { // Defining Buttons private Button storage, camera; // Defining Permission codes. // We can give any value // but unique for each permission. private static final int CAMERA_PERMISSION_CODE = 100; private static final int STORAGE_PERMISSION_CODE = 101; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); storage = findViewById(R.id.storage); camera = findViewById(R.id.camera); // Set Buttons on Click Listeners storage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, STORAGE_PERMISSION_CODE); } }); camera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { checkPermission(Manifest.permission.CAMERA, CAMERA_PERMISSION_CODE); } }); } // Function to check and request permission. public void checkPermission(String permission, int requestCode) { if (ContextCompat.checkSelfPermission(MainActivity.this, permission) == PackageManager.PERMISSION_DENIED) { // Requesting the permission ActivityCompat.requestPermissions(MainActivity.this, new String[] { permission }, requestCode); } else { Toast.makeText(MainActivity.this, \"Permission already granted\", Toast.LENGTH_SHORT).show(); } } // This function is called when the user accepts or decline the permission. // Request Code is used to check which permission called this function. // This request code is provided when the user is prompt for permission. @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == CAMERA_PERMISSION_CODE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(MainActivity.this, \"Camera Permission Granted\", Toast.LENGTH_SHORT) .show(); } else { Toast.makeText(MainActivity.this, \"Camera Permission Denied\", Toast.LENGTH_SHORT) .show(); } } else if (requestCode == STORAGE_PERMISSION_CODE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(MainActivity.this, \"Storage Permission Granted\", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, \"Storage Permission Denied\", Toast.LENGTH_SHORT).show(); } } }}",
"e": 42782,
"s": 39313,
"text": null
},
{
"code": null,
"e": 42791,
"s": 42782,
"text": "Output: "
},
{
"code": null,
"e": 42821,
"s": 42791,
"text": "On starting the application: "
},
{
"code": null,
"e": 42871,
"s": 42821,
"text": "On clicking the camera button for the first time:"
},
{
"code": null,
"e": 42899,
"s": 42871,
"text": "On Granting the permission:"
},
{
"code": null,
"e": 42936,
"s": 42899,
"text": "On clicking the camera button again:"
},
{
"code": null,
"e": 42948,
"s": 42936,
"text": "aashaypawar"
},
{
"code": null,
"e": 42956,
"s": 42948,
"text": "android"
},
{
"code": null,
"e": 42961,
"s": 42956,
"text": "Java"
},
{
"code": null,
"e": 42966,
"s": 42961,
"text": "Java"
},
{
"code": null,
"e": 43064,
"s": 42966,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43115,
"s": 43064,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 43145,
"s": 43115,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 43160,
"s": 43145,
"text": "Stream In Java"
},
{
"code": null,
"e": 43179,
"s": 43160,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 43210,
"s": 43179,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 43228,
"s": 43210,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 43260,
"s": 43228,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 43280,
"s": 43260,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 43312,
"s": 43280,
"text": "Multidimensional Arrays in Java"
}
] |
Java Program to find the sum of a Series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n! - GeeksforGeeks
|
02 Nov, 2021
You have been given a series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n!, find out the sum of the series till nth term.Examples:
Input :n = 5
Output : 2.70833
Input :n = 7
Output : 2.71806
Java
// Java program to print the sum of series import java.io.*;import java.lang.*; class GFG { public static double sumOfSeries(double num) { double res = 0, fact = 1; for (int i = 1; i <= num; i++) { /*fact variable store factorial of the i.*/ fact = fact * i; res = res + (i / fact); } return (res); } public static void main(String[] args) { double n = 5; System.out.println("Sum: " + sumOfSeries(n)); }} // Code contributed by Mohit Gupta_OMG <(0_o)>
Sum: 2.708333333333333
Time Complexity: O(n)
Auxiliary Space: O(1)
Please refer complete article on Program to find the sum of a Series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n! for more details!
subhammahato348
Java Programs
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Iterate HashMap in Java?
Iterate through List in Java
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
Java program to count the occurrence of each character in a string using Hashmap
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 26813,
"s": 26785,
"text": "\n02 Nov, 2021"
},
{
"code": null,
"e": 26941,
"s": 26813,
"text": "You have been given a series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n!, find out the sum of the series till nth term.Examples: "
},
{
"code": null,
"e": 27002,
"s": 26941,
"text": "Input :n = 5\nOutput : 2.70833\n\nInput :n = 7\nOutput : 2.71806"
},
{
"code": null,
"e": 27011,
"s": 27006,
"text": "Java"
},
{
"code": "// Java program to print the sum of series import java.io.*;import java.lang.*; class GFG { public static double sumOfSeries(double num) { double res = 0, fact = 1; for (int i = 1; i <= num; i++) { /*fact variable store factorial of the i.*/ fact = fact * i; res = res + (i / fact); } return (res); } public static void main(String[] args) { double n = 5; System.out.println(\"Sum: \" + sumOfSeries(n)); }} // Code contributed by Mohit Gupta_OMG <(0_o)>",
"e": 27558,
"s": 27011,
"text": null
},
{
"code": null,
"e": 27581,
"s": 27558,
"text": "Sum: 2.708333333333333"
},
{
"code": null,
"e": 27605,
"s": 27583,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 27627,
"s": 27605,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 27756,
"s": 27627,
"text": "Please refer complete article on Program to find the sum of a Series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n! for more details! "
},
{
"code": null,
"e": 27772,
"s": 27756,
"text": "subhammahato348"
},
{
"code": null,
"e": 27786,
"s": 27772,
"text": "Java Programs"
},
{
"code": null,
"e": 27799,
"s": 27786,
"text": "Mathematical"
},
{
"code": null,
"e": 27812,
"s": 27799,
"text": "Mathematical"
},
{
"code": null,
"e": 27910,
"s": 27812,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27942,
"s": 27910,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 27971,
"s": 27942,
"text": "Iterate through List in Java"
},
{
"code": null,
"e": 28009,
"s": 27971,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 28066,
"s": 28009,
"text": "Java Program to Remove Duplicate Elements From the Array"
},
{
"code": null,
"e": 28147,
"s": 28066,
"text": "Java program to count the occurrence of each character in a string using Hashmap"
},
{
"code": null,
"e": 28177,
"s": 28147,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 28237,
"s": 28177,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 28252,
"s": 28237,
"text": "C++ Data Types"
},
{
"code": null,
"e": 28295,
"s": 28252,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
AngularJS | ng-app Directive - GeeksforGeeks
|
28 Mar, 2019
The ng-app Directive in AngularJS is used to define the root element of an AngularJS application. This directive automatically initializes the AngularJS application on page load. It can be used to load various modules in AngularJS Application.
Syntax:
<element ng-app=""> Contents... </element>
Example 1: This example uses ng-app Directive to define a default AngularJS application.
<html> <head> <title>AngularJS ng-app Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body style="text-align:center"> <h2 style = "color:green">ng-app directive</h2> <div ng-app="" ng-init="name='GeeksforGeeks'"> <p>{{ name }} is the portal for geeks.</p> </div></body> </html>
Output:
Example 2: This example uses ng-app Directive to define a default AngularJS application.
<html> <head> <title>AngularJS ng-app Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body ng-app="" style="text-align: center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>ng-app Directive</h2> <div> <p>Name: <input type="text" ng-model="name"></p> <p>You entered: <span ng-bind="name"></span></p> </div></body> </html>
Output:
AngularJS-Directives
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular File Upload
Angular PrimeNG Dropdown Component
Angular | keyup event
Auth Guards in Angular 9/10/11
How to Display Spinner on the Screen till the data from the API loads using Angular 8 ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 29516,
"s": 29488,
"text": "\n28 Mar, 2019"
},
{
"code": null,
"e": 29760,
"s": 29516,
"text": "The ng-app Directive in AngularJS is used to define the root element of an AngularJS application. This directive automatically initializes the AngularJS application on page load. It can be used to load various modules in AngularJS Application."
},
{
"code": null,
"e": 29768,
"s": 29760,
"text": "Syntax:"
},
{
"code": null,
"e": 29811,
"s": 29768,
"text": "<element ng-app=\"\"> Contents... </element>"
},
{
"code": null,
"e": 29900,
"s": 29811,
"text": "Example 1: This example uses ng-app Directive to define a default AngularJS application."
},
{
"code": "<html> <head> <title>AngularJS ng-app Directive</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body style=\"text-align:center\"> <h2 style = \"color:green\">ng-app directive</h2> <div ng-app=\"\" ng-init=\"name='GeeksforGeeks'\"> <p>{{ name }} is the portal for geeks.</p> </div></body> </html>",
"e": 30296,
"s": 29900,
"text": null
},
{
"code": null,
"e": 30304,
"s": 30296,
"text": "Output:"
},
{
"code": null,
"e": 30393,
"s": 30304,
"text": "Example 2: This example uses ng-app Directive to define a default AngularJS application."
},
{
"code": "<html> <head> <title>AngularJS ng-app Directive</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body ng-app=\"\" style=\"text-align: center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>ng-app Directive</h2> <div> <p>Name: <input type=\"text\" ng-model=\"name\"></p> <p>You entered: <span ng-bind=\"name\"></span></p> </div></body> </html>",
"e": 30841,
"s": 30393,
"text": null
},
{
"code": null,
"e": 30849,
"s": 30841,
"text": "Output:"
},
{
"code": null,
"e": 30870,
"s": 30849,
"text": "AngularJS-Directives"
},
{
"code": null,
"e": 30880,
"s": 30870,
"text": "AngularJS"
},
{
"code": null,
"e": 30897,
"s": 30880,
"text": "Web Technologies"
},
{
"code": null,
"e": 30995,
"s": 30897,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31015,
"s": 30995,
"text": "Angular File Upload"
},
{
"code": null,
"e": 31050,
"s": 31015,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 31072,
"s": 31050,
"text": "Angular | keyup event"
},
{
"code": null,
"e": 31103,
"s": 31072,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 31191,
"s": 31103,
"text": "How to Display Spinner on the Screen till the data from the API loads using Angular 8 ?"
},
{
"code": null,
"e": 31231,
"s": 31191,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31264,
"s": 31231,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31309,
"s": 31264,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31352,
"s": 31309,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to find the sum of elements of a Vector using STL in C++? - GeeksforGeeks
|
08 Jul, 2021
Given a vector, find the sum of the elements of this vector using STL in C++.Example:
Input: vec = {1, 45, 54, 71, 76, 12}
Output: 259
Input: vec = {1, 7, 5, 4, 6, 12}
Output: 35
Approach: Sum can be found with the help of accumulate() function provided in STL.Syntax:
accumulate(first_index, last_index, initial value of sum);
Time Complexity: It is linear in the distance between first_index and last_index i.e if your your vector contains n number of elements between two given indices , the time complexity will be O(n).
CPP
// C++ program to find the sum// of Array using accumulate() in STL #include <bits/stdc++.h>using namespace std; int main(){ // Get the vector vector<int> a = { 1, 45, 54, 71, 76, 12 }; // Print the vector cout << "Vector: "; for (int i = 0; i < a.size(); i++) cout << a[i] << " "; cout << endl; // Find the sum of the vector cout << "\nSum = " << accumulate(a.begin(), a.end(), 0); return 0;}
Vector: 1 45 54 71 76 12
Sum = 259
shriyanshi2017
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
C++ Classes and Objects
Virtual Function in C++
Templates in C++ with Examples
Constructors in C++
Operator Overloading in C++
Socket Programming in C/C++
Object Oriented Programming in C++
Copy Constructor in C++
Polymorphism in C++
|
[
{
"code": null,
"e": 25760,
"s": 25732,
"text": "\n08 Jul, 2021"
},
{
"code": null,
"e": 25848,
"s": 25760,
"text": "Given a vector, find the sum of the elements of this vector using STL in C++.Example: "
},
{
"code": null,
"e": 25942,
"s": 25848,
"text": "Input: vec = {1, 45, 54, 71, 76, 12}\nOutput: 259\n\nInput: vec = {1, 7, 5, 4, 6, 12}\nOutput: 35"
},
{
"code": null,
"e": 26036,
"s": 25944,
"text": "Approach: Sum can be found with the help of accumulate() function provided in STL.Syntax: "
},
{
"code": null,
"e": 26095,
"s": 26036,
"text": "accumulate(first_index, last_index, initial value of sum);"
},
{
"code": null,
"e": 26293,
"s": 26095,
"text": "Time Complexity: It is linear in the distance between first_index and last_index i.e if your your vector contains n number of elements between two given indices , the time complexity will be O(n). "
},
{
"code": null,
"e": 26297,
"s": 26293,
"text": "CPP"
},
{
"code": "// C++ program to find the sum// of Array using accumulate() in STL #include <bits/stdc++.h>using namespace std; int main(){ // Get the vector vector<int> a = { 1, 45, 54, 71, 76, 12 }; // Print the vector cout << \"Vector: \"; for (int i = 0; i < a.size(); i++) cout << a[i] << \" \"; cout << endl; // Find the sum of the vector cout << \"\\nSum = \" << accumulate(a.begin(), a.end(), 0); return 0;}",
"e": 26735,
"s": 26297,
"text": null
},
{
"code": null,
"e": 26772,
"s": 26735,
"text": "Vector: 1 45 54 71 76 12 \n\nSum = 259"
},
{
"code": null,
"e": 26789,
"s": 26774,
"text": "shriyanshi2017"
},
{
"code": null,
"e": 26800,
"s": 26789,
"text": "cpp-vector"
},
{
"code": null,
"e": 26804,
"s": 26800,
"text": "STL"
},
{
"code": null,
"e": 26808,
"s": 26804,
"text": "C++"
},
{
"code": null,
"e": 26812,
"s": 26808,
"text": "STL"
},
{
"code": null,
"e": 26816,
"s": 26812,
"text": "CPP"
},
{
"code": null,
"e": 26914,
"s": 26816,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26933,
"s": 26914,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 26957,
"s": 26933,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 26981,
"s": 26957,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 27012,
"s": 26981,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 27032,
"s": 27012,
"text": "Constructors in C++"
},
{
"code": null,
"e": 27060,
"s": 27032,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 27088,
"s": 27060,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 27123,
"s": 27088,
"text": "Object Oriented Programming in C++"
},
{
"code": null,
"e": 27147,
"s": 27123,
"text": "Copy Constructor in C++"
}
] |
Matplotlib.figure.Figure.set_constrained_layout_pads() in Python - GeeksforGeeks
|
03 May, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The set_constrained_layout_pads() method figure module of matplotlib library is used to set padding for constrained_layout.
Syntax: set_constrained_layout_pads(self, **kwargs)
Parameters: This method accept the following parameters that are discussed below:
w_pad : This parameter is the Width padding in inches.
h_pad : This parameter is the height padding in inches.
wspace : This parameter is the Width padding between subplots, expressed as a fraction of the subplot width.
hspace : This parameter is the height padding between subplots, expressed as a fraction of the subplot width.
Returns: This method does not returns any value.
Below examples illustrate the matplotlib.figure.Figure.set_constrained_layout_pads() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltfrom matplotlib.lines import Line2Dimport numpy as npfrom numpy.random import rand fig, ax2 = plt.subplots() ax2.bar(range(10), rand(10), picker = True)for label in ax2.get_xticklabels(): label.set_picker(True) def onpick1(event): if isinstance(event.artist, Line2D): thisline = event.artist xdata = thisline.get_xdata() ydata = thisline.get_ydata() ind = event.ind print('onpick1 line:', np.column_stack([xdata[ind], ydata[ind]])) elif isinstance(event.artist, Rectangle): patch = event.artist print('onpick1 patch:', patch.get_path()) elif isinstance(event.artist, Text): text = event.artist print('onpick1 text:', text.get_text()) fig.set_constrained_layout_pads(w_pad = 4./72., h_pad = 4./72., hspace = 0., wspace = 0.) fig.suptitle("""matplotlib.figure.Figure.set_constrained_layout_pads()function Example\n\n""", fontweight ="bold") plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.patches import Ellipse NUM = 200 ells = [Ellipse(xy = np.random.rand(2) * 10, width = np.random.rand(), height = np.random.rand(), angle = np.random.rand() * 360) for i in range(NUM)] fig, ax = plt.subplots(subplot_kw ={'aspect': 'equal'}) for e in ells: ax.add_artist(e) e.set_clip_box(ax.bbox) e.set_alpha(np.random.rand()) e.set_facecolor(np.random.rand(4)) ax.set_xlim(3, 7)ax.set_ylim(3, 7) fig.set_constrained_layout_pads(w_pad = 2./72., h_pad = 2./72., hspace = 0., wspace = 0.) fig.suptitle("""matplotlib.figure.Figure.set_constrained_layout_pads()function Example\n\n""", fontweight ="bold") plt.show()
Output:
Matplotlib figure-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n03 May, 2020"
},
{
"code": null,
"e": 25848,
"s": 25537,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements."
},
{
"code": null,
"e": 25972,
"s": 25848,
"text": "The set_constrained_layout_pads() method figure module of matplotlib library is used to set padding for constrained_layout."
},
{
"code": null,
"e": 26024,
"s": 25972,
"text": "Syntax: set_constrained_layout_pads(self, **kwargs)"
},
{
"code": null,
"e": 26106,
"s": 26024,
"text": "Parameters: This method accept the following parameters that are discussed below:"
},
{
"code": null,
"e": 26161,
"s": 26106,
"text": "w_pad : This parameter is the Width padding in inches."
},
{
"code": null,
"e": 26217,
"s": 26161,
"text": "h_pad : This parameter is the height padding in inches."
},
{
"code": null,
"e": 26326,
"s": 26217,
"text": "wspace : This parameter is the Width padding between subplots, expressed as a fraction of the subplot width."
},
{
"code": null,
"e": 26436,
"s": 26326,
"text": "hspace : This parameter is the height padding between subplots, expressed as a fraction of the subplot width."
},
{
"code": null,
"e": 26485,
"s": 26436,
"text": "Returns: This method does not returns any value."
},
{
"code": null,
"e": 26601,
"s": 26485,
"text": "Below examples illustrate the matplotlib.figure.Figure.set_constrained_layout_pads() function in matplotlib.figure:"
},
{
"code": null,
"e": 26612,
"s": 26601,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltfrom matplotlib.lines import Line2Dimport numpy as npfrom numpy.random import rand fig, ax2 = plt.subplots() ax2.bar(range(10), rand(10), picker = True)for label in ax2.get_xticklabels(): label.set_picker(True) def onpick1(event): if isinstance(event.artist, Line2D): thisline = event.artist xdata = thisline.get_xdata() ydata = thisline.get_ydata() ind = event.ind print('onpick1 line:', np.column_stack([xdata[ind], ydata[ind]])) elif isinstance(event.artist, Rectangle): patch = event.artist print('onpick1 patch:', patch.get_path()) elif isinstance(event.artist, Text): text = event.artist print('onpick1 text:', text.get_text()) fig.set_constrained_layout_pads(w_pad = 4./72., h_pad = 4./72., hspace = 0., wspace = 0.) fig.suptitle(\"\"\"matplotlib.figure.Figure.set_constrained_layout_pads()function Example\\n\\n\"\"\", fontweight =\"bold\") plt.show() ",
"e": 27649,
"s": 26612,
"text": null
},
{
"code": null,
"e": 27657,
"s": 27649,
"text": "Output:"
},
{
"code": null,
"e": 27668,
"s": 27657,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.patches import Ellipse NUM = 200 ells = [Ellipse(xy = np.random.rand(2) * 10, width = np.random.rand(), height = np.random.rand(), angle = np.random.rand() * 360) for i in range(NUM)] fig, ax = plt.subplots(subplot_kw ={'aspect': 'equal'}) for e in ells: ax.add_artist(e) e.set_clip_box(ax.bbox) e.set_alpha(np.random.rand()) e.set_facecolor(np.random.rand(4)) ax.set_xlim(3, 7)ax.set_ylim(3, 7) fig.set_constrained_layout_pads(w_pad = 2./72., h_pad = 2./72., hspace = 0., wspace = 0.) fig.suptitle(\"\"\"matplotlib.figure.Figure.set_constrained_layout_pads()function Example\\n\\n\"\"\", fontweight =\"bold\") plt.show() ",
"e": 28485,
"s": 27668,
"text": null
},
{
"code": null,
"e": 28493,
"s": 28485,
"text": "Output:"
},
{
"code": null,
"e": 28517,
"s": 28493,
"text": "Matplotlib figure-class"
},
{
"code": null,
"e": 28535,
"s": 28517,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 28542,
"s": 28535,
"text": "Python"
},
{
"code": null,
"e": 28640,
"s": 28542,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28672,
"s": 28640,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28714,
"s": 28672,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28756,
"s": 28714,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28783,
"s": 28756,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28839,
"s": 28783,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28861,
"s": 28839,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28900,
"s": 28861,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28931,
"s": 28900,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28960,
"s": 28931,
"text": "Create a directory in Python"
}
] |
Count the number of Documents in MongoDB using Python - GeeksforGeeks
|
08 Jun, 2020
Mongodb is a document-oriented NoSQL database which is non-relational DB. Mongodb is a schema-free database which is based on Binary JSON format. It is organized with a group of documents (rows in RDBMS) called collection (table in RDBMS). The collections in mongodb are schema-less.
PyMongo is one of the MongoDB drivers or client libraries. Using the PyMongo module we can send requests and receive responses from
Method 1: Using count()
The total number of documents present in the collection can be retrieved by using count() method.
Syntax :
db.collection.count()
Example : Count the number of documents (my_data) in the collection using count().
Sample Database:
from pymongo import MongoClient Client = MongoClient()myclient = MongoClient('localhost', 27017) my_database = myclient["GFG"] my_collection = my_database["Student"] # number of documents in the collectionmydoc = my_collection.find().count()print("The number of documents in collection : ", mydoc)
Output :
The number of documents in collection : 8
Method 2: count_documents()
Alternatively, you can also use count_documents() function in pymongo to count the number of documents present in the collection.
Syntax :
db.collection.count_documents({query, option})
Example : Retrieves the documents present in the collection and the count of the documents using count_documents().
from pymongo import MongoClient Client = MongoClient()myclient = MongoClient('localhost', 27017) my_database = myclient["GFG"] my_collection = my_database["Student"] # number of documents in the collectiontotal_count = my_collection.count_documents({})print("Total number of documents : ", total_count)
Output :
Total number of documents : 8
soniyanagaraj30
Python-mongoDB
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25563,
"s": 25535,
"text": "\n08 Jun, 2020"
},
{
"code": null,
"e": 25847,
"s": 25563,
"text": "Mongodb is a document-oriented NoSQL database which is non-relational DB. Mongodb is a schema-free database which is based on Binary JSON format. It is organized with a group of documents (rows in RDBMS) called collection (table in RDBMS). The collections in mongodb are schema-less."
},
{
"code": null,
"e": 25979,
"s": 25847,
"text": "PyMongo is one of the MongoDB drivers or client libraries. Using the PyMongo module we can send requests and receive responses from"
},
{
"code": null,
"e": 26003,
"s": 25979,
"text": "Method 1: Using count()"
},
{
"code": null,
"e": 26101,
"s": 26003,
"text": "The total number of documents present in the collection can be retrieved by using count() method."
},
{
"code": null,
"e": 26110,
"s": 26101,
"text": "Syntax :"
},
{
"code": null,
"e": 26132,
"s": 26110,
"text": "db.collection.count()"
},
{
"code": null,
"e": 26215,
"s": 26132,
"text": "Example : Count the number of documents (my_data) in the collection using count()."
},
{
"code": null,
"e": 26232,
"s": 26215,
"text": "Sample Database:"
},
{
"code": "from pymongo import MongoClient Client = MongoClient()myclient = MongoClient('localhost', 27017) my_database = myclient[\"GFG\"] my_collection = my_database[\"Student\"] # number of documents in the collectionmydoc = my_collection.find().count()print(\"The number of documents in collection : \", mydoc) ",
"e": 26538,
"s": 26232,
"text": null
},
{
"code": null,
"e": 26547,
"s": 26538,
"text": "Output :"
},
{
"code": null,
"e": 26590,
"s": 26547,
"text": "The number of documents in collection : 8"
},
{
"code": null,
"e": 26618,
"s": 26590,
"text": "Method 2: count_documents()"
},
{
"code": null,
"e": 26748,
"s": 26618,
"text": "Alternatively, you can also use count_documents() function in pymongo to count the number of documents present in the collection."
},
{
"code": null,
"e": 26757,
"s": 26748,
"text": "Syntax :"
},
{
"code": null,
"e": 26804,
"s": 26757,
"text": "db.collection.count_documents({query, option})"
},
{
"code": null,
"e": 26920,
"s": 26804,
"text": "Example : Retrieves the documents present in the collection and the count of the documents using count_documents()."
},
{
"code": "from pymongo import MongoClient Client = MongoClient()myclient = MongoClient('localhost', 27017) my_database = myclient[\"GFG\"] my_collection = my_database[\"Student\"] # number of documents in the collectiontotal_count = my_collection.count_documents({})print(\"Total number of documents : \", total_count)",
"e": 27230,
"s": 26920,
"text": null
},
{
"code": null,
"e": 27239,
"s": 27230,
"text": "Output :"
},
{
"code": null,
"e": 27270,
"s": 27239,
"text": "Total number of documents : 8"
},
{
"code": null,
"e": 27286,
"s": 27270,
"text": "soniyanagaraj30"
},
{
"code": null,
"e": 27301,
"s": 27286,
"text": "Python-mongoDB"
},
{
"code": null,
"e": 27308,
"s": 27301,
"text": "Python"
},
{
"code": null,
"e": 27406,
"s": 27308,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27438,
"s": 27406,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27480,
"s": 27438,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27522,
"s": 27480,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27549,
"s": 27522,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27605,
"s": 27549,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27627,
"s": 27605,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27666,
"s": 27627,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27697,
"s": 27666,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27726,
"s": 27697,
"text": "Create a directory in Python"
}
] |
Iterative Merge Sort for Linked List - GeeksforGeeks
|
31 Oct, 2021
Given a singly linked list of integers, the task is to sort it using iterative merge sort.
Merge Sort is often preferred for sorting a linked list. It is discussed here. However, the method discussed above uses Stack for storing recursion calls. This may consume a lot of memory if the linked list to be sorted is too large. Hence, a purely iterative method for Merge Sort with no recursive calls is discussed in this post.We use bottom-up approach of Merge Sort in this post. We know that Merge Sort first merges two items, then 4 items and so on. The idea is to use an integer variable to store the gap to find the midpoint around which the linked list needs to be sorted. So the problem reduces to merging two sorted Linked List which is discussed here. However, we do not use an additional list to keep the merged list. Instead we merge the lists within itself. The gap is incremented exponentially by 2 in each iteration and the process is repeated.
C++
Java
Python3
C#
Javascript
// Iterative C++ program to do merge sort on// linked list#include <iostream>using namespace std; /* Structure of the Node */struct Node { int data; struct Node* next;}; /* Function to calculate length of linked list */int length(struct Node* current){ int count = 0; while (current != NULL) { current = current->next; count++; } return count;} /* Merge function of Merge Sort to Merge the two sorted parts of the Linked List. We compare the next value of start1 and current value of start2 and insert start2 after start1 if it's smaller than next value of start1. We do this until start1 or start2 end. If start1 ends, then we assign next of start1 to start2 because start2 may have some elements left out which are greater than the last value of start1. If start2 ends then we assign end2 to end1. This is necessary because we use end2 in another function (mergeSort function) to determine the next start1 (i.e) start1 for next iteration = end2->next */void merge(struct Node** start1, struct Node** end1, struct Node** start2, struct Node** end2){ // Making sure that first node of second // list is higher. struct Node* temp = NULL; if ((*start1)->data > (*start2)->data) { swap(*start1, *start2); swap(*end1, *end2); } // Merging remaining nodes struct Node* astart = *start1, *aend = *end1; struct Node* bstart = *start2, *bend = *end2; struct Node* bendnext = (*end2)->next; while (astart != aend && bstart != bendnext) { if (astart->next->data > bstart->data) { temp = bstart->next; bstart->next = astart->next; astart->next = bstart; bstart = temp; } astart = astart->next; } if (astart == aend) astart->next = bstart; else *end2 = *end1;} /* MergeSort of Linked List The gap is initially 1. It is incremented as 2, 4, 8, .. until it reaches the length of the linked list. For each gap, the linked list is sorted around the gap. The prevend stores the address of the last node after sorting a part of linked list so that it's next node can be assigned after sorting the succeeding list. temp is used to store the next start1 because after sorting, the last node will be different. So it is necessary to store the address of start1 before sorting. We select the start1, end1, start2, end2 for sorting. start1 - end1 may be considered as a list and start2 - end2 may be considered as another list and we are merging these two sorted list in merge function and assigning the starting address to the previous end address. */void mergeSort(struct Node** head){ if (*head == NULL) return; struct Node* start1 = NULL, *end1 = NULL; struct Node* start2 = NULL, *end2 = NULL; struct Node* prevend = NULL; int len = length(*head); for (int gap = 1; gap < len; gap = gap*2) { start1 = *head; while (start1) { // If this is first iteration bool isFirstIter = 0; if (start1 == *head) isFirstIter = 1; // First part for merging int counter = gap; end1 = start1; while (--counter && end1->next) end1 = end1->next; // Second part for merging start2 = end1->next; if (!start2) break; counter = gap; end2 = start2; while (--counter && end2->next) end2 = end2->next; // To store for next iteration. Node *temp = end2->next; // Merging two parts. merge(&start1, &end1, &start2, &end2); // Update head for first iteration, else // append after previous list if (isFirstIter) *head = start1; else prevend->next = start1; prevend = end2; start1 = temp; } prevend->next = start1; }} /* Function to print the Linked List */void print(struct Node** head){ if ((*head) == NULL) return; struct Node* temp = *head; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } printf("\n");} /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} int main(){ // start with empty list struct Node* head = NULL; // create linked list // 1->2->3->4->5->6->7 push(&head, 7); push(&head, 6); push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); mergeSort(&head); print(&head);}
// Iterative Java program to do merge sort on// linked listclass GFG{ /* Structure of the Node */static class Node{ int data; Node next;}; /* Function to calculate length of linked list */static int length(Node current){ int count = 0; while (current != null) { current = current.next; count++; } return count;} /* Merge function of Merge Sort to Merge the two sorted partsof the Linked List. We compare the next value of start1 andcurrent value of start2 and insert start2 after start1 ifit's smaller than next value of start1. We do this untilstart1 or start2 end. If start1 ends, then we assign nextof start1 to start2 because start2 may have some elementsleft out which are greater than the last value of start1.If start2 ends then we assign end2 to end1. This is necessarybecause we use end2 in another function (mergeSort function)to determine the next start1 (i.e) start1 for nextiteration = end2.next */static Node merge(Node start1, Node end1, Node start2, Node end2){ // Making sure that first node of second // list is higher. Node temp = null; if ((start1).data > (start2).data) { Node t = start1; start1 = start2; start2 = t; t = end1; end1 = end2; end2 = t; } // Merging remaining nodes Node astart = start1, aend = end1; Node bstart = start2, bend = end2; Node bendnext = (end2).next; while (astart != aend && bstart != bendnext) { if (astart.next.data > bstart.data) { temp = bstart.next; bstart.next = astart.next; astart.next = bstart; bstart = temp; } astart = astart.next; } if (astart == aend) astart.next = bstart; else end2 = end1; return start1;} /* MergeSort of Linked ListThe gap is initially 1. It is incremented as2, 4, 8, .. until it reaches the length of thelinked list. For each gap, the linked list issorted around the gap.The prevend stores the address of the last node aftersorting a part of linked list so that it's next nodecan be assigned after sorting the succeeding list.temp is used to store the next start1 because aftersorting, the last node will be different. So itis necessary to store the address of start1 beforesorting. We select the start1, end1, start2, end2 forsorting. start1 - end1 may be considered as a listand start2 - end2 may be considered as another listand we are merging these two sorted list in mergefunction and assigning the starting address to theprevious end address. */static Node mergeSort(Node head){ if (head == null) return head; Node start1 = null, end1 = null; Node start2 = null, end2 = null; Node prevend = null; int len = length(head); for (int gap = 1; gap < len; gap = gap*2) { start1 = head; while (start1 != null) { // If this is first iteration boolean isFirstIter = false; if (start1 == head) isFirstIter = true; // First part for merging int counter = gap; end1 = start1; while (--counter > 0 && end1.next != null) end1 = end1.next; // Second part for merging start2 = end1.next; if (start2 == null) break; counter = gap; end2 = start2; while (--counter > 0 && end2.next != null) end2 = end2.next; // To store for next iteration. Node temp = end2.next; // Merging two parts. merge(start1, end1, start2, end2); // Update head for first iteration, else // append after previous list if (isFirstIter) head = start1; else prevend.next = start1; prevend = end2; start1 = temp; } prevend.next = start1; } return head;} /* Function to print the Linked List */static void print(Node head){ if ((head) == null) return; Node temp = head; while (temp != null) { System.out.printf("%d ", temp.data); temp = temp.next; } System.out.printf("\n");} /* Given a reference (pointer topointer) to the head of a listand an int, push a new node onthe front of the list. */static Node push( Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref;} public static void main(String args[]){ // start with empty list Node head = null; // create linked list // 1.2.3.4.5.6.7 head = push(head, 7); head = push(head, 6); head = push(head, 5); head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); head = mergeSort(head); print(head);}} // This code is contributed by Arnab Kundu
# Iterative Python3 program to do merge sort on# linked list class Node: """Structure of the Node.""" def __init__(self, data: int): self.data = data self.next = None class LinkedList: """Encapsulate each left/right part's nodes in order to pass them as pointers. Without this workaround, the code would only work for a reverse-ordered list.""" head: Node tail: Node def __init__(self, head=None, tail=None): self.start = head self.end = tail def list_length(current: Node): """Function to calculate length of linked list.""" count = 0; while (current != None): current = current.next; count += 1 return count; def merge(left: LinkedList, right: LinkedList) -> None: """Merge the two sorted parts of the original linked list in order. Merge function of Merge Sort to Merge the two sorted parts of the Linked List. We compare the next value of start1 and current value of start2 and insert start2 after start1 if it's smaller than next value of start1. We do this until start1 or start2 end. If start1 ends, then we assign next of start1 to start2 because start2 may have some elements left out which are greater than the last value of start1. If start2 ends then we assign end2 to end1. This is necessary because we use end2 in another function (mergeSort function) to determine the next start1 (i.e) start1 for next iteration = end2.next""" # Ensure the first node of the second list is higher. if left.start.data > right.start.data: left.start, right.start = right.start, left.start left.end, right.end = right.end, left.end # Merge all remaining nodes. astart = left.start aend = left.end bstart = right.start bendnext = right.end.next while astart != aend and bstart != bendnext: if astart.next.data > bstart.data: temp = bstart.next bstart.next = astart.next astart.next = bstart bstart = temp astart = astart.next if astart == aend: astart.next = bstart else: right.end = left.end def mergeSort(head: LinkedList) -> None: """MergeSort of Linked List The gap is initially 1. It is incremented as 2, 4, 8, .. until it reaches the length of the linked list. For each gap, the linked list is sorted around the gap. The prevend stores the address of the last node after sorting a part of linked list so that it's next node can be assigned after sorting the succeeding list. temp is used to store the next start1 because after sorting, the last node will be different. So it is necessary to store the address of start1 before sorting. We select the start1, end1, start2, end2 for sorting. start1 - end1 may be considered as a list and start2 - end2 may be considered as another list and we are merging these two sorted list in merge function and assigning the starting address to the previous end address.""" # Reject empty lists. if not head: return gap = 1 length = list_length(head.start) left = LinkedList() right = LinkedList() while gap < length: left.start = head.start while left.start: # If this is first iteration isFirstIter = False if left.start == head.start: isFirstIter = True # First part for merging counter = gap left.end = left.start counter -= 1 while counter != 0 and left.end.next: counter -= 1 left.end = left.end.next # Second part for merging right.start = left.end.next if not right.start: break counter = gap right.end = right.start counter -= 1 while counter != 0 and right.end.next: counter -= 1 right.end = right.end.next # To store for next iteration. temp = right.end.next # Merging two parts. merge(left, right) # Update head for first iteration, else append after previous list. if isFirstIter: head.start = left.start else: prevend.next = left.start prevend = right.end left.start = temp gap = gap * 2 prevend.next = left.start def prints(head): """Print the linked list.""" if not head: return temp = head while temp: print(temp.data, end=' ') temp = temp.next print() def push(head: LinkedList, data: int) -> None: """Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list.""" new_node = Node(data) new_node.next = head.start head.start = new_node # Driver codeif __name__=='__main__': # start with empty list head = LinkedList() # create linked list # 1.2.3.4.5.6.7 push(head, 6) push(head, 7) push(head, 2) push(head, 1) push(head, 3) push(head, 5) push(head, 4) mergeSort(head) prints(head.start) # This code is contributed by har2 (har-at-usf)
// Iterative C# program to do merge sort on// linked listusing System;class GFG{ /* Structure of the Node */public class Node{ public int data; public Node next;}; /* Function to calculate length of linked list */static int length(Node current){ int count = 0; while (current != null) { current = current.next; count++; } return count;} /* Merge function of Merge Sort to Merge the two sorted partsof the Linked List. We compare the next value of start1 andcurrent value of start2 and insert start2 after start1 ifit's smaller than next value of start1. We do this untilstart1 or start2 end. If start1 ends, then we assign nextof start1 to start2 because start2 may have some elementsleft out which are greater than the last value of start1.If start2 ends then we assign end2 to end1. This is necessarybecause we use end2 in another function (mergeSort function)to determine the next start1 (i.e) start1 for nextiteration = end2.next */static Node merge(Node start1, Node end1, Node start2, Node end2){ // Making sure that first node of second // list is higher. Node temp = null; if ((start1).data > (start2).data) { Node t = start1; start1 = start2; start2 = t; t = end1; end1 = end2; end2 = t; } // Merging remaining nodes Node astart = start1, aend = end1; Node bstart = start2, bend = end2; Node bendnext = (end2).next; while (astart != aend && bstart != bendnext) { if (astart.next.data > bstart.data) { temp = bstart.next; bstart.next = astart.next; astart.next = bstart; bstart = temp; } astart = astart.next; } if (astart == aend) astart.next = bstart; else end2 = end1; return start1;} /* MergeSort of Linked ListThe gap is initially 1. It is incremented as2, 4, 8, .. until it reaches the length of thelinked list. For each gap, the linked list issorted around the gap.The prevend stores the address of the last node aftersorting a part of linked list so that it's next nodecan be assigned after sorting the succeeding list.temp is used to store the next start1 because aftersorting, the last node will be different. So itis necessary to store the address of start1 beforesorting. We select the start1, end1, start2, end2 forsorting. start1 - end1 may be considered as a listand start2 - end2 may be considered as another listand we are merging these two sorted list in mergefunction and assigning the starting address to theprevious end address. */static Node mergeSort(Node head){ if (head == null) return head; Node start1 = null, end1 = null; Node start2 = null, end2 = null; Node prevend = null; int len = length(head); for (int gap = 1; gap < len; gap = gap*2) { start1 = head; while (start1 != null) { // If this is first iteration Boolean isFirstIter = false; if (start1 == head) isFirstIter = true; // First part for merging int counter = gap; end1 = start1; while (--counter > 0 && end1.next != null) end1 = end1.next; // Second part for merging start2 = end1.next; if (start2 == null) break; counter = gap; end2 = start2; while (--counter > 0 && end2.next != null) end2 = end2.next; // To store for next iteration. Node temp = end2.next; // Merging two parts. merge(start1, end1, start2, end2); // Update head for first iteration, else // append after previous list if (isFirstIter) head = start1; else prevend.next = start1; prevend = end2; start1 = temp; } prevend.next = start1; } return head;} /* Function to print the Linked List */static void print(Node head){ if ((head) == null) return; Node temp = head; while (temp != null) { Console.Write( temp.data + " "); temp = temp.next; } Console.Write("\n");} /* Given a reference (pointer topointer) to the head of a listand an int, push a new node onthe front of the list. */static Node push( Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref;} // Driver codepublic static void Main(String []args){ // start with empty list Node head = null; // create linked list // 1.2.3.4.5.6.7 head = push(head, 7); head = push(head, 6); head = push(head, 5); head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); head = mergeSort(head); print(head);}} // This code is contributed by Arnab Kundu
<script> // Iterative JavaScript program to do merge sort on // linked list /* Structure of the Node */ class Node { constructor() { this.data = 0; this.next = null; } } /* Function to calculate length of linked list */ function length(current) { var count = 0; while (current != null) { current = current.next; count++; } return count; } /* Merge function of Merge Sort to Merge the two sorted partsof the Linked List. We compare the next value of start1 andcurrent value of start2 and insert start2 after start1 ifit's smaller than next value of start1. We do this untilstart1 or start2 end. If start1 ends, then we assign nextof start1 to start2 because start2 may have some elementsleft out which are greater than the last value of start1.If start2 ends then we assign end2 to end1. This is necessarybecause we use end2 in another function (mergeSort function)to determine the next start1 (i.e) start1 for nextiteration = end2.next */ function merge(start1, end1, start2, end2) { // Making sure that first node of second // list is higher. var temp = null; if (start1.data > start2.data) { var t = start1; start1 = start2; start2 = t; t = end1; end1 = end2; end2 = t; } // Merging remaining nodes var astart = start1, aend = end1; var bstart = start2, bend = end2; var bendnext = end2.next; while (astart != aend && bstart != bendnext) { if (astart.next.data > bstart.data) { temp = bstart.next; bstart.next = astart.next; astart.next = bstart; bstart = temp; } astart = astart.next; } if (astart == aend) astart.next = bstart; else end2 = end1; return start1; } /* MergeSort of Linked ListThe gap is initially 1. It is incremented as2, 4, 8, .. until it reaches the length of thelinked list. For each gap, the linked list issorted around the gap.The prevend stores the address of the last node aftersorting a part of linked list so that it's next nodecan be assigned after sorting the succeeding list.temp is used to store the next start1 because aftersorting, the last node will be different. So itis necessary to store the address of start1 beforesorting. We select the start1, end1, start2, end2 forsorting. start1 - end1 may be considered as a listand start2 - end2 may be considered as another listand we are merging these two sorted list in mergefunction and assigning the starting address to theprevious end address. */ function mergeSort(head) { if (head == null) return head; var start1 = null, end1 = null; var start2 = null, end2 = null; var prevend = null; var len = length(head); for (var gap = 1; gap < len; gap = gap * 2) { start1 = head; while (start1 != null) { // If this is first iteration var isFirstIter = false; if (start1 == head) isFirstIter = true; // First part for merging var counter = gap; end1 = start1; while (--counter > 0 && end1.next != null) end1 = end1.next; // Second part for merging start2 = end1.next; if (start2 == null) break; counter = gap; end2 = start2; while (--counter > 0 && end2.next != null) end2 = end2.next; // To store for next iteration. var temp = end2.next; // Merging two parts. merge(start1, end1, start2, end2); // Update head for first iteration, else // append after previous list if (isFirstIter) head = start1; else prevend.next = start1; prevend = end2; start1 = temp; } prevend.next = start1; } return head; } /* Function to print the Linked List */ function print(head) { if (head == null) return; var temp = head; while (temp != null) { document.write(temp.data + " "); temp = temp.next; } document.write("<br>"); } /* Given a reference (pointer topointer) to the head of a listand an int, push a new node onthe front of the list. */ function push(head_ref, new_data) { var new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; return head_ref; } // Driver code // start with empty list var head = null; // create linked list // 1.2.3.4.5.6.7 head = push(head, 7); head = push(head, 6); head = push(head, 5); head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); head = mergeSort(head); print(head); </script>
1 2 3 4 5 6 7
Time Complexity : O(n Log n) Auxiliary Space : O(1)
andrew1234
rutvik_56
rdtank
har2
Linked-List-Sorting
Merge Sort
Linked List
Linked List
Merge Sort
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Delete a Linked List node at a given position
Queue - Linked List Implementation
Implement a stack using singly linked list
Implementing a Linked List in Java using Class
Circular Linked List | Set 1 (Introduction and Applications)
Remove duplicates from a sorted linked list
Function to check if a singly linked list is palindrome
Find Length of a Linked List (Iterative and Recursive)
Top 20 Linked List Interview Question
Remove duplicates from an unsorted linked list
|
[
{
"code": null,
"e": 25941,
"s": 25913,
"text": "\n31 Oct, 2021"
},
{
"code": null,
"e": 26033,
"s": 25941,
"text": "Given a singly linked list of integers, the task is to sort it using iterative merge sort. "
},
{
"code": null,
"e": 26900,
"s": 26035,
"text": "Merge Sort is often preferred for sorting a linked list. It is discussed here. However, the method discussed above uses Stack for storing recursion calls. This may consume a lot of memory if the linked list to be sorted is too large. Hence, a purely iterative method for Merge Sort with no recursive calls is discussed in this post.We use bottom-up approach of Merge Sort in this post. We know that Merge Sort first merges two items, then 4 items and so on. The idea is to use an integer variable to store the gap to find the midpoint around which the linked list needs to be sorted. So the problem reduces to merging two sorted Linked List which is discussed here. However, we do not use an additional list to keep the merged list. Instead we merge the lists within itself. The gap is incremented exponentially by 2 in each iteration and the process is repeated. "
},
{
"code": null,
"e": 26904,
"s": 26900,
"text": "C++"
},
{
"code": null,
"e": 26909,
"s": 26904,
"text": "Java"
},
{
"code": null,
"e": 26917,
"s": 26909,
"text": "Python3"
},
{
"code": null,
"e": 26920,
"s": 26917,
"text": "C#"
},
{
"code": null,
"e": 26931,
"s": 26920,
"text": "Javascript"
},
{
"code": "// Iterative C++ program to do merge sort on// linked list#include <iostream>using namespace std; /* Structure of the Node */struct Node { int data; struct Node* next;}; /* Function to calculate length of linked list */int length(struct Node* current){ int count = 0; while (current != NULL) { current = current->next; count++; } return count;} /* Merge function of Merge Sort to Merge the two sorted parts of the Linked List. We compare the next value of start1 and current value of start2 and insert start2 after start1 if it's smaller than next value of start1. We do this until start1 or start2 end. If start1 ends, then we assign next of start1 to start2 because start2 may have some elements left out which are greater than the last value of start1. If start2 ends then we assign end2 to end1. This is necessary because we use end2 in another function (mergeSort function) to determine the next start1 (i.e) start1 for next iteration = end2->next */void merge(struct Node** start1, struct Node** end1, struct Node** start2, struct Node** end2){ // Making sure that first node of second // list is higher. struct Node* temp = NULL; if ((*start1)->data > (*start2)->data) { swap(*start1, *start2); swap(*end1, *end2); } // Merging remaining nodes struct Node* astart = *start1, *aend = *end1; struct Node* bstart = *start2, *bend = *end2; struct Node* bendnext = (*end2)->next; while (astart != aend && bstart != bendnext) { if (astart->next->data > bstart->data) { temp = bstart->next; bstart->next = astart->next; astart->next = bstart; bstart = temp; } astart = astart->next; } if (astart == aend) astart->next = bstart; else *end2 = *end1;} /* MergeSort of Linked List The gap is initially 1. It is incremented as 2, 4, 8, .. until it reaches the length of the linked list. For each gap, the linked list is sorted around the gap. The prevend stores the address of the last node after sorting a part of linked list so that it's next node can be assigned after sorting the succeeding list. temp is used to store the next start1 because after sorting, the last node will be different. So it is necessary to store the address of start1 before sorting. We select the start1, end1, start2, end2 for sorting. start1 - end1 may be considered as a list and start2 - end2 may be considered as another list and we are merging these two sorted list in merge function and assigning the starting address to the previous end address. */void mergeSort(struct Node** head){ if (*head == NULL) return; struct Node* start1 = NULL, *end1 = NULL; struct Node* start2 = NULL, *end2 = NULL; struct Node* prevend = NULL; int len = length(*head); for (int gap = 1; gap < len; gap = gap*2) { start1 = *head; while (start1) { // If this is first iteration bool isFirstIter = 0; if (start1 == *head) isFirstIter = 1; // First part for merging int counter = gap; end1 = start1; while (--counter && end1->next) end1 = end1->next; // Second part for merging start2 = end1->next; if (!start2) break; counter = gap; end2 = start2; while (--counter && end2->next) end2 = end2->next; // To store for next iteration. Node *temp = end2->next; // Merging two parts. merge(&start1, &end1, &start2, &end2); // Update head for first iteration, else // append after previous list if (isFirstIter) *head = start1; else prevend->next = start1; prevend = end2; start1 = temp; } prevend->next = start1; }} /* Function to print the Linked List */void print(struct Node** head){ if ((*head) == NULL) return; struct Node* temp = *head; while (temp != NULL) { printf(\"%d \", temp->data); temp = temp->next; } printf(\"\\n\");} /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} int main(){ // start with empty list struct Node* head = NULL; // create linked list // 1->2->3->4->5->6->7 push(&head, 7); push(&head, 6); push(&head, 5); push(&head, 4); push(&head, 3); push(&head, 2); push(&head, 1); mergeSort(&head); print(&head);}",
"e": 31800,
"s": 26931,
"text": null
},
{
"code": "// Iterative Java program to do merge sort on// linked listclass GFG{ /* Structure of the Node */static class Node{ int data; Node next;}; /* Function to calculate length of linked list */static int length(Node current){ int count = 0; while (current != null) { current = current.next; count++; } return count;} /* Merge function of Merge Sort to Merge the two sorted partsof the Linked List. We compare the next value of start1 andcurrent value of start2 and insert start2 after start1 ifit's smaller than next value of start1. We do this untilstart1 or start2 end. If start1 ends, then we assign nextof start1 to start2 because start2 may have some elementsleft out which are greater than the last value of start1.If start2 ends then we assign end2 to end1. This is necessarybecause we use end2 in another function (mergeSort function)to determine the next start1 (i.e) start1 for nextiteration = end2.next */static Node merge(Node start1, Node end1, Node start2, Node end2){ // Making sure that first node of second // list is higher. Node temp = null; if ((start1).data > (start2).data) { Node t = start1; start1 = start2; start2 = t; t = end1; end1 = end2; end2 = t; } // Merging remaining nodes Node astart = start1, aend = end1; Node bstart = start2, bend = end2; Node bendnext = (end2).next; while (astart != aend && bstart != bendnext) { if (astart.next.data > bstart.data) { temp = bstart.next; bstart.next = astart.next; astart.next = bstart; bstart = temp; } astart = astart.next; } if (astart == aend) astart.next = bstart; else end2 = end1; return start1;} /* MergeSort of Linked ListThe gap is initially 1. It is incremented as2, 4, 8, .. until it reaches the length of thelinked list. For each gap, the linked list issorted around the gap.The prevend stores the address of the last node aftersorting a part of linked list so that it's next nodecan be assigned after sorting the succeeding list.temp is used to store the next start1 because aftersorting, the last node will be different. So itis necessary to store the address of start1 beforesorting. We select the start1, end1, start2, end2 forsorting. start1 - end1 may be considered as a listand start2 - end2 may be considered as another listand we are merging these two sorted list in mergefunction and assigning the starting address to theprevious end address. */static Node mergeSort(Node head){ if (head == null) return head; Node start1 = null, end1 = null; Node start2 = null, end2 = null; Node prevend = null; int len = length(head); for (int gap = 1; gap < len; gap = gap*2) { start1 = head; while (start1 != null) { // If this is first iteration boolean isFirstIter = false; if (start1 == head) isFirstIter = true; // First part for merging int counter = gap; end1 = start1; while (--counter > 0 && end1.next != null) end1 = end1.next; // Second part for merging start2 = end1.next; if (start2 == null) break; counter = gap; end2 = start2; while (--counter > 0 && end2.next != null) end2 = end2.next; // To store for next iteration. Node temp = end2.next; // Merging two parts. merge(start1, end1, start2, end2); // Update head for first iteration, else // append after previous list if (isFirstIter) head = start1; else prevend.next = start1; prevend = end2; start1 = temp; } prevend.next = start1; } return head;} /* Function to print the Linked List */static void print(Node head){ if ((head) == null) return; Node temp = head; while (temp != null) { System.out.printf(\"%d \", temp.data); temp = temp.next; } System.out.printf(\"\\n\");} /* Given a reference (pointer topointer) to the head of a listand an int, push a new node onthe front of the list. */static Node push( Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref;} public static void main(String args[]){ // start with empty list Node head = null; // create linked list // 1.2.3.4.5.6.7 head = push(head, 7); head = push(head, 6); head = push(head, 5); head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); head = mergeSort(head); print(head);}} // This code is contributed by Arnab Kundu",
"e": 36729,
"s": 31800,
"text": null
},
{
"code": "# Iterative Python3 program to do merge sort on# linked list class Node: \"\"\"Structure of the Node.\"\"\" def __init__(self, data: int): self.data = data self.next = None class LinkedList: \"\"\"Encapsulate each left/right part's nodes in order to pass them as pointers. Without this workaround, the code would only work for a reverse-ordered list.\"\"\" head: Node tail: Node def __init__(self, head=None, tail=None): self.start = head self.end = tail def list_length(current: Node): \"\"\"Function to calculate length of linked list.\"\"\" count = 0; while (current != None): current = current.next; count += 1 return count; def merge(left: LinkedList, right: LinkedList) -> None: \"\"\"Merge the two sorted parts of the original linked list in order. Merge function of Merge Sort to Merge the two sorted parts of the Linked List. We compare the next value of start1 and current value of start2 and insert start2 after start1 if it's smaller than next value of start1. We do this until start1 or start2 end. If start1 ends, then we assign next of start1 to start2 because start2 may have some elements left out which are greater than the last value of start1. If start2 ends then we assign end2 to end1. This is necessary because we use end2 in another function (mergeSort function) to determine the next start1 (i.e) start1 for next iteration = end2.next\"\"\" # Ensure the first node of the second list is higher. if left.start.data > right.start.data: left.start, right.start = right.start, left.start left.end, right.end = right.end, left.end # Merge all remaining nodes. astart = left.start aend = left.end bstart = right.start bendnext = right.end.next while astart != aend and bstart != bendnext: if astart.next.data > bstart.data: temp = bstart.next bstart.next = astart.next astart.next = bstart bstart = temp astart = astart.next if astart == aend: astart.next = bstart else: right.end = left.end def mergeSort(head: LinkedList) -> None: \"\"\"MergeSort of Linked List The gap is initially 1. It is incremented as 2, 4, 8, .. until it reaches the length of the linked list. For each gap, the linked list is sorted around the gap. The prevend stores the address of the last node after sorting a part of linked list so that it's next node can be assigned after sorting the succeeding list. temp is used to store the next start1 because after sorting, the last node will be different. So it is necessary to store the address of start1 before sorting. We select the start1, end1, start2, end2 for sorting. start1 - end1 may be considered as a list and start2 - end2 may be considered as another list and we are merging these two sorted list in merge function and assigning the starting address to the previous end address.\"\"\" # Reject empty lists. if not head: return gap = 1 length = list_length(head.start) left = LinkedList() right = LinkedList() while gap < length: left.start = head.start while left.start: # If this is first iteration isFirstIter = False if left.start == head.start: isFirstIter = True # First part for merging counter = gap left.end = left.start counter -= 1 while counter != 0 and left.end.next: counter -= 1 left.end = left.end.next # Second part for merging right.start = left.end.next if not right.start: break counter = gap right.end = right.start counter -= 1 while counter != 0 and right.end.next: counter -= 1 right.end = right.end.next # To store for next iteration. temp = right.end.next # Merging two parts. merge(left, right) # Update head for first iteration, else append after previous list. if isFirstIter: head.start = left.start else: prevend.next = left.start prevend = right.end left.start = temp gap = gap * 2 prevend.next = left.start def prints(head): \"\"\"Print the linked list.\"\"\" if not head: return temp = head while temp: print(temp.data, end=' ') temp = temp.next print() def push(head: LinkedList, data: int) -> None: \"\"\"Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list.\"\"\" new_node = Node(data) new_node.next = head.start head.start = new_node # Driver codeif __name__=='__main__': # start with empty list head = LinkedList() # create linked list # 1.2.3.4.5.6.7 push(head, 6) push(head, 7) push(head, 2) push(head, 1) push(head, 3) push(head, 5) push(head, 4) mergeSort(head) prints(head.start) # This code is contributed by har2 (har-at-usf)",
"e": 42236,
"s": 36729,
"text": null
},
{
"code": "// Iterative C# program to do merge sort on// linked listusing System;class GFG{ /* Structure of the Node */public class Node{ public int data; public Node next;}; /* Function to calculate length of linked list */static int length(Node current){ int count = 0; while (current != null) { current = current.next; count++; } return count;} /* Merge function of Merge Sort to Merge the two sorted partsof the Linked List. We compare the next value of start1 andcurrent value of start2 and insert start2 after start1 ifit's smaller than next value of start1. We do this untilstart1 or start2 end. If start1 ends, then we assign nextof start1 to start2 because start2 may have some elementsleft out which are greater than the last value of start1.If start2 ends then we assign end2 to end1. This is necessarybecause we use end2 in another function (mergeSort function)to determine the next start1 (i.e) start1 for nextiteration = end2.next */static Node merge(Node start1, Node end1, Node start2, Node end2){ // Making sure that first node of second // list is higher. Node temp = null; if ((start1).data > (start2).data) { Node t = start1; start1 = start2; start2 = t; t = end1; end1 = end2; end2 = t; } // Merging remaining nodes Node astart = start1, aend = end1; Node bstart = start2, bend = end2; Node bendnext = (end2).next; while (astart != aend && bstart != bendnext) { if (astart.next.data > bstart.data) { temp = bstart.next; bstart.next = astart.next; astart.next = bstart; bstart = temp; } astart = astart.next; } if (astart == aend) astart.next = bstart; else end2 = end1; return start1;} /* MergeSort of Linked ListThe gap is initially 1. It is incremented as2, 4, 8, .. until it reaches the length of thelinked list. For each gap, the linked list issorted around the gap.The prevend stores the address of the last node aftersorting a part of linked list so that it's next nodecan be assigned after sorting the succeeding list.temp is used to store the next start1 because aftersorting, the last node will be different. So itis necessary to store the address of start1 beforesorting. We select the start1, end1, start2, end2 forsorting. start1 - end1 may be considered as a listand start2 - end2 may be considered as another listand we are merging these two sorted list in mergefunction and assigning the starting address to theprevious end address. */static Node mergeSort(Node head){ if (head == null) return head; Node start1 = null, end1 = null; Node start2 = null, end2 = null; Node prevend = null; int len = length(head); for (int gap = 1; gap < len; gap = gap*2) { start1 = head; while (start1 != null) { // If this is first iteration Boolean isFirstIter = false; if (start1 == head) isFirstIter = true; // First part for merging int counter = gap; end1 = start1; while (--counter > 0 && end1.next != null) end1 = end1.next; // Second part for merging start2 = end1.next; if (start2 == null) break; counter = gap; end2 = start2; while (--counter > 0 && end2.next != null) end2 = end2.next; // To store for next iteration. Node temp = end2.next; // Merging two parts. merge(start1, end1, start2, end2); // Update head for first iteration, else // append after previous list if (isFirstIter) head = start1; else prevend.next = start1; prevend = end2; start1 = temp; } prevend.next = start1; } return head;} /* Function to print the Linked List */static void print(Node head){ if ((head) == null) return; Node temp = head; while (temp != null) { Console.Write( temp.data + \" \"); temp = temp.next; } Console.Write(\"\\n\");} /* Given a reference (pointer topointer) to the head of a listand an int, push a new node onthe front of the list. */static Node push( Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref;} // Driver codepublic static void Main(String []args){ // start with empty list Node head = null; // create linked list // 1.2.3.4.5.6.7 head = push(head, 7); head = push(head, 6); head = push(head, 5); head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); head = mergeSort(head); print(head);}} // This code is contributed by Arnab Kundu",
"e": 47206,
"s": 42236,
"text": null
},
{
"code": "<script> // Iterative JavaScript program to do merge sort on // linked list /* Structure of the Node */ class Node { constructor() { this.data = 0; this.next = null; } } /* Function to calculate length of linked list */ function length(current) { var count = 0; while (current != null) { current = current.next; count++; } return count; } /* Merge function of Merge Sort to Merge the two sorted partsof the Linked List. We compare the next value of start1 andcurrent value of start2 and insert start2 after start1 ifit's smaller than next value of start1. We do this untilstart1 or start2 end. If start1 ends, then we assign nextof start1 to start2 because start2 may have some elementsleft out which are greater than the last value of start1.If start2 ends then we assign end2 to end1. This is necessarybecause we use end2 in another function (mergeSort function)to determine the next start1 (i.e) start1 for nextiteration = end2.next */ function merge(start1, end1, start2, end2) { // Making sure that first node of second // list is higher. var temp = null; if (start1.data > start2.data) { var t = start1; start1 = start2; start2 = t; t = end1; end1 = end2; end2 = t; } // Merging remaining nodes var astart = start1, aend = end1; var bstart = start2, bend = end2; var bendnext = end2.next; while (astart != aend && bstart != bendnext) { if (astart.next.data > bstart.data) { temp = bstart.next; bstart.next = astart.next; astart.next = bstart; bstart = temp; } astart = astart.next; } if (astart == aend) astart.next = bstart; else end2 = end1; return start1; } /* MergeSort of Linked ListThe gap is initially 1. It is incremented as2, 4, 8, .. until it reaches the length of thelinked list. For each gap, the linked list issorted around the gap.The prevend stores the address of the last node aftersorting a part of linked list so that it's next nodecan be assigned after sorting the succeeding list.temp is used to store the next start1 because aftersorting, the last node will be different. So itis necessary to store the address of start1 beforesorting. We select the start1, end1, start2, end2 forsorting. start1 - end1 may be considered as a listand start2 - end2 may be considered as another listand we are merging these two sorted list in mergefunction and assigning the starting address to theprevious end address. */ function mergeSort(head) { if (head == null) return head; var start1 = null, end1 = null; var start2 = null, end2 = null; var prevend = null; var len = length(head); for (var gap = 1; gap < len; gap = gap * 2) { start1 = head; while (start1 != null) { // If this is first iteration var isFirstIter = false; if (start1 == head) isFirstIter = true; // First part for merging var counter = gap; end1 = start1; while (--counter > 0 && end1.next != null) end1 = end1.next; // Second part for merging start2 = end1.next; if (start2 == null) break; counter = gap; end2 = start2; while (--counter > 0 && end2.next != null) end2 = end2.next; // To store for next iteration. var temp = end2.next; // Merging two parts. merge(start1, end1, start2, end2); // Update head for first iteration, else // append after previous list if (isFirstIter) head = start1; else prevend.next = start1; prevend = end2; start1 = temp; } prevend.next = start1; } return head; } /* Function to print the Linked List */ function print(head) { if (head == null) return; var temp = head; while (temp != null) { document.write(temp.data + \" \"); temp = temp.next; } document.write(\"<br>\"); } /* Given a reference (pointer topointer) to the head of a listand an int, push a new node onthe front of the list. */ function push(head_ref, new_data) { var new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; return head_ref; } // Driver code // start with empty list var head = null; // create linked list // 1.2.3.4.5.6.7 head = push(head, 7); head = push(head, 6); head = push(head, 5); head = push(head, 4); head = push(head, 3); head = push(head, 2); head = push(head, 1); head = mergeSort(head); print(head); </script>",
"e": 52251,
"s": 47206,
"text": null
},
{
"code": null,
"e": 52267,
"s": 52251,
"text": "1 2 3 4 5 6 7 \n"
},
{
"code": null,
"e": 52320,
"s": 52267,
"text": "Time Complexity : O(n Log n) Auxiliary Space : O(1) "
},
{
"code": null,
"e": 52331,
"s": 52320,
"text": "andrew1234"
},
{
"code": null,
"e": 52341,
"s": 52331,
"text": "rutvik_56"
},
{
"code": null,
"e": 52348,
"s": 52341,
"text": "rdtank"
},
{
"code": null,
"e": 52353,
"s": 52348,
"text": "har2"
},
{
"code": null,
"e": 52373,
"s": 52353,
"text": "Linked-List-Sorting"
},
{
"code": null,
"e": 52384,
"s": 52373,
"text": "Merge Sort"
},
{
"code": null,
"e": 52396,
"s": 52384,
"text": "Linked List"
},
{
"code": null,
"e": 52408,
"s": 52396,
"text": "Linked List"
},
{
"code": null,
"e": 52419,
"s": 52408,
"text": "Merge Sort"
},
{
"code": null,
"e": 52517,
"s": 52419,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 52563,
"s": 52517,
"text": "Delete a Linked List node at a given position"
},
{
"code": null,
"e": 52598,
"s": 52563,
"text": "Queue - Linked List Implementation"
},
{
"code": null,
"e": 52641,
"s": 52598,
"text": "Implement a stack using singly linked list"
},
{
"code": null,
"e": 52688,
"s": 52641,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 52749,
"s": 52688,
"text": "Circular Linked List | Set 1 (Introduction and Applications)"
},
{
"code": null,
"e": 52793,
"s": 52749,
"text": "Remove duplicates from a sorted linked list"
},
{
"code": null,
"e": 52849,
"s": 52793,
"text": "Function to check if a singly linked list is palindrome"
},
{
"code": null,
"e": 52904,
"s": 52849,
"text": "Find Length of a Linked List (Iterative and Recursive)"
},
{
"code": null,
"e": 52942,
"s": 52904,
"text": "Top 20 Linked List Interview Question"
}
] |
ISNULL() Function in SQL Server - GeeksforGeeks
|
21 Jan, 2021
ISNULL() :
This function in SQL Server is used to return the value given, in case the stated expression is NULL. Moreover, in case the given expression is not NULL then it returns the stated expression.
Features :
This function is used to find the given value, in case the expression given is NULL.
This function is used to find the given expression, in case the expression given is not NULL.
This function comes under Advanced Functions.
This function accepts two parameters namely expression, and value.
Syntax :
ISNULL(expression, value)
Parameter :
This method accepts two parameters.
expression –The specified expression which is to be checked if it’s NULL or not.
value –The specified value which is to be returned, in case the expression is NULL.
Returns :
It returns the value given, in case the stated expression is NULL else it returns the stated expression if the given expression is not NULL.
Example-1 :
Using ISNULL() function and getting the output.
SELECT ISNULL('gfg', 'Geeks');
Output :
gfg
Here, the expression is returned as the given value is not NULL.
Example-2 :
Using ISNULL() function and getting the output.
SELECT ISNULL(NULL, 'Geeks');
Output :
Geeks
Here, the expression is NULL so, the specified value is returned as output.
Example-3 :
Using ISNULL() function and getting the output using a variable.
DECLARE @exp VARCHAR(50);
SET @exp = 'geeksforgeeks';
SELECT ISNULL(@exp, 150);
Output :
geeksforgeeks
Example-4 :
Using ISNULL() function and getting the output using variables.
DECLARE @exp VARCHAR(50);
DECLARE @val VARCHAR(50);
SET @exp = NULL;
SET @val = 'GFG';
SELECT ISNULL(@exp, @val);
Output :
GFG
Application :
This function is used to find the value given, in case the stated expression is NULL else it finds the stated expression if the given expression is not NULL.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL | Subquery
SQL Query to Convert VARCHAR to INT
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates
|
[
{
"code": null,
"e": 25513,
"s": 25485,
"text": "\n21 Jan, 2021"
},
{
"code": null,
"e": 25524,
"s": 25513,
"text": "ISNULL() :"
},
{
"code": null,
"e": 25716,
"s": 25524,
"text": "This function in SQL Server is used to return the value given, in case the stated expression is NULL. Moreover, in case the given expression is not NULL then it returns the stated expression."
},
{
"code": null,
"e": 25727,
"s": 25716,
"text": "Features :"
},
{
"code": null,
"e": 25812,
"s": 25727,
"text": "This function is used to find the given value, in case the expression given is NULL."
},
{
"code": null,
"e": 25906,
"s": 25812,
"text": "This function is used to find the given expression, in case the expression given is not NULL."
},
{
"code": null,
"e": 25952,
"s": 25906,
"text": "This function comes under Advanced Functions."
},
{
"code": null,
"e": 26019,
"s": 25952,
"text": "This function accepts two parameters namely expression, and value."
},
{
"code": null,
"e": 26028,
"s": 26019,
"text": "Syntax :"
},
{
"code": null,
"e": 26054,
"s": 26028,
"text": "ISNULL(expression, value)"
},
{
"code": null,
"e": 26066,
"s": 26054,
"text": "Parameter :"
},
{
"code": null,
"e": 26102,
"s": 26066,
"text": "This method accepts two parameters."
},
{
"code": null,
"e": 26183,
"s": 26102,
"text": "expression –The specified expression which is to be checked if it’s NULL or not."
},
{
"code": null,
"e": 26267,
"s": 26183,
"text": "value –The specified value which is to be returned, in case the expression is NULL."
},
{
"code": null,
"e": 26277,
"s": 26267,
"text": "Returns :"
},
{
"code": null,
"e": 26418,
"s": 26277,
"text": "It returns the value given, in case the stated expression is NULL else it returns the stated expression if the given expression is not NULL."
},
{
"code": null,
"e": 26430,
"s": 26418,
"text": "Example-1 :"
},
{
"code": null,
"e": 26478,
"s": 26430,
"text": "Using ISNULL() function and getting the output."
},
{
"code": null,
"e": 26509,
"s": 26478,
"text": "SELECT ISNULL('gfg', 'Geeks');"
},
{
"code": null,
"e": 26518,
"s": 26509,
"text": "Output :"
},
{
"code": null,
"e": 26522,
"s": 26518,
"text": "gfg"
},
{
"code": null,
"e": 26587,
"s": 26522,
"text": "Here, the expression is returned as the given value is not NULL."
},
{
"code": null,
"e": 26599,
"s": 26587,
"text": "Example-2 :"
},
{
"code": null,
"e": 26647,
"s": 26599,
"text": "Using ISNULL() function and getting the output."
},
{
"code": null,
"e": 26677,
"s": 26647,
"text": "SELECT ISNULL(NULL, 'Geeks');"
},
{
"code": null,
"e": 26686,
"s": 26677,
"text": "Output :"
},
{
"code": null,
"e": 26692,
"s": 26686,
"text": "Geeks"
},
{
"code": null,
"e": 26768,
"s": 26692,
"text": "Here, the expression is NULL so, the specified value is returned as output."
},
{
"code": null,
"e": 26780,
"s": 26768,
"text": "Example-3 :"
},
{
"code": null,
"e": 26845,
"s": 26780,
"text": "Using ISNULL() function and getting the output using a variable."
},
{
"code": null,
"e": 26925,
"s": 26845,
"text": "DECLARE @exp VARCHAR(50);\nSET @exp = 'geeksforgeeks';\nSELECT ISNULL(@exp, 150);"
},
{
"code": null,
"e": 26934,
"s": 26925,
"text": "Output :"
},
{
"code": null,
"e": 26948,
"s": 26934,
"text": "geeksforgeeks"
},
{
"code": null,
"e": 26960,
"s": 26948,
"text": "Example-4 :"
},
{
"code": null,
"e": 27024,
"s": 26960,
"text": "Using ISNULL() function and getting the output using variables."
},
{
"code": null,
"e": 27138,
"s": 27024,
"text": "DECLARE @exp VARCHAR(50);\nDECLARE @val VARCHAR(50);\nSET @exp = NULL;\nSET @val = 'GFG';\nSELECT ISNULL(@exp, @val);"
},
{
"code": null,
"e": 27147,
"s": 27138,
"text": "Output :"
},
{
"code": null,
"e": 27151,
"s": 27147,
"text": "GFG"
},
{
"code": null,
"e": 27165,
"s": 27151,
"text": "Application :"
},
{
"code": null,
"e": 27323,
"s": 27165,
"text": "This function is used to find the value given, in case the stated expression is NULL else it finds the stated expression if the given expression is not NULL."
},
{
"code": null,
"e": 27332,
"s": 27323,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 27343,
"s": 27332,
"text": "SQL-Server"
},
{
"code": null,
"e": 27347,
"s": 27343,
"text": "SQL"
},
{
"code": null,
"e": 27351,
"s": 27347,
"text": "SQL"
},
{
"code": null,
"e": 27449,
"s": 27351,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27515,
"s": 27449,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 27572,
"s": 27515,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 27604,
"s": 27572,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 27619,
"s": 27604,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 27655,
"s": 27619,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 27733,
"s": 27655,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 27750,
"s": 27733,
"text": "SQL using Python"
},
{
"code": null,
"e": 27816,
"s": 27750,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 27878,
"s": 27816,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
}
] |
Remove BST keys outside the given range - GeeksforGeeks
|
25 May, 2021
Given a Binary Search Tree (BST) and a range [min, max], remove all keys which are outside the given range. The modified tree should also be BST. For example, consider the following BST and range [-10, 13].
The given tree should be changed to the following. Note that all keys outside the range [-10, 13] are removed and the modified tree is BST.
There are two possible cases for every node. 1) Node’s key is outside the given range. This case has two sub-cases. .......a) Node’s key is smaller than the min value. .......b) Node’s key is greater than the max value. 2) Node’s key is in range.We don’t need to do anything for case 2. In case 1, we need to remove the node and change the root of the subtree rooted with this node.
The idea is to fix the tree in a Post-order fashion. When we visit a node, we make sure that its left and right sub-trees are already fixed. In case 1.a), we simply remove the root and return the right sub-tree as a new root. In case 1.b), we remove the root and return the left sub-tree as a new root.
Following is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// A C++ program to remove BST keys outside the given range#include<bits/stdc++.h> using namespace std; // A BST node has key, and left and right pointersstruct node{ int key; struct node *left; struct node *right;}; // Removes all nodes having value outside the given range and returns the root// of modified treenode* removeOutsideRange(node *root, int min, int max){ // Base Case if (root == NULL) return NULL; // First fix the left and right subtrees of root root->left = removeOutsideRange(root->left, min, max); root->right = removeOutsideRange(root->right, min, max); // Now fix the root. There are 2 possible cases for root // 1.a) Root's key is smaller than min value (root is not in range) if (root->key < min) { node *rChild = root->right; delete root; return rChild; } // 1.b) Root's key is greater than max value (root is not in range) if (root->key > max) { node *lChild = root->left; delete root; return lChild; } // 2. Root is in range return root;} // A utility function to create a new BST node with key as given numnode* newNode(int num){ node* temp = new node; temp->key = num; temp->left = temp->right = NULL; return temp;} // A utility function to insert a given key to BSTnode* insert(node* root, int key){ if (root == NULL) return newNode(key); if (root->key > key) root->left = insert(root->left, key); else root->right = insert(root->right, key); return root;} // Utility function to traverse the binary tree after conversionvoid inorderTraversal(node* root){ if (root) { inorderTraversal( root->left ); cout << root->key << " "; inorderTraversal( root->right ); }} // Driver program to test above functionsint main(){ node* root = NULL; root = insert(root, 6); root = insert(root, -13); root = insert(root, 14); root = insert(root, -8); root = insert(root, 15); root = insert(root, 13); root = insert(root, 7); cout << "Inorder traversal of the given tree is: "; inorderTraversal(root); root = removeOutsideRange(root, -10, 13); cout << "\nInorder traversal of the modified tree is: "; inorderTraversal(root); return 0;}
// A Java program to remove BST// keys outside the given rangeimport java.math.BigDecimal;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.Scanner; class Node{ int key; Node left; Node right;} class GFG{ // Removes all nodes having value // outside the given range and // returns the root of modified tree private static Node removeOutsideRange(Node root, int min, int max) { // BASE CASE if(root == null) { return null; } // FIRST FIX THE LEFT AND // RIGHT SUBTREE OF ROOT root.left = removeOutsideRange(root.left, min, max); root.right = removeOutsideRange(root.right, min, max); // NOW FIX THE ROOT. THERE ARE // TWO POSSIBLE CASES FOR THE ROOT // 1. a) Root's key is smaller than // min value(root is not in range) if(root.key < min) { Node rchild = root.right; root = null; return rchild; } // 1. b) Root's key is greater than // max value (Root is not in range) if(root.key > max) { Node lchild = root.left; root = null; return lchild; } // 2. Root in range return root; } public static Node newNode(int num) { Node temp = new Node(); temp.key = num; temp.left = null; temp.right = null; return temp; } public static Node insert(Node root, int key) { if(root == null) { return newNode(key); } if(root.key > key) { root.left = insert(root.left, key); } else { root.right = insert(root.right, key); } return root; } private static void inorderTraversal(Node root) { if(root != null) { inorderTraversal(root.left); System.out.print(root.key + " "); inorderTraversal(root.right); } } // Driver code public static void main(String[] args) { Node root = null; root = insert(root, 6); root = insert(root, -13); root = insert(root, 14); root = insert(root, -8); root = insert(root, 15); root = insert(root, 13); root = insert(root, 7); System.out.print("Inorder Traversal of " + "the given tree is: "); inorderTraversal(root); root = removeOutsideRange(root, -10, 13); System.out.print("\nInorder traversal of " + "the modified tree: "); inorderTraversal(root); }} // This code is contributed// by Divya
# Python3 program to remove BST keys# outside the given range # A BST node has key, and left and right # pointers. A utility function to create# a new BST node with key as given numclass newNode: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None # Removes all nodes having value outside# the given range and returns the root# of modified treedef removeOutsideRange(root, Min, Max): # Base Case if root == None: return None # First fix the left and right # subtrees of root root.left = removeOutsideRange(root.left, Min, Max) root.right = removeOutsideRange(root.right, Min, Max) # Now fix the root. There are 2 # possible cases for root # 1.a) Root's key is smaller than # min value (root is not in range) if root.key < Min: rChild = root.right return rChild # 1.b) Root's key is greater than max # value (root is not in range) if root.key > Max: lChild = root.left return lChild # 2. Root is in range return root # A utility function to insert a given# key to BSTdef insert(root, key): if root == None: return newNode(key) if root.key > key: root.left = insert(root.left, key) else: root.right = insert(root.right, key) return root # Utility function to traverse the binary# tree after conversiondef inorderTraversal(root): if root: inorderTraversal( root.left) print(root.key, end = " ") inorderTraversal( root.right) # Driver Codeif __name__ == '__main__': root = None root = insert(root, 6) root = insert(root, -13) root = insert(root, 14) root = insert(root, -8) root = insert(root, 15) root = insert(root, 13) root = insert(root, 7) print("Inorder traversal of the given tree is:", end = " ") inorderTraversal(root) root = removeOutsideRange(root, -10, 13) print() print("Inorder traversal of the modified tree is:", end = " ") inorderTraversal(root) # This code is contributed by PranchalK
// A C# program to remove BST// keys outside the given rangeusing System; public class Node{ public int key; public Node left; public Node right;} public class GFG{ // Removes all nodes having value // outside the given range and // returns the root of modified tree private static Node removeOutsideRange(Node root, int min, int max) { // BASE CASE if(root == null) { return null; } // FIRST FIX THE LEFT AND // RIGHT SUBTREE OF ROOT root.left = removeOutsideRange(root.left, min, max); root.right = removeOutsideRange(root.right, min, max); // NOW FIX THE ROOT. THERE ARE // TWO POSSIBLE CASES FOR THE ROOT // 1. a) Root's key is smaller than // min value(root is not in range) if(root.key < min) { Node rchild = root.right; root = null; return rchild; } // 1. b) Root's key is greater than // max value (Root is not in range) if(root.key > max) { Node lchild = root.left; root = null; return lchild; } // 2. Root in range return root; } public static Node newNode(int num) { Node temp = new Node(); temp.key = num; temp.left = null; temp.right = null; return temp; } public static Node insert(Node root, int key) { if(root == null) { return newNode(key); } if(root.key > key) { root.left = insert(root.left, key); } else { root.right = insert(root.right, key); } return root; } private static void inorderTraversal(Node root) { if(root != null) { inorderTraversal(root.left); Console.Write(root.key + " "); inorderTraversal(root.right); } } // Driver code public static void Main(String[] args) { Node root = null; root = insert(root, 6); root = insert(root, -13); root = insert(root, 14); root = insert(root, -8); root = insert(root, 15); root = insert(root, 13); root = insert(root, 7); Console.Write("Inorder Traversal of " + "the given tree is: "); inorderTraversal(root); root = removeOutsideRange(root, -10, 13); Console.Write("\nInorder traversal of " + "the modified tree: "); inorderTraversal(root); }} // This code has been contributed// by PrinciRaj1992
<script> // A JavaScript program to remove BST// keys outside the given range class Node { constructor() { this.key = 0; this.left = null; this.right = null; }}// Removes all nodes having value // outside the given range and // returns the root of modified tree function removeOutsideRange(root , min , max) { // BASE CASE if (root == null) { return null; } // FIRST FIX THE LEFT AND // RIGHT SUBTREE OF ROOT root.left = removeOutsideRange(root.left, min, max); root.right = removeOutsideRange(root.right, min, max); // NOW FIX THE ROOT. THERE ARE // TWO POSSIBLE CASES FOR THE ROOT // 1. a) Root's key is smaller than // min value(root is not in range) if (root.key < min) { var rchild = root.right; root = null; return rchild; } // 1. b) Root's key is greater than // max value (Root is not in range) if (root.key > max) { var lchild = root.left; root = null; return lchild; } // 2. Root in range return root; } function newNode(num) {var temp = new Node(); temp.key = num; temp.left = null; temp.right = null; return temp; } function insert(root , key) { if (root == null) { return newNode(key); } if (root.key > key) { root.left = insert(root.left, key); } else { root.right = insert(root.right, key); } return root; } function inorderTraversal(root) { if (root != null) { inorderTraversal(root.left); document.write(root.key + " "); inorderTraversal(root.right); } } // Driver code var root = null; root = insert(root, 6); root = insert(root, -13); root = insert(root, 14); root = insert(root, -8); root = insert(root, 15); root = insert(root, 13); root = insert(root, 7); document.write("Inorder Traversal of " + "the given tree is: "); inorderTraversal(root); root = removeOutsideRange(root, -10, 13); document.write("<br/>Inorder traversal of " + "the modified tree: "); inorderTraversal(root); // This code is contributed by todaysgaurav </script>
Output:
Inorder traversal of the given tree is: -13 -8 6 7 13 14 15
Inorder traversal of the modified tree is: -8 6 7 13
Time Complexity: O(n) where n is the number of nodes in a given BST.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
9divya5
PranchalKatiyar
princiraj1992
pravesh25pandey
todaysgaurav
Binary Search Tree
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorted Array to Balanced BST
Red-Black Tree | Set 2 (Insert)
Optimal Binary Search Tree | DP-24
Find the node with minimum value in a Binary Search Tree
Advantages of BST over Hash Table
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Difference between Binary Tree and Binary Search Tree
Lowest Common Ancestor in a Binary Search Tree.
Binary Tree to Binary Search Tree Conversion
Find k-th smallest element in BST (Order Statistics in BST)
|
[
{
"code": null,
"e": 26265,
"s": 26237,
"text": "\n25 May, 2021"
},
{
"code": null,
"e": 26474,
"s": 26265,
"text": "Given a Binary Search Tree (BST) and a range [min, max], remove all keys which are outside the given range. The modified tree should also be BST. For example, consider the following BST and range [-10, 13]. "
},
{
"code": null,
"e": 26616,
"s": 26474,
"text": "The given tree should be changed to the following. Note that all keys outside the range [-10, 13] are removed and the modified tree is BST. "
},
{
"code": null,
"e": 27000,
"s": 26616,
"text": "There are two possible cases for every node. 1) Node’s key is outside the given range. This case has two sub-cases. .......a) Node’s key is smaller than the min value. .......b) Node’s key is greater than the max value. 2) Node’s key is in range.We don’t need to do anything for case 2. In case 1, we need to remove the node and change the root of the subtree rooted with this node. "
},
{
"code": null,
"e": 27303,
"s": 27000,
"text": "The idea is to fix the tree in a Post-order fashion. When we visit a node, we make sure that its left and right sub-trees are already fixed. In case 1.a), we simply remove the root and return the right sub-tree as a new root. In case 1.b), we remove the root and return the left sub-tree as a new root."
},
{
"code": null,
"e": 27359,
"s": 27303,
"text": "Following is the implementation of the above approach. "
},
{
"code": null,
"e": 27363,
"s": 27359,
"text": "C++"
},
{
"code": null,
"e": 27368,
"s": 27363,
"text": "Java"
},
{
"code": null,
"e": 27376,
"s": 27368,
"text": "Python3"
},
{
"code": null,
"e": 27379,
"s": 27376,
"text": "C#"
},
{
"code": null,
"e": 27390,
"s": 27379,
"text": "Javascript"
},
{
"code": "// A C++ program to remove BST keys outside the given range#include<bits/stdc++.h> using namespace std; // A BST node has key, and left and right pointersstruct node{ int key; struct node *left; struct node *right;}; // Removes all nodes having value outside the given range and returns the root// of modified treenode* removeOutsideRange(node *root, int min, int max){ // Base Case if (root == NULL) return NULL; // First fix the left and right subtrees of root root->left = removeOutsideRange(root->left, min, max); root->right = removeOutsideRange(root->right, min, max); // Now fix the root. There are 2 possible cases for root // 1.a) Root's key is smaller than min value (root is not in range) if (root->key < min) { node *rChild = root->right; delete root; return rChild; } // 1.b) Root's key is greater than max value (root is not in range) if (root->key > max) { node *lChild = root->left; delete root; return lChild; } // 2. Root is in range return root;} // A utility function to create a new BST node with key as given numnode* newNode(int num){ node* temp = new node; temp->key = num; temp->left = temp->right = NULL; return temp;} // A utility function to insert a given key to BSTnode* insert(node* root, int key){ if (root == NULL) return newNode(key); if (root->key > key) root->left = insert(root->left, key); else root->right = insert(root->right, key); return root;} // Utility function to traverse the binary tree after conversionvoid inorderTraversal(node* root){ if (root) { inorderTraversal( root->left ); cout << root->key << \" \"; inorderTraversal( root->right ); }} // Driver program to test above functionsint main(){ node* root = NULL; root = insert(root, 6); root = insert(root, -13); root = insert(root, 14); root = insert(root, -8); root = insert(root, 15); root = insert(root, 13); root = insert(root, 7); cout << \"Inorder traversal of the given tree is: \"; inorderTraversal(root); root = removeOutsideRange(root, -10, 13); cout << \"\\nInorder traversal of the modified tree is: \"; inorderTraversal(root); return 0;}",
"e": 29643,
"s": 27390,
"text": null
},
{
"code": "// A Java program to remove BST// keys outside the given rangeimport java.math.BigDecimal;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.Scanner; class Node{ int key; Node left; Node right;} class GFG{ // Removes all nodes having value // outside the given range and // returns the root of modified tree private static Node removeOutsideRange(Node root, int min, int max) { // BASE CASE if(root == null) { return null; } // FIRST FIX THE LEFT AND // RIGHT SUBTREE OF ROOT root.left = removeOutsideRange(root.left, min, max); root.right = removeOutsideRange(root.right, min, max); // NOW FIX THE ROOT. THERE ARE // TWO POSSIBLE CASES FOR THE ROOT // 1. a) Root's key is smaller than // min value(root is not in range) if(root.key < min) { Node rchild = root.right; root = null; return rchild; } // 1. b) Root's key is greater than // max value (Root is not in range) if(root.key > max) { Node lchild = root.left; root = null; return lchild; } // 2. Root in range return root; } public static Node newNode(int num) { Node temp = new Node(); temp.key = num; temp.left = null; temp.right = null; return temp; } public static Node insert(Node root, int key) { if(root == null) { return newNode(key); } if(root.key > key) { root.left = insert(root.left, key); } else { root.right = insert(root.right, key); } return root; } private static void inorderTraversal(Node root) { if(root != null) { inorderTraversal(root.left); System.out.print(root.key + \" \"); inorderTraversal(root.right); } } // Driver code public static void main(String[] args) { Node root = null; root = insert(root, 6); root = insert(root, -13); root = insert(root, 14); root = insert(root, -8); root = insert(root, 15); root = insert(root, 13); root = insert(root, 7); System.out.print(\"Inorder Traversal of \" + \"the given tree is: \"); inorderTraversal(root); root = removeOutsideRange(root, -10, 13); System.out.print(\"\\nInorder traversal of \" + \"the modified tree: \"); inorderTraversal(root); }} // This code is contributed// by Divya",
"e": 32541,
"s": 29643,
"text": null
},
{
"code": "# Python3 program to remove BST keys# outside the given range # A BST node has key, and left and right # pointers. A utility function to create# a new BST node with key as given numclass newNode: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None # Removes all nodes having value outside# the given range and returns the root# of modified treedef removeOutsideRange(root, Min, Max): # Base Case if root == None: return None # First fix the left and right # subtrees of root root.left = removeOutsideRange(root.left, Min, Max) root.right = removeOutsideRange(root.right, Min, Max) # Now fix the root. There are 2 # possible cases for root # 1.a) Root's key is smaller than # min value (root is not in range) if root.key < Min: rChild = root.right return rChild # 1.b) Root's key is greater than max # value (root is not in range) if root.key > Max: lChild = root.left return lChild # 2. Root is in range return root # A utility function to insert a given# key to BSTdef insert(root, key): if root == None: return newNode(key) if root.key > key: root.left = insert(root.left, key) else: root.right = insert(root.right, key) return root # Utility function to traverse the binary# tree after conversiondef inorderTraversal(root): if root: inorderTraversal( root.left) print(root.key, end = \" \") inorderTraversal( root.right) # Driver Codeif __name__ == '__main__': root = None root = insert(root, 6) root = insert(root, -13) root = insert(root, 14) root = insert(root, -8) root = insert(root, 15) root = insert(root, 13) root = insert(root, 7) print(\"Inorder traversal of the given tree is:\", end = \" \") inorderTraversal(root) root = removeOutsideRange(root, -10, 13) print() print(\"Inorder traversal of the modified tree is:\", end = \" \") inorderTraversal(root) # This code is contributed by PranchalK",
"e": 34818,
"s": 32541,
"text": null
},
{
"code": "// A C# program to remove BST// keys outside the given rangeusing System; public class Node{ public int key; public Node left; public Node right;} public class GFG{ // Removes all nodes having value // outside the given range and // returns the root of modified tree private static Node removeOutsideRange(Node root, int min, int max) { // BASE CASE if(root == null) { return null; } // FIRST FIX THE LEFT AND // RIGHT SUBTREE OF ROOT root.left = removeOutsideRange(root.left, min, max); root.right = removeOutsideRange(root.right, min, max); // NOW FIX THE ROOT. THERE ARE // TWO POSSIBLE CASES FOR THE ROOT // 1. a) Root's key is smaller than // min value(root is not in range) if(root.key < min) { Node rchild = root.right; root = null; return rchild; } // 1. b) Root's key is greater than // max value (Root is not in range) if(root.key > max) { Node lchild = root.left; root = null; return lchild; } // 2. Root in range return root; } public static Node newNode(int num) { Node temp = new Node(); temp.key = num; temp.left = null; temp.right = null; return temp; } public static Node insert(Node root, int key) { if(root == null) { return newNode(key); } if(root.key > key) { root.left = insert(root.left, key); } else { root.right = insert(root.right, key); } return root; } private static void inorderTraversal(Node root) { if(root != null) { inorderTraversal(root.left); Console.Write(root.key + \" \"); inorderTraversal(root.right); } } // Driver code public static void Main(String[] args) { Node root = null; root = insert(root, 6); root = insert(root, -13); root = insert(root, 14); root = insert(root, -8); root = insert(root, 15); root = insert(root, 13); root = insert(root, 7); Console.Write(\"Inorder Traversal of \" + \"the given tree is: \"); inorderTraversal(root); root = removeOutsideRange(root, -10, 13); Console.Write(\"\\nInorder traversal of \" + \"the modified tree: \"); inorderTraversal(root); }} // This code has been contributed// by PrinciRaj1992",
"e": 37627,
"s": 34818,
"text": null
},
{
"code": "<script> // A JavaScript program to remove BST// keys outside the given range class Node { constructor() { this.key = 0; this.left = null; this.right = null; }}// Removes all nodes having value // outside the given range and // returns the root of modified tree function removeOutsideRange(root , min , max) { // BASE CASE if (root == null) { return null; } // FIRST FIX THE LEFT AND // RIGHT SUBTREE OF ROOT root.left = removeOutsideRange(root.left, min, max); root.right = removeOutsideRange(root.right, min, max); // NOW FIX THE ROOT. THERE ARE // TWO POSSIBLE CASES FOR THE ROOT // 1. a) Root's key is smaller than // min value(root is not in range) if (root.key < min) { var rchild = root.right; root = null; return rchild; } // 1. b) Root's key is greater than // max value (Root is not in range) if (root.key > max) { var lchild = root.left; root = null; return lchild; } // 2. Root in range return root; } function newNode(num) {var temp = new Node(); temp.key = num; temp.left = null; temp.right = null; return temp; } function insert(root , key) { if (root == null) { return newNode(key); } if (root.key > key) { root.left = insert(root.left, key); } else { root.right = insert(root.right, key); } return root; } function inorderTraversal(root) { if (root != null) { inorderTraversal(root.left); document.write(root.key + \" \"); inorderTraversal(root.right); } } // Driver code var root = null; root = insert(root, 6); root = insert(root, -13); root = insert(root, 14); root = insert(root, -8); root = insert(root, 15); root = insert(root, 13); root = insert(root, 7); document.write(\"Inorder Traversal of \" + \"the given tree is: \"); inorderTraversal(root); root = removeOutsideRange(root, -10, 13); document.write(\"<br/>Inorder traversal of \" + \"the modified tree: \"); inorderTraversal(root); // This code is contributed by todaysgaurav </script>",
"e": 40018,
"s": 37627,
"text": null
},
{
"code": null,
"e": 40027,
"s": 40018,
"text": "Output: "
},
{
"code": null,
"e": 40140,
"s": 40027,
"text": "Inorder traversal of the given tree is: -13 -8 6 7 13 14 15\nInorder traversal of the modified tree is: -8 6 7 13"
},
{
"code": null,
"e": 40210,
"s": 40140,
"text": "Time Complexity: O(n) where n is the number of nodes in a given BST. "
},
{
"code": null,
"e": 40336,
"s": 40210,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 40344,
"s": 40336,
"text": "9divya5"
},
{
"code": null,
"e": 40360,
"s": 40344,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 40374,
"s": 40360,
"text": "princiraj1992"
},
{
"code": null,
"e": 40390,
"s": 40374,
"text": "pravesh25pandey"
},
{
"code": null,
"e": 40403,
"s": 40390,
"text": "todaysgaurav"
},
{
"code": null,
"e": 40422,
"s": 40403,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 40441,
"s": 40422,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 40539,
"s": 40441,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40568,
"s": 40539,
"text": "Sorted Array to Balanced BST"
},
{
"code": null,
"e": 40600,
"s": 40568,
"text": "Red-Black Tree | Set 2 (Insert)"
},
{
"code": null,
"e": 40635,
"s": 40600,
"text": "Optimal Binary Search Tree | DP-24"
},
{
"code": null,
"e": 40692,
"s": 40635,
"text": "Find the node with minimum value in a Binary Search Tree"
},
{
"code": null,
"e": 40726,
"s": 40692,
"text": "Advantages of BST over Hash Table"
},
{
"code": null,
"e": 40796,
"s": 40726,
"text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)"
},
{
"code": null,
"e": 40850,
"s": 40796,
"text": "Difference between Binary Tree and Binary Search Tree"
},
{
"code": null,
"e": 40898,
"s": 40850,
"text": "Lowest Common Ancestor in a Binary Search Tree."
},
{
"code": null,
"e": 40943,
"s": 40898,
"text": "Binary Tree to Binary Search Tree Conversion"
}
] |
Minimum number of operations required to reduce N to 0 - GeeksforGeeks
|
05 Apr, 2021
Given an integer N, the task is to count the minimum steps required to reduce the value of N to 0 by performing the following two operations:
Consider integers A and B where N = A * B (A != 1 and B != 1), reduce N to min(A, B)
Decrease the value of N by 1
Examples :
Input: N = 3Output: 3Explanation:Steps involved are 3 -> 2 -> 1 -> 0Therefore, the minimum steps required is 3. Input: N = 4Output: 3Explanation:Steps involved are 4->2->1->0.Therefore, the minimum steps required is 3.
Naive Approach: The idea is to use the concept of Dynamic Programming. Follow the steps below to solve the problem:
The simple solution to this problem is to replace N with each possible value until it is not 0.
When N reaches 0, compare the count of moves with the minimum obtained so far to obtain the optimal answer.
Finally, print the minimum steps calculated.
Illustration:
N = 4,
On applying the first rule, factors of 4 are [ 1, 2, 4 ]. Therefore, all possible pairs (a, b) are (1 * 4), (2 * 2), (4 * 1).Only pair satisfying the condition (a!=1 and b!=1) is (2, 2) . Therefore, reduce 4 to 2. Finally, reduce N to 0, in 3 steps(4 -> 2 -> 1 -> 0)
On applying the second rule, steps required is 4, (4 -> 3 -> 2 -> 1 -> 0).
Recursive tree for N = 4 is
4
/ \
3 2(2*2)
| |
2 1
| |
1 0
|
0
Therefore, minimum steps required to reduce N to 0 is 3.
Therefore, the relation is:
f(N) = 1 + min( f(N-1), min(f(x)) ), where N % x == 0 and x is in range [2, K] where K = sqrt(N)
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to count the minimum// steps required to reduce nint downToZero(int n){ // Base case if (n <= 3) return n; // Allocate memory for storing // intermediate results vector<int> dp(n + 1, -1); // Store base values dp[0] = 0; dp[1] = 1; dp[2] = 2; dp[3] = 3; // Stores square root // of each number int sqr; for (int i = 4; i <= n; i++) { // Compute square root sqr = sqrt(i); int best = INT_MAX; // Use rule 1 to find optimized // answer while (sqr > 1) { // Check if it perfectly divides n if (i % sqr == 0) { best = min(best, 1 + dp[sqr]); } sqr--; } // Use of rule 2 to find // the optimized answer best = min(best, 1 + dp[i - 1]); // Store computed value dp[i] = best; } // Return answer return dp[n];} // Driver Codeint main(){ int n = 4; cout << downToZero(n); return 0;}
// Java program to implement// the above approachclass GFG{ // Function to count the minimum// steps required to reduce nstatic int downToZero(int n){ // Base case if (n <= 3) return n; // Allocate memory for storing // intermediate results int []dp = new int[n + 1]; for(int i = 0; i < n + 1; i++) dp[i] = -1; // Store base values dp[0] = 0; dp[1] = 1; dp[2] = 2; dp[3] = 3; // Stores square root // of each number int sqr; for(int i = 4; i <= n; i++) { // Compute square root sqr = (int)Math.sqrt(i); int best = Integer.MAX_VALUE; // Use rule 1 to find optimized // answer while (sqr > 1) { // Check if it perfectly divides n if (i % sqr == 0) { best = Math.min(best, 1 + dp[sqr]); } sqr--; } // Use of rule 2 to find // the optimized answer best = Math.min(best, 1 + dp[i - 1]); // Store computed value dp[i] = best; } // Return answer return dp[n];} // Driver Codepublic static void main(String[] args){ int n = 4; System.out.print(downToZero(n));}} // This code is contributed by amal kumar choubey
# Python3 program to implement# the above approachimport mathimport sys # Function to count the minimum# steps required to reduce ndef downToZero(n): # Base case if (n <= 3): return n # Allocate memory for storing # intermediate results dp = [-1] * (n + 1) # Store base values dp[0] = 0 dp[1] = 1 dp[2] = 2 dp[3] = 3 # Stores square root # of each number for i in range(4, n + 1): # Compute square root sqr = (int)(math.sqrt(i)) best = sys.maxsize # Use rule 1 to find optimized # answer while (sqr > 1): # Check if it perfectly divides n if (i % sqr == 0): best = min(best, 1 + dp[sqr]) sqr -= 1 # Use of rule 2 to find # the optimized answer best = min(best, 1 + dp[i - 1]) # Store computed value dp[i] = best # Return answer return dp[n] # Driver Codeif __name__ == "__main__": n = 4 print(downToZero(n)) # This code is contributed by chitranayal
// C# program to implement// the above approachusing System; class GFG{ // Function to count the minimum// steps required to reduce nstatic int downToZero(int n){ // Base case if (n <= 3) return n; // Allocate memory for storing // intermediate results int []dp = new int[n + 1]; for(int i = 0; i < n + 1; i++) dp[i] = -1; // Store base values dp[0] = 0; dp[1] = 1; dp[2] = 2; dp[3] = 3; // Stores square root // of each number int sqr; for(int i = 4; i <= n; i++) { // Compute square root sqr = (int)Math.Sqrt(i); int best = int.MaxValue; // Use rule 1 to find optimized // answer while (sqr > 1) { // Check if it perfectly divides n if (i % sqr == 0) { best = Math.Min(best, 1 + dp[sqr]); } sqr--; } // Use of rule 2 to find // the optimized answer best = Math.Min(best, 1 + dp[i - 1]); // Store computed value dp[i] = best; } // Return answer return dp[n];} // Driver Codepublic static void Main(String[] args){ int n = 4; Console.Write(downToZero(n));}} // This code is contributed by amal kumar choubey
<script> // Javascript Program to implement // the above approach // Function to count the minimum // steps required to reduce n function downToZero(n) { // Base case if (n <= 3) return n; // Allocate memory for storing // intermediate results let dp = new Array(n + 1) dp.fill(-1); // Store base values dp[0] = 0; dp[1] = 1; dp[2] = 2; dp[3] = 3; // Stores square root // of each number let sqr; for (let i = 4; i <= n; i++) { // Compute square root sqr = Math.sqrt(i); let best = Number.MAX_VALUE; // Use rule 1 to find optimized // answer while (sqr > 1) { // Check if it perfectly divides n if (i % sqr == 0) { best = Math.min(best, 1 + dp[sqr]); } sqr--; } // Use of rule 2 to find // the optimized answer best = Math.min(best, 1 + dp[i - 1]); // Store computed value dp[i] = best; } // Return answer return dp[n]; } let n = 4; document.write(downToZero(n)); // This code is contributed by divyesh072019.</script>
3
Time complexity: O(N * sqrt(n))Auxiliary Space: O(N)
Efficient Approach: The idea is to observe that it is possible to replace N by N’ where N’ = min(a, b) (N = a * b) (a != 1 and b != 1).
If N is even, then the smallest value that divides N is 2. Therefore, directly calculate f(N) = 1 + f(2) = 3.
If N is odd, then reduce N by 1 from it i.e N = N – 1. Apply the same logic as used for even numbers. Therefore, for odd numbers, the minimum steps required is 4.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum// steps required to reduce nint downToZero(int n){ // Base case if (n <= 3) return n; // Return answer based on // parity of n return n % 2 == 0 ? 3 : 4;} // Driver Codeint main(){ int n = 4; cout << downToZero(n); return 0;}
// Java Program to implement// the above approachclass GFG{ // Function to find the minimum// steps required to reduce nstatic int downToZero(int n){ // Base case if (n <= 3) return n; // Return answer based on // parity of n return n % 2 == 0 ? 3 : 4;} // Driver Codepublic static void main(String[] args){ int n = 4; System.out.println(downToZero(n));}} // This code is contributed by rock_cool
# Python3 Program to implement# the above approach # Function to find the minimum# steps required to reduce ndef downToZero(n): # Base case if (n <= 3): return n; # Return answer based on # parity of n if(n % 2 == 0): return 3; else: return 4; # Driver Codeif __name__ == '__main__': n = 4; print(downToZero(n)); # This code is contributed by Rohit_ranjan
// C# Program to implement// the above approachusing System;class GFG{ // Function to find the minimum// steps required to reduce nstatic int downToZero(int n){ // Base case if (n <= 3) return n; // Return answer based on // parity of n return n % 2 == 0 ? 3 : 4;} // Driver Codepublic static void Main(String[] args){ int n = 4; Console.WriteLine(downToZero(n));}} // This code is contributed by Rajput-Ji
<script> // Javascript Program to implement // the above approach // Function to find the minimum // steps required to reduce n function downToZero(n) { // Base case if (n <= 3) return n; // Return answer based on // parity of n return n % 2 == 0 ? 3 : 4; } let n = 4; document.write(downToZero(n)); // This code is contributed by divyeshrabadiya07.</script>
3
Time complexity: O(1)Auxiliary Space: O(1)
rock_cool
Amal Kumar Choubey
Rajput-Ji
Rohit_ranjan
ukasp
divyeshrabadiya07
divyesh072019
Number Divisibility
Numbers
Dynamic Programming
Greedy
Mathematical
Recursion
Dynamic Programming
Greedy
Mathematical
Recursion
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Subset Sum Problem | DP-25
Coin Change | DP-7
Longest Palindromic Substring | Set 1
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Program for array rotation
Write a program to print all permutations of a given string
|
[
{
"code": null,
"e": 26521,
"s": 26493,
"text": "\n05 Apr, 2021"
},
{
"code": null,
"e": 26663,
"s": 26521,
"text": "Given an integer N, the task is to count the minimum steps required to reduce the value of N to 0 by performing the following two operations:"
},
{
"code": null,
"e": 26748,
"s": 26663,
"text": "Consider integers A and B where N = A * B (A != 1 and B != 1), reduce N to min(A, B)"
},
{
"code": null,
"e": 26777,
"s": 26748,
"text": "Decrease the value of N by 1"
},
{
"code": null,
"e": 26788,
"s": 26777,
"text": "Examples :"
},
{
"code": null,
"e": 27008,
"s": 26788,
"text": "Input: N = 3Output: 3Explanation:Steps involved are 3 -> 2 -> 1 -> 0Therefore, the minimum steps required is 3. Input: N = 4Output: 3Explanation:Steps involved are 4->2->1->0.Therefore, the minimum steps required is 3. "
},
{
"code": null,
"e": 27125,
"s": 27008,
"text": "Naive Approach: The idea is to use the concept of Dynamic Programming. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27221,
"s": 27125,
"text": "The simple solution to this problem is to replace N with each possible value until it is not 0."
},
{
"code": null,
"e": 27329,
"s": 27221,
"text": "When N reaches 0, compare the count of moves with the minimum obtained so far to obtain the optimal answer."
},
{
"code": null,
"e": 27374,
"s": 27329,
"text": "Finally, print the minimum steps calculated."
},
{
"code": null,
"e": 27388,
"s": 27374,
"text": "Illustration:"
},
{
"code": null,
"e": 27397,
"s": 27388,
"text": "N = 4, "
},
{
"code": null,
"e": 27665,
"s": 27397,
"text": "On applying the first rule, factors of 4 are [ 1, 2, 4 ]. Therefore, all possible pairs (a, b) are (1 * 4), (2 * 2), (4 * 1).Only pair satisfying the condition (a!=1 and b!=1) is (2, 2) . Therefore, reduce 4 to 2. Finally, reduce N to 0, in 3 steps(4 -> 2 -> 1 -> 0)"
},
{
"code": null,
"e": 27742,
"s": 27665,
"text": "On applying the second rule, steps required is 4, (4 -> 3 -> 2 -> 1 -> 0). "
},
{
"code": null,
"e": 27970,
"s": 27742,
"text": "Recursive tree for N = 4 is\n 4\n / \\\n 3 2(2*2)\n | |\n 2 1\n | |\n 1 0\n |\n 0"
},
{
"code": null,
"e": 28027,
"s": 27970,
"text": "Therefore, minimum steps required to reduce N to 0 is 3."
},
{
"code": null,
"e": 28055,
"s": 28027,
"text": "Therefore, the relation is:"
},
{
"code": null,
"e": 28152,
"s": 28055,
"text": "f(N) = 1 + min( f(N-1), min(f(x)) ), where N % x == 0 and x is in range [2, K] where K = sqrt(N)"
},
{
"code": null,
"e": 28203,
"s": 28152,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28207,
"s": 28203,
"text": "C++"
},
{
"code": null,
"e": 28212,
"s": 28207,
"text": "Java"
},
{
"code": null,
"e": 28220,
"s": 28212,
"text": "Python3"
},
{
"code": null,
"e": 28223,
"s": 28220,
"text": "C#"
},
{
"code": null,
"e": 28234,
"s": 28223,
"text": "Javascript"
},
{
"code": "// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to count the minimum// steps required to reduce nint downToZero(int n){ // Base case if (n <= 3) return n; // Allocate memory for storing // intermediate results vector<int> dp(n + 1, -1); // Store base values dp[0] = 0; dp[1] = 1; dp[2] = 2; dp[3] = 3; // Stores square root // of each number int sqr; for (int i = 4; i <= n; i++) { // Compute square root sqr = sqrt(i); int best = INT_MAX; // Use rule 1 to find optimized // answer while (sqr > 1) { // Check if it perfectly divides n if (i % sqr == 0) { best = min(best, 1 + dp[sqr]); } sqr--; } // Use of rule 2 to find // the optimized answer best = min(best, 1 + dp[i - 1]); // Store computed value dp[i] = best; } // Return answer return dp[n];} // Driver Codeint main(){ int n = 4; cout << downToZero(n); return 0;}",
"e": 29334,
"s": 28234,
"text": null
},
{
"code": "// Java program to implement// the above approachclass GFG{ // Function to count the minimum// steps required to reduce nstatic int downToZero(int n){ // Base case if (n <= 3) return n; // Allocate memory for storing // intermediate results int []dp = new int[n + 1]; for(int i = 0; i < n + 1; i++) dp[i] = -1; // Store base values dp[0] = 0; dp[1] = 1; dp[2] = 2; dp[3] = 3; // Stores square root // of each number int sqr; for(int i = 4; i <= n; i++) { // Compute square root sqr = (int)Math.sqrt(i); int best = Integer.MAX_VALUE; // Use rule 1 to find optimized // answer while (sqr > 1) { // Check if it perfectly divides n if (i % sqr == 0) { best = Math.min(best, 1 + dp[sqr]); } sqr--; } // Use of rule 2 to find // the optimized answer best = Math.min(best, 1 + dp[i - 1]); // Store computed value dp[i] = best; } // Return answer return dp[n];} // Driver Codepublic static void main(String[] args){ int n = 4; System.out.print(downToZero(n));}} // This code is contributed by amal kumar choubey",
"e": 30607,
"s": 29334,
"text": null
},
{
"code": "# Python3 program to implement# the above approachimport mathimport sys # Function to count the minimum# steps required to reduce ndef downToZero(n): # Base case if (n <= 3): return n # Allocate memory for storing # intermediate results dp = [-1] * (n + 1) # Store base values dp[0] = 0 dp[1] = 1 dp[2] = 2 dp[3] = 3 # Stores square root # of each number for i in range(4, n + 1): # Compute square root sqr = (int)(math.sqrt(i)) best = sys.maxsize # Use rule 1 to find optimized # answer while (sqr > 1): # Check if it perfectly divides n if (i % sqr == 0): best = min(best, 1 + dp[sqr]) sqr -= 1 # Use of rule 2 to find # the optimized answer best = min(best, 1 + dp[i - 1]) # Store computed value dp[i] = best # Return answer return dp[n] # Driver Codeif __name__ == \"__main__\": n = 4 print(downToZero(n)) # This code is contributed by chitranayal ",
"e": 31673,
"s": 30607,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System; class GFG{ // Function to count the minimum// steps required to reduce nstatic int downToZero(int n){ // Base case if (n <= 3) return n; // Allocate memory for storing // intermediate results int []dp = new int[n + 1]; for(int i = 0; i < n + 1; i++) dp[i] = -1; // Store base values dp[0] = 0; dp[1] = 1; dp[2] = 2; dp[3] = 3; // Stores square root // of each number int sqr; for(int i = 4; i <= n; i++) { // Compute square root sqr = (int)Math.Sqrt(i); int best = int.MaxValue; // Use rule 1 to find optimized // answer while (sqr > 1) { // Check if it perfectly divides n if (i % sqr == 0) { best = Math.Min(best, 1 + dp[sqr]); } sqr--; } // Use of rule 2 to find // the optimized answer best = Math.Min(best, 1 + dp[i - 1]); // Store computed value dp[i] = best; } // Return answer return dp[n];} // Driver Codepublic static void Main(String[] args){ int n = 4; Console.Write(downToZero(n));}} // This code is contributed by amal kumar choubey",
"e": 32950,
"s": 31673,
"text": null
},
{
"code": "<script> // Javascript Program to implement // the above approach // Function to count the minimum // steps required to reduce n function downToZero(n) { // Base case if (n <= 3) return n; // Allocate memory for storing // intermediate results let dp = new Array(n + 1) dp.fill(-1); // Store base values dp[0] = 0; dp[1] = 1; dp[2] = 2; dp[3] = 3; // Stores square root // of each number let sqr; for (let i = 4; i <= n; i++) { // Compute square root sqr = Math.sqrt(i); let best = Number.MAX_VALUE; // Use rule 1 to find optimized // answer while (sqr > 1) { // Check if it perfectly divides n if (i % sqr == 0) { best = Math.min(best, 1 + dp[sqr]); } sqr--; } // Use of rule 2 to find // the optimized answer best = Math.min(best, 1 + dp[i - 1]); // Store computed value dp[i] = best; } // Return answer return dp[n]; } let n = 4; document.write(downToZero(n)); // This code is contributed by divyesh072019.</script>",
"e": 34273,
"s": 32950,
"text": null
},
{
"code": null,
"e": 34275,
"s": 34273,
"text": "3"
},
{
"code": null,
"e": 34331,
"s": 34277,
"text": "Time complexity: O(N * sqrt(n))Auxiliary Space: O(N) "
},
{
"code": null,
"e": 34468,
"s": 34331,
"text": "Efficient Approach: The idea is to observe that it is possible to replace N by N’ where N’ = min(a, b) (N = a * b) (a != 1 and b != 1). "
},
{
"code": null,
"e": 34578,
"s": 34468,
"text": "If N is even, then the smallest value that divides N is 2. Therefore, directly calculate f(N) = 1 + f(2) = 3."
},
{
"code": null,
"e": 34741,
"s": 34578,
"text": "If N is odd, then reduce N by 1 from it i.e N = N – 1. Apply the same logic as used for even numbers. Therefore, for odd numbers, the minimum steps required is 4."
},
{
"code": null,
"e": 34794,
"s": 34741,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 34798,
"s": 34794,
"text": "C++"
},
{
"code": null,
"e": 34803,
"s": 34798,
"text": "Java"
},
{
"code": null,
"e": 34811,
"s": 34803,
"text": "Python3"
},
{
"code": null,
"e": 34814,
"s": 34811,
"text": "C#"
},
{
"code": null,
"e": 34825,
"s": 34814,
"text": "Javascript"
},
{
"code": "// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum// steps required to reduce nint downToZero(int n){ // Base case if (n <= 3) return n; // Return answer based on // parity of n return n % 2 == 0 ? 3 : 4;} // Driver Codeint main(){ int n = 4; cout << downToZero(n); return 0;}",
"e": 35209,
"s": 34825,
"text": null
},
{
"code": "// Java Program to implement// the above approachclass GFG{ // Function to find the minimum// steps required to reduce nstatic int downToZero(int n){ // Base case if (n <= 3) return n; // Return answer based on // parity of n return n % 2 == 0 ? 3 : 4;} // Driver Codepublic static void main(String[] args){ int n = 4; System.out.println(downToZero(n));}} // This code is contributed by rock_cool",
"e": 35638,
"s": 35209,
"text": null
},
{
"code": "# Python3 Program to implement# the above approach # Function to find the minimum# steps required to reduce ndef downToZero(n): # Base case if (n <= 3): return n; # Return answer based on # parity of n if(n % 2 == 0): return 3; else: return 4; # Driver Codeif __name__ == '__main__': n = 4; print(downToZero(n)); # This code is contributed by Rohit_ranjan",
"e": 36047,
"s": 35638,
"text": null
},
{
"code": "// C# Program to implement// the above approachusing System;class GFG{ // Function to find the minimum// steps required to reduce nstatic int downToZero(int n){ // Base case if (n <= 3) return n; // Return answer based on // parity of n return n % 2 == 0 ? 3 : 4;} // Driver Codepublic static void Main(String[] args){ int n = 4; Console.WriteLine(downToZero(n));}} // This code is contributed by Rajput-Ji",
"e": 36486,
"s": 36047,
"text": null
},
{
"code": "<script> // Javascript Program to implement // the above approach // Function to find the minimum // steps required to reduce n function downToZero(n) { // Base case if (n <= 3) return n; // Return answer based on // parity of n return n % 2 == 0 ? 3 : 4; } let n = 4; document.write(downToZero(n)); // This code is contributed by divyeshrabadiya07.</script>",
"e": 36937,
"s": 36486,
"text": null
},
{
"code": null,
"e": 36939,
"s": 36937,
"text": "3"
},
{
"code": null,
"e": 36985,
"s": 36941,
"text": "Time complexity: O(1)Auxiliary Space: O(1) "
},
{
"code": null,
"e": 36995,
"s": 36985,
"text": "rock_cool"
},
{
"code": null,
"e": 37014,
"s": 36995,
"text": "Amal Kumar Choubey"
},
{
"code": null,
"e": 37024,
"s": 37014,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 37037,
"s": 37024,
"text": "Rohit_ranjan"
},
{
"code": null,
"e": 37043,
"s": 37037,
"text": "ukasp"
},
{
"code": null,
"e": 37061,
"s": 37043,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 37075,
"s": 37061,
"text": "divyesh072019"
},
{
"code": null,
"e": 37095,
"s": 37075,
"text": "Number Divisibility"
},
{
"code": null,
"e": 37103,
"s": 37095,
"text": "Numbers"
},
{
"code": null,
"e": 37123,
"s": 37103,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 37130,
"s": 37123,
"text": "Greedy"
},
{
"code": null,
"e": 37143,
"s": 37130,
"text": "Mathematical"
},
{
"code": null,
"e": 37153,
"s": 37143,
"text": "Recursion"
},
{
"code": null,
"e": 37173,
"s": 37153,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 37180,
"s": 37173,
"text": "Greedy"
},
{
"code": null,
"e": 37193,
"s": 37180,
"text": "Mathematical"
},
{
"code": null,
"e": 37203,
"s": 37193,
"text": "Recursion"
},
{
"code": null,
"e": 37211,
"s": 37203,
"text": "Numbers"
},
{
"code": null,
"e": 37309,
"s": 37211,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37340,
"s": 37309,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 37373,
"s": 37340,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 37400,
"s": 37373,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 37419,
"s": 37400,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 37457,
"s": 37419,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 37508,
"s": 37457,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 37566,
"s": 37508,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 37617,
"s": 37566,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 37644,
"s": 37617,
"text": "Program for array rotation"
}
] |
Queries in a Matrix - GeeksforGeeks
|
28 Jan, 2022
Given a matrix M of size m x n ( 1 <= m,n <= 1000 ). It is initially filled with integers from 1 to m x n sequentially in a row major order. The task is to process a list of queries manipulating M such that every query is one of the following three.
R(x, y): swaps the x-th and y-th rows of M where x and y vary from 1 to m.C(x, y): swaps the x-th and y-th columns of M where x and y vary from 1 to n.P(x, y): prints the element at x-th row and y-th column where x varies from 1 to m and y varies from 1 to n.
R(x, y): swaps the x-th and y-th rows of M where x and y vary from 1 to m.
C(x, y): swaps the x-th and y-th columns of M where x and y vary from 1 to n.
P(x, y): prints the element at x-th row and y-th column where x varies from 1 to m and y varies from 1 to n.
Note that the given matrix is stored as a typical 2D array with indexes start from 0, but values of x and y start from 1.Examples:
Input : m = 3, n = 3
R(1, 2)
P(1, 1)
P(2, 1)
C(1, 2)
P(1, 1)
P(2, 1)
Output: value at (1, 1) = 4
value at (2, 1) = 1
value at (1, 1) = 5
value at (2, 1) = 2
Explanation:
The matrix is {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}}
After first R(1, 2) matrix becomes,
{{4, 5, 6},
{1, 2, 3},
{7, 8, 9}}
After first C(1, 2) matrix becomes,
{{5, 4, 6},
{2, 1, 3},
{8, 7, 9}}
Input : m = 1234, n = 5678
R(1, 2)
P(1, 1)
P(2, 1)
C(1, 2)
P(1, 1)
P(2, 1)
Output: value at (1, 1) = 5679
value at (2, 1) = 1
value at (1, 1) = 5680
value at (2, 1) = 2
A simple solution for this problem is to finish all the queries manually, that means when we have to swap the rows just swap the elements of x’th row and y’th row and similarly for column swapping. But this approach may have time complexity of q*O(m) or q*O(n) where ‘q’ is number of queries and auxiliary space required O(m*n).An efficient approach for this problem requires little bit mathematical observation. Here we are given that elements in matrix are filled from 1 to mxn sequentially in row major order, so we will take advantage of this given scenario and can solve this problem.
Create an auxiliary array rows[m] and fill it with values 0 to m-1 sequentially.
Create another auxiliary array cols[n] and fill it with values 0 to n-1 sequentially.
Now for query ‘R(x, y)’ just swap the value of rows[x-1] with rows[y-1].
Now for query ‘C(x, y)’ just swap the value of cols[x-1] with cols[y-1].
Now for query ‘P(x, y)’ just skip the number of columns you have seen and calculate the value at (x, y) by rows[x-1]*n + cols[y-1] + 1.
Below is implementation of above idea.
C++
Java
Python3
C#
Javascript
// C++ implementation of program#include<bits/stdc++.h>using namespace std; // Fills initial values in rows[] and cols[]void preprocessMatrix(int rows[], int cols[], int m, int n){ // Fill rows with 1 to m-1 for (int i=0; i<m; i++) rows[i] = i; // Fill columns with 1 to n-1 for (int i=0; i<n; i++) cols[i] = i;} // Function to perform queries on matrix// m --> number of rows// n --> number of columns// ch --> type of query// x --> number of row for query// y --> number of column for queryvoid queryMatrix(int rows[], int cols[], int m, int n, char ch, int x, int y){ // perform queries int tmp; switch(ch) { case 'R': // swap row x with y swap(rows[x-1], rows[y-1]); break; case 'C': // swap column x with y swap(cols[x-1], cols[y-1]); break; case 'P': // Print value at (x, y) printf("value at (%d, %d) = %d\n", x, y, rows[x-1]*n + cols[y-1]+1); break; } return ;} // Driver program to run the caseint main(){ int m = 1234, n = 5678; // row[] is array for rows and cols[] // is array for columns int rows[m], cols[n]; // Fill initial values in rows[] and cols[] preprocessMatrix(rows, cols, m, n); queryMatrix(rows, cols, m, n, 'R', 1, 2); queryMatrix(rows, cols, m, n, 'P', 1, 1); queryMatrix(rows, cols, m, n, 'P', 2, 1); queryMatrix(rows, cols, m, n, 'C', 1, 2); queryMatrix(rows, cols, m, n, 'P', 1, 1); queryMatrix(rows, cols, m, n, 'P', 2, 1); return 0;}
// Java implementation of programclass GFG{ // Fills initial values in rows[] and cols[] static void preprocessMatrix(int rows[], int cols[], int m, int n) { // Fill rows with 1 to m-1 for (int i = 0; i < m; i++) { rows[i] = i; } // Fill columns with 1 to n-1 for (int i = 0; i < n; i++) { cols[i] = i; } } // Function to perform queries on matrix // m --> number of rows // n --> number of columns // ch --> type of query // x --> number of row for query // y --> number of column for query static void queryMatrix(int rows[], int cols[], int m, int n, char ch, int x, int y) { // perform queries int tmp; switch (ch) { case 'R': // swap row x with y swap(rows, x - 1, y - 1); break; case 'C': // swap column x with y swap(cols, x - 1, y - 1); break; case 'P': // Print value at (x, y) System.out.printf("value at (%d, %d) = %d\n", x, y, rows[x - 1] * n + cols[y - 1] + 1); break; } return; } static int[] swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } // Driver code public static void main(String[] args) { int m = 1234, n = 5678; // row[] is array for rows and cols[] // is array for columns int rows[] = new int[m], cols[] = new int[n]; // Fill initial values in rows[] and cols[] preprocessMatrix(rows, cols, m, n); queryMatrix(rows, cols, m, n, 'R', 1, 2); queryMatrix(rows, cols, m, n, 'P', 1, 1); queryMatrix(rows, cols, m, n, 'P', 2, 1); queryMatrix(rows, cols, m, n, 'C', 1, 2); queryMatrix(rows, cols, m, n, 'P', 1, 1); queryMatrix(rows, cols, m, n, 'P', 2, 1); }} // This code contributed by Rajput-Ji
# Python3 implementation of program # Fills initial values in rows[] and cols[]def preprocessMatrix(rows, cols, m, n): # Fill rows with 1 to m-1 for i in range(m): rows[i] = i; # Fill columns with 1 to n-1 for i in range(n): cols[i] = i; # Function to perform queries on matrix# m --> number of rows# n --> number of columns# ch --> type of query# x --> number of row for query# y --> number of column for querydef queryMatrix(rows, cols, m, n, ch, x, y): # perform queries tmp = 0; if ch == 'R': # swap row x with y rows[x-1], rows[y-1] = rows[y-1], rows[x-1]; elif ch == 'C': # swap column x with y cols[x-1], cols[y-1] = cols[y-1],cols[x-1]; elif ch == 'P': # Print value at (x, y) print('value at (',x,',',y,') = ',rows[x-1]*n + cols[y-1]+1, sep=''); return ; # Driver program to run the casem = 1234n = 5678; # row[] is array for rows and cols[]# is array for columnsrows = [0 for i in range(m)]cols = [0 for i in range(n)]; # Fill initial values in rows[] and cols[]preprocessMatrix(rows, cols, m, n); queryMatrix(rows, cols, m, n, 'R', 1, 2);queryMatrix(rows, cols, m, n, 'P', 1, 1);queryMatrix(rows, cols, m, n, 'P', 2, 1);queryMatrix(rows, cols, m, n, 'C', 1, 2);queryMatrix(rows, cols, m, n, 'P', 1, 1);queryMatrix(rows, cols, m, n, 'P', 2, 1); # This code is contributed by rutvik_56.
// C# implementation of programusing System; class GFG{ // Fills initial values in rows[] and cols[] static void preprocessMatrix(int []rows, int []cols, int m, int n) { // Fill rows with 1 to m-1 for (int i = 0; i < m; i++) { rows[i] = i; } // Fill columns with 1 to n-1 for (int i = 0; i < n; i++) { cols[i] = i; } } // Function to perform queries on matrix // m --> number of rows // n --> number of columns // ch --> type of query // x --> number of row for query // y --> number of column for query static void queryMatrix(int []rows, int []cols, int m, int n, char ch, int x, int y) { // perform queries int tmp; switch (ch) { case 'R': // swap row x with y swap(rows, x - 1, y - 1); break; case 'C': // swap column x with y swap(cols, x - 1, y - 1); break; case 'P': // Print value at (x, y) Console.Write("value at ({0}, {1}) = {2}\n", x, y, rows[x - 1] * n + cols[y - 1] + 1); break; } return; } static int[] swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } // Driver code public static void Main() { int m = 1234, n = 5678; // row[] is array for rows and cols[] // is array for columns int []rows = new int[m]; int []cols = new int[n]; // Fill initial values in rows[] and cols[] preprocessMatrix(rows, cols, m, n); queryMatrix(rows, cols, m, n, 'R', 1, 2); queryMatrix(rows, cols, m, n, 'P', 1, 1); queryMatrix(rows, cols, m, n, 'P', 2, 1); queryMatrix(rows, cols, m, n, 'C', 1, 2); queryMatrix(rows, cols, m, n, 'P', 1, 1); queryMatrix(rows, cols, m, n, 'P', 2, 1); }} /* This code contributed by PrinciRaj1992 */
<script> // JavaScript implementation of program// Fills initial values in rows[] and cols[]function preprocessMatrix(rows, cols, m, n){ // Fill rows with 1 to m-1 for (var i = 0; i < m; i++) { rows[i] = i; } // Fill columns with 1 to n-1 for (var i = 0; i < n; i++) { cols[i] = i; }}// Function to perform queries on matrix// m --> number of rows// n --> number of columns// ch --> type of query// x --> number of row for query// y --> number of column for queryfunction queryMatrix(rows, cols, m, n, ch, x, y){ // perform queries var tmp; switch (ch) { case 'R': // swap row x with y swap(rows, x - 1, y - 1); break; case 'C': // swap column x with y swap(cols, x - 1, y - 1); break; case 'P': // Print value at (x, y) document.write(`value at (${x}, ${y}) = ${rows[x - 1] * n + cols[y - 1] + 1}<br>`); break; } return;}function swap(arr, i, j){ var temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;}// Driver codevar m = 1234, n = 5678;// row[] is array for rows and cols[]// is array for columnsvar rows = Array(m).fill(0)var cols = Array(n).fill(0)// Fill initial values in rows[] and cols[]preprocessMatrix(rows, cols, m, n);queryMatrix(rows, cols, m, n, 'R', 1, 2);queryMatrix(rows, cols, m, n, 'P', 1, 1);queryMatrix(rows, cols, m, n, 'P', 2, 1);queryMatrix(rows, cols, m, n, 'C', 1, 2);queryMatrix(rows, cols, m, n, 'P', 1, 1);queryMatrix(rows, cols, m, n, 'P', 2, 1); </script>
Output:
value at (1, 1) = 5679
value at (2, 1) = 1
value at (1, 1) = 5680
value at (2, 1) = 2
Time complexity : O(q) , q = number of queries Axillary space : O(m+n)This article is contributed by Shashank Mishra ( Gullu ). 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.
Rajput-Ji
princiraj1992
sweetyty
rrrtnx
rutvik_56
saurabh1990aror
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum size square sub-matrix with all 1s
Sudoku | Backtracking-7
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Count all possible paths from top left to bottom right of a mXn matrix
Maximum size rectangle binary sub-matrix with all 1s
Program to multiply two matrices
Inplace rotate square matrix by 90 degrees | Set 1
Min Cost Path | DP-6
Printing all solutions in N-Queen Problem
Rotate a matrix by 90 degree in clockwise direction without using any extra space
|
[
{
"code": null,
"e": 26591,
"s": 26563,
"text": "\n28 Jan, 2022"
},
{
"code": null,
"e": 26843,
"s": 26591,
"text": "Given a matrix M of size m x n ( 1 <= m,n <= 1000 ). It is initially filled with integers from 1 to m x n sequentially in a row major order. The task is to process a list of queries manipulating M such that every query is one of the following three. "
},
{
"code": null,
"e": 27103,
"s": 26843,
"text": "R(x, y): swaps the x-th and y-th rows of M where x and y vary from 1 to m.C(x, y): swaps the x-th and y-th columns of M where x and y vary from 1 to n.P(x, y): prints the element at x-th row and y-th column where x varies from 1 to m and y varies from 1 to n."
},
{
"code": null,
"e": 27178,
"s": 27103,
"text": "R(x, y): swaps the x-th and y-th rows of M where x and y vary from 1 to m."
},
{
"code": null,
"e": 27256,
"s": 27178,
"text": "C(x, y): swaps the x-th and y-th columns of M where x and y vary from 1 to n."
},
{
"code": null,
"e": 27365,
"s": 27256,
"text": "P(x, y): prints the element at x-th row and y-th column where x varies from 1 to m and y varies from 1 to n."
},
{
"code": null,
"e": 27498,
"s": 27365,
"text": "Note that the given matrix is stored as a typical 2D array with indexes start from 0, but values of x and y start from 1.Examples: "
},
{
"code": null,
"e": 28296,
"s": 27498,
"text": "Input : m = 3, n = 3\n R(1, 2)\n P(1, 1)\n P(2, 1)\n C(1, 2)\n P(1, 1)\n P(2, 1)\nOutput: value at (1, 1) = 4\n value at (2, 1) = 1\n value at (1, 1) = 5\n value at (2, 1) = 2\nExplanation:\nThe matrix is {{1, 2, 3}, \n {4, 5, 6},\n {7, 8, 9}}\nAfter first R(1, 2) matrix becomes, \n {{4, 5, 6}, \n {1, 2, 3}, \n {7, 8, 9}}\nAfter first C(1, 2) matrix becomes, \n {{5, 4, 6}, \n {2, 1, 3}, \n {8, 7, 9}}\n\n\nInput : m = 1234, n = 5678\n R(1, 2)\n P(1, 1)\n P(2, 1)\n C(1, 2)\n P(1, 1)\n P(2, 1)\nOutput: value at (1, 1) = 5679\n value at (2, 1) = 1\n value at (1, 1) = 5680\n value at (2, 1) = 2"
},
{
"code": null,
"e": 28890,
"s": 28298,
"text": "A simple solution for this problem is to finish all the queries manually, that means when we have to swap the rows just swap the elements of x’th row and y’th row and similarly for column swapping. But this approach may have time complexity of q*O(m) or q*O(n) where ‘q’ is number of queries and auxiliary space required O(m*n).An efficient approach for this problem requires little bit mathematical observation. Here we are given that elements in matrix are filled from 1 to mxn sequentially in row major order, so we will take advantage of this given scenario and can solve this problem. "
},
{
"code": null,
"e": 28971,
"s": 28890,
"text": "Create an auxiliary array rows[m] and fill it with values 0 to m-1 sequentially."
},
{
"code": null,
"e": 29057,
"s": 28971,
"text": "Create another auxiliary array cols[n] and fill it with values 0 to n-1 sequentially."
},
{
"code": null,
"e": 29130,
"s": 29057,
"text": "Now for query ‘R(x, y)’ just swap the value of rows[x-1] with rows[y-1]."
},
{
"code": null,
"e": 29203,
"s": 29130,
"text": "Now for query ‘C(x, y)’ just swap the value of cols[x-1] with cols[y-1]."
},
{
"code": null,
"e": 29339,
"s": 29203,
"text": "Now for query ‘P(x, y)’ just skip the number of columns you have seen and calculate the value at (x, y) by rows[x-1]*n + cols[y-1] + 1."
},
{
"code": null,
"e": 29380,
"s": 29339,
"text": "Below is implementation of above idea. "
},
{
"code": null,
"e": 29384,
"s": 29380,
"text": "C++"
},
{
"code": null,
"e": 29389,
"s": 29384,
"text": "Java"
},
{
"code": null,
"e": 29397,
"s": 29389,
"text": "Python3"
},
{
"code": null,
"e": 29400,
"s": 29397,
"text": "C#"
},
{
"code": null,
"e": 29411,
"s": 29400,
"text": "Javascript"
},
{
"code": "// C++ implementation of program#include<bits/stdc++.h>using namespace std; // Fills initial values in rows[] and cols[]void preprocessMatrix(int rows[], int cols[], int m, int n){ // Fill rows with 1 to m-1 for (int i=0; i<m; i++) rows[i] = i; // Fill columns with 1 to n-1 for (int i=0; i<n; i++) cols[i] = i;} // Function to perform queries on matrix// m --> number of rows// n --> number of columns// ch --> type of query// x --> number of row for query// y --> number of column for queryvoid queryMatrix(int rows[], int cols[], int m, int n, char ch, int x, int y){ // perform queries int tmp; switch(ch) { case 'R': // swap row x with y swap(rows[x-1], rows[y-1]); break; case 'C': // swap column x with y swap(cols[x-1], cols[y-1]); break; case 'P': // Print value at (x, y) printf(\"value at (%d, %d) = %d\\n\", x, y, rows[x-1]*n + cols[y-1]+1); break; } return ;} // Driver program to run the caseint main(){ int m = 1234, n = 5678; // row[] is array for rows and cols[] // is array for columns int rows[m], cols[n]; // Fill initial values in rows[] and cols[] preprocessMatrix(rows, cols, m, n); queryMatrix(rows, cols, m, n, 'R', 1, 2); queryMatrix(rows, cols, m, n, 'P', 1, 1); queryMatrix(rows, cols, m, n, 'P', 2, 1); queryMatrix(rows, cols, m, n, 'C', 1, 2); queryMatrix(rows, cols, m, n, 'P', 1, 1); queryMatrix(rows, cols, m, n, 'P', 2, 1); return 0;}",
"e": 30995,
"s": 29411,
"text": null
},
{
"code": "// Java implementation of programclass GFG{ // Fills initial values in rows[] and cols[] static void preprocessMatrix(int rows[], int cols[], int m, int n) { // Fill rows with 1 to m-1 for (int i = 0; i < m; i++) { rows[i] = i; } // Fill columns with 1 to n-1 for (int i = 0; i < n; i++) { cols[i] = i; } } // Function to perform queries on matrix // m --> number of rows // n --> number of columns // ch --> type of query // x --> number of row for query // y --> number of column for query static void queryMatrix(int rows[], int cols[], int m, int n, char ch, int x, int y) { // perform queries int tmp; switch (ch) { case 'R': // swap row x with y swap(rows, x - 1, y - 1); break; case 'C': // swap column x with y swap(cols, x - 1, y - 1); break; case 'P': // Print value at (x, y) System.out.printf(\"value at (%d, %d) = %d\\n\", x, y, rows[x - 1] * n + cols[y - 1] + 1); break; } return; } static int[] swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } // Driver code public static void main(String[] args) { int m = 1234, n = 5678; // row[] is array for rows and cols[] // is array for columns int rows[] = new int[m], cols[] = new int[n]; // Fill initial values in rows[] and cols[] preprocessMatrix(rows, cols, m, n); queryMatrix(rows, cols, m, n, 'R', 1, 2); queryMatrix(rows, cols, m, n, 'P', 1, 1); queryMatrix(rows, cols, m, n, 'P', 2, 1); queryMatrix(rows, cols, m, n, 'C', 1, 2); queryMatrix(rows, cols, m, n, 'P', 1, 1); queryMatrix(rows, cols, m, n, 'P', 2, 1); }} // This code contributed by Rajput-Ji",
"e": 33122,
"s": 30995,
"text": null
},
{
"code": "# Python3 implementation of program # Fills initial values in rows[] and cols[]def preprocessMatrix(rows, cols, m, n): # Fill rows with 1 to m-1 for i in range(m): rows[i] = i; # Fill columns with 1 to n-1 for i in range(n): cols[i] = i; # Function to perform queries on matrix# m --> number of rows# n --> number of columns# ch --> type of query# x --> number of row for query# y --> number of column for querydef queryMatrix(rows, cols, m, n, ch, x, y): # perform queries tmp = 0; if ch == 'R': # swap row x with y rows[x-1], rows[y-1] = rows[y-1], rows[x-1]; elif ch == 'C': # swap column x with y cols[x-1], cols[y-1] = cols[y-1],cols[x-1]; elif ch == 'P': # Print value at (x, y) print('value at (',x,',',y,') = ',rows[x-1]*n + cols[y-1]+1, sep=''); return ; # Driver program to run the casem = 1234n = 5678; # row[] is array for rows and cols[]# is array for columnsrows = [0 for i in range(m)]cols = [0 for i in range(n)]; # Fill initial values in rows[] and cols[]preprocessMatrix(rows, cols, m, n); queryMatrix(rows, cols, m, n, 'R', 1, 2);queryMatrix(rows, cols, m, n, 'P', 1, 1);queryMatrix(rows, cols, m, n, 'P', 2, 1);queryMatrix(rows, cols, m, n, 'C', 1, 2);queryMatrix(rows, cols, m, n, 'P', 1, 1);queryMatrix(rows, cols, m, n, 'P', 2, 1); # This code is contributed by rutvik_56.",
"e": 34526,
"s": 33122,
"text": null
},
{
"code": "// C# implementation of programusing System; class GFG{ // Fills initial values in rows[] and cols[] static void preprocessMatrix(int []rows, int []cols, int m, int n) { // Fill rows with 1 to m-1 for (int i = 0; i < m; i++) { rows[i] = i; } // Fill columns with 1 to n-1 for (int i = 0; i < n; i++) { cols[i] = i; } } // Function to perform queries on matrix // m --> number of rows // n --> number of columns // ch --> type of query // x --> number of row for query // y --> number of column for query static void queryMatrix(int []rows, int []cols, int m, int n, char ch, int x, int y) { // perform queries int tmp; switch (ch) { case 'R': // swap row x with y swap(rows, x - 1, y - 1); break; case 'C': // swap column x with y swap(cols, x - 1, y - 1); break; case 'P': // Print value at (x, y) Console.Write(\"value at ({0}, {1}) = {2}\\n\", x, y, rows[x - 1] * n + cols[y - 1] + 1); break; } return; } static int[] swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } // Driver code public static void Main() { int m = 1234, n = 5678; // row[] is array for rows and cols[] // is array for columns int []rows = new int[m]; int []cols = new int[n]; // Fill initial values in rows[] and cols[] preprocessMatrix(rows, cols, m, n); queryMatrix(rows, cols, m, n, 'R', 1, 2); queryMatrix(rows, cols, m, n, 'P', 1, 1); queryMatrix(rows, cols, m, n, 'P', 2, 1); queryMatrix(rows, cols, m, n, 'C', 1, 2); queryMatrix(rows, cols, m, n, 'P', 1, 1); queryMatrix(rows, cols, m, n, 'P', 2, 1); }} /* This code contributed by PrinciRaj1992 */",
"e": 36662,
"s": 34526,
"text": null
},
{
"code": "<script> // JavaScript implementation of program// Fills initial values in rows[] and cols[]function preprocessMatrix(rows, cols, m, n){ // Fill rows with 1 to m-1 for (var i = 0; i < m; i++) { rows[i] = i; } // Fill columns with 1 to n-1 for (var i = 0; i < n; i++) { cols[i] = i; }}// Function to perform queries on matrix// m --> number of rows// n --> number of columns// ch --> type of query// x --> number of row for query// y --> number of column for queryfunction queryMatrix(rows, cols, m, n, ch, x, y){ // perform queries var tmp; switch (ch) { case 'R': // swap row x with y swap(rows, x - 1, y - 1); break; case 'C': // swap column x with y swap(cols, x - 1, y - 1); break; case 'P': // Print value at (x, y) document.write(`value at (${x}, ${y}) = ${rows[x - 1] * n + cols[y - 1] + 1}<br>`); break; } return;}function swap(arr, i, j){ var temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;}// Driver codevar m = 1234, n = 5678;// row[] is array for rows and cols[]// is array for columnsvar rows = Array(m).fill(0)var cols = Array(n).fill(0)// Fill initial values in rows[] and cols[]preprocessMatrix(rows, cols, m, n);queryMatrix(rows, cols, m, n, 'R', 1, 2);queryMatrix(rows, cols, m, n, 'P', 1, 1);queryMatrix(rows, cols, m, n, 'P', 2, 1);queryMatrix(rows, cols, m, n, 'C', 1, 2);queryMatrix(rows, cols, m, n, 'P', 1, 1);queryMatrix(rows, cols, m, n, 'P', 2, 1); </script>",
"e": 38259,
"s": 36662,
"text": null
},
{
"code": null,
"e": 38269,
"s": 38259,
"text": "Output: "
},
{
"code": null,
"e": 38355,
"s": 38269,
"text": "value at (1, 1) = 5679\nvalue at (2, 1) = 1\nvalue at (1, 1) = 5680\nvalue at (2, 1) = 2"
},
{
"code": null,
"e": 38859,
"s": 38355,
"text": "Time complexity : O(q) , q = number of queries Axillary space : O(m+n)This article is contributed by Shashank Mishra ( Gullu ). 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": 38869,
"s": 38859,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 38883,
"s": 38869,
"text": "princiraj1992"
},
{
"code": null,
"e": 38892,
"s": 38883,
"text": "sweetyty"
},
{
"code": null,
"e": 38899,
"s": 38892,
"text": "rrrtnx"
},
{
"code": null,
"e": 38909,
"s": 38899,
"text": "rutvik_56"
},
{
"code": null,
"e": 38925,
"s": 38909,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 38932,
"s": 38925,
"text": "Matrix"
},
{
"code": null,
"e": 38939,
"s": 38932,
"text": "Matrix"
},
{
"code": null,
"e": 39037,
"s": 38939,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39080,
"s": 39037,
"text": "Maximum size square sub-matrix with all 1s"
},
{
"code": null,
"e": 39104,
"s": 39080,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 39166,
"s": 39104,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
},
{
"code": null,
"e": 39237,
"s": 39166,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 39290,
"s": 39237,
"text": "Maximum size rectangle binary sub-matrix with all 1s"
},
{
"code": null,
"e": 39323,
"s": 39290,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 39374,
"s": 39323,
"text": "Inplace rotate square matrix by 90 degrees | Set 1"
},
{
"code": null,
"e": 39395,
"s": 39374,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 39437,
"s": 39395,
"text": "Printing all solutions in N-Queen Problem"
}
] |
Displaying horizontal bar graphs using Matplotlib
|
In this program, we will plot a bar graph using the matplotlib library. The most important Step in solving matplotlib related problems using the matplotlib library is importing the matplotlib library. The syntax is:
import matplotlib.pyplot as plt
Pyplot is a collection of command style functions that make Matplotlib work like MATLAB. We will use the function barh() for plotting the horizontal bar charts
Step 1: Define a list of values.
Step 2: Use the barh() function in the matplotlib.pyplot library and define different parameters like height width, etc.
Step 3: Label the axes using xlabel() and ylabel().
Step 3: Plot the graph using show().
import matplotlib.pyplot as plt
data_x = ['Mumbai', 'Delhi', 'Ahmedabad', 'Banglore']
data_y = [40, 35, 29, 32]
plt.xlabel("CITY")
plt.ylabel("POPULATION")
plt.title("BAR PLOT")
plt.barh(data_x, data_y, color='red')
plt.show()
|
[
{
"code": null,
"e": 1278,
"s": 1062,
"text": "In this program, we will plot a bar graph using the matplotlib library. The most important Step in solving matplotlib related problems using the matplotlib library is importing the matplotlib library. The syntax is:"
},
{
"code": null,
"e": 1310,
"s": 1278,
"text": "import matplotlib.pyplot as plt"
},
{
"code": null,
"e": 1470,
"s": 1310,
"text": "Pyplot is a collection of command style functions that make Matplotlib work like MATLAB. We will use the function barh() for plotting the horizontal bar charts"
},
{
"code": null,
"e": 1713,
"s": 1470,
"text": "Step 1: Define a list of values.\nStep 2: Use the barh() function in the matplotlib.pyplot library and define different parameters like height width, etc.\nStep 3: Label the axes using xlabel() and ylabel().\nStep 3: Plot the graph using show()."
},
{
"code": null,
"e": 1942,
"s": 1713,
"text": "import matplotlib.pyplot as plt\n\ndata_x = ['Mumbai', 'Delhi', 'Ahmedabad', 'Banglore']\ndata_y = [40, 35, 29, 32]\n\nplt.xlabel(\"CITY\")\nplt.ylabel(\"POPULATION\")\nplt.title(\"BAR PLOT\")\nplt.barh(data_x, data_y, color='red')\nplt.show()"
}
] |
Automatic Type Promotion in Overloading in Java - GeeksforGeeks
|
11 Jan, 2022
Before going into the actual topic, first, we need to know about method overloading and type promotions.
When a class consists of more than one method with the same name but with different signatures and return types, then we call those overloaded methods, and the process is called method overloading.
Example:
void method(int i)
int method(int i,int j)
void method(double d)
The name Type Promotion specifies that a small size datatype can be promoted to a large size datatype. i.e., an Integer data type can be promoted to long, float, double, etc. This Automatic Type Promotion is done when any method which accepts a higher size data type argument is called with the smaller data type.
Example:
public void method(double a){
System.out.println("Method called");
}
public static void main(){
method(2);
}
In the above method call, we passed an integer as an argument, but no method accepts an integer in the below code. The Java compiler won’t throw an error because of the Automatic Type Promotion. The Integer is promoted to the available large size datatype, double.
Note:- This is important to remember is Automatic Type Promotion is only possible from small size datatype to higher size datatype but not from higher size to smaller size. i.e., integer to character is not possible.
Type Promotion Hierarchy
Example 1: In this example, we are testing the automatic type promotion from small size datatype to high size datatype.
Java
class GFG { // A method that accept double as parameter public static void method(double d) { System.out.println( "Automatic Type Promoted to Double-" + d); } public static void main(String[] args) { // method call with int as parameter method(2); }}
Automatic Type Promoted to Double-2.0
Explanation: Here we passed an Integer as a parameter to a method and there is a method in the same class that accepts double as parameter but not Integer. In this case, the Java compiler performs automatic type promotion from int to double and calls the method.
Example 2: Let’s try to write a code to check whether the automatic type promotion happens from high size datatype to small size datatype.
Java
class GFG { // A method that accept integer as parameter public static void method(int i) { System.out.println( "Automatic Type Promoted possible from high to small?"); } public static void main(String[] args) { // method call with double as parameter method(2.02); }}
Output:
Error message
Explanation: From this example, it is proven that Automatic Type Promotion is only applicable from small size datatype to big size datatype. As the double size is large when compared to integer so large size to small size conversion fails.
Example 3: In this example, we are going to look at the overloaded methods and how the automatic type of promotion is happening there.
Java
class GFG { // A method that accept integer as parameter public static void method(int i) { System.out.println( "Automatic Type Promoted to Integer-" + i); } // A method that accept double as parameter public static void method(double d) { System.out.println( "Automatic Type Promoted to Double-" + d); } // A method that accept object as parameter public static void method(Object o) { System.out.println("Object method called"); } public static void main(String[] args) { // method call with char as parameter method('a'); // method call with int as parameter method(2); // method call with float as parameter method(2.0f); // method call with a string as parameter method("Geeks for Geeks"); }}
Automatic Type Promoted to Integer-97
Automatic Type Promoted to Integer-2
Automatic Type Promoted to Double-2.0
Object method called
Explanation: In the above code,
First, we called a method with a character as a parameter but we didn’t have any method that is defined that accepts character so it will check the next high size datatype, i.e., Integer. If there is a method that accepts Integer, then it performs automatic type promotion and call that method. If not found, it searches for the next level higher size datatype.
Here we have a method that accepts Integer so character ‘a’ is converted to an integer- 97, and that respective method is called.
Next, we called a method by passing two integer variables. As it directly found a method, no promotions happened, and the method is called.
Next, a float variable is passed, i.e., 2.0f. Here we have a method that accepts double, so the float is converted to double and the method is called.
Finally, a string is passed which occupies more space when compared to double. So its searches for the methods that accept either a string or Object which is a superclass of all types. In this code, there is no method that accepts string but there is a method that accepts objects. So that method is called after type promotion.
Example 4: In this example, consider the overloaded methods with more than one argument and observe how automatic type conversion is happening here:
Java
class GFG { // overloaded methods // Method that accepts integer and double public static void method(int i, double d) { System.out.println("Integer-Double"); } // Method that accepts double and integer public static void method(double d, int i) { System.out.println("Double-Integer"); } public static void main(String[] args) { // method call by passing integer and double method(2, 2.0); // method call by passing double and integer method(2.0, 2); // method call by passing both integers // method(2, 2); // Ambiguous error }}
Integer-Double
Double-Integer
Explanation: In the above code, when we pass arguments to a method call, the compiler will search for the corresponding method that accepts the same arguments. If present, then it will call that method. Else, it will look for scenarios for automatic type promotion.
For the first method call, there is already a method that accepts similar arguments, so that it will call that Integer-Double method.
For the second method call also there is a method defined in the class, and the compiler will call the respective method. (Double-Integer)
But when we pass 2 Integers as arguments, the Compiler first checks for a respective method that accepts 2 integers. In this case, there is no method that accepts two integers. So it will check for scenarios for type promotion.
Here there are 2 methods that accept an integer and double and any of the integers can be promoted to double simply, but the problem is ambiguity. The compiler didn’t know what method to call if the type was promoted. So compiler throws an error message like specified below if we uncomment line 20 in the above code-
Ambiguity Error
These are the few examples that can give clear insight on Automatic type conversion in overloaded methods.
surinderdawra388
Java-Overloading
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n11 Jan, 2022"
},
{
"code": null,
"e": 25330,
"s": 25225,
"text": "Before going into the actual topic, first, we need to know about method overloading and type promotions."
},
{
"code": null,
"e": 25528,
"s": 25330,
"text": "When a class consists of more than one method with the same name but with different signatures and return types, then we call those overloaded methods, and the process is called method overloading."
},
{
"code": null,
"e": 25537,
"s": 25528,
"text": "Example:"
},
{
"code": null,
"e": 25602,
"s": 25537,
"text": "void method(int i)\nint method(int i,int j)\nvoid method(double d)"
},
{
"code": null,
"e": 25916,
"s": 25602,
"text": "The name Type Promotion specifies that a small size datatype can be promoted to a large size datatype. i.e., an Integer data type can be promoted to long, float, double, etc. This Automatic Type Promotion is done when any method which accepts a higher size data type argument is called with the smaller data type."
},
{
"code": null,
"e": 25926,
"s": 25916,
"text": "Example: "
},
{
"code": null,
"e": 26044,
"s": 25926,
"text": "public void method(double a){\n System.out.println(\"Method called\");\n}\n\npublic static void main(){\n method(2);\n}"
},
{
"code": null,
"e": 26309,
"s": 26044,
"text": "In the above method call, we passed an integer as an argument, but no method accepts an integer in the below code. The Java compiler won’t throw an error because of the Automatic Type Promotion. The Integer is promoted to the available large size datatype, double."
},
{
"code": null,
"e": 26526,
"s": 26309,
"text": "Note:- This is important to remember is Automatic Type Promotion is only possible from small size datatype to higher size datatype but not from higher size to smaller size. i.e., integer to character is not possible."
},
{
"code": null,
"e": 26551,
"s": 26526,
"text": "Type Promotion Hierarchy"
},
{
"code": null,
"e": 26671,
"s": 26551,
"text": "Example 1: In this example, we are testing the automatic type promotion from small size datatype to high size datatype."
},
{
"code": null,
"e": 26676,
"s": 26671,
"text": "Java"
},
{
"code": "class GFG { // A method that accept double as parameter public static void method(double d) { System.out.println( \"Automatic Type Promoted to Double-\" + d); } public static void main(String[] args) { // method call with int as parameter method(2); }}",
"e": 26986,
"s": 26676,
"text": null
},
{
"code": null,
"e": 27024,
"s": 26986,
"text": "Automatic Type Promoted to Double-2.0"
},
{
"code": null,
"e": 27287,
"s": 27024,
"text": "Explanation: Here we passed an Integer as a parameter to a method and there is a method in the same class that accepts double as parameter but not Integer. In this case, the Java compiler performs automatic type promotion from int to double and calls the method."
},
{
"code": null,
"e": 27427,
"s": 27287,
"text": "Example 2: Let’s try to write a code to check whether the automatic type promotion happens from high size datatype to small size datatype. "
},
{
"code": null,
"e": 27432,
"s": 27427,
"text": "Java"
},
{
"code": "class GFG { // A method that accept integer as parameter public static void method(int i) { System.out.println( \"Automatic Type Promoted possible from high to small?\"); } public static void main(String[] args) { // method call with double as parameter method(2.02); }}",
"e": 27760,
"s": 27432,
"text": null
},
{
"code": null,
"e": 27768,
"s": 27760,
"text": "Output:"
},
{
"code": null,
"e": 27782,
"s": 27768,
"text": "Error message"
},
{
"code": null,
"e": 28022,
"s": 27782,
"text": "Explanation: From this example, it is proven that Automatic Type Promotion is only applicable from small size datatype to big size datatype. As the double size is large when compared to integer so large size to small size conversion fails."
},
{
"code": null,
"e": 28158,
"s": 28022,
"text": "Example 3: In this example, we are going to look at the overloaded methods and how the automatic type of promotion is happening there. "
},
{
"code": null,
"e": 28163,
"s": 28158,
"text": "Java"
},
{
"code": "class GFG { // A method that accept integer as parameter public static void method(int i) { System.out.println( \"Automatic Type Promoted to Integer-\" + i); } // A method that accept double as parameter public static void method(double d) { System.out.println( \"Automatic Type Promoted to Double-\" + d); } // A method that accept object as parameter public static void method(Object o) { System.out.println(\"Object method called\"); } public static void main(String[] args) { // method call with char as parameter method('a'); // method call with int as parameter method(2); // method call with float as parameter method(2.0f); // method call with a string as parameter method(\"Geeks for Geeks\"); }}",
"e": 29038,
"s": 28163,
"text": null
},
{
"code": null,
"e": 29172,
"s": 29038,
"text": "Automatic Type Promoted to Integer-97\nAutomatic Type Promoted to Integer-2\nAutomatic Type Promoted to Double-2.0\nObject method called"
},
{
"code": null,
"e": 29206,
"s": 29172,
"text": "Explanation: In the above code, "
},
{
"code": null,
"e": 29568,
"s": 29206,
"text": "First, we called a method with a character as a parameter but we didn’t have any method that is defined that accepts character so it will check the next high size datatype, i.e., Integer. If there is a method that accepts Integer, then it performs automatic type promotion and call that method. If not found, it searches for the next level higher size datatype."
},
{
"code": null,
"e": 29698,
"s": 29568,
"text": "Here we have a method that accepts Integer so character ‘a’ is converted to an integer- 97, and that respective method is called."
},
{
"code": null,
"e": 29838,
"s": 29698,
"text": "Next, we called a method by passing two integer variables. As it directly found a method, no promotions happened, and the method is called."
},
{
"code": null,
"e": 29989,
"s": 29838,
"text": "Next, a float variable is passed, i.e., 2.0f. Here we have a method that accepts double, so the float is converted to double and the method is called."
},
{
"code": null,
"e": 30318,
"s": 29989,
"text": "Finally, a string is passed which occupies more space when compared to double. So its searches for the methods that accept either a string or Object which is a superclass of all types. In this code, there is no method that accepts string but there is a method that accepts objects. So that method is called after type promotion."
},
{
"code": null,
"e": 30467,
"s": 30318,
"text": "Example 4: In this example, consider the overloaded methods with more than one argument and observe how automatic type conversion is happening here:"
},
{
"code": null,
"e": 30472,
"s": 30467,
"text": "Java"
},
{
"code": "class GFG { // overloaded methods // Method that accepts integer and double public static void method(int i, double d) { System.out.println(\"Integer-Double\"); } // Method that accepts double and integer public static void method(double d, int i) { System.out.println(\"Double-Integer\"); } public static void main(String[] args) { // method call by passing integer and double method(2, 2.0); // method call by passing double and integer method(2.0, 2); // method call by passing both integers // method(2, 2); // Ambiguous error }}",
"e": 31104,
"s": 30472,
"text": null
},
{
"code": null,
"e": 31134,
"s": 31104,
"text": "Integer-Double\nDouble-Integer"
},
{
"code": null,
"e": 31400,
"s": 31134,
"text": "Explanation: In the above code, when we pass arguments to a method call, the compiler will search for the corresponding method that accepts the same arguments. If present, then it will call that method. Else, it will look for scenarios for automatic type promotion."
},
{
"code": null,
"e": 31534,
"s": 31400,
"text": "For the first method call, there is already a method that accepts similar arguments, so that it will call that Integer-Double method."
},
{
"code": null,
"e": 31673,
"s": 31534,
"text": "For the second method call also there is a method defined in the class, and the compiler will call the respective method. (Double-Integer)"
},
{
"code": null,
"e": 31901,
"s": 31673,
"text": "But when we pass 2 Integers as arguments, the Compiler first checks for a respective method that accepts 2 integers. In this case, there is no method that accepts two integers. So it will check for scenarios for type promotion."
},
{
"code": null,
"e": 32219,
"s": 31901,
"text": "Here there are 2 methods that accept an integer and double and any of the integers can be promoted to double simply, but the problem is ambiguity. The compiler didn’t know what method to call if the type was promoted. So compiler throws an error message like specified below if we uncomment line 20 in the above code-"
},
{
"code": null,
"e": 32235,
"s": 32219,
"text": "Ambiguity Error"
},
{
"code": null,
"e": 32342,
"s": 32235,
"text": "These are the few examples that can give clear insight on Automatic type conversion in overloaded methods."
},
{
"code": null,
"e": 32361,
"s": 32344,
"text": "surinderdawra388"
},
{
"code": null,
"e": 32378,
"s": 32361,
"text": "Java-Overloading"
},
{
"code": null,
"e": 32385,
"s": 32378,
"text": "Picked"
},
{
"code": null,
"e": 32390,
"s": 32385,
"text": "Java"
},
{
"code": null,
"e": 32395,
"s": 32390,
"text": "Java"
},
{
"code": null,
"e": 32493,
"s": 32395,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32508,
"s": 32493,
"text": "Stream In Java"
},
{
"code": null,
"e": 32529,
"s": 32508,
"text": "Constructors in Java"
},
{
"code": null,
"e": 32548,
"s": 32529,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 32578,
"s": 32548,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 32624,
"s": 32578,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 32641,
"s": 32624,
"text": "Generics in Java"
},
{
"code": null,
"e": 32662,
"s": 32641,
"text": "Introduction to Java"
},
{
"code": null,
"e": 32705,
"s": 32662,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 32741,
"s": 32705,
"text": "Internal Working of HashMap in Java"
}
] |
How to Make USB Rubber Ducky at Home? - GeeksforGeeks
|
08 Jul, 2020
USB Rubber ducky is an HID device that looks similar to a USB Pen drive. It may be used to inject keystroke into a system, used to hack a system, steal victims essential and credential data can inject payload to the victim’s computers. The main important thing about USB Rubber ducky is that it cannot be detected by any Anti-Virus or Firewall as it acts as an HID device.
Android mobiles can also be used to make a USB rubber ducky, if an Android device is rooted we may use it as a Rubber ducky device. And can perform all the operations that an original ducky can perform.
To Make USB rubber ducky from android :
Android mobile must be rooted
Kali net hunter installed on the device
In this article, we must be using some other components to create a USB Rubber Ducky at home.
Material Requirements
Arduino based boardUSB connectorArduino IDE
Arduino based board
USB connector
Arduino IDE
Step 1: First of all download Arduino IDE from the link, and install the software like any other software you install on windows.
Step 2: Connect the Arduino board to the computer using the USB connector and open the IDE.
Step 3: Now from the Payload list choose according to your task.
Step 4: Convert the code that you have chosen to make executable in Arduino here.
Script for turning off the Windows Defender
REM turn off windows defender then clear action center
REM author:geeksforgeeks
REM You take responsibility for any laws you break with this, I simply point out the security flaw
REM start of script
REM let the HID enumerate
DELAY 2000
ESCAPE
DELAY 100
CONTROL ESCAPE
DELAY 100
STRING Windows Defender Settings
ENTER
DELAY 2000
REM why TAB and HOME?
TAB
DELAY 50
REM why TAB and HOME?HOME
DELAY 50
ALT F4
DELAY 3200
REM windows + a = ????
GUI a
DELAY 500
ENTER
DELAY 100
GUI a
Step 5:In the Arduino IDE creates a new project, by clicking on File–> New project.
Step 6: After converting to new code adding to the Arduino IDE, now select the board which you are using. Tools–>Board–>Your board.
Step 7: Click on the project and choose the port, where Arduino is connected. Tools–>Port–>Your Port.
Step 8: Now when the board is connected, enter the code or payload you want to work with.
Step 9: Now verify and compile your code. Sketch–>verify/compile.
Step 10: After compiling, upload the code to the Arduino device.
Whenever you will Connect this board with any computer it works as a USB rubber ducky and executes the payload written. You can Check about USB rubber ducky in Details Here.
GBlog
How To
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
GET and POST requests using Python
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Types of Software Testing
Working with csv files in Python
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
How to Align Text in HTML?
How to Install OpenCV for Python on Windows?
|
[
{
"code": null,
"e": 26009,
"s": 25981,
"text": "\n08 Jul, 2020"
},
{
"code": null,
"e": 26383,
"s": 26009,
"text": "USB Rubber ducky is an HID device that looks similar to a USB Pen drive. It may be used to inject keystroke into a system, used to hack a system, steal victims essential and credential data can inject payload to the victim’s computers. The main important thing about USB Rubber ducky is that it cannot be detected by any Anti-Virus or Firewall as it acts as an HID device. "
},
{
"code": null,
"e": 26587,
"s": 26383,
"text": "Android mobiles can also be used to make a USB rubber ducky, if an Android device is rooted we may use it as a Rubber ducky device. And can perform all the operations that an original ducky can perform. "
},
{
"code": null,
"e": 26628,
"s": 26587,
"text": "To Make USB rubber ducky from android : "
},
{
"code": null,
"e": 26658,
"s": 26628,
"text": "Android mobile must be rooted"
},
{
"code": null,
"e": 26698,
"s": 26658,
"text": "Kali net hunter installed on the device"
},
{
"code": null,
"e": 26793,
"s": 26698,
"text": "In this article, we must be using some other components to create a USB Rubber Ducky at home. "
},
{
"code": null,
"e": 26815,
"s": 26793,
"text": "Material Requirements"
},
{
"code": null,
"e": 26859,
"s": 26815,
"text": "Arduino based boardUSB connectorArduino IDE"
},
{
"code": null,
"e": 26879,
"s": 26859,
"text": "Arduino based board"
},
{
"code": null,
"e": 26893,
"s": 26879,
"text": "USB connector"
},
{
"code": null,
"e": 26905,
"s": 26893,
"text": "Arduino IDE"
},
{
"code": null,
"e": 27036,
"s": 26905,
"text": "Step 1: First of all download Arduino IDE from the link, and install the software like any other software you install on windows. "
},
{
"code": null,
"e": 27131,
"s": 27038,
"text": "Step 2: Connect the Arduino board to the computer using the USB connector and open the IDE. "
},
{
"code": null,
"e": 27197,
"s": 27131,
"text": "Step 3: Now from the Payload list choose according to your task. "
},
{
"code": null,
"e": 27280,
"s": 27197,
"text": "Step 4: Convert the code that you have chosen to make executable in Arduino here. "
},
{
"code": null,
"e": 27325,
"s": 27280,
"text": "Script for turning off the Windows Defender "
},
{
"code": null,
"e": 27804,
"s": 27325,
"text": "REM turn off windows defender then clear action center\nREM author:geeksforgeeks\nREM You take responsibility for any laws you break with this, I simply point out the security flaw\nREM start of script\nREM let the HID enumerate\nDELAY 2000\nESCAPE\nDELAY 100\nCONTROL ESCAPE\nDELAY 100\nSTRING Windows Defender Settings\nENTER\nDELAY 2000\nREM why TAB and HOME?\nTAB\nDELAY 50\nREM why TAB and HOME?HOME\nDELAY 50\nALT F4\nDELAY 3200\nREM windows + a = ????\nGUI a \nDELAY 500\nENTER\nDELAY 100\nGUI a\n"
},
{
"code": null,
"e": 27889,
"s": 27804,
"text": "Step 5:In the Arduino IDE creates a new project, by clicking on File–> New project. "
},
{
"code": null,
"e": 28022,
"s": 27889,
"text": "Step 6: After converting to new code adding to the Arduino IDE, now select the board which you are using. Tools–>Board–>Your board. "
},
{
"code": null,
"e": 28125,
"s": 28022,
"text": "Step 7: Click on the project and choose the port, where Arduino is connected. Tools–>Port–>Your Port. "
},
{
"code": null,
"e": 28216,
"s": 28125,
"text": "Step 8: Now when the board is connected, enter the code or payload you want to work with. "
},
{
"code": null,
"e": 28283,
"s": 28216,
"text": "Step 9: Now verify and compile your code. Sketch–>verify/compile. "
},
{
"code": null,
"e": 28349,
"s": 28283,
"text": "Step 10: After compiling, upload the code to the Arduino device. "
},
{
"code": null,
"e": 28523,
"s": 28349,
"text": "Whenever you will Connect this board with any computer it works as a USB rubber ducky and executes the payload written. You can Check about USB rubber ducky in Details Here."
},
{
"code": null,
"e": 28529,
"s": 28523,
"text": "GBlog"
},
{
"code": null,
"e": 28536,
"s": 28529,
"text": "How To"
},
{
"code": null,
"e": 28634,
"s": 28536,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28659,
"s": 28634,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 28694,
"s": 28659,
"text": "GET and POST requests using Python"
},
{
"code": null,
"e": 28756,
"s": 28694,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28782,
"s": 28756,
"text": "Types of Software Testing"
},
{
"code": null,
"e": 28815,
"s": 28782,
"text": "Working with csv files in Python"
},
{
"code": null,
"e": 28847,
"s": 28815,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28900,
"s": 28847,
"text": "How to Find the Wi-Fi Password Using CMD in Windows?"
},
{
"code": null,
"e": 28944,
"s": 28900,
"text": "How to install Jupyter Notebook on Windows?"
},
{
"code": null,
"e": 28971,
"s": 28944,
"text": "How to Align Text in HTML?"
}
] |
DFA for exactly one of a and at least one of b - GeeksforGeeks
|
02 Dec, 2021
Deterministic Finite Automata (DFA) is defined as an abstract mathematical concept which is used to solve various specific problems in different software and hardware.In this type of problems we have some given parameters according to which we should design DFA.
In this article,two instructions are given:
DFA should have one of a
DFA should have at least one b
This DFA should accept the strings such as ab, ba, abb, bab, bba, abbb, babb, bbab, bbba, abbbb.... etc but it should not accept string such as a, b, bb, bbb, aabb, ababa... etc.
Designing step-by-step :
Step-1: Take a initial state A,and smallest possible string are ab and ba, if A takes ‘a’ as first input alphabet it goes to state B and if A takes ‘b’ as first input alphabet it goes to state C.
Step-2: Now think about state B, if it takes input alphabet ‘a’,it breaks our condition of only one ‘a’ but if takes input alphabet ‘b’ it makes a acceptable string and now it goes to state D which is set to final state.
Step-3: On state C if it can take any numbers of ‘b’ which is possible and it can also take ‘a’ as input alphabet.On alphabet ‘b’ it remains on same state but on input ‘a’ it goes to state E which will set to final state.
Step-4: Input alphabet ‘a’ of state B breaks the condition so it goes to some dead state(Q).
Step-5: Till now, our machine accepts string which are end from ‘a’ and ‘ab’.But what about if ‘a’ comes in middle such as bab,babb,bbab etc and what if there are many ‘b’ in the end.To do that give self loop of ‘b’ to both final state and send their ‘a’ to dead state.
Note – Input alphabets of dead state is going to dead state only that is why these are not showing in diagrams.
Transition Table and Transition Rules of above diagram.
finite set of states = {A, B, C, D, E, Q}
In transition table initial state is represented by → and the final state are E and D.
set of input alphabets = {a, b}
shivamtyagi0918
varshagumber28
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between IPv4 and IPv6
Preemptive and Non-Preemptive Scheduling
Difference between Clustered and Non-clustered index
Phases of a Compiler
Introduction of Process Synchronization
Turing Machine in TOC
Introduction of Pushdown Automata
Difference between DFA and NFA
Introduction of Finite Automata
Construct Pushdown Automata for given languages
|
[
{
"code": null,
"e": 25652,
"s": 25624,
"text": "\n02 Dec, 2021"
},
{
"code": null,
"e": 25916,
"s": 25652,
"text": "Deterministic Finite Automata (DFA) is defined as an abstract mathematical concept which is used to solve various specific problems in different software and hardware.In this type of problems we have some given parameters according to which we should design DFA. "
},
{
"code": null,
"e": 25961,
"s": 25916,
"text": "In this article,two instructions are given: "
},
{
"code": null,
"e": 25988,
"s": 25961,
"text": "DFA should have one of a "
},
{
"code": null,
"e": 26021,
"s": 25988,
"text": "DFA should have at least one b "
},
{
"code": null,
"e": 26201,
"s": 26021,
"text": "This DFA should accept the strings such as ab, ba, abb, bab, bba, abbb, babb, bbab, bbba, abbbb.... etc but it should not accept string such as a, b, bb, bbb, aabb, ababa... etc. "
},
{
"code": null,
"e": 26227,
"s": 26201,
"text": "Designing step-by-step : "
},
{
"code": null,
"e": 26424,
"s": 26227,
"text": "Step-1: Take a initial state A,and smallest possible string are ab and ba, if A takes ‘a’ as first input alphabet it goes to state B and if A takes ‘b’ as first input alphabet it goes to state C. "
},
{
"code": null,
"e": 26648,
"s": 26426,
"text": "Step-2: Now think about state B, if it takes input alphabet ‘a’,it breaks our condition of only one ‘a’ but if takes input alphabet ‘b’ it makes a acceptable string and now it goes to state D which is set to final state. "
},
{
"code": null,
"e": 26873,
"s": 26650,
"text": "Step-3: On state C if it can take any numbers of ‘b’ which is possible and it can also take ‘a’ as input alphabet.On alphabet ‘b’ it remains on same state but on input ‘a’ it goes to state E which will set to final state. "
},
{
"code": null,
"e": 26969,
"s": 26875,
"text": "Step-4: Input alphabet ‘a’ of state B breaks the condition so it goes to some dead state(Q). "
},
{
"code": null,
"e": 27242,
"s": 26971,
"text": "Step-5: Till now, our machine accepts string which are end from ‘a’ and ‘ab’.But what about if ‘a’ comes in middle such as bab,babb,bbab etc and what if there are many ‘b’ in the end.To do that give self loop of ‘b’ to both final state and send their ‘a’ to dead state. "
},
{
"code": null,
"e": 27357,
"s": 27244,
"text": "Note – Input alphabets of dead state is going to dead state only that is why these are not showing in diagrams. "
},
{
"code": null,
"e": 27415,
"s": 27357,
"text": "Transition Table and Transition Rules of above diagram. "
},
{
"code": null,
"e": 27458,
"s": 27415,
"text": "finite set of states = {A, B, C, D, E, Q} "
},
{
"code": null,
"e": 27547,
"s": 27458,
"text": "In transition table initial state is represented by → and the final state are E and D. "
},
{
"code": null,
"e": 27580,
"s": 27547,
"text": "set of input alphabets = {a, b} "
},
{
"code": null,
"e": 27600,
"s": 27584,
"text": "shivamtyagi0918"
},
{
"code": null,
"e": 27615,
"s": 27600,
"text": "varshagumber28"
},
{
"code": null,
"e": 27623,
"s": 27615,
"text": "GATE CS"
},
{
"code": null,
"e": 27656,
"s": 27623,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 27754,
"s": 27656,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27788,
"s": 27754,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 27829,
"s": 27788,
"text": "Preemptive and Non-Preemptive Scheduling"
},
{
"code": null,
"e": 27882,
"s": 27829,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 27903,
"s": 27882,
"text": "Phases of a Compiler"
},
{
"code": null,
"e": 27943,
"s": 27903,
"text": "Introduction of Process Synchronization"
},
{
"code": null,
"e": 27965,
"s": 27943,
"text": "Turing Machine in TOC"
},
{
"code": null,
"e": 27999,
"s": 27965,
"text": "Introduction of Pushdown Automata"
},
{
"code": null,
"e": 28030,
"s": 27999,
"text": "Difference between DFA and NFA"
},
{
"code": null,
"e": 28062,
"s": 28030,
"text": "Introduction of Finite Automata"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.