title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
tclsh - Unix, Linux Command
|
\L’|0u-1v’\l’75u+3n_’\L’0u+1v-0u’\l’|0u-1.5n_’
\L’|0u-1v’\L’0u+1v-0u’\l’|0u-1.5n_’
Tclsh is a shell-like application that reads Tcl commands
from its standard input or from a file and evaluates them.
If invoked with no arguments then it runs interactively, reading
Tcl commands from standard input and printing command results and
error messages to standard output.
It runs until the exit command is invoked or until it
reaches end-of-file on its standard input.
If there exists a file .tclshrc (or tclshrc.tcl on
the Windows platforms) in the home directory of
the user, tclsh evaluates the file as a Tcl script
just before reading the first command from standard input.
If tclsh is invoked with arguments then the first argument
is the name of a script file and any additional arguments
are made available to the script as variables (see below).
Instead of reading commands from standard input tclsh will
read Tcl commands from the named file; tclsh will exit
when it reaches the end of the file.
The end of the file may be marked either by the physical end of
the medium, or by the character, ’\032’ (’\u001a’, control-Z).
If this character is present in the file, the tclsh application
will read text up to but not including the character. An application
that requires this character in the file may safely encode it as
‘‘\032’’, ‘‘\x1a’’, or ‘‘\u001a’’; or may generate it by use of commands
such as format or binary.
\L’|0u-1v|’
If you create a Tcl script in a file whose first line is
#!/usr/local/bin/tclsh
An even better approach is to start your script files with the
following three lines:
#!/bin/sh
# the next line restarts using tclsh \
exec tclsh "$0" "$@"
You should note that it is also common practise to install tclsh with
its version number as part of the name. This has the advantage of
allowing multiple versions of Tcl to exist on the same system at once,
but also the disadvantage of making it harder to write scripts that
start up uniformly across different versions of Tcl.
\L’|0u-1v|’
Tclsh sets the following Tcl variables:
When tclsh is invoked interactively it normally prompts for each
command with ‘‘% ’’. You can change the prompt by setting the
variables tcl_prompt1 and tcl_prompt2. If variable
tcl_prompt1 exists then it must consist of a Tcl script
to output a prompt; instead of outputting a prompt tclsh
will evaluate the script in tcl_prompt1.
The variable tcl_prompt2 is used in a similar way when
a newline is typed but the current command isn’t yet complete;
if tcl_prompt2 isn’t set then no prompt is output for
incomplete commands.
See Tcl_StandardChannels for more explanations.
Advertisements
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 10672,
"s": 10577,
"text": " \n\n\n\n\\L’|0u-1v’\\l’75u+3n_’\\L’0u+1v-0u’\\l’|0u-1.5n_’\n\n\n\\L’|0u-1v’\\L’0u+1v-0u’\\l’|0u-1.5n_’\n\n\n"
},
{
"code": null,
"e": 11265,
"s": 10674,
"text": "\nTclsh is a shell-like application that reads Tcl commands\nfrom its standard input or from a file and evaluates them.\nIf invoked with no arguments then it runs interactively, reading\nTcl commands from standard input and printing command results and\nerror messages to standard output.\nIt runs until the exit command is invoked or until it\nreaches end-of-file on its standard input.\nIf there exists a file .tclshrc (or tclshrc.tcl on\nthe Windows platforms) in the home directory of\nthe user, tclsh evaluates the file as a Tcl script\njust before reading the first command from standard input.\n"
},
{
"code": null,
"e": 12027,
"s": 11267,
"text": "\nIf tclsh is invoked with arguments then the first argument\nis the name of a script file and any additional arguments\nare made available to the script as variables (see below).\nInstead of reading commands from standard input tclsh will\nread Tcl commands from the named file; tclsh will exit\nwhen it reaches the end of the file.\n\n\n\nThe end of the file may be marked either by the physical end of\nthe medium, or by the character, ’\\032’ (’\\u001a’, control-Z).\nIf this character is present in the file, the tclsh application\nwill read text up to but not including the character. An application\nthat requires this character in the file may safely encode it as\n‘‘\\032’’, ‘‘\\x1a’’, or ‘‘\\u001a’’; or may generate it by use of commands\nsuch as format or binary.\n\n\n"
},
{
"code": null,
"e": 12045,
"s": 12027,
"text": " \n\\L’|0u-1v|’\n\n"
},
{
"code": null,
"e": 12106,
"s": 12047,
"text": "\nIf you create a Tcl script in a file whose first line is\n"
},
{
"code": null,
"e": 12130,
"s": 12106,
"text": "#!/usr/local/bin/tclsh\n"
},
{
"code": null,
"e": 12218,
"s": 12130,
"text": "\nAn even better approach is to start your script files with the\nfollowing three lines:\n"
},
{
"code": null,
"e": 12289,
"s": 12218,
"text": "#!/bin/sh\n# the next line restarts using tclsh \\\nexec tclsh \"$0\" \"$@\"\n"
},
{
"code": null,
"e": 12625,
"s": 12289,
"text": "\n\n\n\nYou should note that it is also common practise to install tclsh with\nits version number as part of the name. This has the advantage of\nallowing multiple versions of Tcl to exist on the same system at once,\nbut also the disadvantage of making it harder to write scripts that\nstart up uniformly across different versions of Tcl.\n\n\n"
},
{
"code": null,
"e": 12643,
"s": 12625,
"text": " \n\\L’|0u-1v|’\n\n"
},
{
"code": null,
"e": 12689,
"s": 12647,
"text": "\nTclsh sets the following Tcl variables:\n"
},
{
"code": null,
"e": 13221,
"s": 12691,
"text": "\nWhen tclsh is invoked interactively it normally prompts for each\ncommand with ‘‘% ’’. You can change the prompt by setting the\nvariables tcl_prompt1 and tcl_prompt2. If variable\ntcl_prompt1 exists then it must consist of a Tcl script\nto output a prompt; instead of outputting a prompt tclsh\nwill evaluate the script in tcl_prompt1.\nThe variable tcl_prompt2 is used in a similar way when\na newline is typed but the current command isn’t yet complete;\nif tcl_prompt2 isn’t set then no prompt is output for\nincomplete commands.\n"
},
{
"code": null,
"e": 13273,
"s": 13223,
"text": "\nSee Tcl_StandardChannels for more explanations.\n"
},
{
"code": null,
"e": 13294,
"s": 13277,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 13329,
"s": 13294,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 13357,
"s": 13329,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 13391,
"s": 13357,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 13408,
"s": 13391,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 13441,
"s": 13408,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 13452,
"s": 13441,
"text": " Pradeep D"
},
{
"code": null,
"e": 13487,
"s": 13452,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 13503,
"s": 13487,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 13536,
"s": 13503,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 13548,
"s": 13536,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 13580,
"s": 13548,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 13588,
"s": 13580,
"text": " Uplatz"
},
{
"code": null,
"e": 13595,
"s": 13588,
"text": " Print"
},
{
"code": null,
"e": 13606,
"s": 13595,
"text": " Add Notes"
}
] |
Diving into Gremlin queries in Azure Cosmos DB | by Will Velida | Towards Data Science
|
Thanks to the Gremlin API offering of Azure Cosmos DB, we can build globally distributed databases that store and operate on graph data. We can perform graph queries in Cosmos DB using the Gremlin query language.
In this article, I’m going to show you how to set up a Cosmos DB account that supports the Gremlin API and how you can perform some simple graph queries in that account.
If you want to follow along, you’ll need to set up an Azure subscription. Check out this link on how to do that. Otherwise, let’s begin!
Setting up our Graph Database
Let’s start with creating our graph database. Head to your Azure Portal and click “Create a new resource”. Search for Azure Cosmos DB and click “‘Create New”.
In order to create our graph database, we’ll need to provide some basic information:
Subscription — Essentially the subscription that your Cosmos DB account will be charged to.
Resource Group — Resource groups are great for managing a collection of Azure resources. At the end of this tutorial, we can delete all the resources within a group, rather than deleting resources one by one. You can assign your Cosmos DB account to a pre-existing resource group or create a new one for it. I’ve decided that I’m going to create a new one for this tutorial.
API — We can create different kinds of Cosmos DB datastores depending on the API that we assign it. In this case, we’re creating a Graph database, so we’ll be picking the Gremlin (Graph) API.
Notebooks — Love Jupyter notebooks? Cosmos DB supports that! It’s out of scope for this tutorial so I’m not going to enable it.
Location — Cosmos DB is a fundamental service in Azure, meaning that’s it’s available in all Azure regions. Pick a region that’s closest to where you are right now. In my case, I’m based in Auckland, New Zealand, so I’m deploying my database in Australia East.
Account Type — This is new?! I’ve never experienced this before. Hovering over the tooltip, it looks like it has something to do with how the UI experience works. I’ll have to do some more investigation into this, but for now, I’ve just set it to Production for now. You can change it and it doesn’t impact the engine.
Geo-redundancy and multi-region writes — I’ve disabled this for now.
Look at the screenshot below for an example:
Click “Review + Create” and you’ll be redirected to a validation page. We don’t need to worry about networking or tags just for the moment. If your configuration is valid, you’ll be shown a success message and you can click “Create ”to provision your graph database!
For this tutorial, we’re going to use the sample graph that the Cosmos DB provides for all new Graph accounts. In order to do this, click “Quick Start”. You’ll be asked to choose a platform for creating a sample app, but all we’re doing here is creating a container with some sample data.
The Cosmos DB team have a Persons container that we can use, so click on Create ‘Persons’ container and that should be enough.
Click on “Data Explorer” to navigate to your graph.
This is new? They’ve changed the way that the data explorer works! It looks like we have to add our current IP address to our firewall rules in order to see our data? (Very Azure SQL, if you’ve used Azure SQL before).
Click on the notification and you’ll be redirected to the firewall settings tab. Your IP address should be prepopulated in the Firewall section below, so just click “Save ”to add your IP address to the allow access list. After a few minutes you should be good to go.
Once this is all done, navigate back to the Data Explorer and we should see our new Persons Graph in our Cosmos DB account.
Alright, that’s all the admin setup that we need to do, let’s start diving into some awesome graph queries!
Performing queries in our Graph Database
Let’s start by inserting a couple of items into our Persons Graph. Head to your data explorer and you should see a text box that allows us to execute Gremlin queries.
Let’s start by adding 5 people to our graph. Type in the following Gremlin queries:
# Add Will Velidag.addV('person').property('firstName', 'Will').property('lastName', 'Velida').property('age', 28).property('hairColor', 'blonde').property('userId', 1).property('pk', 'pk')g.addV('person').property('firstName', 'Alex').property('lastName', 'Smith').property('age', 22).property('hairColor', 'brown').property('userId', 2).property('pk', 'pk')g.addV('person').property('firstName', 'Mike').property('lastName', 'Jones').property('hairColor', 'black').property('userId', 2).property('pk', 'pk')g.addV('person').property('firstName', 'Sarah').property('lastName', 'Smith').property('hairColor', 'blonde').property('userId', 4).property('pk', 'pk')g.addV('person').property('firstName', 'Debbie').property('lastName', 'Stevens').property('hairColor', 'black').property('age', 57).property('userId', 5).property('pk', 'pk')
What we’ve done here is added 5 people vertices. Vertices are discrete entities in our graphs. In this example, we have used People as our vertices, but they could be places or events.
Let’s take a bit of a deeper dive as to what each Gremlin command is doing:
addV() — This adds a vertex (our discrete entities) to our graph.
property() — This adds a property to our verticies
Now let’s add some relationships between our vertices. These are referred to as edges in graph databases. Let’s write the following queries:
g.V().hasLabel('person').has('firstName', 'Will').addE('knows').to(g.V().hasLabel('person').has('firstName', 'Alex'))g.V().hasLabel('person').has('firstName', 'Alex').addE('knows').to(g.V().hasLabel('person').has('firstName', 'Mike'))
Let’s examine the new Gremlin queries:
addE() — has an edge (relationship) between two vertices.
has() and hasLabel() — used to filter properties, vertices and edges. in this example, we are filtering on our ‘firstName’ property.
We can update our vertices with a command like so:
g.V().hasLabel('person').has('firstName', 'Mike').property('userId', 3)
Let’s try filtering our Persons collection. Let’s retrieve all the vertices that have an age less than 30:
g.V().hasLabel('person').has('age', lt(30))
Here, we get two results back:
We can refine this query further to return just the name properties:
g.V().hasLabel('person').has('age', lt(30)).values('firstName')
which returns the following result:
Finally, let’s perform a simple traversal in our graph to find out all the people that Alex knows:
g.V().hasLabel('person').has('firstName', 'Alex').outE('knows').inV().hasLabel('person')
As we can see, he knows 1 person, Mike Jones:
[ { "id": "c2260feb-207b-403b-82cb-30cd47006912", "label": "person", "type": "vertex" "properties": "firstName": [ { "id": "1a383c60-82ce-414b-a610-8c2b9ab08759", "value": "Mike" } ] "lastName": [ { "id": "1a1a762a-dace-4912-aa16-e87f4327d1a7", "value": "Jones" } ], "hairColor": [ { "id": "5f71ca42-1cf0-4da4-93a9-c24693975e56", "value": "black" } ], "userId": [ { "id": "9e06cf3a-e58a-494f-aaf2-e0f1e2940cce", "value": 3 } ], "pk": [ { "id": "4f27fd02-1861-480a-8887-4b40c8c7d6c6", "value": "pk" } ] } }]
Assessing performance of graph queries
This is pretty cool stuff, but I can already hear some of you say ‘how can I measure the performance of these queries?’.
The Gremlin query language has a method called executionProfile() that allows us to look at metrics on how our query performed. Let’s append this method to our previous query and see how it performs:
g.V().hasLabel('person').has('firstName', 'Alex').outE('knows').inV().hasLabel('person').executionProfile()
This is the response we get back:
Let’s go through the following properties:
gremlin — The statement that was executed.
totalTime — The time in milliseconds that the operation took
metrics — metrics for each of the steps that were executed in our gremlin query. These are separated into GetVertices (getting our properties),GetEdges (seeing what the relationship between our vertices are) and GetNeighborVertices (seeing which vertices have what relationships). These metrics include the time it took to execute the query in milliseconds, the percentTime of total query execution time, how many results were returned, count and size.
Conclusion
In this post, we set up a new Cosmos DB Graph database and perform some basic queries in it. We also looked at how we can assess the performance of those queries. If you’re done with this graph db, feel free to delete it. Otherwise, why not add some more properties and take a look at the Cosmos DB Graph documentation to discover what else you can do with Gremlin queries.
In a future post, I’ll talk about how we can model our data for graph databases and look at some best practices. I’ll also talk about how we can apply these concepts in the context of developing applications for Azure Cosmos DB.
If you have any questions, please feel free to ask them in the comment section below.
Until next time!
|
[
{
"code": null,
"e": 385,
"s": 172,
"text": "Thanks to the Gremlin API offering of Azure Cosmos DB, we can build globally distributed databases that store and operate on graph data. We can perform graph queries in Cosmos DB using the Gremlin query language."
},
{
"code": null,
"e": 555,
"s": 385,
"text": "In this article, I’m going to show you how to set up a Cosmos DB account that supports the Gremlin API and how you can perform some simple graph queries in that account."
},
{
"code": null,
"e": 692,
"s": 555,
"text": "If you want to follow along, you’ll need to set up an Azure subscription. Check out this link on how to do that. Otherwise, let’s begin!"
},
{
"code": null,
"e": 722,
"s": 692,
"text": "Setting up our Graph Database"
},
{
"code": null,
"e": 881,
"s": 722,
"text": "Let’s start with creating our graph database. Head to your Azure Portal and click “Create a new resource”. Search for Azure Cosmos DB and click “‘Create New”."
},
{
"code": null,
"e": 966,
"s": 881,
"text": "In order to create our graph database, we’ll need to provide some basic information:"
},
{
"code": null,
"e": 1058,
"s": 966,
"text": "Subscription — Essentially the subscription that your Cosmos DB account will be charged to."
},
{
"code": null,
"e": 1433,
"s": 1058,
"text": "Resource Group — Resource groups are great for managing a collection of Azure resources. At the end of this tutorial, we can delete all the resources within a group, rather than deleting resources one by one. You can assign your Cosmos DB account to a pre-existing resource group or create a new one for it. I’ve decided that I’m going to create a new one for this tutorial."
},
{
"code": null,
"e": 1625,
"s": 1433,
"text": "API — We can create different kinds of Cosmos DB datastores depending on the API that we assign it. In this case, we’re creating a Graph database, so we’ll be picking the Gremlin (Graph) API."
},
{
"code": null,
"e": 1753,
"s": 1625,
"text": "Notebooks — Love Jupyter notebooks? Cosmos DB supports that! It’s out of scope for this tutorial so I’m not going to enable it."
},
{
"code": null,
"e": 2014,
"s": 1753,
"text": "Location — Cosmos DB is a fundamental service in Azure, meaning that’s it’s available in all Azure regions. Pick a region that’s closest to where you are right now. In my case, I’m based in Auckland, New Zealand, so I’m deploying my database in Australia East."
},
{
"code": null,
"e": 2333,
"s": 2014,
"text": "Account Type — This is new?! I’ve never experienced this before. Hovering over the tooltip, it looks like it has something to do with how the UI experience works. I’ll have to do some more investigation into this, but for now, I’ve just set it to Production for now. You can change it and it doesn’t impact the engine."
},
{
"code": null,
"e": 2402,
"s": 2333,
"text": "Geo-redundancy and multi-region writes — I’ve disabled this for now."
},
{
"code": null,
"e": 2447,
"s": 2402,
"text": "Look at the screenshot below for an example:"
},
{
"code": null,
"e": 2714,
"s": 2447,
"text": "Click “Review + Create” and you’ll be redirected to a validation page. We don’t need to worry about networking or tags just for the moment. If your configuration is valid, you’ll be shown a success message and you can click “Create ”to provision your graph database!"
},
{
"code": null,
"e": 3003,
"s": 2714,
"text": "For this tutorial, we’re going to use the sample graph that the Cosmos DB provides for all new Graph accounts. In order to do this, click “Quick Start”. You’ll be asked to choose a platform for creating a sample app, but all we’re doing here is creating a container with some sample data."
},
{
"code": null,
"e": 3130,
"s": 3003,
"text": "The Cosmos DB team have a Persons container that we can use, so click on Create ‘Persons’ container and that should be enough."
},
{
"code": null,
"e": 3182,
"s": 3130,
"text": "Click on “Data Explorer” to navigate to your graph."
},
{
"code": null,
"e": 3400,
"s": 3182,
"text": "This is new? They’ve changed the way that the data explorer works! It looks like we have to add our current IP address to our firewall rules in order to see our data? (Very Azure SQL, if you’ve used Azure SQL before)."
},
{
"code": null,
"e": 3667,
"s": 3400,
"text": "Click on the notification and you’ll be redirected to the firewall settings tab. Your IP address should be prepopulated in the Firewall section below, so just click “Save ”to add your IP address to the allow access list. After a few minutes you should be good to go."
},
{
"code": null,
"e": 3791,
"s": 3667,
"text": "Once this is all done, navigate back to the Data Explorer and we should see our new Persons Graph in our Cosmos DB account."
},
{
"code": null,
"e": 3899,
"s": 3791,
"text": "Alright, that’s all the admin setup that we need to do, let’s start diving into some awesome graph queries!"
},
{
"code": null,
"e": 3940,
"s": 3899,
"text": "Performing queries in our Graph Database"
},
{
"code": null,
"e": 4107,
"s": 3940,
"text": "Let’s start by inserting a couple of items into our Persons Graph. Head to your data explorer and you should see a text box that allows us to execute Gremlin queries."
},
{
"code": null,
"e": 4191,
"s": 4107,
"text": "Let’s start by adding 5 people to our graph. Type in the following Gremlin queries:"
},
{
"code": null,
"e": 5027,
"s": 4191,
"text": "# Add Will Velidag.addV('person').property('firstName', 'Will').property('lastName', 'Velida').property('age', 28).property('hairColor', 'blonde').property('userId', 1).property('pk', 'pk')g.addV('person').property('firstName', 'Alex').property('lastName', 'Smith').property('age', 22).property('hairColor', 'brown').property('userId', 2).property('pk', 'pk')g.addV('person').property('firstName', 'Mike').property('lastName', 'Jones').property('hairColor', 'black').property('userId', 2).property('pk', 'pk')g.addV('person').property('firstName', 'Sarah').property('lastName', 'Smith').property('hairColor', 'blonde').property('userId', 4).property('pk', 'pk')g.addV('person').property('firstName', 'Debbie').property('lastName', 'Stevens').property('hairColor', 'black').property('age', 57).property('userId', 5).property('pk', 'pk')"
},
{
"code": null,
"e": 5212,
"s": 5027,
"text": "What we’ve done here is added 5 people vertices. Vertices are discrete entities in our graphs. In this example, we have used People as our vertices, but they could be places or events."
},
{
"code": null,
"e": 5288,
"s": 5212,
"text": "Let’s take a bit of a deeper dive as to what each Gremlin command is doing:"
},
{
"code": null,
"e": 5354,
"s": 5288,
"text": "addV() — This adds a vertex (our discrete entities) to our graph."
},
{
"code": null,
"e": 5405,
"s": 5354,
"text": "property() — This adds a property to our verticies"
},
{
"code": null,
"e": 5546,
"s": 5405,
"text": "Now let’s add some relationships between our vertices. These are referred to as edges in graph databases. Let’s write the following queries:"
},
{
"code": null,
"e": 5781,
"s": 5546,
"text": "g.V().hasLabel('person').has('firstName', 'Will').addE('knows').to(g.V().hasLabel('person').has('firstName', 'Alex'))g.V().hasLabel('person').has('firstName', 'Alex').addE('knows').to(g.V().hasLabel('person').has('firstName', 'Mike'))"
},
{
"code": null,
"e": 5820,
"s": 5781,
"text": "Let’s examine the new Gremlin queries:"
},
{
"code": null,
"e": 5878,
"s": 5820,
"text": "addE() — has an edge (relationship) between two vertices."
},
{
"code": null,
"e": 6011,
"s": 5878,
"text": "has() and hasLabel() — used to filter properties, vertices and edges. in this example, we are filtering on our ‘firstName’ property."
},
{
"code": null,
"e": 6062,
"s": 6011,
"text": "We can update our vertices with a command like so:"
},
{
"code": null,
"e": 6134,
"s": 6062,
"text": "g.V().hasLabel('person').has('firstName', 'Mike').property('userId', 3)"
},
{
"code": null,
"e": 6241,
"s": 6134,
"text": "Let’s try filtering our Persons collection. Let’s retrieve all the vertices that have an age less than 30:"
},
{
"code": null,
"e": 6285,
"s": 6241,
"text": "g.V().hasLabel('person').has('age', lt(30))"
},
{
"code": null,
"e": 6316,
"s": 6285,
"text": "Here, we get two results back:"
},
{
"code": null,
"e": 6385,
"s": 6316,
"text": "We can refine this query further to return just the name properties:"
},
{
"code": null,
"e": 6449,
"s": 6385,
"text": "g.V().hasLabel('person').has('age', lt(30)).values('firstName')"
},
{
"code": null,
"e": 6485,
"s": 6449,
"text": "which returns the following result:"
},
{
"code": null,
"e": 6584,
"s": 6485,
"text": "Finally, let’s perform a simple traversal in our graph to find out all the people that Alex knows:"
},
{
"code": null,
"e": 6673,
"s": 6584,
"text": "g.V().hasLabel('person').has('firstName', 'Alex').outE('knows').inV().hasLabel('person')"
},
{
"code": null,
"e": 6719,
"s": 6673,
"text": "As we can see, he knows 1 person, Mike Jones:"
},
{
"code": null,
"e": 7354,
"s": 6719,
"text": "[ { \"id\": \"c2260feb-207b-403b-82cb-30cd47006912\", \"label\": \"person\", \"type\": \"vertex\" \"properties\": \"firstName\": [ { \"id\": \"1a383c60-82ce-414b-a610-8c2b9ab08759\", \"value\": \"Mike\" } ] \"lastName\": [ { \"id\": \"1a1a762a-dace-4912-aa16-e87f4327d1a7\", \"value\": \"Jones\" } ], \"hairColor\": [ { \"id\": \"5f71ca42-1cf0-4da4-93a9-c24693975e56\", \"value\": \"black\" } ], \"userId\": [ { \"id\": \"9e06cf3a-e58a-494f-aaf2-e0f1e2940cce\", \"value\": 3 } ], \"pk\": [ { \"id\": \"4f27fd02-1861-480a-8887-4b40c8c7d6c6\", \"value\": \"pk\" } ] } }]"
},
{
"code": null,
"e": 7393,
"s": 7354,
"text": "Assessing performance of graph queries"
},
{
"code": null,
"e": 7514,
"s": 7393,
"text": "This is pretty cool stuff, but I can already hear some of you say ‘how can I measure the performance of these queries?’."
},
{
"code": null,
"e": 7714,
"s": 7514,
"text": "The Gremlin query language has a method called executionProfile() that allows us to look at metrics on how our query performed. Let’s append this method to our previous query and see how it performs:"
},
{
"code": null,
"e": 7822,
"s": 7714,
"text": "g.V().hasLabel('person').has('firstName', 'Alex').outE('knows').inV().hasLabel('person').executionProfile()"
},
{
"code": null,
"e": 7856,
"s": 7822,
"text": "This is the response we get back:"
},
{
"code": null,
"e": 7899,
"s": 7856,
"text": "Let’s go through the following properties:"
},
{
"code": null,
"e": 7942,
"s": 7899,
"text": "gremlin — The statement that was executed."
},
{
"code": null,
"e": 8003,
"s": 7942,
"text": "totalTime — The time in milliseconds that the operation took"
},
{
"code": null,
"e": 8456,
"s": 8003,
"text": "metrics — metrics for each of the steps that were executed in our gremlin query. These are separated into GetVertices (getting our properties),GetEdges (seeing what the relationship between our vertices are) and GetNeighborVertices (seeing which vertices have what relationships). These metrics include the time it took to execute the query in milliseconds, the percentTime of total query execution time, how many results were returned, count and size."
},
{
"code": null,
"e": 8467,
"s": 8456,
"text": "Conclusion"
},
{
"code": null,
"e": 8841,
"s": 8467,
"text": "In this post, we set up a new Cosmos DB Graph database and perform some basic queries in it. We also looked at how we can assess the performance of those queries. If you’re done with this graph db, feel free to delete it. Otherwise, why not add some more properties and take a look at the Cosmos DB Graph documentation to discover what else you can do with Gremlin queries."
},
{
"code": null,
"e": 9070,
"s": 8841,
"text": "In a future post, I’ll talk about how we can model our data for graph databases and look at some best practices. I’ll also talk about how we can apply these concepts in the context of developing applications for Azure Cosmos DB."
},
{
"code": null,
"e": 9156,
"s": 9070,
"text": "If you have any questions, please feel free to ask them in the comment section below."
}
] |
How to create a matrix using vector of string values in R?
|
You might have heard that matrix can contain only numerical values but it is also possible to create a matrix with string values, and of course calculations using these types of matrices would not be possible. To create a matrix using string values, we can first create a vector of strings then define its dimension with dim function and that will convert the vector into matrix of string values.
Live Demo
M1<-rep(c("A","B","C","D","E"),each=5)
M1
[1] "A" "A" "A" "A" "A" "B" "B" "B" "B" "B" "C" "C" "C" "C" "C" "D" "D" "D" "D"
[20] "D" "E" "E" "E" "E" "E"
dim(M1)<-c(5,5)
M1
[,1] [,2] [,3] [,4] [,5]
[1,] "A" "B" "C" "D" "E"
[2,] "A" "B" "C" "D" "E"
[3,] "A" "B" "C" "D" "E"
[4,] "A" "B" "C" "D" "E"
[5,] "A" "B" "C" "D" "E"
is.matrix(M1) [1] TRUE
Live Demo
M2<-sample(c("A","B","C","D"),36,replace=TRUE)
M2
[1] "C" "A" "B" "C" "B" "D" "A" "D" "A" "A" "D" "D" "A" "D" "C" "D" "D" "D" "C"
[20] "C" "C" "B" "A" "A" "D" "A" "C" "B" "D" "D" "C" "D" "D" "C" "C" "C"
dim(M2)<-c(6,6)
M2
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] "D" "A" "C" "A" "B" "C"
[2,] "D" "B" "B" "D" "A" "B"
[3,] "C" "B" "B" "A" "D" "C"
[4,] "D" "D" "C" "B" "A" "B"
[5,] "C" "B" "A" "A" "D" "A"
[6,] "A" "B" "B" "A" "A" "D"
is.matrix(M2) [1] TRUE
Live Demo
M3<-sample(letters[1:10],60,replace=TRUE) M3
[1] "d" "a" "d" "b" "b" "c" "j" "d" "h" "f" "f" "b" "a" "i" "h" "i" "e" "h" "d"
[20] "a" "i" "g" "a" "g" "h" "h" "e" "g" "a" "g" "c" "i" "j" "d" "e" "f" "b" "b"
[39] "i" "d" "d" "e" "d" "e" "g" "g" "j" "g" "a" "g" "j" "j" "d" "c" "b" "j" "h"
[58] "f" "e" "a"
dim(M3)<-c(10,6)
M3
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] "f" "h" "a" "f" "d" "c"
[2,] "e" "h" "g" "b" "i" "e"
[3,] "b" "j" "h" "h" "h" "g"
[4,] "i" "f" "d" "i" "c" "d"
[5,] "j" "f" "j" "b" "j" "d"
[6,] "a" "d" "c" "j" "e" "j"
[7,] "b" "i" "j" "i" "e" "c"
[8,] "c" "i" "d" "i" "b" "a"
[9,] "g" "f" "a" "d" "d" "j"
[10,] "d" "f" "e" "b" "f" "i"
is.matrix(M3) [1] TRUE
Live Demo
M4<-sample(LETTERS[1:26],100,replace=TRUE)M4
[1] "J" "R" "D" "B" "Z" "F" "V" "M" "U" "M" "X" "A" "L" "L" "N" "G" "O" "H"
[19] "J" "C" "Y" "L" "I" "N" "Y" "D" "E" "N" "U" "Q" "Y" "X" "J" "O" "T" "Q"
[37] "X" "H" "V" "Z" "I" "P" "J" "Q" "Z" "G" "J" "V" "U" "P" "X" "P" "K" "O"
[55] "Y" "L" "E" "B" "B" "P" "Y" "D" "M" "S" "U" "K" "D" "N" "B" "B" "P" "V"
[73] "O" "Z" "L" "L" "G" "J" "Y" "Z" "K" "C" "Z" "Q" "Y" "C" "G" "H" "F" "J"
[91] "Q" "W" "Q" "H" "H" "Q" "O" "M" "I" "S"
dim(M4)<-c(10,10)
M4
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] "I" "K" "A" "X" "X" "N" "Y" "U" "U" "P"
[2,] "Y" "R" "Q" "Y" "V" "M" "T" "L" "X" "X"
[3,] "F" "H" "E" "N" "V" "G" "A" "G" "Y" "P"
[4,] "C" "D" "K" "E" "P" "M" "S" "B" "K" "Z"
[5,] "W" "C" "G" "H" "J" "E" "U" "G" "C" "Q"
[6,] "D" "T" "J" "V" "D" "A" "L" "S" "I" "P"
[7,] "N" "T" "W" "T" "J" "T" "R" "E" "S" "S"
[8,] "W" "N" "P" "O" "B" "E" "M" "W" "G" "P"
[9,] "I" "I" "N" "M" "I" "L" "W" "E" "D" "W"
[10,] "E" "Y" "B" "T" "M" "C" "F" "P" "R" "L"
is.matrix(M4) [1] TRUE
Live Demo
M5<-sample(c("India","Russia","China","Denmark"),60,replace=TRUE)
M5
[1] "China" "Denmark" "China" "China" "Russia" "Russia" "Denmark"
[8] "China" "Russia" "Russia" "Denmark" "India" "China" "Russia"
[15] "India" "China" "China" "China" "Russia" "India" "India"
[22] "Denmark" "Russia" "Russia" "Russia" "China" "China" "India"
[29] "Russia" "Denmark" "Russia" "Russia" "China" "India" "Russia"
[36] "Russia" "Russia" "India" "China" "Denmark" "Russia" "China"
[43] "India" "Russia" "China" "China" "China" "Russia" "India"
[50] "Denmark" "India" "China" "India" "Denmark" "Denmark" "Denmark"
[57] "Denmark" "India" "Russia" "China"
dim(M5)<-c(10,6)
M5
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] "India" "China" "India" "Russia" "Denmark" "Denmark"
[2,] "Russia" "Denmark" "Russia" "Russia" "Denmark" "India"
[3,] "China" "India" "China" "China" "Denmark" "Denmark"
[4,] "Denmark" "India" "Russia" "India" "Denmark" "China"
[5,] "Russia" "China" "Russia" "China" "Russia" "China"
[6,] "Denmark" "China" "Russia" "Denmark" "Denmark" "China"
[7,] "Denmark" "Russia" "China" "India" "China" "China"
[8,] "Denmark" "China" "Denmark" "India" "India" "Denmark"
[9,] "Denmark" "India" "Denmark" "India" "Russia" "China"
[10,] "Russia" "Denmark" "China" "India" "Denmark" "India"
is.matrix(M5) [1] TRUE
Live Demo
M6<-sample(c("Cold","Winter","Hot"),40,replace=TRUE)
M6
[1] "Hot" "Cold" "Hot" "Winter" "Winter" "Hot" "Cold" "Winter"
[9] "Hot" "Winter" "Cold" "Winter" "Hot" "Winter" "Hot" "Winter"
[17] "Hot" "Winter" "Cold" "Cold" "Winter" "Cold" "Cold" "Hot"
[25] "Hot" "Hot" "Hot" "Hot" "Cold" "Winter" "Winter" "Cold"
[33] "Cold" "Winter" "Winter" "Hot" "Hot" "Hot" "Hot" "Hot"
dim(M6)<-c(10,4)
M6
[,1] [,2] [,3] [,4]
[1,] "Hot" "Hot" "Cold" "Winter"
[2,] "Hot" "Hot" "Winter" "Winter"
[3,] "Winter" "Cold" "Winter" "Cold"
[4,] "Cold" "Cold" "Hot" "Winter"
[5,] "Hot" "Cold" "Cold" "Hot"
[6,] "Cold" "Winter" "Hot" "Cold"
[7,] "Winter" "Winter" "Cold" "Hot"
[8,] "Cold" "Cold" "Cold" "Hot"
[9,] "Cold" "Cold" "Winter" "Cold"
[10,] "Cold" "Winter" "Winter" "Hot"
is.matrix(M6) [1] TRUE
|
[
{
"code": null,
"e": 1459,
"s": 1062,
"text": "You might have heard that matrix can contain only numerical values but it is also possible to create a matrix with string values, and of course calculations using these types of matrices would not be possible. To create a matrix using string values, we can first create a vector of strings then define its dimension with dim function and that will convert the vector into matrix of string values."
},
{
"code": null,
"e": 1470,
"s": 1459,
"text": " Live Demo"
},
{
"code": null,
"e": 1512,
"s": 1470,
"text": "M1<-rep(c(\"A\",\"B\",\"C\",\"D\",\"E\"),each=5)\nM1"
},
{
"code": null,
"e": 1621,
"s": 1512,
"text": "[1] \"A\" \"A\" \"A\" \"A\" \"A\" \"B\" \"B\" \"B\" \"B\" \"B\" \"C\" \"C\" \"C\" \"C\" \"C\" \"D\" \"D\" \"D\" \"D\"\n[20] \"D\" \"E\" \"E\" \"E\" \"E\" \"E\""
},
{
"code": null,
"e": 1640,
"s": 1621,
"text": "dim(M1)<-c(5,5)\nM1"
},
{
"code": null,
"e": 1814,
"s": 1640,
"text": " [,1] [,2] [,3] [,4] [,5] \n[1,] \"A\" \"B\" \"C\" \"D\" \"E\" \n[2,] \"A\" \"B\" \"C\" \"D\" \"E\" \n[3,] \"A\" \"B\" \"C\" \"D\" \"E\" \n[4,] \"A\" \"B\" \"C\" \"D\" \"E\" \n[5,] \"A\" \"B\" \"C\" \"D\" \"E\""
},
{
"code": null,
"e": 1837,
"s": 1814,
"text": "is.matrix(M1) [1] TRUE"
},
{
"code": null,
"e": 1848,
"s": 1837,
"text": " Live Demo"
},
{
"code": null,
"e": 1898,
"s": 1848,
"text": "M2<-sample(c(\"A\",\"B\",\"C\",\"D\"),36,replace=TRUE)\nM2"
},
{
"code": null,
"e": 2051,
"s": 1898,
"text": "[1] \"C\" \"A\" \"B\" \"C\" \"B\" \"D\" \"A\" \"D\" \"A\" \"A\" \"D\" \"D\" \"A\" \"D\" \"C\" \"D\" \"D\" \"D\" \"C\"\n[20] \"C\" \"C\" \"B\" \"A\" \"A\" \"D\" \"A\" \"C\" \"B\" \"D\" \"D\" \"C\" \"D\" \"D\" \"C\" \"C\" \"C\""
},
{
"code": null,
"e": 2070,
"s": 2051,
"text": "dim(M2)<-c(6,6)\nM2"
},
{
"code": null,
"e": 2308,
"s": 2070,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] \n[1,] \"D\" \"A\" \"C\" \"A\" \"B\" \"C\" \n[2,] \"D\" \"B\" \"B\" \"D\" \"A\" \"B\" \n[3,] \"C\" \"B\" \"B\" \"A\" \"D\" \"C\" \n[4,] \"D\" \"D\" \"C\" \"B\" \"A\" \"B\" \n[5,] \"C\" \"B\" \"A\" \"A\" \"D\" \"A\" \n[6,] \"A\" \"B\" \"B\" \"A\" \"A\" \"D\""
},
{
"code": null,
"e": 2331,
"s": 2308,
"text": "is.matrix(M2) [1] TRUE"
},
{
"code": null,
"e": 2342,
"s": 2331,
"text": " Live Demo"
},
{
"code": null,
"e": 2387,
"s": 2342,
"text": "M3<-sample(letters[1:10],60,replace=TRUE) M3"
},
{
"code": null,
"e": 2646,
"s": 2387,
"text": "[1] \"d\" \"a\" \"d\" \"b\" \"b\" \"c\" \"j\" \"d\" \"h\" \"f\" \"f\" \"b\" \"a\" \"i\" \"h\" \"i\" \"e\" \"h\" \"d\"\n[20] \"a\" \"i\" \"g\" \"a\" \"g\" \"h\" \"h\" \"e\" \"g\" \"a\" \"g\" \"c\" \"i\" \"j\" \"d\" \"e\" \"f\" \"b\" \"b\"\n[39] \"i\" \"d\" \"d\" \"e\" \"d\" \"e\" \"g\" \"g\" \"j\" \"g\" \"a\" \"g\" \"j\" \"j\" \"d\" \"c\" \"b\" \"j\" \"h\"\n[58] \"f\" \"e\" \"a\""
},
{
"code": null,
"e": 2666,
"s": 2646,
"text": "dim(M3)<-c(10,6)\nM3"
},
{
"code": null,
"e": 3058,
"s": 2666,
"text": " [,1] [,2] [,3] [,4] [,5] [,6]\n[1,] \"f\" \"h\" \"a\" \"f\" \"d\" \"c\" \n[2,] \"e\" \"h\" \"g\" \"b\" \"i\" \"e\"\n[3,] \"b\" \"j\" \"h\" \"h\" \"h\" \"g\"\n[4,] \"i\" \"f\" \"d\" \"i\" \"c\" \"d\"\n[5,] \"j\" \"f\" \"j\" \"b\" \"j\" \"d\" \n[6,] \"a\" \"d\" \"c\" \"j\" \"e\" \"j\" \n[7,] \"b\" \"i\" \"j\" \"i\" \"e\" \"c\" \n[8,] \"c\" \"i\" \"d\" \"i\" \"b\" \"a\" \n[9,] \"g\" \"f\" \"a\" \"d\" \"d\" \"j\" \n[10,] \"d\" \"f\" \"e\" \"b\" \"f\" \"i\""
},
{
"code": null,
"e": 3081,
"s": 3058,
"text": "is.matrix(M3) [1] TRUE"
},
{
"code": null,
"e": 3092,
"s": 3081,
"text": " Live Demo"
},
{
"code": null,
"e": 3137,
"s": 3092,
"text": "M4<-sample(LETTERS[1:26],100,replace=TRUE)M4"
},
{
"code": null,
"e": 3566,
"s": 3137,
"text": "[1] \"J\" \"R\" \"D\" \"B\" \"Z\" \"F\" \"V\" \"M\" \"U\" \"M\" \"X\" \"A\" \"L\" \"L\" \"N\" \"G\" \"O\" \"H\"\n[19] \"J\" \"C\" \"Y\" \"L\" \"I\" \"N\" \"Y\" \"D\" \"E\" \"N\" \"U\" \"Q\" \"Y\" \"X\" \"J\" \"O\" \"T\" \"Q\"\n[37] \"X\" \"H\" \"V\" \"Z\" \"I\" \"P\" \"J\" \"Q\" \"Z\" \"G\" \"J\" \"V\" \"U\" \"P\" \"X\" \"P\" \"K\" \"O\"\n[55] \"Y\" \"L\" \"E\" \"B\" \"B\" \"P\" \"Y\" \"D\" \"M\" \"S\" \"U\" \"K\" \"D\" \"N\" \"B\" \"B\" \"P\" \"V\"\n[73] \"O\" \"Z\" \"L\" \"L\" \"G\" \"J\" \"Y\" \"Z\" \"K\" \"C\" \"Z\" \"Q\" \"Y\" \"C\" \"G\" \"H\" \"F\" \"J\"\n[91] \"Q\" \"W\" \"Q\" \"H\" \"H\" \"Q\" \"O\" \"M\" \"I\" \"S\""
},
{
"code": null,
"e": 3587,
"s": 3566,
"text": "dim(M4)<-c(10,10)\nM4"
},
{
"code": null,
"e": 4201,
"s": 3587,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] \"I\" \"K\" \"A\" \"X\" \"X\" \"N\" \"Y\" \"U\" \"U\" \"P\"\n[2,] \"Y\" \"R\" \"Q\" \"Y\" \"V\" \"M\" \"T\" \"L\" \"X\" \"X\" \n[3,] \"F\" \"H\" \"E\" \"N\" \"V\" \"G\" \"A\" \"G\" \"Y\" \"P\" \n[4,] \"C\" \"D\" \"K\" \"E\" \"P\" \"M\" \"S\" \"B\" \"K\" \"Z\" \n[5,] \"W\" \"C\" \"G\" \"H\" \"J\" \"E\" \"U\" \"G\" \"C\" \"Q\" \n[6,] \"D\" \"T\" \"J\" \"V\" \"D\" \"A\" \"L\" \"S\" \"I\" \"P\" \n[7,] \"N\" \"T\" \"W\" \"T\" \"J\" \"T\" \"R\" \"E\" \"S\" \"S\" \n[8,] \"W\" \"N\" \"P\" \"O\" \"B\" \"E\" \"M\" \"W\" \"G\" \"P\" \n[9,] \"I\" \"I\" \"N\" \"M\" \"I\" \"L\" \"W\" \"E\" \"D\" \"W\" \n[10,] \"E\" \"Y\" \"B\" \"T\" \"M\" \"C\" \"F\" \"P\" \"R\" \"L\""
},
{
"code": null,
"e": 4224,
"s": 4201,
"text": "is.matrix(M4) [1] TRUE"
},
{
"code": null,
"e": 4235,
"s": 4224,
"text": " Live Demo"
},
{
"code": null,
"e": 4304,
"s": 4235,
"text": "M5<-sample(c(\"India\",\"Russia\",\"China\",\"Denmark\"),60,replace=TRUE)\nM5"
},
{
"code": null,
"e": 4868,
"s": 4304,
"text": "[1] \"China\" \"Denmark\" \"China\" \"China\" \"Russia\" \"Russia\" \"Denmark\"\n[8] \"China\" \"Russia\" \"Russia\" \"Denmark\" \"India\" \"China\" \"Russia\"\n[15] \"India\" \"China\" \"China\" \"China\" \"Russia\" \"India\" \"India\"\n[22] \"Denmark\" \"Russia\" \"Russia\" \"Russia\" \"China\" \"China\" \"India\"\n[29] \"Russia\" \"Denmark\" \"Russia\" \"Russia\" \"China\" \"India\" \"Russia\"\n[36] \"Russia\" \"Russia\" \"India\" \"China\" \"Denmark\" \"Russia\" \"China\"\n[43] \"India\" \"Russia\" \"China\" \"China\" \"China\" \"Russia\" \"India\"\n[50] \"Denmark\" \"India\" \"China\" \"India\" \"Denmark\" \"Denmark\" \"Denmark\"\n[57] \"Denmark\" \"India\" \"Russia\" \"China\""
},
{
"code": null,
"e": 4888,
"s": 4868,
"text": "dim(M5)<-c(10,6)\nM5"
},
{
"code": null,
"e": 5599,
"s": 4888,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] \n[1,] \"India\" \"China\" \"India\" \"Russia\" \"Denmark\" \"Denmark\" \n[2,] \"Russia\" \"Denmark\" \"Russia\" \"Russia\" \"Denmark\" \"India\" \n[3,] \"China\" \"India\" \"China\" \"China\" \"Denmark\" \"Denmark\"\n [4,] \"Denmark\" \"India\" \"Russia\" \"India\" \"Denmark\" \"China\" \n[5,] \"Russia\" \"China\" \"Russia\" \"China\" \"Russia\" \"China\" \n[6,] \"Denmark\" \"China\" \"Russia\" \"Denmark\" \"Denmark\" \"China\"\n [7,] \"Denmark\" \"Russia\" \"China\" \"India\" \"China\" \"China\" \n[8,] \"Denmark\" \"China\" \"Denmark\" \"India\" \"India\" \"Denmark\" \n[9,] \"Denmark\" \"India\" \"Denmark\" \"India\" \"Russia\" \"China\" \n[10,] \"Russia\" \"Denmark\" \"China\" \"India\" \"Denmark\" \"India\""
},
{
"code": null,
"e": 5622,
"s": 5599,
"text": "is.matrix(M5) [1] TRUE"
},
{
"code": null,
"e": 5633,
"s": 5622,
"text": " Live Demo"
},
{
"code": null,
"e": 5689,
"s": 5633,
"text": "M6<-sample(c(\"Cold\",\"Winter\",\"Hot\"),40,replace=TRUE)\nM6"
},
{
"code": null,
"e": 6001,
"s": 5689,
"text": "[1] \"Hot\" \"Cold\" \"Hot\" \"Winter\" \"Winter\" \"Hot\" \"Cold\" \"Winter\"\n[9] \"Hot\" \"Winter\" \"Cold\" \"Winter\" \"Hot\" \"Winter\" \"Hot\" \"Winter\"\n[17] \"Hot\" \"Winter\" \"Cold\" \"Cold\" \"Winter\" \"Cold\" \"Cold\" \"Hot\"\n[25] \"Hot\" \"Hot\" \"Hot\" \"Hot\" \"Cold\" \"Winter\" \"Winter\" \"Cold\"\n[33] \"Cold\" \"Winter\" \"Winter\" \"Hot\" \"Hot\" \"Hot\" \"Hot\" \"Hot\""
},
{
"code": null,
"e": 6021,
"s": 6001,
"text": "dim(M6)<-c(10,4)\nM6"
},
{
"code": null,
"e": 6458,
"s": 6021,
"text": " [,1] [,2] [,3] [,4] \n[1,] \"Hot\" \"Hot\" \"Cold\" \"Winter\"\n[2,] \"Hot\" \"Hot\" \"Winter\" \"Winter\"\n[3,] \"Winter\" \"Cold\" \"Winter\" \"Cold\" \n[4,] \"Cold\" \"Cold\" \"Hot\" \"Winter\"\n[5,] \"Hot\" \"Cold\" \"Cold\" \"Hot\" \n[6,] \"Cold\" \"Winter\" \"Hot\" \"Cold\" \n[7,] \"Winter\" \"Winter\" \"Cold\" \"Hot\" \n[8,] \"Cold\" \"Cold\" \"Cold\" \"Hot\"\n[9,] \"Cold\" \"Cold\" \"Winter\" \"Cold\" \n[10,] \"Cold\" \"Winter\" \"Winter\" \"Hot\""
},
{
"code": null,
"e": 6481,
"s": 6458,
"text": "is.matrix(M6) [1] TRUE"
}
] |
Central Limit Theorem Explained with Python Code | by Sujeewa Kumaratunga PhD | Towards Data Science
|
A simulation to explain Central Limit Theorem: even when a sample is not normally distributed, if you draw multiple samples and take each of their averages, these averages will represent a normal distribution.
All roads lead to Rome! Wait, no! All roads lead to Shibuya! Wait, no! All sample means lead to the population mean.
Central Limit Theorem suggests that if you randomly draw a sample of your customers, say 1000 customers, this sample itself might not be normally distributed. But if you now repeat the experiment say 100 times, then the 100 means of those 100 samples (of 1000 customers) will make up a normal distribution.
This line is important for us: ‘this sample itself might not be normally distributed’. Why? Because most things in life are not normally distributed; not grades, not wealth, not food, certainly not how much our customers pay in our shop. But everything in life has a Poisson distribution; better yet, everything in life can be explained by a Dirichlet distribution, but let’s stick with a Poisson for simplicity (Poisson is a simplified case of Dirichlet, in fact).
But actually in an e-commerce shop, most of our customers are non-buying customers. So the distribution actually looks like an exponential, and since a Poisson can be derived from an exponential, let’s make some exponential distributions to reflect our customers’ purchases.
Let us assume our customer base has an average order value of $170, so we will create exponential distributions with this average. We will attempt to get this value by looking at some sample averages.
Here, I draw a sample of 1000 customers. Then repeat this 4 times. I get the following four distributions (To get graphs similar to this, use the code at the end with repeat_sample_draws_exponential(4, 1000, 170, True) ):
And here is each of those 4 averages plotted (To get graphs similar to this, use the code at the end with repeat_sample_draws_exponential(4, 1000, 170, True)):
The mean of the above 4 sample-means is $165.48The standard deviation of the above 4 sample-means is $5.36
So if you stopped your experiments here, at four samples, you will report that your customer base has an average order value of $166 with 68% (1 standard deviation encompasses 68%) of your customers purchasing between $161 and $171 (from $166+/-$5). And that would be a wrong conclusion because we made all these simulations from the original assumption that the population mean is $170!
What happens if we repeat this experiment 100 times? i.e., Draw 100 samples of 1000 customers?
Use the code at the end with:repeat_sample_draws_exponential(100, 1000, 170, True)
We will get 100 exponential distributions like so (To get graphs similar to this, use the code at the end with repeat_sample_draws_exponential(100, 1000, 170, True) ):
And the distribution of the 100 averages now starts looking like a normal distribution (To get graphs similar to this, use the code at the end with repeat_sample_draws_exponential(100, 1000, 170, True) ):
The mean of the above 100 sample-means is $169.55The standard deviation of the above 100 sample-means is $5.18
So now you would conclude that your customer base has an average spending of $170 (yey! this was our very first assumption actually!) with 68% of our customers buying between $165 and $175.
Notice how the standard deviation did not change: it was $5 when we drew 4 samples and it was $5 when we drew 100 samples. You could run the code below for 10000 samples and see that the standard deviation would not change from $5. Why is this?
This brings us to the often overlooked second part of the Central Limit Theorem: the standard deviation of the sample-means is equal to the standard deviation of the population divided by the square-root of the sample size.
Our population is an exponential distribution of mean $170. An exponential has the special property that its standard deviation equals its mean, so the standard deviation of the population mean is $170. So then in this case we would expect the standard deviation of the sample means to be 170/sqrt(1000) = 5.4
And this is exactly what we get, a standard deviation of the sample-means that is around $5. No matter how many times we repeat the sampling, the standard deviation will not change, since it only depends on the sample size (it also depends on the population mean, but that remains a constant for a given population).
So that is Central Limit Theorem. The more samples you draw, the better you get at making the correct prediction of the population mean. We can not possibly test/survey all our customers (or all of our population), so the next best thing we can do is to draw several samples of a smaller number and get the average of those averages. The key here is to draw as many samples as possible. When we do that we have:
And the standard deviation of the sample mean distribution will change if you increase your sample size (the sample size is not the number of samples; in our example the sample size is 1000, the number of samples is 100):
In a later post I will describe why this is an important concept in A/B testing.
Code to reproduce this :
import numpy as npimport matplotlib.pyplot as pltdef repeat_sample_draws_exponential(n, samp_size, mu, show_all=False): means = [] samples = [] for ii in range(0, n): samples.append(np.random.exponential(mu, samp_size)) means.append(np.mean(samples[ii])) if show_all: pltdim = np.math.ceil(np.math.sqrt(n)) fig, axs = plt.subplots(pltdim, pltdim, figsize=(8, 8), gridspec_kw={'hspace': 0.2}, sharex=True, sharey=True) fig.suptitle('Individual Samples\' Order Value Distribution') fig.text(0.5, 0.04, 'Order Values ($)', ha='center') fig.text(0.04, 0.5, 'Number of Customers', ha='center', rotation='vertical') axs = axs.flatten() for ii in range(0, n): plt.sca(axs[ii]) plt.gca().hist(samples[ii], bins=int(50), histtype='step', label='$mean = {0:.2f}$'.format(np.mean(samples[ii])), range=[0, 2 * mu]) if n < 10: plt.gca().set_title('Sample #{0} : average={1:.2f}'.format(ii, np.mean(samples[ii]))) for item in ([axs[ii].title, axs[ii].xaxis.label, axs[ii].yaxis.label] + axs[ii].get_xticklabels() + axs[ii].get_yticklabels()): item.set_fontsize(8) plt.savefig('expdist_{0}_mu_{1}_sample_{2}_sampsize'.format(mu, n, samp_size)) plt.clf() plt.hist(means, bins=int(10), histtype='step') plt.title('Overall Average of {} Samples\' Average Order Value'.format(n)) plt.xlabel('Average of Individual Sample\'s Order Value ($)') plt.savefig('average_of_expdist_{0}_mu_{1}_sample_{2}_sampsize'.format(mu, n, samp_size)) print('mean of the samples is {0:.2f}'.format(np.mean(means))) print('standard deviation of the samples is {0:.2f}'.format(np.std(means)))repeat_sample_draws_exponential(100, 1000, 170, True)
|
[
{
"code": null,
"e": 382,
"s": 172,
"text": "A simulation to explain Central Limit Theorem: even when a sample is not normally distributed, if you draw multiple samples and take each of their averages, these averages will represent a normal distribution."
},
{
"code": null,
"e": 499,
"s": 382,
"text": "All roads lead to Rome! Wait, no! All roads lead to Shibuya! Wait, no! All sample means lead to the population mean."
},
{
"code": null,
"e": 806,
"s": 499,
"text": "Central Limit Theorem suggests that if you randomly draw a sample of your customers, say 1000 customers, this sample itself might not be normally distributed. But if you now repeat the experiment say 100 times, then the 100 means of those 100 samples (of 1000 customers) will make up a normal distribution."
},
{
"code": null,
"e": 1272,
"s": 806,
"text": "This line is important for us: ‘this sample itself might not be normally distributed’. Why? Because most things in life are not normally distributed; not grades, not wealth, not food, certainly not how much our customers pay in our shop. But everything in life has a Poisson distribution; better yet, everything in life can be explained by a Dirichlet distribution, but let’s stick with a Poisson for simplicity (Poisson is a simplified case of Dirichlet, in fact)."
},
{
"code": null,
"e": 1547,
"s": 1272,
"text": "But actually in an e-commerce shop, most of our customers are non-buying customers. So the distribution actually looks like an exponential, and since a Poisson can be derived from an exponential, let’s make some exponential distributions to reflect our customers’ purchases."
},
{
"code": null,
"e": 1748,
"s": 1547,
"text": "Let us assume our customer base has an average order value of $170, so we will create exponential distributions with this average. We will attempt to get this value by looking at some sample averages."
},
{
"code": null,
"e": 1970,
"s": 1748,
"text": "Here, I draw a sample of 1000 customers. Then repeat this 4 times. I get the following four distributions (To get graphs similar to this, use the code at the end with repeat_sample_draws_exponential(4, 1000, 170, True) ):"
},
{
"code": null,
"e": 2130,
"s": 1970,
"text": "And here is each of those 4 averages plotted (To get graphs similar to this, use the code at the end with repeat_sample_draws_exponential(4, 1000, 170, True)):"
},
{
"code": null,
"e": 2237,
"s": 2130,
"text": "The mean of the above 4 sample-means is $165.48The standard deviation of the above 4 sample-means is $5.36"
},
{
"code": null,
"e": 2625,
"s": 2237,
"text": "So if you stopped your experiments here, at four samples, you will report that your customer base has an average order value of $166 with 68% (1 standard deviation encompasses 68%) of your customers purchasing between $161 and $171 (from $166+/-$5). And that would be a wrong conclusion because we made all these simulations from the original assumption that the population mean is $170!"
},
{
"code": null,
"e": 2720,
"s": 2625,
"text": "What happens if we repeat this experiment 100 times? i.e., Draw 100 samples of 1000 customers?"
},
{
"code": null,
"e": 2803,
"s": 2720,
"text": "Use the code at the end with:repeat_sample_draws_exponential(100, 1000, 170, True)"
},
{
"code": null,
"e": 2971,
"s": 2803,
"text": "We will get 100 exponential distributions like so (To get graphs similar to this, use the code at the end with repeat_sample_draws_exponential(100, 1000, 170, True) ):"
},
{
"code": null,
"e": 3176,
"s": 2971,
"text": "And the distribution of the 100 averages now starts looking like a normal distribution (To get graphs similar to this, use the code at the end with repeat_sample_draws_exponential(100, 1000, 170, True) ):"
},
{
"code": null,
"e": 3287,
"s": 3176,
"text": "The mean of the above 100 sample-means is $169.55The standard deviation of the above 100 sample-means is $5.18"
},
{
"code": null,
"e": 3477,
"s": 3287,
"text": "So now you would conclude that your customer base has an average spending of $170 (yey! this was our very first assumption actually!) with 68% of our customers buying between $165 and $175."
},
{
"code": null,
"e": 3722,
"s": 3477,
"text": "Notice how the standard deviation did not change: it was $5 when we drew 4 samples and it was $5 when we drew 100 samples. You could run the code below for 10000 samples and see that the standard deviation would not change from $5. Why is this?"
},
{
"code": null,
"e": 3946,
"s": 3722,
"text": "This brings us to the often overlooked second part of the Central Limit Theorem: the standard deviation of the sample-means is equal to the standard deviation of the population divided by the square-root of the sample size."
},
{
"code": null,
"e": 4256,
"s": 3946,
"text": "Our population is an exponential distribution of mean $170. An exponential has the special property that its standard deviation equals its mean, so the standard deviation of the population mean is $170. So then in this case we would expect the standard deviation of the sample means to be 170/sqrt(1000) = 5.4"
},
{
"code": null,
"e": 4573,
"s": 4256,
"text": "And this is exactly what we get, a standard deviation of the sample-means that is around $5. No matter how many times we repeat the sampling, the standard deviation will not change, since it only depends on the sample size (it also depends on the population mean, but that remains a constant for a given population)."
},
{
"code": null,
"e": 4985,
"s": 4573,
"text": "So that is Central Limit Theorem. The more samples you draw, the better you get at making the correct prediction of the population mean. We can not possibly test/survey all our customers (or all of our population), so the next best thing we can do is to draw several samples of a smaller number and get the average of those averages. The key here is to draw as many samples as possible. When we do that we have:"
},
{
"code": null,
"e": 5207,
"s": 4985,
"text": "And the standard deviation of the sample mean distribution will change if you increase your sample size (the sample size is not the number of samples; in our example the sample size is 1000, the number of samples is 100):"
},
{
"code": null,
"e": 5288,
"s": 5207,
"text": "In a later post I will describe why this is an important concept in A/B testing."
},
{
"code": null,
"e": 5313,
"s": 5288,
"text": "Code to reproduce this :"
}
] |
Change/add only one character and print '*' exactly 20 times - GeeksforGeeks
|
20 Apr, 2022
In the below code, change/add only one character and print ‘*’ exactly 20 times.
int main()
{
int i, n = 20;
for (i = 0; i < n; i--)
printf("*");
getchar();
return 0;
}
Solutions:1. Replace i by n in for loop’s third expression
C++
C
Java
Python3
C#
Javascript
#include <iostream>using namespace std;int main(){ int i, n = 20; for (i = 0; i < n; n--) cout << "*"; getchar(); return 0;}
#include <stdio.h>int main(){ int i, n = 20; for (i = 0; i < n; n--) printf("*"); getchar(); return 0;}
// Java codeclass GfG {public static void main(String[] args){ int i, n = 20; for (i = 0; i < n; n--) System.out.print("*");}}
# Python3 program to implement # the above approachif __name__ == '__main__': n = 20; for i in range(0, n): print("*"); n -= 1; # This code is contributed by gauravrajput1
// C# codeusing System;class GfG{ public static void Main() { int i, n = 20; for (i = 0; i < n; n--) Console.Write("*"); }} // This code is contributed by SoumikMondal
<script> // Javascript codevar i, n = 20;for(i = 0; i < n; n--) document.write("*"); // This code is contributed by Ankita Saini </script>
2. Put ‘-‘ before i in for loop’s second expression
C++
C
Java
Python3
C#
Javascript
#include<bits/stdc++.h>using namespace std; int main(){ int i, n = 20; for (i = 0; -i < n; i--) cout<<"*"; return 0;} // This code is contributed by rutvik_56.
#include <stdio.h>int main(){ int i, n = 20; for (i = 0; -i < n; i--) printf("*"); getchar(); return 0;}
// Java codeimport java.util.*;public class GFG{ public static void main(String[] args) { int i, n = 20; for (i = 0; -i < n; i--) System.out.print("*"); }} // This code is contributed by divyesh072019.
# Python3 program to implement # the above approachif __name__ == '__main__': n = 20 for i in range(0,n): print("*", end="") # This code is contributed by shivanisinghss2110
// C# codeusing System;class GfG{ public static void Main() { int i, n = 20; for (i = 0; -i < n; i--) Console.Write("*"); }} // This code is contributed by divyeshrabadiya07.
<script> let i, n = 20;for (i = 0; -i < n; i--) document.write("*"); // This code is contributed by patel2127</script>
3. Replace < by + in for loop’s second expression
C++
C
Python3
Javascript
#include <iostream>using namespace std; int main(){ int i, n = 20; for(i = 0; i + n; i--) cout << "*"; return 0;} // This code is contributed by shivani
#include <stdio.h>int main(){ int i, n = 20; for (i = 0; i + n; i--) printf("*"); getchar(); return 0;}
i,n = 0,20 while(i+n): print("*",end="") i -= 1 # This code is contributed by shinjanpatra
<script> let i, n = 20; for(i = 0; i + n; i--) document.write("*"); // This code is contributed by unknown2108</script>
Let’s extend the problem little.Change/add only one character and print ‘*’ exactly 21 times.Solution: Put negation operator before i in for loop’s second expression.Explanation: Negation operator converts the number into its one’s complement.
No. One's complement
0 (00000..00) -1 (1111..11)
-1 (11..1111) 0 (00..0000)
-2 (11..1110) 1 (00..0001)
-3 (11..1101) 2 (00..0010)
...............................................
-20 (11..01100) 19 (00..10011)
C++
C
Java
C#
Javascript
// C++ program for the above approach#include <iostream>using namespace std; int main(){ int i, n = 20; for (i = 0; ~i < n; i--) printf("*"); getchar(); return 0;} // This code is contributed by shivanisinghss2110
#include <stdio.h>int main(){ int i, n = 20; for (i = 0; ~i < n; i--) printf("*"); getchar(); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ public static void main(String[] args){ int i, n = 20; for(i = 0; ~i < n; i--) System.out.print( "*" );}} // This code is contributed by shivani
// C# program for the above approachusing System; class GFG{ public static void Main(String[] args){ int i, n = 20; for(i = 0; ~i < n; i--) Console.Write( "*" );}} // This code is contributed by shivanisinghss2110
<script> // JavaScript program for the above approach{ var i, n = 20; for(i = 0; ~i < n; i--) document.write("*");} // This code is contributed by shivanisinghss2110 </script>
Please comment if you find more solutions to the above problems.
prerna saini
SoumikMondal
SHUBHAMSINGH10
GauravRajput1
divyeshrabadiya07
divyesh072019
rutvik_56
shivanisinghss2110
ankita_saini
patel2127
unknown2108
khushboogoyal499
shinjanpatra
c-puzzle
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
rand() and srand() in C/C++
Substring in C++
Command line arguments in C/C++
fork() in C
Function Pointer in C
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
|
[
{
"code": null,
"e": 25072,
"s": 25044,
"text": "\n20 Apr, 2022"
},
{
"code": null,
"e": 25154,
"s": 25072,
"text": "In the below code, change/add only one character and print ‘*’ exactly 20 times. "
},
{
"code": null,
"e": 25279,
"s": 25154,
"text": "int main()\n{\n int i, n = 20;\n for (i = 0; i < n; i--)\n printf(\"*\"); \n getchar();\n return 0;\n}"
},
{
"code": null,
"e": 25340,
"s": 25279,
"text": "Solutions:1. Replace i by n in for loop’s third expression "
},
{
"code": null,
"e": 25344,
"s": 25340,
"text": "C++"
},
{
"code": null,
"e": 25346,
"s": 25344,
"text": "C"
},
{
"code": null,
"e": 25351,
"s": 25346,
"text": "Java"
},
{
"code": null,
"e": 25359,
"s": 25351,
"text": "Python3"
},
{
"code": null,
"e": 25362,
"s": 25359,
"text": "C#"
},
{
"code": null,
"e": 25373,
"s": 25362,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std;int main(){ int i, n = 20; for (i = 0; i < n; n--) cout << \"*\"; getchar(); return 0;}",
"e": 25517,
"s": 25373,
"text": null
},
{
"code": "#include <stdio.h>int main(){ int i, n = 20; for (i = 0; i < n; n--) printf(\"*\"); getchar(); return 0;}",
"e": 25643,
"s": 25517,
"text": null
},
{
"code": "// Java codeclass GfG {public static void main(String[] args){ int i, n = 20; for (i = 0; i < n; n--) System.out.print(\"*\");}}",
"e": 25783,
"s": 25643,
"text": null
},
{
"code": "# Python3 program to implement # the above approachif __name__ == '__main__': n = 20; for i in range(0, n): print(\"*\"); n -= 1; # This code is contributed by gauravrajput1",
"e": 25960,
"s": 25783,
"text": null
},
{
"code": "// C# codeusing System;class GfG{ public static void Main() { int i, n = 20; for (i = 0; i < n; n--) Console.Write(\"*\"); }} // This code is contributed by SoumikMondal",
"e": 26162,
"s": 25960,
"text": null
},
{
"code": "<script> // Javascript codevar i, n = 20;for(i = 0; i < n; n--) document.write(\"*\"); // This code is contributed by Ankita Saini </script>",
"e": 26308,
"s": 26162,
"text": null
},
{
"code": null,
"e": 26361,
"s": 26308,
"text": "2. Put ‘-‘ before i in for loop’s second expression "
},
{
"code": null,
"e": 26365,
"s": 26361,
"text": "C++"
},
{
"code": null,
"e": 26367,
"s": 26365,
"text": "C"
},
{
"code": null,
"e": 26372,
"s": 26367,
"text": "Java"
},
{
"code": null,
"e": 26380,
"s": 26372,
"text": "Python3"
},
{
"code": null,
"e": 26383,
"s": 26380,
"text": "C#"
},
{
"code": null,
"e": 26394,
"s": 26383,
"text": "Javascript"
},
{
"code": "#include<bits/stdc++.h>using namespace std; int main(){ int i, n = 20; for (i = 0; -i < n; i--) cout<<\"*\"; return 0;} // This code is contributed by rutvik_56.",
"e": 26586,
"s": 26394,
"text": null
},
{
"code": "#include <stdio.h>int main(){ int i, n = 20; for (i = 0; -i < n; i--) printf(\"*\"); getchar(); return 0;}",
"e": 26723,
"s": 26586,
"text": null
},
{
"code": "// Java codeimport java.util.*;public class GFG{ public static void main(String[] args) { int i, n = 20; for (i = 0; -i < n; i--) System.out.print(\"*\"); }} // This code is contributed by divyesh072019.",
"e": 26939,
"s": 26723,
"text": null
},
{
"code": "# Python3 program to implement # the above approachif __name__ == '__main__': n = 20 for i in range(0,n): print(\"*\", end=\"\") # This code is contributed by shivanisinghss2110",
"e": 27118,
"s": 26939,
"text": null
},
{
"code": "// C# codeusing System;class GfG{ public static void Main() { int i, n = 20; for (i = 0; -i < n; i--) Console.Write(\"*\"); }} // This code is contributed by divyeshrabadiya07.",
"e": 27327,
"s": 27118,
"text": null
},
{
"code": "<script> let i, n = 20;for (i = 0; -i < n; i--) document.write(\"*\"); // This code is contributed by patel2127</script>",
"e": 27451,
"s": 27327,
"text": null
},
{
"code": null,
"e": 27503,
"s": 27451,
"text": "3. Replace < by + in for loop’s second expression "
},
{
"code": null,
"e": 27507,
"s": 27503,
"text": "C++"
},
{
"code": null,
"e": 27509,
"s": 27507,
"text": "C"
},
{
"code": null,
"e": 27517,
"s": 27509,
"text": "Python3"
},
{
"code": null,
"e": 27528,
"s": 27517,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std; int main(){ int i, n = 20; for(i = 0; i + n; i--) cout << \"*\"; return 0;} // This code is contributed by shivani",
"e": 27700,
"s": 27528,
"text": null
},
{
"code": "#include <stdio.h>int main(){ int i, n = 20; for (i = 0; i + n; i--) printf(\"*\"); getchar(); return 0;}",
"e": 27822,
"s": 27700,
"text": null
},
{
"code": "i,n = 0,20 while(i+n): print(\"*\",end=\"\") i -= 1 # This code is contributed by shinjanpatra",
"e": 27917,
"s": 27822,
"text": null
},
{
"code": "<script> let i, n = 20; for(i = 0; i + n; i--) document.write(\"*\"); // This code is contributed by unknown2108</script>",
"e": 28044,
"s": 27917,
"text": null
},
{
"code": null,
"e": 28290,
"s": 28044,
"text": "Let’s extend the problem little.Change/add only one character and print ‘*’ exactly 21 times.Solution: Put negation operator before i in for loop’s second expression.Explanation: Negation operator converts the number into its one’s complement. "
},
{
"code": null,
"e": 28654,
"s": 28290,
"text": " No. One's complement\n 0 (00000..00) -1 (1111..11) \n-1 (11..1111) 0 (00..0000) \n-2 (11..1110) 1 (00..0001) \n-3 (11..1101) 2 (00..0010)\n...............................................\n-20 (11..01100) 19 (00..10011)"
},
{
"code": null,
"e": 28658,
"s": 28654,
"text": "C++"
},
{
"code": null,
"e": 28660,
"s": 28658,
"text": "C"
},
{
"code": null,
"e": 28665,
"s": 28660,
"text": "Java"
},
{
"code": null,
"e": 28668,
"s": 28665,
"text": "C#"
},
{
"code": null,
"e": 28679,
"s": 28668,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <iostream>using namespace std; int main(){ int i, n = 20; for (i = 0; ~i < n; i--) printf(\"*\"); getchar(); return 0;} // This code is contributed by shivanisinghss2110",
"e": 28912,
"s": 28679,
"text": null
},
{
"code": "#include <stdio.h>int main(){ int i, n = 20; for (i = 0; ~i < n; i--) printf(\"*\"); getchar(); return 0;}",
"e": 29036,
"s": 28912,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ public static void main(String[] args){ int i, n = 20; for(i = 0; ~i < n; i--) System.out.print( \"*\" );}} // This code is contributed by shivani",
"e": 29263,
"s": 29036,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ public static void Main(String[] args){ int i, n = 20; for(i = 0; ~i < n; i--) Console.Write( \"*\" );}} // This code is contributed by shivanisinghss2110",
"e": 29490,
"s": 29263,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach{ var i, n = 20; for(i = 0; ~i < n; i--) document.write(\"*\");} // This code is contributed by shivanisinghss2110 </script>",
"e": 29679,
"s": 29490,
"text": null
},
{
"code": null,
"e": 29744,
"s": 29679,
"text": "Please comment if you find more solutions to the above problems."
},
{
"code": null,
"e": 29757,
"s": 29744,
"text": "prerna saini"
},
{
"code": null,
"e": 29770,
"s": 29757,
"text": "SoumikMondal"
},
{
"code": null,
"e": 29785,
"s": 29770,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 29799,
"s": 29785,
"text": "GauravRajput1"
},
{
"code": null,
"e": 29817,
"s": 29799,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 29831,
"s": 29817,
"text": "divyesh072019"
},
{
"code": null,
"e": 29841,
"s": 29831,
"text": "rutvik_56"
},
{
"code": null,
"e": 29860,
"s": 29841,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 29873,
"s": 29860,
"text": "ankita_saini"
},
{
"code": null,
"e": 29883,
"s": 29873,
"text": "patel2127"
},
{
"code": null,
"e": 29895,
"s": 29883,
"text": "unknown2108"
},
{
"code": null,
"e": 29912,
"s": 29895,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 29925,
"s": 29912,
"text": "shinjanpatra"
},
{
"code": null,
"e": 29934,
"s": 29925,
"text": "c-puzzle"
},
{
"code": null,
"e": 29945,
"s": 29934,
"text": "C Language"
},
{
"code": null,
"e": 29949,
"s": 29945,
"text": "C++"
},
{
"code": null,
"e": 29953,
"s": 29949,
"text": "CPP"
},
{
"code": null,
"e": 30051,
"s": 29953,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30079,
"s": 30051,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 30096,
"s": 30079,
"text": "Substring in C++"
},
{
"code": null,
"e": 30128,
"s": 30096,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 30140,
"s": 30128,
"text": "fork() in C"
},
{
"code": null,
"e": 30162,
"s": 30140,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 30180,
"s": 30162,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 30226,
"s": 30180,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 30245,
"s": 30226,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 30288,
"s": 30245,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
Python String rfind() Method
|
Python string method rfind() returns the last index where the substring str is found, or -1 if no such index exists, optionally restricting the search to string[beg:end].
Following is the syntax for rfind() method −
obj.rfind(str, beg=0 end=len(string))
str − This specifies the string to be searched.
str − This specifies the string to be searched.
beg − This is the starting index, by default its 0.
beg − This is the starting index, by default its 0.
end − This is the ending index, by default its equal to the length of the string.
end − This is the ending index, by default its equal to the length of the string.
This method returns last index if found and -1 otherwise.
The following example shows the usage of rfind() method.
#!/usr/bin/python
str1 = "this is really a string example....wow!!!";
str2 = "is";
print str1.rfind(str2)
print str1.rfind(str2, 0, 10)
print str1.rfind(str2, 10, 0)
print str1.find(str2)
print str1.find(str2, 0, 10)
print str1.find(str2, 10, 0)
When we run above program, it produces following result −
5
5
-1
2
2
-1
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2416,
"s": 2244,
"text": "Python string method rfind() returns the last index where the substring str is found, or -1 if no such index exists, optionally restricting the search to string[beg:end]."
},
{
"code": null,
"e": 2461,
"s": 2416,
"text": "Following is the syntax for rfind() method −"
},
{
"code": null,
"e": 2500,
"s": 2461,
"text": "obj.rfind(str, beg=0 end=len(string))\n"
},
{
"code": null,
"e": 2548,
"s": 2500,
"text": "str − This specifies the string to be searched."
},
{
"code": null,
"e": 2596,
"s": 2548,
"text": "str − This specifies the string to be searched."
},
{
"code": null,
"e": 2648,
"s": 2596,
"text": "beg − This is the starting index, by default its 0."
},
{
"code": null,
"e": 2700,
"s": 2648,
"text": "beg − This is the starting index, by default its 0."
},
{
"code": null,
"e": 2782,
"s": 2700,
"text": "end − This is the ending index, by default its equal to the length of the string."
},
{
"code": null,
"e": 2864,
"s": 2782,
"text": "end − This is the ending index, by default its equal to the length of the string."
},
{
"code": null,
"e": 2922,
"s": 2864,
"text": "This method returns last index if found and -1 otherwise."
},
{
"code": null,
"e": 2979,
"s": 2922,
"text": "The following example shows the usage of rfind() method."
},
{
"code": null,
"e": 3228,
"s": 2979,
"text": "#!/usr/bin/python\n\nstr1 = \"this is really a string example....wow!!!\";\nstr2 = \"is\";\n\nprint str1.rfind(str2)\nprint str1.rfind(str2, 0, 10)\nprint str1.rfind(str2, 10, 0)\n\nprint str1.find(str2)\nprint str1.find(str2, 0, 10)\nprint str1.find(str2, 10, 0)"
},
{
"code": null,
"e": 3286,
"s": 3228,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 3301,
"s": 3286,
"text": "5\n5\n-1\n2\n2\n-1\n"
},
{
"code": null,
"e": 3338,
"s": 3301,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3354,
"s": 3338,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3387,
"s": 3354,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3406,
"s": 3387,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3441,
"s": 3406,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3463,
"s": 3441,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3497,
"s": 3463,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3525,
"s": 3497,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3560,
"s": 3525,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3574,
"s": 3560,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3607,
"s": 3574,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3624,
"s": 3607,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3631,
"s": 3624,
"text": " Print"
},
{
"code": null,
"e": 3642,
"s": 3631,
"text": " Add Notes"
}
] |
Create Directory or Folder with C/C++ Program
|
In this tutorial, we will be discussing a program to create directory or folder with C/C++ program.
To create a new directory we will be using the mkdir() command. Note that the given code will work only for windows compiler.
#include <conio.h>
#include <dir.h>
#include <process.h>
#include <stdio.h>
void main(){
int check;
char* dirname = "tutorialspoint";
clrscr();
check = mkdir(dirname);
//checking if directory is created
if (!check)
printf("Directory created\n");
else {
printf("Unable to create directory\n");
exit(1);
}
getch();
system("dir/p");
getch();
}
Directory created
|
[
{
"code": null,
"e": 1162,
"s": 1062,
"text": "In this tutorial, we will be discussing a program to create directory or folder with C/C++ program."
},
{
"code": null,
"e": 1288,
"s": 1162,
"text": "To create a new directory we will be using the mkdir() command. Note that the given code will work only for windows compiler."
},
{
"code": null,
"e": 1680,
"s": 1288,
"text": "#include <conio.h>\n#include <dir.h>\n#include <process.h>\n#include <stdio.h>\nvoid main(){\n int check;\n char* dirname = \"tutorialspoint\";\n clrscr();\n check = mkdir(dirname);\n //checking if directory is created\n if (!check)\n printf(\"Directory created\\n\");\n else {\n printf(\"Unable to create directory\\n\");\n exit(1);\n }\n getch();\n system(\"dir/p\");\n getch();\n}"
},
{
"code": null,
"e": 1698,
"s": 1680,
"text": "Directory created"
}
] |
Stream Editor - Pattern Range
|
In the previous chapter, we learnt how SED handles an address range. This chapter covers how SED takes care of a pattern range. A pattern range can be a simple text or a complex regular expression. Let us take an example. The following example prints all the books of the author Paulo Coelho.
[jerry]$ sed -n '/Paulo/ p' books.txt
On executing the above code, you get the following result:
3) The Alchemist, Paulo Coelho, 197
5) The Pilgrimage, Paulo Coelho, 288
In the above example, the SED operates on each line and prints only those lines that match the string Paulo.
We can also combine a pattern range with an address range. The following example prints lines starting with the first match of Alchemist until the fifth line.
[jerry]$ sed -n '/Alchemist/, 5 p' books.txt
On executing the above code, you get the following result:
3) The Alchemist, Paulo Coelho, 197
4) The Fellowship of the Ring, J. R. R. Tolkien, 432
5) The Pilgrimage, Paulo Coelho, 288
We can use the Dollar($) character to print all the lines after finding the first occurrence of the pattern. The following example finds the first occurrence of the pattern The and immediately prints the remaining lines from the file
[jerry]$ sed -n '/The/,$ p' books.txt
On executing the above code, you get the following result:
2) The Two Towers, J. R. R. Tolkien, 352
3) The Alchemist, Paulo Coelho, 197
4) The Fellowship of the Ring, J. R. R. Tolkien, 432
5) The Pilgrimage, Paulo Coelho, 288
6) A Game of Thrones, George R. R. Martin, 864
We can also specify more than one pattern ranges using the comma(,) operator. The following example prints all the lines that exist between the patterns Two and Pilgrimage.
[jerry]$ sed -n '/Two/, /Pilgrimage/ p' books.txt
On executing the above code, you get the following result:
2) The Two Towers, J. R. R. Tolkien, 352
3) The Alchemist, Paulo Coelho, 197
4) The Fellowship of the Ring, J. R. R. Tolkien, 432
5) The Pilgrimage, Paulo Coelho, 288
Additionally, we can use the plus(+) operator within a pattern range. The following example finds the first occurrence of the pattern Two and prints the next 4 lines after that.
[jerry]$ sed -n '/Two/, +4 p' books.txt
On executing the above code, you get the following result:
2) The Two Towers, J. R. R. Tolkien, 352
3) The Alchemist, Paulo Coelho, 197
4) The Fellowship of the Ring, J. R. R. Tolkien, 432
5) The Pilgrimage, Paulo Coelho, 288
6) A Game of Thrones, George R. R. Martin, 864
We have supplied here only a few examples to get you acquainted with SED. You can always get to know more by trying a few examples on your own.
53 Lectures
3.5 hours
Senol Atac
14 Lectures
44 mins
Zach Miller
13 Lectures
2 hours
Sandip Bhattacharya
28 Lectures
1 hours
PARTHA MAJUMDAR
16 Lectures
1.5 hours
Taurius Litvinavicius
38 Lectures
2 hours
Davida Shensky
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2116,
"s": 1823,
"text": "In the previous chapter, we learnt how SED handles an address range. This chapter covers how SED takes care of a pattern range. A pattern range can be a simple text or a complex regular expression. Let us take an example. The following example prints all the books of the author Paulo Coelho."
},
{
"code": null,
"e": 2155,
"s": 2116,
"text": "[jerry]$ sed -n '/Paulo/ p' books.txt\n"
},
{
"code": null,
"e": 2214,
"s": 2155,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 2289,
"s": 2214,
"text": "3) The Alchemist, Paulo Coelho, 197 \n5) The Pilgrimage, Paulo Coelho, 288\n"
},
{
"code": null,
"e": 2398,
"s": 2289,
"text": "In the above example, the SED operates on each line and prints only those lines that match the string Paulo."
},
{
"code": null,
"e": 2557,
"s": 2398,
"text": "We can also combine a pattern range with an address range. The following example prints lines starting with the first match of Alchemist until the fifth line."
},
{
"code": null,
"e": 2603,
"s": 2557,
"text": "[jerry]$ sed -n '/Alchemist/, 5 p' books.txt\n"
},
{
"code": null,
"e": 2662,
"s": 2603,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 2791,
"s": 2662,
"text": "3) The Alchemist, Paulo Coelho, 197 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n5) The Pilgrimage, Paulo Coelho, 288\n"
},
{
"code": null,
"e": 3025,
"s": 2791,
"text": "We can use the Dollar($) character to print all the lines after finding the first occurrence of the pattern. The following example finds the first occurrence of the pattern The and immediately prints the remaining lines from the file"
},
{
"code": null,
"e": 3064,
"s": 3025,
"text": "[jerry]$ sed -n '/The/,$ p' books.txt\n"
},
{
"code": null,
"e": 3123,
"s": 3064,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 3342,
"s": 3123,
"text": "2) The Two Towers, J. R. R. Tolkien, 352 \n3) The Alchemist, Paulo Coelho, 197 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432\n5) The Pilgrimage, Paulo Coelho, 288 \n6) A Game of Thrones, George R. R. Martin, 864 \n"
},
{
"code": null,
"e": 3515,
"s": 3342,
"text": "We can also specify more than one pattern ranges using the comma(,) operator. The following example prints all the lines that exist between the patterns Two and Pilgrimage."
},
{
"code": null,
"e": 3567,
"s": 3515,
"text": "[jerry]$ sed -n '/Two/, /Pilgrimage/ p' books.txt \n"
},
{
"code": null,
"e": 3626,
"s": 3567,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 3797,
"s": 3626,
"text": "2) The Two Towers, J. R. R. Tolkien, 352 \n3) The Alchemist, Paulo Coelho, 197 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n5) The Pilgrimage, Paulo Coelho, 288\n"
},
{
"code": null,
"e": 3975,
"s": 3797,
"text": "Additionally, we can use the plus(+) operator within a pattern range. The following example finds the first occurrence of the pattern Two and prints the next 4 lines after that."
},
{
"code": null,
"e": 4016,
"s": 3975,
"text": "[jerry]$ sed -n '/Two/, +4 p' books.txt\n"
},
{
"code": null,
"e": 4075,
"s": 4016,
"text": "On executing the above code, you get the following result:"
},
{
"code": null,
"e": 4295,
"s": 4075,
"text": "2) The Two Towers, J. R. R. Tolkien, 352 \n3) The Alchemist, Paulo Coelho, 197 \n4) The Fellowship of the Ring, J. R. R. Tolkien, 432 \n5) The Pilgrimage, Paulo Coelho, 288 \n6) A Game of Thrones, George R. R. Martin, 864 \n"
},
{
"code": null,
"e": 4439,
"s": 4295,
"text": "We have supplied here only a few examples to get you acquainted with SED. You can always get to know more by trying a few examples on your own."
},
{
"code": null,
"e": 4474,
"s": 4439,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4486,
"s": 4474,
"text": " Senol Atac"
},
{
"code": null,
"e": 4518,
"s": 4486,
"text": "\n 14 Lectures \n 44 mins\n"
},
{
"code": null,
"e": 4531,
"s": 4518,
"text": " Zach Miller"
},
{
"code": null,
"e": 4564,
"s": 4531,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4585,
"s": 4564,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 4618,
"s": 4585,
"text": "\n 28 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4635,
"s": 4618,
"text": " PARTHA MAJUMDAR"
},
{
"code": null,
"e": 4670,
"s": 4635,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4693,
"s": 4670,
"text": " Taurius Litvinavicius"
},
{
"code": null,
"e": 4726,
"s": 4693,
"text": "\n 38 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4742,
"s": 4726,
"text": " Davida Shensky"
},
{
"code": null,
"e": 4749,
"s": 4742,
"text": " Print"
},
{
"code": null,
"e": 4760,
"s": 4749,
"text": " Add Notes"
}
] |
Instance-level Recognition. Introduction, challenges, and recent... | by Kb Pachauri | Towards Data Science
|
In this blog, I will walk through an introduction to instance-level recognition, use cases, challenges, currently available dataset, and state of the art results (recent winner solutions) on these challenges/datasets.
Instance Level Recognition (ILR), is a visual recognition task to recognize a specific instance of an object not just object class.
For example, as shown in the above image, painting is an object class, and “Mona Lisa” by Leonardo Da Vinci is an instance of that painting. Similarly, the Taj Mahal, India is an instance of the object class building.
Landmark Recognition: Recognize landmarks in images.
Landmark Retrieval: Retrieve relevant landmark images from a large-scale database.
Artwork Recognition: Recognize artworks in images.
Product Retrieval: Retrieve relevant product images from a large-scale database.
Large scale: Most of the current state of the art results of recognition tasks are measured on very limited categories e.g. ~1000 image classes in ImageNet, ~80 categories in COCO. But use-cases like landmark retrieval and recognition, has 200K+ classes e.g. in Google Landmark Dataset V2 (GLDv2), 100K+ classes of the product on Amazon.
Long-tailed: Few popular places have more than 1000+ images but many less know places have less than 5 images in GLDv2.
Intra-class variability: Landmarks are mostly spread across a wide region and have very high intra-class variability as shown in the below image.
Noisy Labels: The success of machine learning models depends on high-quality labeled training data, as the presence of labels errors can greatly reduce the model's performance. These noisy labels as shown in the below image, unfortunately, noisy labels are part of a large training set and need additional learning steps.
Google Landmarks Dataset V2 (GLDv2): Google Landmark Dataset v2 is a new benchmark for large-scale, fine-grained instance recognition and image retrieval in the domain of human-made and natural landmarks. The below image shows all the details of the landmark dataset
CVPR 2020 AliProducts Challenge: AliProducts Challenge is a large-scale, noisy, and fine-grained product dataset with ~50K categories with ~3M images. This dataset is proposed as competition for studying commodity image recognition problems encountered by world-leading e-commerce companies. This competition is part of the RetailVision workshop RetailVision CVPR 2020 workshop at CVPR 2020.
Amazon Product Challenge: Amazon product dataset is announced in ILR ECCVW 2020 workshop and will be released by 2021 Q1. Images in the dataset have a domain mismatch due to product catalog images are shot by professional and query images are often shot by mobile phone camera and have bad lighting condition with a cluttered background.
Below I will discuss recent winner solutions for landmark recognition and product recognition.
In the landmark recognition challenge, the task is to predict landmark labels from the image and is conducted every year since 2018. The below image shows the progress in the Global Average Precision of this competition.
An ensemble of 7 global descriptors model (SeResNext101, EfficientNet-B3, ResNet152, Res2Net101). The below image shows the setup for the SeResNext101 backbone and for others also we follow similar architecture. Each backbone network is aggregated using Generalized-Mean (GeM) pooling and followed by linear neck (Linear 512, BatchNorm1D, PReLU), before finally feeding into the arc margin head.
ResNet variants (152 & 101) both rely on identifying shortcut connections that skip one or more layers to tackle the vanishing gradient issue. SeResNeXt is a variant of ResNeXt which is an inception net with a shortcut connection and Se refers to the Squeeze and Excitation module added to ResNeXt. Se network improves channel interdependency by adaptively adjusting the weights of feature maps. EfficientNet is a state of the art network for image classification which relies on Auto Machine Learning to find out the best base network and efficient compound scaling to achieve improved results depending on available compute resources.
Generalized Mean Pooling (GeM) in the neck network computes the generalized mean of each channel in a tensor. If pk → ∞, GeM behaves as max-pooling and pk → 1, it behaves as average pooling. With an increase in pk, the contrast of the pooled feature map increases and focuses on salient features of the image.
PReLU: PReLU is a generalization of leaky ReLU, to solve the dying neuron problem which happens when data is not normalized or network weights are not properly initialized.
Arc margin improves on softmax loss to enforce higher similarity for intra-class variation and diversity for inter-class by distributing learned embedding on hypersphere with a radius of s. Below is the pseudo-code of ArcFace loss on MxNet.
Models are trained at different image scales [448x448, 568x568, 600x600, 512x512] using albumentations.
Each model is trained for 10 epochs with cosine annealing scheduler.
The test set of the 2019 competition which was released with labels is used as validation.
As a post-processing step re-ranking was done to penalize non-landmarks images to improve the GAP metric.
Test: Leaderboard test set.
Train: Candidate images to determine labels and confidence.
Non-Landmark: Images with no landmark from the GLDv2 test set.
Calculate the cosine similarity between the test and train image (A)Calculate the average (top-5 or top-10) cosine similarity between the train and non-landmark images. (B)Calculate Ai,j — BjSum the confidence of the same label and pick the highest.
Calculate the cosine similarity between the test and train image (A)
Calculate the average (top-5 or top-10) cosine similarity between the train and non-landmark images. (B)
Calculate Ai,j — Bj
Sum the confidence of the same label and pick the highest.
The most important point of the above solution is the use of the 2019 competition test set as validation for re-ranking as post-processing after inferencing and led to a top leaderboard score of 0.6598 which is ~1.75x better than the 2019 result.
Backbone networks (EfficientNet-B3, EfficientNet-B4, ResNet50, SeResNext50, SeResNext101) are fine-tune with Destruction and Construction Learning (DCL) and Look into Object (LIO) method. The model averaging is used to ensemble all the fine-tune models, achieving a top-1 error rate of 6.27%.
DCL as shown in the below image enhances fine-grained recognition by learning local discriminative regions and features by shuffling local regions. To prevent the network to learn the noisy patterns, an adversarial counterpart is proposed to reject Region Confusion Mechanism (RCM)-induced patterns that are not relevant. For more details kindly check the paper.
LIO as shown in the below image, models structure using self-supervised learning. Object extent learning helps the backbone network to distinguish between foreground and background. Spatial context learning using a self-supervision strengthen structural information for the backbone network. For more details kindly check the paper.
All images are resized to 256x256 then random crop to 224x224 for training and center crop 224x224 for the test. Train data is augmented using
AutoAugmentation
Cutout
Training
All models are trained with an SGD optimizer with manual learning rate decay.
All backbone networks with basic training achieve a top-1 error rate of 20–25%.All backbone networks are fine-tuned with balanced training, achieving a top-1 error rate of 9–12%. The balanced training set includes all the images from validation as well if the number of images in a category is less than 30.All backbone are further fine-tuned using DCL on higher resolution image (448x448), reducing error rate by 1–2% further.All networks are further fine-tuned using accuracy loss as shown in the below image, which is optimized for the top-1 error rate, reducing error rate by ~0.2–0.5%.
All backbone networks with basic training achieve a top-1 error rate of 20–25%.
All backbone networks are fine-tuned with balanced training, achieving a top-1 error rate of 9–12%. The balanced training set includes all the images from validation as well if the number of images in a category is less than 30.
All backbone are further fine-tuned using DCL on higher resolution image (448x448), reducing error rate by 1–2% further.
All networks are further fine-tuned using accuracy loss as shown in the below image, which is optimized for the top-1 error rate, reducing error rate by ~0.2–0.5%.
def acc_loss(y_true, y_pred): tp = (y_pred, y_true).sum(1) fp = ((1-y_true)*y_pred).sum(1) acc = tp/(tp+fp) return 1 - acc.mean()
Below 11 models are used to calculate final probabilities
Balanced fine-tuned resnet50, seresnext50, seresnext101, efficientnet-b3, efficientnet-b4
DCL fine-tuned resnet50, seresnext50
Accuray loss fine-tunes resnet50, seresnext50, efficientnet-b3
LIO fine-tuned resnet50
Instance-level recognition will unravel the true potential of deep learning technologies for semantic image classification/retrieval for eCommerce, travel, media & entertainment, agriculture, etc. Some of the major building block for an efficient instance-level solution is
Backbone Network Selection (Residual, Squeeze & Excitation, EfficientNet)
Data Augmentation (Albumentation, AutoAugment, Cutout, etc).
Loss function (ArcFace, AccuracyLoss).
Multi-scale processing.
Fine-tuning and post-processing.
Thanks for reading the article, I hope you found this to be helpful. If you did, please share it on your favorite social media so other folks can find it, too. Also, please let me know in the comment section if something is not clear or incorrect.
|
[
{
"code": null,
"e": 390,
"s": 172,
"text": "In this blog, I will walk through an introduction to instance-level recognition, use cases, challenges, currently available dataset, and state of the art results (recent winner solutions) on these challenges/datasets."
},
{
"code": null,
"e": 522,
"s": 390,
"text": "Instance Level Recognition (ILR), is a visual recognition task to recognize a specific instance of an object not just object class."
},
{
"code": null,
"e": 740,
"s": 522,
"text": "For example, as shown in the above image, painting is an object class, and “Mona Lisa” by Leonardo Da Vinci is an instance of that painting. Similarly, the Taj Mahal, India is an instance of the object class building."
},
{
"code": null,
"e": 793,
"s": 740,
"text": "Landmark Recognition: Recognize landmarks in images."
},
{
"code": null,
"e": 876,
"s": 793,
"text": "Landmark Retrieval: Retrieve relevant landmark images from a large-scale database."
},
{
"code": null,
"e": 927,
"s": 876,
"text": "Artwork Recognition: Recognize artworks in images."
},
{
"code": null,
"e": 1008,
"s": 927,
"text": "Product Retrieval: Retrieve relevant product images from a large-scale database."
},
{
"code": null,
"e": 1346,
"s": 1008,
"text": "Large scale: Most of the current state of the art results of recognition tasks are measured on very limited categories e.g. ~1000 image classes in ImageNet, ~80 categories in COCO. But use-cases like landmark retrieval and recognition, has 200K+ classes e.g. in Google Landmark Dataset V2 (GLDv2), 100K+ classes of the product on Amazon."
},
{
"code": null,
"e": 1466,
"s": 1346,
"text": "Long-tailed: Few popular places have more than 1000+ images but many less know places have less than 5 images in GLDv2."
},
{
"code": null,
"e": 1612,
"s": 1466,
"text": "Intra-class variability: Landmarks are mostly spread across a wide region and have very high intra-class variability as shown in the below image."
},
{
"code": null,
"e": 1934,
"s": 1612,
"text": "Noisy Labels: The success of machine learning models depends on high-quality labeled training data, as the presence of labels errors can greatly reduce the model's performance. These noisy labels as shown in the below image, unfortunately, noisy labels are part of a large training set and need additional learning steps."
},
{
"code": null,
"e": 2201,
"s": 1934,
"text": "Google Landmarks Dataset V2 (GLDv2): Google Landmark Dataset v2 is a new benchmark for large-scale, fine-grained instance recognition and image retrieval in the domain of human-made and natural landmarks. The below image shows all the details of the landmark dataset"
},
{
"code": null,
"e": 2593,
"s": 2201,
"text": "CVPR 2020 AliProducts Challenge: AliProducts Challenge is a large-scale, noisy, and fine-grained product dataset with ~50K categories with ~3M images. This dataset is proposed as competition for studying commodity image recognition problems encountered by world-leading e-commerce companies. This competition is part of the RetailVision workshop RetailVision CVPR 2020 workshop at CVPR 2020."
},
{
"code": null,
"e": 2931,
"s": 2593,
"text": "Amazon Product Challenge: Amazon product dataset is announced in ILR ECCVW 2020 workshop and will be released by 2021 Q1. Images in the dataset have a domain mismatch due to product catalog images are shot by professional and query images are often shot by mobile phone camera and have bad lighting condition with a cluttered background."
},
{
"code": null,
"e": 3026,
"s": 2931,
"text": "Below I will discuss recent winner solutions for landmark recognition and product recognition."
},
{
"code": null,
"e": 3247,
"s": 3026,
"text": "In the landmark recognition challenge, the task is to predict landmark labels from the image and is conducted every year since 2018. The below image shows the progress in the Global Average Precision of this competition."
},
{
"code": null,
"e": 3643,
"s": 3247,
"text": "An ensemble of 7 global descriptors model (SeResNext101, EfficientNet-B3, ResNet152, Res2Net101). The below image shows the setup for the SeResNext101 backbone and for others also we follow similar architecture. Each backbone network is aggregated using Generalized-Mean (GeM) pooling and followed by linear neck (Linear 512, BatchNorm1D, PReLU), before finally feeding into the arc margin head."
},
{
"code": null,
"e": 4280,
"s": 3643,
"text": "ResNet variants (152 & 101) both rely on identifying shortcut connections that skip one or more layers to tackle the vanishing gradient issue. SeResNeXt is a variant of ResNeXt which is an inception net with a shortcut connection and Se refers to the Squeeze and Excitation module added to ResNeXt. Se network improves channel interdependency by adaptively adjusting the weights of feature maps. EfficientNet is a state of the art network for image classification which relies on Auto Machine Learning to find out the best base network and efficient compound scaling to achieve improved results depending on available compute resources."
},
{
"code": null,
"e": 4590,
"s": 4280,
"text": "Generalized Mean Pooling (GeM) in the neck network computes the generalized mean of each channel in a tensor. If pk → ∞, GeM behaves as max-pooling and pk → 1, it behaves as average pooling. With an increase in pk, the contrast of the pooled feature map increases and focuses on salient features of the image."
},
{
"code": null,
"e": 4763,
"s": 4590,
"text": "PReLU: PReLU is a generalization of leaky ReLU, to solve the dying neuron problem which happens when data is not normalized or network weights are not properly initialized."
},
{
"code": null,
"e": 5004,
"s": 4763,
"text": "Arc margin improves on softmax loss to enforce higher similarity for intra-class variation and diversity for inter-class by distributing learned embedding on hypersphere with a radius of s. Below is the pseudo-code of ArcFace loss on MxNet."
},
{
"code": null,
"e": 5108,
"s": 5004,
"text": "Models are trained at different image scales [448x448, 568x568, 600x600, 512x512] using albumentations."
},
{
"code": null,
"e": 5177,
"s": 5108,
"text": "Each model is trained for 10 epochs with cosine annealing scheduler."
},
{
"code": null,
"e": 5268,
"s": 5177,
"text": "The test set of the 2019 competition which was released with labels is used as validation."
},
{
"code": null,
"e": 5374,
"s": 5268,
"text": "As a post-processing step re-ranking was done to penalize non-landmarks images to improve the GAP metric."
},
{
"code": null,
"e": 5402,
"s": 5374,
"text": "Test: Leaderboard test set."
},
{
"code": null,
"e": 5462,
"s": 5402,
"text": "Train: Candidate images to determine labels and confidence."
},
{
"code": null,
"e": 5525,
"s": 5462,
"text": "Non-Landmark: Images with no landmark from the GLDv2 test set."
},
{
"code": null,
"e": 5775,
"s": 5525,
"text": "Calculate the cosine similarity between the test and train image (A)Calculate the average (top-5 or top-10) cosine similarity between the train and non-landmark images. (B)Calculate Ai,j — BjSum the confidence of the same label and pick the highest."
},
{
"code": null,
"e": 5844,
"s": 5775,
"text": "Calculate the cosine similarity between the test and train image (A)"
},
{
"code": null,
"e": 5949,
"s": 5844,
"text": "Calculate the average (top-5 or top-10) cosine similarity between the train and non-landmark images. (B)"
},
{
"code": null,
"e": 5969,
"s": 5949,
"text": "Calculate Ai,j — Bj"
},
{
"code": null,
"e": 6028,
"s": 5969,
"text": "Sum the confidence of the same label and pick the highest."
},
{
"code": null,
"e": 6275,
"s": 6028,
"text": "The most important point of the above solution is the use of the 2019 competition test set as validation for re-ranking as post-processing after inferencing and led to a top leaderboard score of 0.6598 which is ~1.75x better than the 2019 result."
},
{
"code": null,
"e": 6568,
"s": 6275,
"text": "Backbone networks (EfficientNet-B3, EfficientNet-B4, ResNet50, SeResNext50, SeResNext101) are fine-tune with Destruction and Construction Learning (DCL) and Look into Object (LIO) method. The model averaging is used to ensemble all the fine-tune models, achieving a top-1 error rate of 6.27%."
},
{
"code": null,
"e": 6931,
"s": 6568,
"text": "DCL as shown in the below image enhances fine-grained recognition by learning local discriminative regions and features by shuffling local regions. To prevent the network to learn the noisy patterns, an adversarial counterpart is proposed to reject Region Confusion Mechanism (RCM)-induced patterns that are not relevant. For more details kindly check the paper."
},
{
"code": null,
"e": 7264,
"s": 6931,
"text": "LIO as shown in the below image, models structure using self-supervised learning. Object extent learning helps the backbone network to distinguish between foreground and background. Spatial context learning using a self-supervision strengthen structural information for the backbone network. For more details kindly check the paper."
},
{
"code": null,
"e": 7407,
"s": 7264,
"text": "All images are resized to 256x256 then random crop to 224x224 for training and center crop 224x224 for the test. Train data is augmented using"
},
{
"code": null,
"e": 7424,
"s": 7407,
"text": "AutoAugmentation"
},
{
"code": null,
"e": 7431,
"s": 7424,
"text": "Cutout"
},
{
"code": null,
"e": 7440,
"s": 7431,
"text": "Training"
},
{
"code": null,
"e": 7518,
"s": 7440,
"text": "All models are trained with an SGD optimizer with manual learning rate decay."
},
{
"code": null,
"e": 8109,
"s": 7518,
"text": "All backbone networks with basic training achieve a top-1 error rate of 20–25%.All backbone networks are fine-tuned with balanced training, achieving a top-1 error rate of 9–12%. The balanced training set includes all the images from validation as well if the number of images in a category is less than 30.All backbone are further fine-tuned using DCL on higher resolution image (448x448), reducing error rate by 1–2% further.All networks are further fine-tuned using accuracy loss as shown in the below image, which is optimized for the top-1 error rate, reducing error rate by ~0.2–0.5%."
},
{
"code": null,
"e": 8189,
"s": 8109,
"text": "All backbone networks with basic training achieve a top-1 error rate of 20–25%."
},
{
"code": null,
"e": 8418,
"s": 8189,
"text": "All backbone networks are fine-tuned with balanced training, achieving a top-1 error rate of 9–12%. The balanced training set includes all the images from validation as well if the number of images in a category is less than 30."
},
{
"code": null,
"e": 8539,
"s": 8418,
"text": "All backbone are further fine-tuned using DCL on higher resolution image (448x448), reducing error rate by 1–2% further."
},
{
"code": null,
"e": 8703,
"s": 8539,
"text": "All networks are further fine-tuned using accuracy loss as shown in the below image, which is optimized for the top-1 error rate, reducing error rate by ~0.2–0.5%."
},
{
"code": null,
"e": 8845,
"s": 8703,
"text": "def acc_loss(y_true, y_pred): tp = (y_pred, y_true).sum(1) fp = ((1-y_true)*y_pred).sum(1) acc = tp/(tp+fp) return 1 - acc.mean()"
},
{
"code": null,
"e": 8903,
"s": 8845,
"text": "Below 11 models are used to calculate final probabilities"
},
{
"code": null,
"e": 8993,
"s": 8903,
"text": "Balanced fine-tuned resnet50, seresnext50, seresnext101, efficientnet-b3, efficientnet-b4"
},
{
"code": null,
"e": 9030,
"s": 8993,
"text": "DCL fine-tuned resnet50, seresnext50"
},
{
"code": null,
"e": 9093,
"s": 9030,
"text": "Accuray loss fine-tunes resnet50, seresnext50, efficientnet-b3"
},
{
"code": null,
"e": 9117,
"s": 9093,
"text": "LIO fine-tuned resnet50"
},
{
"code": null,
"e": 9391,
"s": 9117,
"text": "Instance-level recognition will unravel the true potential of deep learning technologies for semantic image classification/retrieval for eCommerce, travel, media & entertainment, agriculture, etc. Some of the major building block for an efficient instance-level solution is"
},
{
"code": null,
"e": 9465,
"s": 9391,
"text": "Backbone Network Selection (Residual, Squeeze & Excitation, EfficientNet)"
},
{
"code": null,
"e": 9526,
"s": 9465,
"text": "Data Augmentation (Albumentation, AutoAugment, Cutout, etc)."
},
{
"code": null,
"e": 9565,
"s": 9526,
"text": "Loss function (ArcFace, AccuracyLoss)."
},
{
"code": null,
"e": 9589,
"s": 9565,
"text": "Multi-scale processing."
},
{
"code": null,
"e": 9622,
"s": 9589,
"text": "Fine-tuning and post-processing."
}
] |
Servlets - Auto Page Refresh
|
Consider a webpage which is displaying live game score or stock market status or currency exchange ration. For all such type of pages, you would need to refresh your web page regularly using refresh or reload button with your browser.
Java Servlet makes this job easy by providing you a mechanism where you can make a webpage in such a way that it would refresh automatically after a given interval.
The simplest way of refreshing a web page is using method setIntHeader() of response object. Following is the signature of this method −
public void setIntHeader(String header, int headerValue)
This method sends back header "Refresh" to the browser along with an integer value which indicates time interval in seconds.
This example shows how a servlet performs auto page refresh using setIntHeader() method to set Refresh header.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
// Extend HttpServlet class
public class Refresh extends HttpServlet {
// Method to handle GET method request.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set refresh, autoload time as 5 seconds
response.setIntHeader("Refresh", 5);
// Set response content type
response.setContentType("text/html");
// Get current time
Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
PrintWriter out = response.getWriter();
String title = "Auto Page Refresh using Servlet";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<p>Current Time is: " + CT + "</p>\n"
);
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Now let us compile the above servlet and create the following entries in web.xml
....
<servlet>
<servlet-name>Refresh</servlet-name>
<servlet-class>Refresh</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Refresh</servlet-name>
<url-pattern>/Refresh</url-pattern>
</servlet-mapping>
....
Now call this servlet using URL http://localhost:8080/Refresh which would display current system time after every 5 seconds as follows. Just run the servlet and wait to see the result −
Auto Page Refresh using Servlet
Current Time is: 9:44:50 PM
Current Time is: 9:44:50 PM
41 Lectures
4.5 hours
Karthikeya T
42 Lectures
5.5 hours
TELCOMA Global
15 Lectures
3 hours
TELCOMA Global
31 Lectures
12.5 hours
Uplatz
38 Lectures
4.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2420,
"s": 2185,
"text": "Consider a webpage which is displaying live game score or stock market status or currency exchange ration. For all such type of pages, you would need to refresh your web page regularly using refresh or reload button with your browser."
},
{
"code": null,
"e": 2585,
"s": 2420,
"text": "Java Servlet makes this job easy by providing you a mechanism where you can make a webpage in such a way that it would refresh automatically after a given interval."
},
{
"code": null,
"e": 2722,
"s": 2585,
"text": "The simplest way of refreshing a web page is using method setIntHeader() of response object. Following is the signature of this method −"
},
{
"code": null,
"e": 2779,
"s": 2722,
"text": "public void setIntHeader(String header, int headerValue)"
},
{
"code": null,
"e": 2904,
"s": 2779,
"text": "This method sends back header \"Refresh\" to the browser along with an integer value which indicates time interval in seconds."
},
{
"code": null,
"e": 3016,
"s": 2904,
"text": "This example shows how a servlet performs auto page refresh using setIntHeader() method to set Refresh header. "
},
{
"code": null,
"e": 4686,
"s": 3016,
"text": "// Import required java libraries\nimport java.io.*;\nimport javax.servlet.*;\nimport javax.servlet.http.*;\nimport java.util.*;\n \n// Extend HttpServlet class\npublic class Refresh extends HttpServlet {\n \n // Method to handle GET method request.\n public void doGet(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n \n // Set refresh, autoload time as 5 seconds\n response.setIntHeader(\"Refresh\", 5);\n \n // Set response content type\n response.setContentType(\"text/html\");\n \n // Get current time\n Calendar calendar = new GregorianCalendar();\n String am_pm;\n int hour = calendar.get(Calendar.HOUR);\n int minute = calendar.get(Calendar.MINUTE);\n int second = calendar.get(Calendar.SECOND);\n \n if(calendar.get(Calendar.AM_PM) == 0)\n am_pm = \"AM\";\n else\n am_pm = \"PM\";\n \n String CT = hour+\":\"+ minute +\":\"+ second +\" \"+ am_pm;\n \n PrintWriter out = response.getWriter();\n String title = \"Auto Page Refresh using Servlet\";\n String docType =\n \"<!doctype html public \\\"-//w3c//dtd html 4.0 \" + \"transitional//en\\\">\\n\";\n \n out.println(docType +\n \"<html>\\n\" +\n \"<head><title>\" + title + \"</title></head>\\n\"+\n \"<body bgcolor = \\\"#f0f0f0\\\">\\n\" +\n \"<h1 align = \\\"center\\\">\" + title + \"</h1>\\n\" +\n \"<p>Current Time is: \" + CT + \"</p>\\n\"\n );\n }\n \n // Method to handle POST method request.\n public void doPost(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n \n doGet(request, response);\n }\n}"
},
{
"code": null,
"e": 4767,
"s": 4686,
"text": "Now let us compile the above servlet and create the following entries in web.xml"
},
{
"code": null,
"e": 5011,
"s": 4767,
"text": "....\n <servlet>\n <servlet-name>Refresh</servlet-name>\n <servlet-class>Refresh</servlet-class>\n </servlet>\n \n <servlet-mapping>\n <servlet-name>Refresh</servlet-name>\n <url-pattern>/Refresh</url-pattern>\n </servlet-mapping>\n....\n"
},
{
"code": null,
"e": 5197,
"s": 5011,
"text": "Now call this servlet using URL http://localhost:8080/Refresh which would display current system time after every 5 seconds as follows. Just run the servlet and wait to see the result −"
},
{
"code": null,
"e": 5258,
"s": 5197,
"text": "Auto Page Refresh using Servlet\nCurrent Time is: 9:44:50 PM\n"
},
{
"code": null,
"e": 5286,
"s": 5258,
"text": "Current Time is: 9:44:50 PM"
},
{
"code": null,
"e": 5321,
"s": 5286,
"text": "\n 41 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5335,
"s": 5321,
"text": " Karthikeya T"
},
{
"code": null,
"e": 5370,
"s": 5335,
"text": "\n 42 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5386,
"s": 5370,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 5419,
"s": 5386,
"text": "\n 15 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5435,
"s": 5419,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 5471,
"s": 5435,
"text": "\n 31 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 5479,
"s": 5471,
"text": " Uplatz"
},
{
"code": null,
"e": 5514,
"s": 5479,
"text": "\n 38 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5532,
"s": 5514,
"text": " Packt Publishing"
},
{
"code": null,
"e": 5539,
"s": 5532,
"text": " Print"
},
{
"code": null,
"e": 5550,
"s": 5539,
"text": " Add Notes"
}
] |
Controlling a Stepper Motor with Arduino
|
A stepper motor divides the full rotation into a number of discrete steps, ranging from as low as 12 to as high as 200 steps per revolution (corresponding to angles of 30 degrees per step to 1.8 degrees per step). While a DC motor rotates continuously, a stepper motor rotates discretely, in step angles.
The circuit diagram and the required components for both Unipolar and Bipolar stepper motors can be found here − https://www.arduino.cc/en/Tutorial/LibraryExamples/StepperOneRevolution
Note that the stepper motor is connected to pins 8-11 of Arduino Uno, via a Darlington Array (for unipolar stepper) or H-bridge (for bipolar stepper). The stepper motor is powered using an external supply as it draws too much power to be directly powered from the Arduino board.
We will be walking through an example code. Go to File → Examples → Stepper → stepper_oneRevolution.
Alternatively, the code can be found on GitHub − https://github.com/arduinolibraries/Stepper/blob/master/examples/stepper_oneRevolution/stepper_oneRevolution.ino
Through this code, we make the stepper motor rotate one revolution in one direction, and another revolution in the opposite direction.
We begin with the inclusion of the Stepper library and defining the number of steps per revolution (change this according to the specification of your stepper motor)
#include <Stepper.h>
const int stepsPerRevolution = 200;
Next, we initialize the Stepper object using the stepsPerRevolution and the four pins of the Arduino which are connected to the Stepper motor.
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
Within the setup, we set the speed of the stepper motor in RPM, and initialize Serial.
void setup() {
// set the speed at 60 rpm:
myStepper.setSpeed(60);
// initialize the serial port:
Serial.begin(9600);
}
Within the loop, we make the motor step stepsPerRevolution in one direction, and then step stepsPerRevolution in the opposite direction (by just appending a negative sign)
void loop() {
// step one revolution in one direction:
Serial.println("clockwise");
myStepper.step(stepsPerRevolution);
delay(500);
// step one revolution in the other direction:
Serial.println("counterclockwise");
myStepper.step(-stepsPerRevolution);
delay(500);
}
|
[
{
"code": null,
"e": 1367,
"s": 1062,
"text": "A stepper motor divides the full rotation into a number of discrete steps, ranging from as low as 12 to as high as 200 steps per revolution (corresponding to angles of 30 degrees per step to 1.8 degrees per step). While a DC motor rotates continuously, a stepper motor rotates discretely, in step angles."
},
{
"code": null,
"e": 1552,
"s": 1367,
"text": "The circuit diagram and the required components for both Unipolar and Bipolar stepper motors can be found here − https://www.arduino.cc/en/Tutorial/LibraryExamples/StepperOneRevolution"
},
{
"code": null,
"e": 1831,
"s": 1552,
"text": "Note that the stepper motor is connected to pins 8-11 of Arduino Uno, via a Darlington Array (for unipolar stepper) or H-bridge (for bipolar stepper). The stepper motor is powered using an external supply as it draws too much power to be directly powered from the Arduino board."
},
{
"code": null,
"e": 1932,
"s": 1831,
"text": "We will be walking through an example code. Go to File → Examples → Stepper → stepper_oneRevolution."
},
{
"code": null,
"e": 2094,
"s": 1932,
"text": "Alternatively, the code can be found on GitHub − https://github.com/arduinolibraries/Stepper/blob/master/examples/stepper_oneRevolution/stepper_oneRevolution.ino"
},
{
"code": null,
"e": 2229,
"s": 2094,
"text": "Through this code, we make the stepper motor rotate one revolution in one direction, and another revolution in the opposite direction."
},
{
"code": null,
"e": 2395,
"s": 2229,
"text": "We begin with the inclusion of the Stepper library and defining the number of steps per revolution (change this according to the specification of your stepper motor)"
},
{
"code": null,
"e": 2453,
"s": 2395,
"text": "#include <Stepper.h>\n\nconst int stepsPerRevolution = 200;"
},
{
"code": null,
"e": 2596,
"s": 2453,
"text": "Next, we initialize the Stepper object using the stepsPerRevolution and the four pins of the Arduino which are connected to the Stepper motor."
},
{
"code": null,
"e": 2649,
"s": 2596,
"text": "Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);"
},
{
"code": null,
"e": 2736,
"s": 2649,
"text": "Within the setup, we set the speed of the stepper motor in RPM, and initialize Serial."
},
{
"code": null,
"e": 2868,
"s": 2736,
"text": "void setup() {\n // set the speed at 60 rpm:\n myStepper.setSpeed(60);\n // initialize the serial port:\n Serial.begin(9600);\n}"
},
{
"code": null,
"e": 3040,
"s": 2868,
"text": "Within the loop, we make the motor step stepsPerRevolution in one direction, and then step stepsPerRevolution in the opposite direction (by just appending a negative sign)"
},
{
"code": null,
"e": 3331,
"s": 3040,
"text": "void loop() {\n // step one revolution in one direction:\n Serial.println(\"clockwise\");\n myStepper.step(stepsPerRevolution);\n delay(500);\n\n // step one revolution in the other direction:\n Serial.println(\"counterclockwise\");\n myStepper.step(-stepsPerRevolution);\n delay(500);\n}"
}
] |
Function Pointer in C
|
Function Pointers point to code like normal pointers.
In Functions Pointers, function’s name can be used to get function’s address.
A function can also be passed as an arguments and can be returned from a function.
function_return_type(*Pointer_name)(function argument list)
Live Demo
#include<stdio.h>
int subtraction (int a, int b) {
return a-b;
}
int main() {
int (*fp) (int, int)=subtraction;
//Calling function using function pointer
int result = fp(5, 4);
printf(" Using function pointer we get the result: %d",result);
return 0;
}
Using function pointer we get the result: 1
|
[
{
"code": null,
"e": 1116,
"s": 1062,
"text": "Function Pointers point to code like normal pointers."
},
{
"code": null,
"e": 1194,
"s": 1116,
"text": "In Functions Pointers, function’s name can be used to get function’s address."
},
{
"code": null,
"e": 1277,
"s": 1194,
"text": "A function can also be passed as an arguments and can be returned from a function."
},
{
"code": null,
"e": 1337,
"s": 1277,
"text": "function_return_type(*Pointer_name)(function argument list)"
},
{
"code": null,
"e": 1348,
"s": 1337,
"text": " Live Demo"
},
{
"code": null,
"e": 1619,
"s": 1348,
"text": "#include<stdio.h>\nint subtraction (int a, int b) {\n return a-b;\n}\nint main() {\n int (*fp) (int, int)=subtraction;\n //Calling function using function pointer\n int result = fp(5, 4);\n printf(\" Using function pointer we get the result: %d\",result);\n return 0;\n}"
},
{
"code": null,
"e": 1663,
"s": 1619,
"text": "Using function pointer we get the result: 1"
}
] |
How to generate sequences in Python?
|
List comprehensions in python are useful for such tasks. These are very powerful expressions that you can use to generate sequences in a very concise and efficient manner. For example, if you want first 100 integers from 0, you can use −
a = [i for i in range(100)]
print(a)
This will give the output −
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65,
66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86,87,
88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
Want the squares for first 10 even numbers? You can get it using −
a = [i * i for i in range(20) if i % 2 == 0]
print(a)
This will give the output −
[0, 4, 16, 36, 64, 100, 144, 196, 256, 324]
These expressions can get much more powerful once you know how to use them.
|
[
{
"code": null,
"e": 1300,
"s": 1062,
"text": "List comprehensions in python are useful for such tasks. These are very powerful expressions that you can use to generate sequences in a very concise and efficient manner. For example, if you want first 100 integers from 0, you can use −"
},
{
"code": null,
"e": 1337,
"s": 1300,
"text": "a = [i for i in range(100)]\nprint(a)"
},
{
"code": null,
"e": 1365,
"s": 1337,
"text": "This will give the output −"
},
{
"code": null,
"e": 1754,
"s": 1365,
"text": "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,\n24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65,\n66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86,87,\n88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]"
},
{
"code": null,
"e": 1821,
"s": 1754,
"text": "Want the squares for first 10 even numbers? You can get it using −"
},
{
"code": null,
"e": 1875,
"s": 1821,
"text": "a = [i * i for i in range(20) if i % 2 == 0]\nprint(a)"
},
{
"code": null,
"e": 1903,
"s": 1875,
"text": "This will give the output −"
},
{
"code": null,
"e": 1947,
"s": 1903,
"text": "[0, 4, 16, 36, 64, 100, 144, 196, 256, 324]"
},
{
"code": null,
"e": 2023,
"s": 1947,
"text": "These expressions can get much more powerful once you know how to use them."
}
] |
13 Conda Commands for Data Scientists | by Jeff Hale | Towards Data Science
|
Python is the most popular language for data scientists. 🐍 Conda is the most common tool to create a virtual environment and manage packages for data scientists using Python.
Unfortunately, figuring out the best way to get conda on your machine and when to install packages from various channels isn’t straightforward. And it’s not easy to find the most useful commands for using conda and pip all in one place. ☹️
In this article I’m going to provide the essential conda commands and suggestions to help you avoid headaches with installation and use. 🎉
Let’s get to it! 🚀
Whether working locally or on a server in the cloud, you want a virtual environment to isolate your Python version and packages so that you can:
use different package versions for different projectsexperiment with bleeding edge package versionsget the same Python and package versions as your teammates so your shared code works similarly
use different package versions for different projects
experiment with bleeding edge package versions
get the same Python and package versions as your teammates so your shared code works similarly
Nope. It’s very common in data analysis and scientific computing, but not so common outside.
There are lots of tools you can use to manage virtual Python environments. conda, Venv, pyenv, pipenv, poetry, Docker, and virtualenv are the most prominent. Trust me, you don’t even want to go down this rabbit hole. 🐇
But if you must, here’s a Hacker News thread for a taste of the fun. And Yufeng G, Developer Advocate for Google Cloud, has a nice video on conda, virtualenv, and pyenv here.
Today we’re exploring conda, so let’s dive in!
Anaconda is both the name of the company behind the software and the name of the fully featured software distribution. The Anaconda company offers consulting and three Anaconda editions: individual, team, and enterprise. Individual is common and powerful. It’s not like there are freeware gotchas. 😉 It’s what I use.
You can choose to download and install one of two distributions: Anaconda or Miniconda.
Both Anaconda and Miniconda get you conda, the package manager and virtual environment manager in one.
Both can be installed on Windows, Mac, or Linux systems.
Both come with Python and pip installed.
The Anaconda distribution installs many Python packages and tools that are common for data science. Miniconda does not. It’s the difference between a big, batteries-included download and a minimal download without many packages installed for you.
Miniconda install ranges between 50 and 90 MiB in mid-2020, depending on your operating system .
The Anaconda distribution requires a “minimum 5 GB disc space to download and install” — according to the docs in mid-2020.
The Anaconda distribution installer also includes options to install a GUI and other popular software such as the VSCode text editor.
If you are getting started with scientific computing using Python and have the space on your computer, I suggest you download the Anaconda distribution. It’s a lot of stuff, but it’s good stuff. 👍
If you’ve worked with conda previously, I suggest you download Miniconda. You can add just the packages you need as you go. 😀
See install instructions for Anaconda here and for Miniconda here.
If you installed the Anaconda distribution you can use the GUI installer, but I suggest using the command line interface to help you work faster. You are a programmer after all (or becoming one)! 😉
Let’s look at common conda commands to create and manage conda environments. Everything is the same whether you installed Anaconda or Miniconda. It’s all conda at this point. 😀
conda create -n myenv pandas jupyterlab Create a new conda environment named myenv with the latest version of Python available on the main conda channel. Install pandas and jupyterlab packages into the environment. -n is short for --name.
Conda asks for confirmation with package changes. Press y when asked whether you want to proceed.
conda create -n myclone --clone myenv Duplicate the environment named myenv into the new environment named myclone. All the packages come along for the ride! 🚙
conda create -n myenv python=3.8 Create a new conda environment named myenv with the Python version specified. Pip and about 15 other packages are installed.
conda activate myenv — Activate the myenv virtual environment.
You can tell you are in an active virtual environment because your command line prompt will start with the name of your virtual environment in parentheses. Like this:
(base) Jeffs-MBP:~ jeffhale$
The default conda environment is named base.
Conda can be set up to activate an environment whenever you open your terminal. When installing the software the installer will ask you if you want to initialize it “by running conda init". I suggest you say yes so that your shell scripts get modified. Then you’ll start your terminal sessions in a conda environment.
Wherever you navigate in your on CLI, you will be within your activated conda virtual environment. 🎉
conda deactivate — Deactivate the current environment. Now you won’t be in a virtual environment. The conda environment you were in still exists, you just aren’t in it. 👍
conda env list — List conda environments.
conda env remove --name myenv — Remove the myenv conda environment. Delete it forever.
Use these commands from within an active conda environment. These are the conda commands I use most frequently. 😀
conda list — List installed packages in the active environment. The output includes the package version and the conda channel the package was installed from. 👍
conda install pandas — Download and install the pandas package from the main conda channel.
conda install -c conda-forge pandas — Download and install the pandas package from the main conda-forge channel.
The conda-forge channel is “A community-led collection of recipes, build infrastructure and distributions for the conda package manager.” Use the conda-forge channel when a package doesn't exist on the main channel or the version on the main channel isn't as new as you would like. Packages often get updated on conda-forge before the main conda channel. ☝️
You can also specify some other channel, but conda-forge is where you will find many packages.
conda update pandas — Download and install the latest pandas package from the main conda channel.
conda update all — Download and install the the latest versions of all installed packages. Can be very slow if you have a lot of outdated packages. ⚠️
conda uninstall pandas — Uninstall the pandas package in your conda environment.
Pip is the most common package installer. It ships with Python.
When in an active conda environment, pip will install packages into that active conda environment. ⚠️
pip install -U pandas — Install or update the pandas package from PyPI, the Python package index. -U specifies to update all dependent packages.
pip uninstall pandas — Uninstall the pandas package that was installed by pip.
PyPI is the most common place to find Python packages. PyPI often has packages that are not on conda or conda-forge. PyPI often gets the latest version of packages first.
Occasionally conda has packages that aren’t on PyPI, but that is less common.
Conda and PyPI packages generally play together nicely. 🎉
Make sure that if you are installing a version of a package from PyPI you don't already have the same package installed from conda. If you do have it installed, then uninstall the conda version first. Otherwise conda won’t use the new PyPI version. By default, the official conda channel is the highest priority channel and conda will use package versions from higher priority channels first.☝️
The official conda recommendation is to try to install packages from the main conda channel first, then conda-forge as necessary, and then pip. This helps avoid conflicts. In general, installing from any of those sources should work fine.
Sometimes things get messed up. Generally uninstalling packages or creating a new conda environment is all you need to fix the situation.
If that doesn’t work, conda update conda updates the conda software itself.
If that doesn’t work, you can uninstall and reinstall conda. 👍
There are lots of conda users out there and lots of documentation, so as always, the search engine is your friend. 😉
I hope you’ve enjoyed this overview of conda. If you did, please share it on your favorite social media so other folks can find it, too. 😀
I write about Python, SQL, Docker, and other tech topics. If any of that’s of interest to you, sign up for my mailing list of awesome data science resources and checkout out some of my 60+ articles you grow your skills here. 👍
|
[
{
"code": null,
"e": 347,
"s": 172,
"text": "Python is the most popular language for data scientists. 🐍 Conda is the most common tool to create a virtual environment and manage packages for data scientists using Python."
},
{
"code": null,
"e": 587,
"s": 347,
"text": "Unfortunately, figuring out the best way to get conda on your machine and when to install packages from various channels isn’t straightforward. And it’s not easy to find the most useful commands for using conda and pip all in one place. ☹️"
},
{
"code": null,
"e": 726,
"s": 587,
"text": "In this article I’m going to provide the essential conda commands and suggestions to help you avoid headaches with installation and use. 🎉"
},
{
"code": null,
"e": 745,
"s": 726,
"text": "Let’s get to it! 🚀"
},
{
"code": null,
"e": 890,
"s": 745,
"text": "Whether working locally or on a server in the cloud, you want a virtual environment to isolate your Python version and packages so that you can:"
},
{
"code": null,
"e": 1084,
"s": 890,
"text": "use different package versions for different projectsexperiment with bleeding edge package versionsget the same Python and package versions as your teammates so your shared code works similarly"
},
{
"code": null,
"e": 1138,
"s": 1084,
"text": "use different package versions for different projects"
},
{
"code": null,
"e": 1185,
"s": 1138,
"text": "experiment with bleeding edge package versions"
},
{
"code": null,
"e": 1280,
"s": 1185,
"text": "get the same Python and package versions as your teammates so your shared code works similarly"
},
{
"code": null,
"e": 1373,
"s": 1280,
"text": "Nope. It’s very common in data analysis and scientific computing, but not so common outside."
},
{
"code": null,
"e": 1592,
"s": 1373,
"text": "There are lots of tools you can use to manage virtual Python environments. conda, Venv, pyenv, pipenv, poetry, Docker, and virtualenv are the most prominent. Trust me, you don’t even want to go down this rabbit hole. 🐇"
},
{
"code": null,
"e": 1767,
"s": 1592,
"text": "But if you must, here’s a Hacker News thread for a taste of the fun. And Yufeng G, Developer Advocate for Google Cloud, has a nice video on conda, virtualenv, and pyenv here."
},
{
"code": null,
"e": 1814,
"s": 1767,
"text": "Today we’re exploring conda, so let’s dive in!"
},
{
"code": null,
"e": 2131,
"s": 1814,
"text": "Anaconda is both the name of the company behind the software and the name of the fully featured software distribution. The Anaconda company offers consulting and three Anaconda editions: individual, team, and enterprise. Individual is common and powerful. It’s not like there are freeware gotchas. 😉 It’s what I use."
},
{
"code": null,
"e": 2219,
"s": 2131,
"text": "You can choose to download and install one of two distributions: Anaconda or Miniconda."
},
{
"code": null,
"e": 2322,
"s": 2219,
"text": "Both Anaconda and Miniconda get you conda, the package manager and virtual environment manager in one."
},
{
"code": null,
"e": 2379,
"s": 2322,
"text": "Both can be installed on Windows, Mac, or Linux systems."
},
{
"code": null,
"e": 2420,
"s": 2379,
"text": "Both come with Python and pip installed."
},
{
"code": null,
"e": 2667,
"s": 2420,
"text": "The Anaconda distribution installs many Python packages and tools that are common for data science. Miniconda does not. It’s the difference between a big, batteries-included download and a minimal download without many packages installed for you."
},
{
"code": null,
"e": 2764,
"s": 2667,
"text": "Miniconda install ranges between 50 and 90 MiB in mid-2020, depending on your operating system ."
},
{
"code": null,
"e": 2888,
"s": 2764,
"text": "The Anaconda distribution requires a “minimum 5 GB disc space to download and install” — according to the docs in mid-2020."
},
{
"code": null,
"e": 3022,
"s": 2888,
"text": "The Anaconda distribution installer also includes options to install a GUI and other popular software such as the VSCode text editor."
},
{
"code": null,
"e": 3219,
"s": 3022,
"text": "If you are getting started with scientific computing using Python and have the space on your computer, I suggest you download the Anaconda distribution. It’s a lot of stuff, but it’s good stuff. 👍"
},
{
"code": null,
"e": 3345,
"s": 3219,
"text": "If you’ve worked with conda previously, I suggest you download Miniconda. You can add just the packages you need as you go. 😀"
},
{
"code": null,
"e": 3412,
"s": 3345,
"text": "See install instructions for Anaconda here and for Miniconda here."
},
{
"code": null,
"e": 3610,
"s": 3412,
"text": "If you installed the Anaconda distribution you can use the GUI installer, but I suggest using the command line interface to help you work faster. You are a programmer after all (or becoming one)! 😉"
},
{
"code": null,
"e": 3787,
"s": 3610,
"text": "Let’s look at common conda commands to create and manage conda environments. Everything is the same whether you installed Anaconda or Miniconda. It’s all conda at this point. 😀"
},
{
"code": null,
"e": 4026,
"s": 3787,
"text": "conda create -n myenv pandas jupyterlab Create a new conda environment named myenv with the latest version of Python available on the main conda channel. Install pandas and jupyterlab packages into the environment. -n is short for --name."
},
{
"code": null,
"e": 4124,
"s": 4026,
"text": "Conda asks for confirmation with package changes. Press y when asked whether you want to proceed."
},
{
"code": null,
"e": 4284,
"s": 4124,
"text": "conda create -n myclone --clone myenv Duplicate the environment named myenv into the new environment named myclone. All the packages come along for the ride! 🚙"
},
{
"code": null,
"e": 4442,
"s": 4284,
"text": "conda create -n myenv python=3.8 Create a new conda environment named myenv with the Python version specified. Pip and about 15 other packages are installed."
},
{
"code": null,
"e": 4505,
"s": 4442,
"text": "conda activate myenv — Activate the myenv virtual environment."
},
{
"code": null,
"e": 4672,
"s": 4505,
"text": "You can tell you are in an active virtual environment because your command line prompt will start with the name of your virtual environment in parentheses. Like this:"
},
{
"code": null,
"e": 4701,
"s": 4672,
"text": "(base) Jeffs-MBP:~ jeffhale$"
},
{
"code": null,
"e": 4746,
"s": 4701,
"text": "The default conda environment is named base."
},
{
"code": null,
"e": 5064,
"s": 4746,
"text": "Conda can be set up to activate an environment whenever you open your terminal. When installing the software the installer will ask you if you want to initialize it “by running conda init\". I suggest you say yes so that your shell scripts get modified. Then you’ll start your terminal sessions in a conda environment."
},
{
"code": null,
"e": 5165,
"s": 5064,
"text": "Wherever you navigate in your on CLI, you will be within your activated conda virtual environment. 🎉"
},
{
"code": null,
"e": 5336,
"s": 5165,
"text": "conda deactivate — Deactivate the current environment. Now you won’t be in a virtual environment. The conda environment you were in still exists, you just aren’t in it. 👍"
},
{
"code": null,
"e": 5378,
"s": 5336,
"text": "conda env list — List conda environments."
},
{
"code": null,
"e": 5465,
"s": 5378,
"text": "conda env remove --name myenv — Remove the myenv conda environment. Delete it forever."
},
{
"code": null,
"e": 5579,
"s": 5465,
"text": "Use these commands from within an active conda environment. These are the conda commands I use most frequently. 😀"
},
{
"code": null,
"e": 5739,
"s": 5579,
"text": "conda list — List installed packages in the active environment. The output includes the package version and the conda channel the package was installed from. 👍"
},
{
"code": null,
"e": 5831,
"s": 5739,
"text": "conda install pandas — Download and install the pandas package from the main conda channel."
},
{
"code": null,
"e": 5944,
"s": 5831,
"text": "conda install -c conda-forge pandas — Download and install the pandas package from the main conda-forge channel."
},
{
"code": null,
"e": 6302,
"s": 5944,
"text": "The conda-forge channel is “A community-led collection of recipes, build infrastructure and distributions for the conda package manager.” Use the conda-forge channel when a package doesn't exist on the main channel or the version on the main channel isn't as new as you would like. Packages often get updated on conda-forge before the main conda channel. ☝️"
},
{
"code": null,
"e": 6397,
"s": 6302,
"text": "You can also specify some other channel, but conda-forge is where you will find many packages."
},
{
"code": null,
"e": 6495,
"s": 6397,
"text": "conda update pandas — Download and install the latest pandas package from the main conda channel."
},
{
"code": null,
"e": 6646,
"s": 6495,
"text": "conda update all — Download and install the the latest versions of all installed packages. Can be very slow if you have a lot of outdated packages. ⚠️"
},
{
"code": null,
"e": 6727,
"s": 6646,
"text": "conda uninstall pandas — Uninstall the pandas package in your conda environment."
},
{
"code": null,
"e": 6791,
"s": 6727,
"text": "Pip is the most common package installer. It ships with Python."
},
{
"code": null,
"e": 6893,
"s": 6791,
"text": "When in an active conda environment, pip will install packages into that active conda environment. ⚠️"
},
{
"code": null,
"e": 7038,
"s": 6893,
"text": "pip install -U pandas — Install or update the pandas package from PyPI, the Python package index. -U specifies to update all dependent packages."
},
{
"code": null,
"e": 7117,
"s": 7038,
"text": "pip uninstall pandas — Uninstall the pandas package that was installed by pip."
},
{
"code": null,
"e": 7288,
"s": 7117,
"text": "PyPI is the most common place to find Python packages. PyPI often has packages that are not on conda or conda-forge. PyPI often gets the latest version of packages first."
},
{
"code": null,
"e": 7366,
"s": 7288,
"text": "Occasionally conda has packages that aren’t on PyPI, but that is less common."
},
{
"code": null,
"e": 7424,
"s": 7366,
"text": "Conda and PyPI packages generally play together nicely. 🎉"
},
{
"code": null,
"e": 7819,
"s": 7424,
"text": "Make sure that if you are installing a version of a package from PyPI you don't already have the same package installed from conda. If you do have it installed, then uninstall the conda version first. Otherwise conda won’t use the new PyPI version. By default, the official conda channel is the highest priority channel and conda will use package versions from higher priority channels first.☝️"
},
{
"code": null,
"e": 8058,
"s": 7819,
"text": "The official conda recommendation is to try to install packages from the main conda channel first, then conda-forge as necessary, and then pip. This helps avoid conflicts. In general, installing from any of those sources should work fine."
},
{
"code": null,
"e": 8196,
"s": 8058,
"text": "Sometimes things get messed up. Generally uninstalling packages or creating a new conda environment is all you need to fix the situation."
},
{
"code": null,
"e": 8272,
"s": 8196,
"text": "If that doesn’t work, conda update conda updates the conda software itself."
},
{
"code": null,
"e": 8335,
"s": 8272,
"text": "If that doesn’t work, you can uninstall and reinstall conda. 👍"
},
{
"code": null,
"e": 8452,
"s": 8335,
"text": "There are lots of conda users out there and lots of documentation, so as always, the search engine is your friend. 😉"
},
{
"code": null,
"e": 8591,
"s": 8452,
"text": "I hope you’ve enjoyed this overview of conda. If you did, please share it on your favorite social media so other folks can find it, too. 😀"
}
] |
Web Scrapping using cURL in PHP - GeeksforGeeks
|
19 Jan, 2022
We all have tried getting data from a website in many ways. In this article, we will learn how to web scrape using bots to extract content and data from a website.
We will use PHP cURL to scrape a web page, it looks like a typo from leaving caps lock on, but that’s really how you write it. cURL is the system used to make HTTP requests with PHP. It is the way of calling web pages from within your script.
The “Scrape Data, Not Content” this statement is for all the people who want to learn web scraping. cURL and web scraping are powerful tools that can be used to automate what would otherwise be somewhat long and tedious repetitive tasks. We should only scrape information, not full articles and content.
Example: The following example demonstrates the scraping of images from the article https://www.geeksforgeeks.org/matlab-data-types/
PHP
<?php // Initialize curl$ch = curl_init(); // URL for Scrapingcurl_setopt($ch, CURLOPT_URL, 'https://www.geeksforgeeks.org/matlab-data-types/'); // Return Transfer Truecurl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($ch); // Closing cURLcurl_close($ch); // For web page displayecho '<head>';echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';echo '</head>';echo '<body>'; echo '<h1>Web Scraping using cURL</h1>'; // Checking for imagespreg_match_all('!https://media.geeksforgeeks.org/wp-content/uploads/(.*)/(.*).png!', $output, $data); foreach ($data[0] as $list) { echo "<img src='$list'/>";} echo '</body>'; ?>
Output:
web scrape
sagartomar9927
PHP-Questions
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from localserver database and display on HTML table using PHP ?
How to pass form variables from one page to other page in PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
How to create admin login page using PHP?
Different ways for passing data to view in Laravel
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24581,
"s": 24553,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 24746,
"s": 24581,
"text": "We all have tried getting data from a website in many ways. In this article, we will learn how to web scrape using bots to extract content and data from a website. "
},
{
"code": null,
"e": 24989,
"s": 24746,
"text": "We will use PHP cURL to scrape a web page, it looks like a typo from leaving caps lock on, but that’s really how you write it. cURL is the system used to make HTTP requests with PHP. It is the way of calling web pages from within your script."
},
{
"code": null,
"e": 25293,
"s": 24989,
"text": "The “Scrape Data, Not Content” this statement is for all the people who want to learn web scraping. cURL and web scraping are powerful tools that can be used to automate what would otherwise be somewhat long and tedious repetitive tasks. We should only scrape information, not full articles and content."
},
{
"code": null,
"e": 25427,
"s": 25293,
"text": "Example: The following example demonstrates the scraping of images from the article https://www.geeksforgeeks.org/matlab-data-types/ "
},
{
"code": null,
"e": 25431,
"s": 25427,
"text": "PHP"
},
{
"code": "<?php // Initialize curl$ch = curl_init(); // URL for Scrapingcurl_setopt($ch, CURLOPT_URL, 'https://www.geeksforgeeks.org/matlab-data-types/'); // Return Transfer Truecurl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($ch); // Closing cURLcurl_close($ch); // For web page displayecho '<head>';echo '<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />';echo '</head>';echo '<body>'; echo '<h1>Web Scraping using cURL</h1>'; // Checking for imagespreg_match_all('!https://media.geeksforgeeks.org/wp-content/uploads/(.*)/(.*).png!', $output, $data); foreach ($data[0] as $list) { echo \"<img src='$list'/>\";} echo '</body>'; ?>",
"e": 26103,
"s": 25431,
"text": null
},
{
"code": null,
"e": 26111,
"s": 26103,
"text": "Output:"
},
{
"code": null,
"e": 26122,
"s": 26111,
"text": "web scrape"
},
{
"code": null,
"e": 26137,
"s": 26122,
"text": "sagartomar9927"
},
{
"code": null,
"e": 26151,
"s": 26137,
"text": "PHP-Questions"
},
{
"code": null,
"e": 26155,
"s": 26151,
"text": "PHP"
},
{
"code": null,
"e": 26172,
"s": 26155,
"text": "Web Technologies"
},
{
"code": null,
"e": 26176,
"s": 26172,
"text": "PHP"
},
{
"code": null,
"e": 26274,
"s": 26176,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26283,
"s": 26274,
"text": "Comments"
},
{
"code": null,
"e": 26296,
"s": 26283,
"text": "Old Comments"
},
{
"code": null,
"e": 26378,
"s": 26296,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 26442,
"s": 26378,
"text": "How to pass form variables from one page to other page in PHP ?"
},
{
"code": null,
"e": 26516,
"s": 26442,
"text": "Create a drop-down list that options fetched from a MySQL database in PHP"
},
{
"code": null,
"e": 26558,
"s": 26516,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 26609,
"s": 26558,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 26665,
"s": 26609,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26698,
"s": 26665,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26760,
"s": 26698,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26803,
"s": 26760,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
ForkJoinPool Class in Java with Examples - GeeksforGeeks
|
07 Jun, 2021
The ForkJoinPool class is the center of the fork/join framework, which is an implementation of the ExecutorService interface. ForkJoinPool class is an extension of the AbstractExecutorService class, and it implements the work-stealing algorithm (i.e., worker threads that run out of things to do can steal tasks from other threads that are still busy) of fork/join framework and can execute ForkJoinTask processes.
The ForkJoinPool class inherits the following methods from java.util.concurrent.AbstractExecutorService class:
invokeAll()
invokeAny()
The ForkJoinPool class inherits the following methods from Methods inherited from class java.lang.Object class:
clone()
equals()
finalize()
getClass()
hashCode()
notify()
notifyAll()
wait()
Syntax:
public class ForkJoinPool extends AbstractExecutorService
Fork: Fork step splits the task into smaller subtasks and these tasks are executed concurrently.
Join: After the execution of the subtasks, the task may join all the results into one result.
This is illustrated in the diagram below:
Example:
getActiveThreadCount(): This method returns an estimated number of threads that are currently stealing or executing tasks. It may overestimate the number of active threads.
Syntax
public int getActiveThreadCount()
Java
// Java program to demonstrate the// Implementation of getActiveThreadCount() import java.util.ArrayList;import java.util.List;import java.util.concurrent.ForkJoinPool;import java.util.concurrent.RecursiveAction;class NewTask extends RecursiveAction{ private long Load = 0; public NewTask(long Load) { this.Load = Load; } protected void compute() { // fork tasks into smaller subtasks List<NewTask> subtasks = new ArrayList<NewTask>(); subtasks.addAll(createSubtasks()); for (RecursiveAction subtask : subtasks) { subtask.fork(); } } // function to create and add subtasks private List<NewTask> createSubtasks() { // create subtasks List<NewTask> subtasks = new ArrayList<NewTask>(); NewTask subtask1 = new NewTask(this.Load / 2); NewTask subtask2 = new NewTask(this.Load / 2); NewTask subtask3 = new NewTask(this.Load / 2); // to add the subtasks subtasks.add(subtask1); subtasks.add(subtask2); subtasks.add(subtask3); return subtasks; }}public class JavaForkJoingetActivethreadcountExample1 { public static void main(final String[] arguments) throws InterruptedException { // get no. of available core available int proc = Runtime.getRuntime().availableProcessors(); System.out.println("Number of available core in the processor is: " + proc); // get no. of threads active ForkJoinPool Pool = ForkJoinPool.commonPool(); System.out.println("Number of active thread before invoking: " + Pool.getActiveThreadCount()); NewTask t = new NewTask(400); Pool.invoke(t); System.out.println("Number of active thread after invoking: " + Pool.getActiveThreadCount()); System.out.println("Common Pool Size is: " + Pool.getPoolSize()); }}
Number of available core in the processor is: 4
Number of active thread before invoking: 0
Number of active thread after invoking: 3
Common Pool Size is: 3
METHOD
DESCRIPTION
kulpreetk2
Picked
Technical Scripter 2020
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors 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
PriorityQueue in Java
How to remove an element from ArrayList in Java?
|
[
{
"code": null,
"e": 25371,
"s": 25343,
"text": "\n07 Jun, 2021"
},
{
"code": null,
"e": 25786,
"s": 25371,
"text": "The ForkJoinPool class is the center of the fork/join framework, which is an implementation of the ExecutorService interface. ForkJoinPool class is an extension of the AbstractExecutorService class, and it implements the work-stealing algorithm (i.e., worker threads that run out of things to do can steal tasks from other threads that are still busy) of fork/join framework and can execute ForkJoinTask processes."
},
{
"code": null,
"e": 25897,
"s": 25786,
"text": "The ForkJoinPool class inherits the following methods from java.util.concurrent.AbstractExecutorService class:"
},
{
"code": null,
"e": 25909,
"s": 25897,
"text": "invokeAll()"
},
{
"code": null,
"e": 25921,
"s": 25909,
"text": "invokeAny()"
},
{
"code": null,
"e": 26033,
"s": 25921,
"text": "The ForkJoinPool class inherits the following methods from Methods inherited from class java.lang.Object class:"
},
{
"code": null,
"e": 26041,
"s": 26033,
"text": "clone()"
},
{
"code": null,
"e": 26050,
"s": 26041,
"text": "equals()"
},
{
"code": null,
"e": 26061,
"s": 26050,
"text": "finalize()"
},
{
"code": null,
"e": 26072,
"s": 26061,
"text": "getClass()"
},
{
"code": null,
"e": 26083,
"s": 26072,
"text": "hashCode()"
},
{
"code": null,
"e": 26092,
"s": 26083,
"text": "notify()"
},
{
"code": null,
"e": 26104,
"s": 26092,
"text": "notifyAll()"
},
{
"code": null,
"e": 26111,
"s": 26104,
"text": "wait()"
},
{
"code": null,
"e": 26119,
"s": 26111,
"text": "Syntax:"
},
{
"code": null,
"e": 26179,
"s": 26119,
"text": "public class ForkJoinPool extends AbstractExecutorService "
},
{
"code": null,
"e": 26277,
"s": 26179,
"text": "Fork: Fork step splits the task into smaller subtasks and these tasks are executed concurrently. "
},
{
"code": null,
"e": 26371,
"s": 26277,
"text": "Join: After the execution of the subtasks, the task may join all the results into one result."
},
{
"code": null,
"e": 26413,
"s": 26371,
"text": "This is illustrated in the diagram below:"
},
{
"code": null,
"e": 26422,
"s": 26413,
"text": "Example:"
},
{
"code": null,
"e": 26595,
"s": 26422,
"text": "getActiveThreadCount(): This method returns an estimated number of threads that are currently stealing or executing tasks. It may overestimate the number of active threads."
},
{
"code": null,
"e": 26602,
"s": 26595,
"text": "Syntax"
},
{
"code": null,
"e": 26636,
"s": 26602,
"text": "public int getActiveThreadCount()"
},
{
"code": null,
"e": 26641,
"s": 26636,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// Implementation of getActiveThreadCount() import java.util.ArrayList;import java.util.List;import java.util.concurrent.ForkJoinPool;import java.util.concurrent.RecursiveAction;class NewTask extends RecursiveAction{ private long Load = 0; public NewTask(long Load) { this.Load = Load; } protected void compute() { // fork tasks into smaller subtasks List<NewTask> subtasks = new ArrayList<NewTask>(); subtasks.addAll(createSubtasks()); for (RecursiveAction subtask : subtasks) { subtask.fork(); } } // function to create and add subtasks private List<NewTask> createSubtasks() { // create subtasks List<NewTask> subtasks = new ArrayList<NewTask>(); NewTask subtask1 = new NewTask(this.Load / 2); NewTask subtask2 = new NewTask(this.Load / 2); NewTask subtask3 = new NewTask(this.Load / 2); // to add the subtasks subtasks.add(subtask1); subtasks.add(subtask2); subtasks.add(subtask3); return subtasks; }}public class JavaForkJoingetActivethreadcountExample1 { public static void main(final String[] arguments) throws InterruptedException { // get no. of available core available int proc = Runtime.getRuntime().availableProcessors(); System.out.println(\"Number of available core in the processor is: \" + proc); // get no. of threads active ForkJoinPool Pool = ForkJoinPool.commonPool(); System.out.println(\"Number of active thread before invoking: \" + Pool.getActiveThreadCount()); NewTask t = new NewTask(400); Pool.invoke(t); System.out.println(\"Number of active thread after invoking: \" + Pool.getActiveThreadCount()); System.out.println(\"Common Pool Size is: \" + Pool.getPoolSize()); }}",
"e": 28655,
"s": 26641,
"text": null
},
{
"code": null,
"e": 28814,
"s": 28658,
"text": "Number of available core in the processor is: 4\nNumber of active thread before invoking: 0\nNumber of active thread after invoking: 3\nCommon Pool Size is: 3"
},
{
"code": null,
"e": 28821,
"s": 28814,
"text": "METHOD"
},
{
"code": null,
"e": 28833,
"s": 28821,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 28846,
"s": 28835,
"text": "kulpreetk2"
},
{
"code": null,
"e": 28853,
"s": 28846,
"text": "Picked"
},
{
"code": null,
"e": 28877,
"s": 28853,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28882,
"s": 28877,
"text": "Java"
},
{
"code": null,
"e": 28901,
"s": 28882,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28906,
"s": 28901,
"text": "Java"
},
{
"code": null,
"e": 29004,
"s": 28906,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29019,
"s": 29004,
"text": "Stream In Java"
},
{
"code": null,
"e": 29038,
"s": 29019,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29059,
"s": 29038,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29089,
"s": 29059,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29135,
"s": 29089,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29152,
"s": 29135,
"text": "Generics in Java"
},
{
"code": null,
"e": 29173,
"s": 29152,
"text": "Introduction to Java"
},
{
"code": null,
"e": 29216,
"s": 29173,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 29238,
"s": 29216,
"text": "PriorityQueue in Java"
}
] |
Python strftime() function
|
15 Mar, 2021
The strftime() function is used to convert date and time objects to their string representation. It takes one or more input of formatted code and returns the string representation.
Syntax :
strftime(format)
Returns : It returns the string representation of the date or time object.
List of format codes : Reference table for the format codes.
Example:
# Python program to demonstrate# strftime() function from datetime import datetime as dt # Getting current date and timenow = dt.now()print("Without formatting", now) # Example 1s = now.strftime("%a %m %y")print('\nExample 1:', s) # Example 2s = now.strftime("%A %-m %Y")print('\nExample 2:', s) # Example 3s = now.strftime("%-I %p %S")print('\nExample 3:', s) # Example 4s = now.strftime("%-j")print('\nExample 4:', s)
Output:
Without formatting 2019-12-17 18:21:39.211378
Example 1: Tue-12-19
Example 2: Tuesday-12-2019
Example 3: 6 PM 39
Example 4: 351
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Mar, 2021"
},
{
"code": null,
"e": 233,
"s": 52,
"text": "The strftime() function is used to convert date and time objects to their string representation. It takes one or more input of formatted code and returns the string representation."
},
{
"code": null,
"e": 242,
"s": 233,
"text": "Syntax :"
},
{
"code": null,
"e": 260,
"s": 242,
"text": "strftime(format)\n"
},
{
"code": null,
"e": 335,
"s": 260,
"text": "Returns : It returns the string representation of the date or time object."
},
{
"code": null,
"e": 396,
"s": 335,
"text": "List of format codes : Reference table for the format codes."
},
{
"code": null,
"e": 405,
"s": 396,
"text": "Example:"
},
{
"code": "# Python program to demonstrate# strftime() function from datetime import datetime as dt # Getting current date and timenow = dt.now()print(\"Without formatting\", now) # Example 1s = now.strftime(\"%a %m %y\")print('\\nExample 1:', s) # Example 2s = now.strftime(\"%A %-m %Y\")print('\\nExample 2:', s) # Example 3s = now.strftime(\"%-I %p %S\")print('\\nExample 3:', s) # Example 4s = now.strftime(\"%-j\")print('\\nExample 4:', s)",
"e": 833,
"s": 405,
"text": null
},
{
"code": null,
"e": 841,
"s": 833,
"text": "Output:"
},
{
"code": null,
"e": 974,
"s": 841,
"text": "Without formatting 2019-12-17 18:21:39.211378\n\nExample 1: Tue-12-19\n\nExample 2: Tuesday-12-2019\n\nExample 3: 6 PM 39\n\nExample 4: 351\n"
},
{
"code": null,
"e": 990,
"s": 974,
"text": "Python-datetime"
},
{
"code": null,
"e": 997,
"s": 990,
"text": "Python"
},
{
"code": null,
"e": 1095,
"s": 997,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1113,
"s": 1095,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1155,
"s": 1113,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1177,
"s": 1155,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1209,
"s": 1177,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1238,
"s": 1209,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1265,
"s": 1238,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1286,
"s": 1265,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1309,
"s": 1286,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1345,
"s": 1309,
"text": "Convert integer to string in Python"
}
] |
Inserting Records in Batch Using JDBC
|
07 Jul, 2021
It is carried out using the functions namely addBatch() and executeBatch() methods. For that lets us do have a prior understanding of JDBC drivers. So, in order to connect to your database in Java, you need a JDBC driver. Every database (MySQL, Oracle, etc.) comes with its own JDBC driver, usually built by the database vendor and found on the database’s website. Considering the example of the MySQL database, you will need to go to the MySQL website, download the MySQL JDBC driver .jar file (also called Connector/J), and add it to your project.
Now let’s discuss the methods that they operate on. So, the above two methods namely addBatch() and executeBatch() method is as follows:
Method 1: addBatch()
This method adds the parameter values to the batch internally. You can now add another set of values, to be inserted into the SQL statement. Each set of parameters are inserted into the SQL and executed separately, once the full batch is sent to the database.
Method 2: executeBatch()
This method is called, which executes all the batch updates. The SQL statement plus the parameter sets are sent to the database in one go. The int[] array returned by the executeBatch() method is an array of int telling how many records were affected by each executed SQL statement in the batch.
Syntax: Creation of the database
create table emp(eid varchar(200) unique,ename varchar(200)
Example:
Java
// Step 1: Importing DB(SQL) classesimport java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;import java.sql.Statement; // Classpublic class insertion { // Main driver method public static void main(String[] args) throws Exception { // Try block to check for exceptions try { // Step 2: Loading and registering drivers // Loading drivers using forName() method Class.forName("com.mysql.jdbc.Driver"); // Registering driver using DriverManager Connection con = DriverManager.getConnection( "jdbc:mysql://localhost/test", "root", ""); // Step 3: Create a statement Statement st = con.createStatement(); String sql = "insert into emp (eid,ename) values (?, ?)"; // Step 4: Execute the query PreparedStatement pstmt; pstmt = con.prepareStatement(sql); final int batchSize = 5000; int count = 0; for (int i = 4000; i <= 4500; i++) { pstmt.setString(1, "181FA0" + i); pstmt.setString(2, "181FA0" + i); pstmt.addBatch(); count++; if (count % batchSize == 0) { System.out.println("Commit the batch"); pstmt.executeBatch(); } pstmt.executeBatch(); } } catch (Exception e) { System.out.println("Error:" + e.getMessage()); } }}
Output:
simranarora5sos
JDBC
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Jul, 2021"
},
{
"code": null,
"e": 602,
"s": 52,
"text": "It is carried out using the functions namely addBatch() and executeBatch() methods. For that lets us do have a prior understanding of JDBC drivers. So, in order to connect to your database in Java, you need a JDBC driver. Every database (MySQL, Oracle, etc.) comes with its own JDBC driver, usually built by the database vendor and found on the database’s website. Considering the example of the MySQL database, you will need to go to the MySQL website, download the MySQL JDBC driver .jar file (also called Connector/J), and add it to your project."
},
{
"code": null,
"e": 739,
"s": 602,
"text": "Now let’s discuss the methods that they operate on. So, the above two methods namely addBatch() and executeBatch() method is as follows:"
},
{
"code": null,
"e": 760,
"s": 739,
"text": "Method 1: addBatch()"
},
{
"code": null,
"e": 1020,
"s": 760,
"text": "This method adds the parameter values to the batch internally. You can now add another set of values, to be inserted into the SQL statement. Each set of parameters are inserted into the SQL and executed separately, once the full batch is sent to the database."
},
{
"code": null,
"e": 1045,
"s": 1020,
"text": "Method 2: executeBatch()"
},
{
"code": null,
"e": 1341,
"s": 1045,
"text": "This method is called, which executes all the batch updates. The SQL statement plus the parameter sets are sent to the database in one go. The int[] array returned by the executeBatch() method is an array of int telling how many records were affected by each executed SQL statement in the batch."
},
{
"code": null,
"e": 1375,
"s": 1341,
"text": "Syntax: Creation of the database "
},
{
"code": null,
"e": 1435,
"s": 1375,
"text": "create table emp(eid varchar(200) unique,ename varchar(200)"
},
{
"code": null,
"e": 1444,
"s": 1435,
"text": "Example:"
},
{
"code": null,
"e": 1449,
"s": 1444,
"text": "Java"
},
{
"code": "// Step 1: Importing DB(SQL) classesimport java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;import java.sql.Statement; // Classpublic class insertion { // Main driver method public static void main(String[] args) throws Exception { // Try block to check for exceptions try { // Step 2: Loading and registering drivers // Loading drivers using forName() method Class.forName(\"com.mysql.jdbc.Driver\"); // Registering driver using DriverManager Connection con = DriverManager.getConnection( \"jdbc:mysql://localhost/test\", \"root\", \"\"); // Step 3: Create a statement Statement st = con.createStatement(); String sql = \"insert into emp (eid,ename) values (?, ?)\"; // Step 4: Execute the query PreparedStatement pstmt; pstmt = con.prepareStatement(sql); final int batchSize = 5000; int count = 0; for (int i = 4000; i <= 4500; i++) { pstmt.setString(1, \"181FA0\" + i); pstmt.setString(2, \"181FA0\" + i); pstmt.addBatch(); count++; if (count % batchSize == 0) { System.out.println(\"Commit the batch\"); pstmt.executeBatch(); } pstmt.executeBatch(); } } catch (Exception e) { System.out.println(\"Error:\" + e.getMessage()); } }}",
"e": 3035,
"s": 1449,
"text": null
},
{
"code": null,
"e": 3047,
"s": 3039,
"text": "Output:"
},
{
"code": null,
"e": 3067,
"s": 3051,
"text": "simranarora5sos"
},
{
"code": null,
"e": 3072,
"s": 3067,
"text": "JDBC"
},
{
"code": null,
"e": 3077,
"s": 3072,
"text": "Java"
},
{
"code": null,
"e": 3082,
"s": 3077,
"text": "Java"
}
] |
How to remove global CSS file from a particular page using jQuery ?
|
01 Feb, 2021
This article describes the approach to remove a global CSS file from a page. It can be used in scenarios where a template might have a global CSS file included and you need to remove the file so that any other CSS file takes effect. We will see this in the example below:
Consider the index.html file with two CSS file imports, the global.css with the id of “one“ and a second page.css with the id of “two“. The global.css is the file that remains across all pages and page.css is the file for a particular page.
The code below is for the index.html file. Both the global.css and page.css files are included for demonstration.
HTML
<!DOCTYPE html><html> <head> <!-- CSS --> <link id="one" type="text/css" rel="stylesheet" href="global.css" /> <link id="two" type="text/css" rel="stylesheet" href="page.css" /></head> <body> <h1>GeeksForGeeks</h1> <h2>Welcome to GeeksForGeeks</h2> <div id="para-one"> <p> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and questions. A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and questions. </p> </div> <div id="para-two"> <p> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and questions. A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and questions. </p> </div></body> </html>
CSS Files: global.css file
p {
color: red;
text-align: center;
}
h3 {
color: chocolate;
text-align: center;
}
body {
background-color: rgb(178, 248, 248);
}
The below code is the page.css file.
h1 {
color: green;
text-align: center;
}
h2 {
text-align: center;
}
p {
color: magenta;
}
Output: This is the Index.html with global.css and page.css files.
Approach: We will create a script that will find the global stylesheet with the id of “one” and will remove it from the head section. The find() and remove() methods of jQuery are used for this purpose. This is demonstrated in the example given below:
jQuery
<script> $(document).ready(function() { // Find the stylesheet with id of 'one' // and remove it from the document $('head').find('link#one').remove(); });</script>
Final Code:
HTML
<!DOCTYPE html><html> <head> <!-- CSS --> <link id="one" type="text/css" rel="stylesheet" href="global.css" /> <link id="two" type="text/css" rel="stylesheet" href="page.css" /> <!-- Jquery --> <script src= "https://code.jquery.com/jquery-3.5.1.min.js"> </script> <script> $(document).ready(function() { $('head').find('link#one').remove(); }); </script></head> <body> <h1>GeeksForGeeks</h1> <h2>Welcome to GeeksForGeeks</h2> <div id="para-one"> <p> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and questions. A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and questions. </p> </div> <div id="para-two"> <p> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and questions. A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and questions. </p> </div></body> </html>
Output: This is an index page after the global.css removal.
CSS-Misc
HTML-Misc
jQuery-Misc
Picked
CSS
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Feb, 2021"
},
{
"code": null,
"e": 301,
"s": 28,
"text": "This article describes the approach to remove a global CSS file from a page. It can be used in scenarios where a template might have a global CSS file included and you need to remove the file so that any other CSS file takes effect. We will see this in the example below: "
},
{
"code": null,
"e": 542,
"s": 301,
"text": "Consider the index.html file with two CSS file imports, the global.css with the id of “one“ and a second page.css with the id of “two“. The global.css is the file that remains across all pages and page.css is the file for a particular page."
},
{
"code": null,
"e": 656,
"s": 542,
"text": "The code below is for the index.html file. Both the global.css and page.css files are included for demonstration."
},
{
"code": null,
"e": 661,
"s": 656,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- CSS --> <link id=\"one\" type=\"text/css\" rel=\"stylesheet\" href=\"global.css\" /> <link id=\"two\" type=\"text/css\" rel=\"stylesheet\" href=\"page.css\" /></head> <body> <h1>GeeksForGeeks</h1> <h2>Welcome to GeeksForGeeks</h2> <div id=\"para-one\"> <p> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and questions. A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and questions. </p> </div> <div id=\"para-two\"> <p> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and questions. A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and questions. </p> </div></body> </html>",
"e": 1961,
"s": 661,
"text": null
},
{
"code": null,
"e": 1988,
"s": 1961,
"text": "CSS Files: global.css file"
},
{
"code": null,
"e": 2140,
"s": 1988,
"text": "p {\n color: red;\n text-align: center;\n}\n\nh3 {\n color: chocolate;\n text-align: center;\n}\n\nbody {\n background-color: rgb(178, 248, 248);\n}"
},
{
"code": null,
"e": 2177,
"s": 2140,
"text": "The below code is the page.css file."
},
{
"code": null,
"e": 2285,
"s": 2177,
"text": "h1 {\n color: green;\n text-align: center;\n}\n\nh2 {\n text-align: center;\n}\n\np {\n color: magenta;\n}"
},
{
"code": null,
"e": 2352,
"s": 2285,
"text": "Output: This is the Index.html with global.css and page.css files."
},
{
"code": null,
"e": 2604,
"s": 2352,
"text": "Approach: We will create a script that will find the global stylesheet with the id of “one” and will remove it from the head section. The find() and remove() methods of jQuery are used for this purpose. This is demonstrated in the example given below:"
},
{
"code": null,
"e": 2611,
"s": 2604,
"text": "jQuery"
},
{
"code": "<script> $(document).ready(function() { // Find the stylesheet with id of 'one' // and remove it from the document $('head').find('link#one').remove(); });</script>",
"e": 2793,
"s": 2611,
"text": null
},
{
"code": null,
"e": 2805,
"s": 2793,
"text": "Final Code:"
},
{
"code": null,
"e": 2810,
"s": 2805,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- CSS --> <link id=\"one\" type=\"text/css\" rel=\"stylesheet\" href=\"global.css\" /> <link id=\"two\" type=\"text/css\" rel=\"stylesheet\" href=\"page.css\" /> <!-- Jquery --> <script src= \"https://code.jquery.com/jquery-3.5.1.min.js\"> </script> <script> $(document).ready(function() { $('head').find('link#one').remove(); }); </script></head> <body> <h1>GeeksForGeeks</h1> <h2>Welcome to GeeksForGeeks</h2> <div id=\"para-one\"> <p> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and questions. A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and questions. </p> </div> <div id=\"para-two\"> <p> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and questions. A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and questions. </p> </div></body> </html>",
"e": 4339,
"s": 2810,
"text": null
},
{
"code": null,
"e": 4399,
"s": 4339,
"text": "Output: This is an index page after the global.css removal."
},
{
"code": null,
"e": 4408,
"s": 4399,
"text": "CSS-Misc"
},
{
"code": null,
"e": 4418,
"s": 4408,
"text": "HTML-Misc"
},
{
"code": null,
"e": 4430,
"s": 4418,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 4437,
"s": 4430,
"text": "Picked"
},
{
"code": null,
"e": 4441,
"s": 4437,
"text": "CSS"
},
{
"code": null,
"e": 4446,
"s": 4441,
"text": "HTML"
},
{
"code": null,
"e": 4453,
"s": 4446,
"text": "JQuery"
},
{
"code": null,
"e": 4470,
"s": 4453,
"text": "Web Technologies"
},
{
"code": null,
"e": 4475,
"s": 4470,
"text": "HTML"
}
] |
Remove extra delimiter from a String in Java
|
11 Dec, 2018
Given a String with extra delimiter at the end, the task is to remove this extra delimiter in Java.
Examples:
Input: String = "Geeks, For, Geeks, ", delimiter = ', '
Output: "Geeks, For, Geeks"
Input: String = "G.e.e.k.s.", delimiter = '.'
Output: "G.e.e.k.s"
Approach:
Get the String.Get the last index of the delimiter using lastIndexOf() method.Construct a new String with the 2 different substrings: one from beginning till the found index – 1, and the other from the index + 1 till the end.Below is the implementation of the above approach:// Java program to remove// extra delimiter at the end of a String public class GFG { public static void main(String args[]) { // Get the String String str = "Geeks, For, Geeks,"; // Get the delimiter char delimiter = ','; // Print the original string System.out.println("Original String: " + str); // Get the index of delimiter int index = str.lastIndexOf(delimiter); // Remove the extra delimiter by skipping it str = str.substring(0, index) + str.substring(index + 1); // Print the new String System.out.println("String with extra " + "delimiter removed: " + str); }}Output:Original String: Geeks, For, Geeks,
String with extra delimiter removed: Geeks, For, Geeks
My Personal Notes
arrow_drop_upSave
Get the String.
Get the last index of the delimiter using lastIndexOf() method.
Construct a new String with the 2 different substrings: one from beginning till the found index – 1, and the other from the index + 1 till the end.Below is the implementation of the above approach:// Java program to remove// extra delimiter at the end of a String public class GFG { public static void main(String args[]) { // Get the String String str = "Geeks, For, Geeks,"; // Get the delimiter char delimiter = ','; // Print the original string System.out.println("Original String: " + str); // Get the index of delimiter int index = str.lastIndexOf(delimiter); // Remove the extra delimiter by skipping it str = str.substring(0, index) + str.substring(index + 1); // Print the new String System.out.println("String with extra " + "delimiter removed: " + str); }}Output:Original String: Geeks, For, Geeks,
String with extra delimiter removed: Geeks, For, Geeks
My Personal Notes
arrow_drop_upSave
Below is the implementation of the above approach:
// Java program to remove// extra delimiter at the end of a String public class GFG { public static void main(String args[]) { // Get the String String str = "Geeks, For, Geeks,"; // Get the delimiter char delimiter = ','; // Print the original string System.out.println("Original String: " + str); // Get the index of delimiter int index = str.lastIndexOf(delimiter); // Remove the extra delimiter by skipping it str = str.substring(0, index) + str.substring(index + 1); // Print the new String System.out.println("String with extra " + "delimiter removed: " + str); }}
Original String: Geeks, For, Geeks,
String with extra delimiter removed: Geeks, For, Geeks
Java-lang package
Java-String-Programs
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 128,
"s": 28,
"text": "Given a String with extra delimiter at the end, the task is to remove this extra delimiter in Java."
},
{
"code": null,
"e": 138,
"s": 128,
"text": "Examples:"
},
{
"code": null,
"e": 290,
"s": 138,
"text": "Input: String = \"Geeks, For, Geeks, \", delimiter = ', '\nOutput: \"Geeks, For, Geeks\"\n\nInput: String = \"G.e.e.k.s.\", delimiter = '.'\nOutput: \"G.e.e.k.s\"\n"
},
{
"code": null,
"e": 300,
"s": 290,
"text": "Approach:"
},
{
"code": null,
"e": 1479,
"s": 300,
"text": "Get the String.Get the last index of the delimiter using lastIndexOf() method.Construct a new String with the 2 different substrings: one from beginning till the found index – 1, and the other from the index + 1 till the end.Below is the implementation of the above approach:// Java program to remove// extra delimiter at the end of a String public class GFG { public static void main(String args[]) { // Get the String String str = \"Geeks, For, Geeks,\"; // Get the delimiter char delimiter = ','; // Print the original string System.out.println(\"Original String: \" + str); // Get the index of delimiter int index = str.lastIndexOf(delimiter); // Remove the extra delimiter by skipping it str = str.substring(0, index) + str.substring(index + 1); // Print the new String System.out.println(\"String with extra \" + \"delimiter removed: \" + str); }}Output:Original String: Geeks, For, Geeks,\nString with extra delimiter removed: Geeks, For, Geeks\nMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 1495,
"s": 1479,
"text": "Get the String."
},
{
"code": null,
"e": 1559,
"s": 1495,
"text": "Get the last index of the delimiter using lastIndexOf() method."
},
{
"code": null,
"e": 2660,
"s": 1559,
"text": "Construct a new String with the 2 different substrings: one from beginning till the found index – 1, and the other from the index + 1 till the end.Below is the implementation of the above approach:// Java program to remove// extra delimiter at the end of a String public class GFG { public static void main(String args[]) { // Get the String String str = \"Geeks, For, Geeks,\"; // Get the delimiter char delimiter = ','; // Print the original string System.out.println(\"Original String: \" + str); // Get the index of delimiter int index = str.lastIndexOf(delimiter); // Remove the extra delimiter by skipping it str = str.substring(0, index) + str.substring(index + 1); // Print the new String System.out.println(\"String with extra \" + \"delimiter removed: \" + str); }}Output:Original String: Geeks, For, Geeks,\nString with extra delimiter removed: Geeks, For, Geeks\nMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 2711,
"s": 2660,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// Java program to remove// extra delimiter at the end of a String public class GFG { public static void main(String args[]) { // Get the String String str = \"Geeks, For, Geeks,\"; // Get the delimiter char delimiter = ','; // Print the original string System.out.println(\"Original String: \" + str); // Get the index of delimiter int index = str.lastIndexOf(delimiter); // Remove the extra delimiter by skipping it str = str.substring(0, index) + str.substring(index + 1); // Print the new String System.out.println(\"String with extra \" + \"delimiter removed: \" + str); }}",
"e": 3482,
"s": 2711,
"text": null
},
{
"code": null,
"e": 3574,
"s": 3482,
"text": "Original String: Geeks, For, Geeks,\nString with extra delimiter removed: Geeks, For, Geeks\n"
},
{
"code": null,
"e": 3592,
"s": 3574,
"text": "Java-lang package"
},
{
"code": null,
"e": 3613,
"s": 3592,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 3626,
"s": 3613,
"text": "Java-Strings"
},
{
"code": null,
"e": 3631,
"s": 3626,
"text": "Java"
},
{
"code": null,
"e": 3644,
"s": 3631,
"text": "Java-Strings"
},
{
"code": null,
"e": 3649,
"s": 3644,
"text": "Java"
},
{
"code": null,
"e": 3747,
"s": 3649,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3762,
"s": 3747,
"text": "Stream In Java"
},
{
"code": null,
"e": 3783,
"s": 3762,
"text": "Introduction to Java"
},
{
"code": null,
"e": 3804,
"s": 3783,
"text": "Constructors in Java"
},
{
"code": null,
"e": 3823,
"s": 3804,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 3840,
"s": 3823,
"text": "Generics in Java"
},
{
"code": null,
"e": 3870,
"s": 3840,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 3896,
"s": 3870,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 3912,
"s": 3896,
"text": "Strings in Java"
},
{
"code": null,
"e": 3949,
"s": 3912,
"text": "Differences between JDK, JRE and JVM"
}
] |
How to Display all Threads Status in Java?
|
24 Feb, 2022
Threads are light-weight processes within a process.. Multithreading in java is a feature that allows concurrent execution of two or more parts of a program to maximize the utilization of CPU. here the approach to retrieve the state of the thread is via getState() method of the Thread class. A java thread can exist in any one of the following states, the status of a thread is the state in which it exists at a given instance. The life cycle of a thread as shown above is the best way out to learn more about the states where the states are as follows:
New
Runnable
Blocked
Waiting
Timed Waiting
Terminated
Note: When a thread is getting executed all other threads are in blocking state and not in waiting state.
Procedure: Displaying thread status
Threads are created by implementing the runnable interface.The status of a thread can be retrieved by getState() method of the Thread class object.
Threads are created by implementing the runnable interface.
The status of a thread can be retrieved by getState() method of the Thread class object.
Example:
Java
// Java Program to Display all Threads Status // Importing Set class from java.util packageimport java.util.Set; // Class 1// helper Class implementing Runnable interfaceclass MyThread implements Runnable { // run() method whenever thread is invoked public void run() { // Try block to check for exceptions try { // making thread to Thread.sleep(2000); } // Catch block to handle the exceptions catch (Exception err) { // Print the exception System.out.println(err); } }} // Class 2// Main Class to check thread statuspublic class GFG { // Main driver method public static void main(String args[]) throws Exception { // Iterating to create multiple threads // Customly creating 5 threads for (int thread_num = 0; thread_num < 5; thread_num++) { // Creating single thread object Thread t = new Thread(new MyThread()); // Setting name of the particular thread // using setName() method t.setName("MyThread:" + thread_num); // Starting the current thread // using start() method t.start(); } // Creating set object to hold all the threads where // Thread.getAllStackTraces().keySet() returns // all threads including application threads and // system threads Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); // Now, for loop is used to iterate through the // threadset for (Thread t : threadSet) { // Printing the thread status using getState() // method System.out.println("Thread :" + t + ":" + "Thread status : " + t.getState()); } }}
Output:
kapoorsagar226
rajeev0719singh
sagar0719kumar
surinderdawra388
Java-Multithreading
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Queue Interface In Java
Stack Class in Java
Interfaces in Java
ArrayList in Java
Collections in Java
Initializing a List in Java
Java Programming Examples
Convert a String to Character Array in Java
Implementing a Linked List in Java using Class
Convert Double to Integer in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Feb, 2022"
},
{
"code": null,
"e": 583,
"s": 28,
"text": "Threads are light-weight processes within a process.. Multithreading in java is a feature that allows concurrent execution of two or more parts of a program to maximize the utilization of CPU. here the approach to retrieve the state of the thread is via getState() method of the Thread class. A java thread can exist in any one of the following states, the status of a thread is the state in which it exists at a given instance. The life cycle of a thread as shown above is the best way out to learn more about the states where the states are as follows:"
},
{
"code": null,
"e": 587,
"s": 583,
"text": "New"
},
{
"code": null,
"e": 596,
"s": 587,
"text": "Runnable"
},
{
"code": null,
"e": 604,
"s": 596,
"text": "Blocked"
},
{
"code": null,
"e": 612,
"s": 604,
"text": "Waiting"
},
{
"code": null,
"e": 626,
"s": 612,
"text": "Timed Waiting"
},
{
"code": null,
"e": 637,
"s": 626,
"text": "Terminated"
},
{
"code": null,
"e": 743,
"s": 637,
"text": "Note: When a thread is getting executed all other threads are in blocking state and not in waiting state."
},
{
"code": null,
"e": 779,
"s": 743,
"text": "Procedure: Displaying thread status"
},
{
"code": null,
"e": 927,
"s": 779,
"text": "Threads are created by implementing the runnable interface.The status of a thread can be retrieved by getState() method of the Thread class object."
},
{
"code": null,
"e": 987,
"s": 927,
"text": "Threads are created by implementing the runnable interface."
},
{
"code": null,
"e": 1076,
"s": 987,
"text": "The status of a thread can be retrieved by getState() method of the Thread class object."
},
{
"code": null,
"e": 1085,
"s": 1076,
"text": "Example:"
},
{
"code": null,
"e": 1090,
"s": 1085,
"text": "Java"
},
{
"code": "// Java Program to Display all Threads Status // Importing Set class from java.util packageimport java.util.Set; // Class 1// helper Class implementing Runnable interfaceclass MyThread implements Runnable { // run() method whenever thread is invoked public void run() { // Try block to check for exceptions try { // making thread to Thread.sleep(2000); } // Catch block to handle the exceptions catch (Exception err) { // Print the exception System.out.println(err); } }} // Class 2// Main Class to check thread statuspublic class GFG { // Main driver method public static void main(String args[]) throws Exception { // Iterating to create multiple threads // Customly creating 5 threads for (int thread_num = 0; thread_num < 5; thread_num++) { // Creating single thread object Thread t = new Thread(new MyThread()); // Setting name of the particular thread // using setName() method t.setName(\"MyThread:\" + thread_num); // Starting the current thread // using start() method t.start(); } // Creating set object to hold all the threads where // Thread.getAllStackTraces().keySet() returns // all threads including application threads and // system threads Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); // Now, for loop is used to iterate through the // threadset for (Thread t : threadSet) { // Printing the thread status using getState() // method System.out.println(\"Thread :\" + t + \":\" + \"Thread status : \" + t.getState()); } }}",
"e": 2955,
"s": 1090,
"text": null
},
{
"code": null,
"e": 2966,
"s": 2955,
"text": " Output: "
},
{
"code": null,
"e": 2981,
"s": 2966,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 2997,
"s": 2981,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 3012,
"s": 2997,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 3029,
"s": 3012,
"text": "surinderdawra388"
},
{
"code": null,
"e": 3049,
"s": 3029,
"text": "Java-Multithreading"
},
{
"code": null,
"e": 3056,
"s": 3049,
"text": "Picked"
},
{
"code": null,
"e": 3061,
"s": 3056,
"text": "Java"
},
{
"code": null,
"e": 3075,
"s": 3061,
"text": "Java Programs"
},
{
"code": null,
"e": 3080,
"s": 3075,
"text": "Java"
},
{
"code": null,
"e": 3178,
"s": 3080,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3202,
"s": 3178,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 3222,
"s": 3202,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 3241,
"s": 3222,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3259,
"s": 3241,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3279,
"s": 3259,
"text": "Collections in Java"
},
{
"code": null,
"e": 3307,
"s": 3279,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 3333,
"s": 3307,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 3377,
"s": 3333,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 3424,
"s": 3377,
"text": "Implementing a Linked List in Java using Class"
}
] |
Dangling, Void , Null and Wild Pointers
|
15 Jun, 2022
Dangling pointer
A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer. There are three different ways where Pointer acts as dangling pointer
De-allocation of memory
De-allocation of memory
C++
C
// Deallocating a memory pointed by ptr causes// dangling pointer #include <cstdlib>#include <iostream> int main(){ int* ptr = (int *)malloc(sizeof(int)); // After below free call, ptr becomes a // dangling pointer free(ptr); // No more a dangling pointer ptr = NULL;} // This code is contributed by sarajadhav12052009
// Deallocating a memory pointed by ptr causes// dangling pointer#include <stdlib.h>#include <stdio.h> int main(){ int *ptr = (int *)malloc(sizeof(int)); // After below free call, ptr becomes a // dangling pointer free(ptr); // No more a dangling pointer ptr = NULL;}
Function Call
Function Call
C++
C
// The pointer pointing to local variable becomes// dangling when local variable is not static. #include <iostream> int* fun(){ // x is local variable and goes out of // scope after an execution of fun() is // over. int x = 5; return &x;} // Driver Codeint main(){ int *p = fun(); fflush(stdin); // p points to something which is not // valid anymore std::cout << *p; return 0;} // This code is contributed by sarajadhav12052009
// The pointer pointing to local variable becomes// dangling when local variable is not static.#include<stdio.h> int *fun(){ // x is local variable and goes out of // scope after an execution of fun() is // over. int x = 5; return &x;} // Driver Codeint main(){ int *p = fun(); fflush(stdin); // p points to something which is not // valid anymore printf("%d", *p); return 0;}
Output:
Output:
A garbage Address
The above problem doesn’t appear (or p doesn’t become dangling) if x is a static variable.
The above problem doesn’t appear (or p doesn’t become dangling) if x is a static variable.
C++
C
// The pointer pointing to local variable doesn't// become dangling when local variable is static. #include <iostream>using namespace std; int *fun(){ // x now has scope throughout the program static int x = 5; return &x;} int main(){ int *p = fun(); fflush(stdin); // Not a dangling pointer as it points // to static variable. cout << *p; return 0;} // This code is contributed by sarajadhav12052009
// The pointer pointing to local variable doesn't// become dangling when local variable is static.#include <stdio.h> int *fun(){ // x now has scope throughout the program static int x = 5; return &x;} int main(){ int *p = fun(); fflush(stdin); // Not a dangling pointer as it points // to static variable. printf("%d",*p);}
Output:
Output:
5
Variable goes out of scope
Variable goes out of scope
void main()
{
int *ptr;
.....
.....
{
int ch;
ptr = &ch;
}
.....
// Here ptr is dangling pointer
}
Void pointer
Void pointer is a specific pointer type – void * – a pointer that points to some data location in storage, which doesn’t have any specific type. Void refers to the type. Basically the type of data that it points to is can be any. If we assign address of char data type to void pointer it will become char Pointer, if int data type then int pointer and so on. Any pointer type is convertible to a void pointer hence it can point to any value. Important Points
void pointers cannot be dereferenced. It can however be done using typecasting the void pointerPointer arithmetic is not possible on pointers of void due to lack of concrete value and thus size.
void pointers cannot be dereferenced. It can however be done using typecasting the void pointer
Pointer arithmetic is not possible on pointers of void due to lack of concrete value and thus size.
Example:
CPP
#include<stdlib.h> int main(){ int x = 4; float y = 5.5; //A void pointer void *ptr; ptr = &x; // (int*)ptr - does type casting of void // *((int*)ptr) dereferences the typecasted // void pointer variable. printf("Integer variable is = %d", *( (int*) ptr) ); // void pointer is now float ptr = &y; printf("\nFloat variable is= %f", *( (float*) ptr) ); return 0;}
Output:
Integer variable is = 4
Float variable is= 5.500000
Refer void pointer article for details.
NULL Pointer
NULL Pointer is a pointer which is pointing to nothing. In case, if we don’t have address to be assigned to a pointer, then we can simply use NULL.
C++
C
#include <iostream>using namespace std; int main(){ // Null Pointer int *ptr = NULL; cout << "The value of ptr is " << ptr; return 0;} // This code is contributed by sarajadhav12052009
#include <stdio.h>int main(){ // Null Pointer int *ptr = NULL; printf("The value of ptr is %p", ptr); return 0;}
Output :
The value of ptr is (nil)
Important Points
NULL vs Uninitialized pointer – An uninitialized pointer stores an undefined value. A null pointer stores a defined value, but one that is defined by the environment to not be a valid address for any member or object.NULL vs Void Pointer – Null pointer is a value, while void pointer is a type
NULL vs Uninitialized pointer – An uninitialized pointer stores an undefined value. A null pointer stores a defined value, but one that is defined by the environment to not be a valid address for any member or object.
NULL vs Void Pointer – Null pointer is a value, while void pointer is a type
Wild pointer
A pointer which has not been initialized to anything (not even NULL) is known as wild pointer. The pointer may be initialized to a non-NULL garbage value that may not be a valid address.
CPP
int main(){ int *p; /* wild pointer */ int x = 10; // p is not a wild pointer now p = &x; return 0;}
This article is contributed by Spoorthi Arun. 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.
ashoklb
sharathmaidargi
sarajadhav12052009
C-Pointers
cpp-pointer
C Language
C++
School Programming
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Jun, 2022"
},
{
"code": null,
"e": 69,
"s": 52,
"text": "Dangling pointer"
},
{
"code": null,
"e": 240,
"s": 69,
"text": "A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer. There are three different ways where Pointer acts as dangling pointer"
},
{
"code": null,
"e": 265,
"s": 240,
"text": "De-allocation of memory "
},
{
"code": null,
"e": 290,
"s": 265,
"text": "De-allocation of memory "
},
{
"code": null,
"e": 294,
"s": 290,
"text": "C++"
},
{
"code": null,
"e": 296,
"s": 294,
"text": "C"
},
{
"code": "// Deallocating a memory pointed by ptr causes// dangling pointer #include <cstdlib>#include <iostream> int main(){ int* ptr = (int *)malloc(sizeof(int)); // After below free call, ptr becomes a // dangling pointer free(ptr); // No more a dangling pointer ptr = NULL;} // This code is contributed by sarajadhav12052009",
"e": 639,
"s": 296,
"text": null
},
{
"code": "// Deallocating a memory pointed by ptr causes// dangling pointer#include <stdlib.h>#include <stdio.h> int main(){ int *ptr = (int *)malloc(sizeof(int)); // After below free call, ptr becomes a // dangling pointer free(ptr); // No more a dangling pointer ptr = NULL;}",
"e": 931,
"s": 639,
"text": null
},
{
"code": null,
"e": 946,
"s": 931,
"text": "Function Call "
},
{
"code": null,
"e": 961,
"s": 946,
"text": "Function Call "
},
{
"code": null,
"e": 965,
"s": 961,
"text": "C++"
},
{
"code": null,
"e": 967,
"s": 965,
"text": "C"
},
{
"code": "// The pointer pointing to local variable becomes// dangling when local variable is not static. #include <iostream> int* fun(){ // x is local variable and goes out of // scope after an execution of fun() is // over. int x = 5; return &x;} // Driver Codeint main(){ int *p = fun(); fflush(stdin); // p points to something which is not // valid anymore std::cout << *p; return 0;} // This code is contributed by sarajadhav12052009",
"e": 1442,
"s": 967,
"text": null
},
{
"code": "// The pointer pointing to local variable becomes// dangling when local variable is not static.#include<stdio.h> int *fun(){ // x is local variable and goes out of // scope after an execution of fun() is // over. int x = 5; return &x;} // Driver Codeint main(){ int *p = fun(); fflush(stdin); // p points to something which is not // valid anymore printf(\"%d\", *p); return 0;}",
"e": 1862,
"s": 1442,
"text": null
},
{
"code": null,
"e": 1870,
"s": 1862,
"text": "Output:"
},
{
"code": null,
"e": 1878,
"s": 1870,
"text": "Output:"
},
{
"code": null,
"e": 1896,
"s": 1878,
"text": "A garbage Address"
},
{
"code": null,
"e": 1988,
"s": 1896,
"text": "The above problem doesn’t appear (or p doesn’t become dangling) if x is a static variable. "
},
{
"code": null,
"e": 2080,
"s": 1988,
"text": "The above problem doesn’t appear (or p doesn’t become dangling) if x is a static variable. "
},
{
"code": null,
"e": 2084,
"s": 2080,
"text": "C++"
},
{
"code": null,
"e": 2086,
"s": 2084,
"text": "C"
},
{
"code": "// The pointer pointing to local variable doesn't// become dangling when local variable is static. #include <iostream>using namespace std; int *fun(){ // x now has scope throughout the program static int x = 5; return &x;} int main(){ int *p = fun(); fflush(stdin); // Not a dangling pointer as it points // to static variable. cout << *p; return 0;} // This code is contributed by sarajadhav12052009",
"e": 2525,
"s": 2086,
"text": null
},
{
"code": "// The pointer pointing to local variable doesn't// become dangling when local variable is static.#include <stdio.h> int *fun(){ // x now has scope throughout the program static int x = 5; return &x;} int main(){ int *p = fun(); fflush(stdin); // Not a dangling pointer as it points // to static variable. printf(\"%d\",*p);}",
"e": 2879,
"s": 2525,
"text": null
},
{
"code": null,
"e": 2887,
"s": 2879,
"text": "Output:"
},
{
"code": null,
"e": 2895,
"s": 2887,
"text": "Output:"
},
{
"code": null,
"e": 2898,
"s": 2895,
"text": " 5"
},
{
"code": null,
"e": 2926,
"s": 2898,
"text": "Variable goes out of scope "
},
{
"code": null,
"e": 2954,
"s": 2926,
"text": "Variable goes out of scope "
},
{
"code": null,
"e": 3092,
"s": 2954,
"text": "void main()\n{\n int *ptr;\n .....\n .....\n {\n int ch;\n ptr = &ch;\n } \n ..... \n // Here ptr is dangling pointer\n}"
},
{
"code": null,
"e": 3105,
"s": 3092,
"text": "Void pointer"
},
{
"code": null,
"e": 3564,
"s": 3105,
"text": "Void pointer is a specific pointer type – void * – a pointer that points to some data location in storage, which doesn’t have any specific type. Void refers to the type. Basically the type of data that it points to is can be any. If we assign address of char data type to void pointer it will become char Pointer, if int data type then int pointer and so on. Any pointer type is convertible to a void pointer hence it can point to any value. Important Points"
},
{
"code": null,
"e": 3759,
"s": 3564,
"text": "void pointers cannot be dereferenced. It can however be done using typecasting the void pointerPointer arithmetic is not possible on pointers of void due to lack of concrete value and thus size."
},
{
"code": null,
"e": 3855,
"s": 3759,
"text": "void pointers cannot be dereferenced. It can however be done using typecasting the void pointer"
},
{
"code": null,
"e": 3955,
"s": 3855,
"text": "Pointer arithmetic is not possible on pointers of void due to lack of concrete value and thus size."
},
{
"code": null,
"e": 3965,
"s": 3955,
"text": "Example: "
},
{
"code": null,
"e": 3969,
"s": 3965,
"text": "CPP"
},
{
"code": "#include<stdlib.h> int main(){ int x = 4; float y = 5.5; //A void pointer void *ptr; ptr = &x; // (int*)ptr - does type casting of void // *((int*)ptr) dereferences the typecasted // void pointer variable. printf(\"Integer variable is = %d\", *( (int*) ptr) ); // void pointer is now float ptr = &y; printf(\"\\nFloat variable is= %f\", *( (float*) ptr) ); return 0;}",
"e": 4379,
"s": 3969,
"text": null
},
{
"code": null,
"e": 4387,
"s": 4379,
"text": "Output:"
},
{
"code": null,
"e": 4439,
"s": 4387,
"text": "Integer variable is = 4\nFloat variable is= 5.500000"
},
{
"code": null,
"e": 4481,
"s": 4439,
"text": "Refer void pointer article for details. "
},
{
"code": null,
"e": 4494,
"s": 4481,
"text": "NULL Pointer"
},
{
"code": null,
"e": 4643,
"s": 4494,
"text": "NULL Pointer is a pointer which is pointing to nothing. In case, if we don’t have address to be assigned to a pointer, then we can simply use NULL. "
},
{
"code": null,
"e": 4647,
"s": 4643,
"text": "C++"
},
{
"code": null,
"e": 4649,
"s": 4647,
"text": "C"
},
{
"code": "#include <iostream>using namespace std; int main(){ // Null Pointer int *ptr = NULL; cout << \"The value of ptr is \" << ptr; return 0;} // This code is contributed by sarajadhav12052009",
"e": 4851,
"s": 4649,
"text": null
},
{
"code": "#include <stdio.h>int main(){ // Null Pointer int *ptr = NULL; printf(\"The value of ptr is %p\", ptr); return 0;}",
"e": 4981,
"s": 4851,
"text": null
},
{
"code": null,
"e": 4990,
"s": 4981,
"text": "Output :"
},
{
"code": null,
"e": 5016,
"s": 4990,
"text": "The value of ptr is (nil)"
},
{
"code": null,
"e": 5033,
"s": 5016,
"text": "Important Points"
},
{
"code": null,
"e": 5327,
"s": 5033,
"text": "NULL vs Uninitialized pointer – An uninitialized pointer stores an undefined value. A null pointer stores a defined value, but one that is defined by the environment to not be a valid address for any member or object.NULL vs Void Pointer – Null pointer is a value, while void pointer is a type"
},
{
"code": null,
"e": 5545,
"s": 5327,
"text": "NULL vs Uninitialized pointer – An uninitialized pointer stores an undefined value. A null pointer stores a defined value, but one that is defined by the environment to not be a valid address for any member or object."
},
{
"code": null,
"e": 5622,
"s": 5545,
"text": "NULL vs Void Pointer – Null pointer is a value, while void pointer is a type"
},
{
"code": null,
"e": 5635,
"s": 5622,
"text": "Wild pointer"
},
{
"code": null,
"e": 5823,
"s": 5635,
"text": "A pointer which has not been initialized to anything (not even NULL) is known as wild pointer. The pointer may be initialized to a non-NULL garbage value that may not be a valid address. "
},
{
"code": null,
"e": 5827,
"s": 5823,
"text": "CPP"
},
{
"code": "int main(){ int *p; /* wild pointer */ int x = 10; // p is not a wild pointer now p = &x; return 0;}",
"e": 5947,
"s": 5827,
"text": null
},
{
"code": null,
"e": 6369,
"s": 5947,
"text": "This article is contributed by Spoorthi Arun. 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": 6377,
"s": 6369,
"text": "ashoklb"
},
{
"code": null,
"e": 6393,
"s": 6377,
"text": "sharathmaidargi"
},
{
"code": null,
"e": 6412,
"s": 6393,
"text": "sarajadhav12052009"
},
{
"code": null,
"e": 6423,
"s": 6412,
"text": "C-Pointers"
},
{
"code": null,
"e": 6435,
"s": 6423,
"text": "cpp-pointer"
},
{
"code": null,
"e": 6446,
"s": 6435,
"text": "C Language"
},
{
"code": null,
"e": 6450,
"s": 6446,
"text": "C++"
},
{
"code": null,
"e": 6469,
"s": 6450,
"text": "School Programming"
},
{
"code": null,
"e": 6473,
"s": 6469,
"text": "CPP"
},
{
"code": null,
"e": 6571,
"s": 6473,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6588,
"s": 6571,
"text": "Substring in C++"
},
{
"code": null,
"e": 6623,
"s": 6588,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 6669,
"s": 6623,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 6714,
"s": 6669,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 6739,
"s": 6714,
"text": "std::string class in C++"
},
{
"code": null,
"e": 6757,
"s": 6739,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 6800,
"s": 6757,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 6846,
"s": 6800,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 6889,
"s": 6846,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Convert camel case string to snake case in Java
|
09 Aug, 2021
Given a string in camel case, the task is to write a Java program to convert the given string from camel case to snake case and print the modified string.
Examples:
Input: GeeksForGeeks
Output: geeks_for_geeks
Input: CamelCaseToSnakeCase
Output: camel_case_to_snake_case
Method 1: Naive Approach
First we initialize a variable ‘result’ with an empty string and append the first character (in lower case) to it.
Now iterate over each character of the string from first index to the last index, if the character is upper case alphabet, we append ‘_’ and the character (in lower case) to result, otherwise just append the character only.
Below is the implementation of the above approach:
Java
class GFG { // Function to convert camel case // string to snake case string public static String camelToSnake(String str) { // Empty String String result = ""; // Append first character(in lower case) // to result string char c = str.charAt(0); result = result + Character.toLowerCase(c); // Traverse the string from // ist index to last index for (int i = 1; i < str.length(); i++) { char ch = str.charAt(i); // Check if the character is upper case // then append '_' and such character // (in lower case) to result string if (Character.isUpperCase(ch)) { result = result + '_'; result = result + Character.toLowerCase(ch); } // If the character is lower case then // add such character into result string else { result = result + ch; } } // return the result return result; } public static void main(String args[]) { // Given string str String str = "GeeksForGeeks"; // Print the modified string System.out.print(camelToSnake(str)); }}
geeks_for_geeks
Method 2: Using String.replaceAll method
The idea is to use the String.replaceAll method to convert given string from camel case to snake case.
The String.replaceAll method accepts two parameters a regular expression and a replacement string. It replaces the regular expression with the replacement string and prints the modified string.
Below is the implementation of the above approach:
Java
class GFG { // Function to convert camel case // string to snake case string public static String camelToSnake(String str) { // Regular Expression String regex = "([a-z])([A-Z]+)"; // Replacement string String replacement = "$1_$2"; // Replace the given regex // with replacement string // and convert it to lower case. str = str .replaceAll( regex, replacement) .toLowerCase(); // return string return str; } // Driver Code public static void main(String args[]) { // Given string str String str = "GeeksForGeeks"; // Print the modified string System.out.print(camelToSnake(str)); }}
geeks_for_geeks
anikakapoor
sagartomar9927
java-regular-expression
Java-String-Programs
regular-expression
Java Programs
Pattern Searching
Strings
Strings
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n09 Aug, 2021"
},
{
"code": null,
"e": 208,
"s": 53,
"text": "Given a string in camel case, the task is to write a Java program to convert the given string from camel case to snake case and print the modified string."
},
{
"code": null,
"e": 218,
"s": 208,
"text": "Examples:"
},
{
"code": null,
"e": 239,
"s": 218,
"text": "Input: GeeksForGeeks"
},
{
"code": null,
"e": 263,
"s": 239,
"text": "Output: geeks_for_geeks"
},
{
"code": null,
"e": 292,
"s": 263,
"text": "Input: CamelCaseToSnakeCase "
},
{
"code": null,
"e": 326,
"s": 292,
"text": "Output: camel_case_to_snake_case "
},
{
"code": null,
"e": 351,
"s": 326,
"text": "Method 1: Naive Approach"
},
{
"code": null,
"e": 466,
"s": 351,
"text": "First we initialize a variable ‘result’ with an empty string and append the first character (in lower case) to it."
},
{
"code": null,
"e": 690,
"s": 466,
"text": "Now iterate over each character of the string from first index to the last index, if the character is upper case alphabet, we append ‘_’ and the character (in lower case) to result, otherwise just append the character only."
},
{
"code": null,
"e": 741,
"s": 690,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 746,
"s": 741,
"text": "Java"
},
{
"code": "class GFG { // Function to convert camel case // string to snake case string public static String camelToSnake(String str) { // Empty String String result = \"\"; // Append first character(in lower case) // to result string char c = str.charAt(0); result = result + Character.toLowerCase(c); // Traverse the string from // ist index to last index for (int i = 1; i < str.length(); i++) { char ch = str.charAt(i); // Check if the character is upper case // then append '_' and such character // (in lower case) to result string if (Character.isUpperCase(ch)) { result = result + '_'; result = result + Character.toLowerCase(ch); } // If the character is lower case then // add such character into result string else { result = result + ch; } } // return the result return result; } public static void main(String args[]) { // Given string str String str = \"GeeksForGeeks\"; // Print the modified string System.out.print(camelToSnake(str)); }}",
"e": 2026,
"s": 746,
"text": null
},
{
"code": null,
"e": 2042,
"s": 2026,
"text": "geeks_for_geeks"
},
{
"code": null,
"e": 2086,
"s": 2044,
"text": "Method 2: Using String.replaceAll method "
},
{
"code": null,
"e": 2189,
"s": 2086,
"text": "The idea is to use the String.replaceAll method to convert given string from camel case to snake case."
},
{
"code": null,
"e": 2383,
"s": 2189,
"text": "The String.replaceAll method accepts two parameters a regular expression and a replacement string. It replaces the regular expression with the replacement string and prints the modified string."
},
{
"code": null,
"e": 2435,
"s": 2383,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 2440,
"s": 2435,
"text": "Java"
},
{
"code": "class GFG { // Function to convert camel case // string to snake case string public static String camelToSnake(String str) { // Regular Expression String regex = \"([a-z])([A-Z]+)\"; // Replacement string String replacement = \"$1_$2\"; // Replace the given regex // with replacement string // and convert it to lower case. str = str .replaceAll( regex, replacement) .toLowerCase(); // return string return str; } // Driver Code public static void main(String args[]) { // Given string str String str = \"GeeksForGeeks\"; // Print the modified string System.out.print(camelToSnake(str)); }}",
"e": 3214,
"s": 2440,
"text": null
},
{
"code": null,
"e": 3230,
"s": 3214,
"text": "geeks_for_geeks"
},
{
"code": null,
"e": 3246,
"s": 3234,
"text": "anikakapoor"
},
{
"code": null,
"e": 3261,
"s": 3246,
"text": "sagartomar9927"
},
{
"code": null,
"e": 3285,
"s": 3261,
"text": "java-regular-expression"
},
{
"code": null,
"e": 3306,
"s": 3285,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 3325,
"s": 3306,
"text": "regular-expression"
},
{
"code": null,
"e": 3339,
"s": 3325,
"text": "Java Programs"
},
{
"code": null,
"e": 3357,
"s": 3339,
"text": "Pattern Searching"
},
{
"code": null,
"e": 3365,
"s": 3357,
"text": "Strings"
},
{
"code": null,
"e": 3373,
"s": 3365,
"text": "Strings"
},
{
"code": null,
"e": 3391,
"s": 3373,
"text": "Pattern Searching"
}
] |
How to Compare Time in MS SQL Server?
|
03 Jun, 2021
Here, we are going to see how to Compare Time in SQL Server. In this article, we will be making use of the Microsoft SQL Server as our database.
Here, we will first create a database named “geeks”. After, that we will execute our query on that database.
CREATE DATABASE geeks;
USE geeks;
Here, we could create two variables of datetime, that we need to compare.
Syntax:
declare @input1 datetime;
declare @input2 datetime;
select @input1 = CONVERT(varchar(20),CONVERT(datetime, 'date and time'), 114)
select @input2 = CONVERT(varchar(20),CONVERT(datetime, 'date and time'), 114)
if @input1 <= @input2
print '@input1 less then @input2'
else
print '@input1 more then @input2'
In MS SQL Server the query can be designed to compare two or more datetime variables using just the “if” statements.
Example:
declare @day1 datetime;
declare @day2 datetime;
select @day1 = CONVERT(varchar(20),CONVERT(datetime, '2019-02-11 08:00:00'), 114)
select @day2 = CONVERT(varchar(20),CONVERT(datetime, '2020-02-11 08:00:00'), 114)
if @day1 <= @day2
print '@@day1 less then @@day2'
else
print '@@day1 more then @@day2'
Output :
@@day1 less then @@day2
The GETDATE() function in SQL can also be used to compare multiple dates.
Example:
declare @day1 datetime;
declare @day2 datetime;
select @day1 = CONVERT(varchar(20),GETDATE(), 114)
select @day2 = CONVERT(varchar(20),CONVERT(datetime, '2019-02-11 08:00:00'), 114)
if @day1 <= @day2
print '@@day1 less then @@day2'
else
print '@@day1 more then @@day2'
Output:
@@day1 more then @@day2
anikakapoor
Picked
SQL-Query
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?
SQL | Sub queries in From Clause
Window functions in SQL
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
RANK() Function in SQL Server
SQL Query to Compare Two Dates
SQL Query to Convert Rows to Columns in SQL Server
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 173,
"s": 28,
"text": "Here, we are going to see how to Compare Time in SQL Server. In this article, we will be making use of the Microsoft SQL Server as our database."
},
{
"code": null,
"e": 282,
"s": 173,
"text": "Here, we will first create a database named “geeks”. After, that we will execute our query on that database."
},
{
"code": null,
"e": 305,
"s": 282,
"text": "CREATE DATABASE geeks;"
},
{
"code": null,
"e": 316,
"s": 305,
"text": "USE geeks;"
},
{
"code": null,
"e": 390,
"s": 316,
"text": "Here, we could create two variables of datetime, that we need to compare."
},
{
"code": null,
"e": 398,
"s": 390,
"text": "Syntax:"
},
{
"code": null,
"e": 712,
"s": 398,
"text": "declare @input1 datetime;\ndeclare @input2 datetime;\nselect @input1 = CONVERT(varchar(20),CONVERT(datetime, 'date and time'), 114)\nselect @input2 = CONVERT(varchar(20),CONVERT(datetime, 'date and time'), 114)\n\nif @input1 <= @input2\n print '@input1 less then @input2'\nelse\n print '@input1 more then @input2'"
},
{
"code": null,
"e": 829,
"s": 712,
"text": "In MS SQL Server the query can be designed to compare two or more datetime variables using just the “if” statements."
},
{
"code": null,
"e": 838,
"s": 829,
"text": "Example:"
},
{
"code": null,
"e": 1145,
"s": 838,
"text": "declare @day1 datetime;\ndeclare @day2 datetime;\nselect @day1 = CONVERT(varchar(20),CONVERT(datetime, '2019-02-11 08:00:00'), 114)\nselect @day2 = CONVERT(varchar(20),CONVERT(datetime, '2020-02-11 08:00:00'), 114)\nif @day1 <= @day2\n print '@@day1 less then @@day2'\nelse\n print '@@day1 more then @@day2'"
},
{
"code": null,
"e": 1154,
"s": 1145,
"text": "Output :"
},
{
"code": null,
"e": 1178,
"s": 1154,
"text": "@@day1 less then @@day2"
},
{
"code": null,
"e": 1252,
"s": 1178,
"text": "The GETDATE() function in SQL can also be used to compare multiple dates."
},
{
"code": null,
"e": 1261,
"s": 1252,
"text": "Example:"
},
{
"code": null,
"e": 1537,
"s": 1261,
"text": "declare @day1 datetime;\ndeclare @day2 datetime;\nselect @day1 = CONVERT(varchar(20),GETDATE(), 114)\nselect @day2 = CONVERT(varchar(20),CONVERT(datetime, '2019-02-11 08:00:00'), 114)\nif @day1 <= @day2\n print '@@day1 less then @@day2'\nelse\n print '@@day1 more then @@day2'"
},
{
"code": null,
"e": 1545,
"s": 1537,
"text": "Output:"
},
{
"code": null,
"e": 1569,
"s": 1545,
"text": "@@day1 more then @@day2"
},
{
"code": null,
"e": 1581,
"s": 1569,
"text": "anikakapoor"
},
{
"code": null,
"e": 1588,
"s": 1581,
"text": "Picked"
},
{
"code": null,
"e": 1598,
"s": 1588,
"text": "SQL-Query"
},
{
"code": null,
"e": 1602,
"s": 1598,
"text": "SQL"
},
{
"code": null,
"e": 1606,
"s": 1602,
"text": "SQL"
},
{
"code": null,
"e": 1704,
"s": 1606,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1770,
"s": 1704,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 1803,
"s": 1770,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 1827,
"s": 1803,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 1859,
"s": 1827,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 1876,
"s": 1859,
"text": "SQL using Python"
},
{
"code": null,
"e": 1954,
"s": 1876,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 1990,
"s": 1954,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 2020,
"s": 1990,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 2051,
"s": 2020,
"text": "SQL Query to Compare Two Dates"
}
] |
Mallow Technologies Interview Experience | Set 1 (On-Campus)
|
30 May, 2018
Recently Mallow Technologies visited our campus for recruiting Web developer, IOS and Android app developers.
No. of Rounds: 3
Round 1:
It was online coding round at Hackerrank which consists of 3 programs and 3Hrs time.
Program 1:Given an array with n distinct integers d[0], d[1], ... d[n – 1] and a threshold t, how many triplets (i, j, k) exist such that d[i] < d[j] < d[k], and d[i] + d[j] + d[k] <= t.
Constraint:
0 < n ? 30,000
0 <= d[i] < 10,000,000
0 < t < 300,000,000
(Note that the input is not always sorted.)
Sample Input:
t => Threshold, N=> No. of values in array then N number follows denotes values..
8 5 1 2 3 4 6
Sample Output:
3
Explanation:
{1, 2, 3} => 1 + 2 + 3 <= 8
{1, 2, 4} => 1 + 2 + 4 <= 8
{1, 3, 4} => 1 + 3 + 4 <= 8
Program 2:
Louise and Richard decided to stay in on Friday night to play a game. They have a counter set to N. Louise gets the first turn and they alternate turns thereafter.In the game, they perform one of the following two operations.If N is not a power of 2, they reduce the counter by the largest power of 2 less than N.If N is a power of 2, they reduce the counter by half of N. The resultant value is the new N which is by the next player for her or his turn. The game ends when the counter reduces to 1, i.e. N = 1. The player who makes the last valid move (i.e. who gets to 1) wins. Given N, your task is to find the winner of the game.
Note: If the counter is set to 1 at the start, Richard wins, because its Louise’s turn and shecannot make a move.
Input Format:
The first line contains an integer T, the number of test cases. T lines follow. Each line contains N, the initial number set in the counter.Output Format:For each test case, print the winner’s name in a new line. So if Louise wins the game, print “Louise”. Otherwise, print “Richard” (minus the quotation marks.)
Constraints:
1 <= T <= 10
1 <= N <= 264 - 1
Sample Input:
1 6
Sample Output
Richard
Explanation6 is not a power of 2, so Louise subtracts the largest power of 2 less than 6, i.e. 4, and the counter goes down to 2. 2 is a power of 2, so Richard reduces the counter by half of 2, i.e. 1, and the counter goes down to 1. Since N = 1, Louise has no more moves, so Richard wins the game
Program 3:
You are given a 14 digit date time value as input (D), whose format is YYYYMMDDHHMISS.YYYY – represents year (Examples: 1947, 2000, 2015)MM – represents month (Examples: 12, 01, 03)DD – represents day (Examples: 31, 01, 15)HH – represents hour (Examples: 00, 01, 12, 23)MI – represents minute (Examples: 59, 50, 00, 05)SS – represents second (Examples: 59, 50, 00 06)
You will also be given another integer, called the offset value (O), in seconds. You are requiredto print a 14 digit output date in the format YYYYMMDDHHMISS which is adjusted for the offset from the input date.
Proper conditions to check for leap year:1. https://en.wikipedia.org/wiki/Leap_year#Algorithm2. http://www.wwu.edu/skywise/leapyear.htmlSpecial condition for the year 1752:1. https://en.wikipedia.org/wiki/1752
Please note that, the conditions for a leap year is different for Julian (Used until September 2, 1752) and Gregorian calendars (Used from September 14, 1752).
Constraints:
10010101000000 < D < 39991231235959
-94638758399 < O < 94638758399
Sample Input:
19470815000008
17
Sample Output:
19470815000025
Explanation:
The input 19470815000008 represents August 15, 1947 00:00:08. If you adjust the input date with 17 seconds, you will get the date August 15, 1947 00:0025. Hence the output is 19470815000025.
Round 2:
It was also conducted online at hackerrank 2 Hrs time which consists of following:
1. Program with errors (Both logic & syntax) – We need to debug it and pass all test cases.
2. There was two database questions for which we need to write query and pass the test cases.
Technical and HR:
Questions related to the problems given in Round 1 and Round 2 how we solved. Someconcept in data structures and basic CS questions. Thanks GeeksforGeeks for providing this wonderful resources.
If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Mallow Technologies
Interview Experiences
Mallow Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE 1
Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022
Amazon Interview Experience SDE-2 (3 Years Experienced)
Google SWE Interview Experience (Google Online Coding Challenge) 2022
Write It Up: Share Your Interview Experiences
Nagarro Interview Experience | On-Campus 2021
Amazon Interview Experience for SDE-1
Nagarro Interview Experience
TCS Ninja Interview Experience (2020 batch)
Samsung Software Competency Test (SWC) for Working professionals
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 May, 2018"
},
{
"code": null,
"e": 162,
"s": 52,
"text": "Recently Mallow Technologies visited our campus for recruiting Web developer, IOS and Android app developers."
},
{
"code": null,
"e": 179,
"s": 162,
"text": "No. of Rounds: 3"
},
{
"code": null,
"e": 188,
"s": 179,
"text": "Round 1:"
},
{
"code": null,
"e": 273,
"s": 188,
"text": "It was online coding round at Hackerrank which consists of 3 programs and 3Hrs time."
},
{
"code": null,
"e": 460,
"s": 273,
"text": "Program 1:Given an array with n distinct integers d[0], d[1], ... d[n – 1] and a threshold t, how many triplets (i, j, k) exist such that d[i] < d[j] < d[k], and d[i] + d[j] + d[k] <= t."
},
{
"code": null,
"e": 801,
"s": 460,
"text": "Constraint:\n0 < n ? 30,000\n0 <= d[i] < 10,000,000\n0 < t < 300,000,000\n(Note that the input is not always sorted.)\n\nSample Input:\nt => Threshold, N=> No. of values in array then N number follows denotes values..\n8 5 1 2 3 4 6\n\nSample Output:\n3\nExplanation:\n\n{1, 2, 3} => 1 + 2 + 3 <= 8\n{1, 2, 4} => 1 + 2 + 4 <= 8\n{1, 3, 4} => 1 + 3 + 4 <= 8"
},
{
"code": null,
"e": 812,
"s": 801,
"text": "Program 2:"
},
{
"code": null,
"e": 1446,
"s": 812,
"text": "Louise and Richard decided to stay in on Friday night to play a game. They have a counter set to N. Louise gets the first turn and they alternate turns thereafter.In the game, they perform one of the following two operations.If N is not a power of 2, they reduce the counter by the largest power of 2 less than N.If N is a power of 2, they reduce the counter by half of N. The resultant value is the new N which is by the next player for her or his turn. The game ends when the counter reduces to 1, i.e. N = 1. The player who makes the last valid move (i.e. who gets to 1) wins. Given N, your task is to find the winner of the game."
},
{
"code": null,
"e": 1560,
"s": 1446,
"text": "Note: If the counter is set to 1 at the start, Richard wins, because its Louise’s turn and shecannot make a move."
},
{
"code": null,
"e": 1574,
"s": 1560,
"text": "Input Format:"
},
{
"code": null,
"e": 1887,
"s": 1574,
"text": "The first line contains an integer T, the number of test cases. T lines follow. Each line contains N, the initial number set in the counter.Output Format:For each test case, print the winner’s name in a new line. So if Louise wins the game, print “Louise”. Otherwise, print “Richard” (minus the quotation marks.)"
},
{
"code": null,
"e": 1973,
"s": 1887,
"text": "Constraints:\n1 <= T <= 10\n1 <= N <= 264 - 1\n\nSample Input:\n1 6\n\nSample Output\nRichard"
},
{
"code": null,
"e": 2271,
"s": 1973,
"text": "Explanation6 is not a power of 2, so Louise subtracts the largest power of 2 less than 6, i.e. 4, and the counter goes down to 2. 2 is a power of 2, so Richard reduces the counter by half of 2, i.e. 1, and the counter goes down to 1. Since N = 1, Louise has no more moves, so Richard wins the game"
},
{
"code": null,
"e": 2282,
"s": 2271,
"text": "Program 3:"
},
{
"code": null,
"e": 2650,
"s": 2282,
"text": "You are given a 14 digit date time value as input (D), whose format is YYYYMMDDHHMISS.YYYY – represents year (Examples: 1947, 2000, 2015)MM – represents month (Examples: 12, 01, 03)DD – represents day (Examples: 31, 01, 15)HH – represents hour (Examples: 00, 01, 12, 23)MI – represents minute (Examples: 59, 50, 00, 05)SS – represents second (Examples: 59, 50, 00 06)"
},
{
"code": null,
"e": 2862,
"s": 2650,
"text": "You will also be given another integer, called the offset value (O), in seconds. You are requiredto print a 14 digit output date in the format YYYYMMDDHHMISS which is adjusted for the offset from the input date."
},
{
"code": null,
"e": 3072,
"s": 2862,
"text": "Proper conditions to check for leap year:1. https://en.wikipedia.org/wiki/Leap_year#Algorithm2. http://www.wwu.edu/skywise/leapyear.htmlSpecial condition for the year 1752:1. https://en.wikipedia.org/wiki/1752"
},
{
"code": null,
"e": 3232,
"s": 3072,
"text": "Please note that, the conditions for a leap year is different for Julian (Used until September 2, 1752) and Gregorian calendars (Used from September 14, 1752)."
},
{
"code": null,
"e": 3376,
"s": 3232,
"text": "Constraints:\n10010101000000 < D < 39991231235959\n-94638758399 < O < 94638758399\n\nSample Input:\n19470815000008\n17\n\nSample Output:\n19470815000025"
},
{
"code": null,
"e": 3389,
"s": 3376,
"text": "Explanation:"
},
{
"code": null,
"e": 3580,
"s": 3389,
"text": "The input 19470815000008 represents August 15, 1947 00:00:08. If you adjust the input date with 17 seconds, you will get the date August 15, 1947 00:0025. Hence the output is 19470815000025."
},
{
"code": null,
"e": 3589,
"s": 3580,
"text": "Round 2:"
},
{
"code": null,
"e": 3672,
"s": 3589,
"text": "It was also conducted online at hackerrank 2 Hrs time which consists of following:"
},
{
"code": null,
"e": 3764,
"s": 3672,
"text": "1. Program with errors (Both logic & syntax) – We need to debug it and pass all test cases."
},
{
"code": null,
"e": 3858,
"s": 3764,
"text": "2. There was two database questions for which we need to write query and pass the test cases."
},
{
"code": null,
"e": 3876,
"s": 3858,
"text": "Technical and HR:"
},
{
"code": null,
"e": 4070,
"s": 3876,
"text": "Questions related to the problems given in Round 1 and Round 2 how we solved. Someconcept in data structures and basic CS questions. Thanks GeeksforGeeks for providing this wonderful resources."
},
{
"code": null,
"e": 4291,
"s": 4070,
"text": "If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 4311,
"s": 4291,
"text": "Mallow Technologies"
},
{
"code": null,
"e": 4333,
"s": 4311,
"text": "Interview Experiences"
},
{
"code": null,
"e": 4353,
"s": 4333,
"text": "Mallow Technologies"
},
{
"code": null,
"e": 4451,
"s": 4353,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4489,
"s": 4451,
"text": "Amazon Interview Experience for SDE 1"
},
{
"code": null,
"e": 4562,
"s": 4489,
"text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022"
},
{
"code": null,
"e": 4618,
"s": 4562,
"text": "Amazon Interview Experience SDE-2 (3 Years Experienced)"
},
{
"code": null,
"e": 4688,
"s": 4618,
"text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022"
},
{
"code": null,
"e": 4734,
"s": 4688,
"text": "Write It Up: Share Your Interview Experiences"
},
{
"code": null,
"e": 4780,
"s": 4734,
"text": "Nagarro Interview Experience | On-Campus 2021"
},
{
"code": null,
"e": 4818,
"s": 4780,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 4847,
"s": 4818,
"text": "Nagarro Interview Experience"
},
{
"code": null,
"e": 4891,
"s": 4847,
"text": "TCS Ninja Interview Experience (2020 batch)"
}
] |
How do we insert/store a file into MySQL database using JDBC?
|
In general, the contents of a file are stored under Clob (TINYTEXT, TEXT, MEDIUMTEXT, LONGTEXT) datatype in MySQL database.
JDBC provides support for the Clob datatype, to store the contents of a file in to a table in a database.
The setCharacterStream() method of the PreparedStatement interface accepts an integer representing the index of the parameter and, a Reader object as a parameter.
And sets the contents of the given reader object (file) as value to the parameter (place holder) in the specified index.
Whenever you need to send very large text value you can use this method.
If you need to store a file in a database using JDBC program create table with a Clob (TINYTEXT, TEXT, MEDIUMTEXT, LONGTEXT) datatype as shown below:
CREATE TABLE Articles(Name VARCHAR(255), Article LONGTEXT);
Now, using JDBC connect to the database and prepare a PreparedStatement to insert values into the above created table:
String query = "INSERT INTO Tutorial(Name, Article) VALUES (?,?)";PreparedStatement pstmt = con.prepareStatement(query);
Set values to the place holders using the setter methods of the PreparedStatement interface and for the Clob datatype set value using the setCharacterStream() method.
Following is an example demonstrating how to insert file
in to a MySQL database using JDBC program. Here we are have created a table with a Clob datatype, inserted values in to it.
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class InsertingFileToDatabase {
public static void main(String args[]) throws Exception {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Inserting values
String query = "INSERT INTO Articles(Name, Article) VALUES (?, ?)";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, "article1");
FileReader reader = new FileReader("E:\\data\\article1.txt");
pstmt.setCharacterStream(2, reader);
pstmt.execute();
pstmt.setString(1, "article2");
reader = new FileReader("E:\\data\\article2.txt");
pstmt.setCharacterStream(2, reader);
pstmt.execute();
pstmt.setString(1, "article3");
reader = new FileReader("E:\\data\\article3.txt");
pstmt.setCharacterStream(2, reader);
pstmt.execute();
System.out.println("Data inserted......");
}
}
Connection established......
Data inserted......
Using MySQL workbench, you can export the contents of a table to various files such as html files, .csv files text files etc. If you export the contents of the table after inserting data to a HTTML file its output will look like:
|
[
{
"code": null,
"e": 1311,
"s": 1187,
"text": "In general, the contents of a file are stored under Clob (TINYTEXT, TEXT, MEDIUMTEXT, LONGTEXT) datatype in MySQL database."
},
{
"code": null,
"e": 1417,
"s": 1311,
"text": "JDBC provides support for the Clob datatype, to store the contents of a file in to a table in a database."
},
{
"code": null,
"e": 1580,
"s": 1417,
"text": "The setCharacterStream() method of the PreparedStatement interface accepts an integer representing the index of the parameter and, a Reader object as a parameter."
},
{
"code": null,
"e": 1701,
"s": 1580,
"text": "And sets the contents of the given reader object (file) as value to the parameter (place holder) in the specified index."
},
{
"code": null,
"e": 1774,
"s": 1701,
"text": "Whenever you need to send very large text value you can use this method."
},
{
"code": null,
"e": 1924,
"s": 1774,
"text": "If you need to store a file in a database using JDBC program create table with a Clob (TINYTEXT, TEXT, MEDIUMTEXT, LONGTEXT) datatype as shown below:"
},
{
"code": null,
"e": 1984,
"s": 1924,
"text": "CREATE TABLE Articles(Name VARCHAR(255), Article LONGTEXT);"
},
{
"code": null,
"e": 2103,
"s": 1984,
"text": "Now, using JDBC connect to the database and prepare a PreparedStatement to insert values into the above created table:"
},
{
"code": null,
"e": 2224,
"s": 2103,
"text": "String query = \"INSERT INTO Tutorial(Name, Article) VALUES (?,?)\";PreparedStatement pstmt = con.prepareStatement(query);"
},
{
"code": null,
"e": 2391,
"s": 2224,
"text": "Set values to the place holders using the setter methods of the PreparedStatement interface and for the Clob datatype set value using the setCharacterStream() method."
},
{
"code": null,
"e": 2572,
"s": 2391,
"text": "Following is an example demonstrating how to insert file\nin to a MySQL database using JDBC program. Here we are have created a table with a Clob datatype, inserted values in to it."
},
{
"code": null,
"e": 3829,
"s": 2572,
"text": "import java.io.FileReader;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\npublic class InsertingFileToDatabase {\n public static void main(String args[]) throws Exception {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/sampleDB\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Inserting values\n String query = \"INSERT INTO Articles(Name, Article) VALUES (?, ?)\";\n PreparedStatement pstmt = con.prepareStatement(query);\n pstmt.setString(1, \"article1\");\n FileReader reader = new FileReader(\"E:\\\\data\\\\article1.txt\");\n pstmt.setCharacterStream(2, reader);\n pstmt.execute();\n pstmt.setString(1, \"article2\");\n reader = new FileReader(\"E:\\\\data\\\\article2.txt\");\n pstmt.setCharacterStream(2, reader);\n pstmt.execute();\n pstmt.setString(1, \"article3\");\n reader = new FileReader(\"E:\\\\data\\\\article3.txt\");\n pstmt.setCharacterStream(2, reader);\n pstmt.execute();\n System.out.println(\"Data inserted......\");\n }\n}"
},
{
"code": null,
"e": 3878,
"s": 3829,
"text": "Connection established......\nData inserted......"
},
{
"code": null,
"e": 4108,
"s": 3878,
"text": "Using MySQL workbench, you can export the contents of a table to various files such as html files, .csv files text files etc. If you export the contents of the table after inserting data to a HTTML file its output will look like:"
}
] |
GATE | GATE CS 2012 | Question 15
|
09 Oct, 2019
Which of the following statements are TRUE about an SQL query?P : An SQL query can contain a HAVING clause even if it does not have a GROUP BY clauseQ : An SQL query can contain a HAVING clause only if it has a GROUP BY clauseR : All attributes used in the GROUP BY clause must appear in the SELECT clauseS : Not all attributes used in the GROUP BY clause need to appear in the SELECT clause
(A) P and R(B) P and S(C) Q and R(D) Q and SAnswer: (B)Explanation: According to standard SQL answer should be option (C) which is answer key given by GATE authority.
If we talk about different SQL implementations like MySQL, then option (B) is also right. But in question they seem to be talking about standard SQL not about implementation. For example below is a
P is correct in most of the implementations. HAVING clause can also be used with aggregate function. If we use a HAVING clause without a GROUP BY clause, the HAVING condition applies to all rows that satisfy the search condition. In other words, all rows that satisfy the search condition make up a single group. See this for more details.
S is correct . To verify S, try following queries in SQL.
CREATE TABLE temp
(
id INT,
name VARCHAR(100)
);
INSERT INTO temp VALUES (1, "abc");
INSERT INTO temp VALUES (2, "abc");
INSERT INTO temp VALUES (3, "bcd");
INSERT INTO temp VALUES (4, "cde");
SELECT Count(*)
FROM temp
GROUP BY name;
Output:
count(*)
--------
2
1
1
Alternative way –
Statement (P) “An SQL query can contain a HAVING clause even if it does not have a GROUP BY clause” is correct because Having caluse is applied after the aggregation phase and must be used if you want to filter aggregate results and Having doesn’t require Group By clause. A HAVING clause without a GROUP BY clause is valid and (arguably) useful syntax in Standard SQL. Consider this example, which is valid Standard SQL:
SELECT 'T' AS result
FROM Book
HAVING MIN(NumberOfPages) < MAX(NumberOfPages);
Statement (S) "Not all attributes used in the GROUP BY clause need to appear in the SELECT clause" is correct but if we use Group By clause must, there are limitations on what we can put into the Select clause.
Quiz of this Question
GATE-CS-2012
GATE-GATE CS 2012
DBMS Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Oct, 2019"
},
{
"code": null,
"e": 446,
"s": 54,
"text": "Which of the following statements are TRUE about an SQL query?P : An SQL query can contain a HAVING clause even if it does not have a GROUP BY clauseQ : An SQL query can contain a HAVING clause only if it has a GROUP BY clauseR : All attributes used in the GROUP BY clause must appear in the SELECT clauseS : Not all attributes used in the GROUP BY clause need to appear in the SELECT clause"
},
{
"code": null,
"e": 613,
"s": 446,
"text": "(A) P and R(B) P and S(C) Q and R(D) Q and SAnswer: (B)Explanation: According to standard SQL answer should be option (C) which is answer key given by GATE authority."
},
{
"code": null,
"e": 811,
"s": 613,
"text": "If we talk about different SQL implementations like MySQL, then option (B) is also right. But in question they seem to be talking about standard SQL not about implementation. For example below is a"
},
{
"code": null,
"e": 1151,
"s": 811,
"text": "P is correct in most of the implementations. HAVING clause can also be used with aggregate function. If we use a HAVING clause without a GROUP BY clause, the HAVING condition applies to all rows that satisfy the search condition. In other words, all rows that satisfy the search condition make up a single group. See this for more details."
},
{
"code": null,
"e": 1209,
"s": 1151,
"text": "S is correct . To verify S, try following queries in SQL."
},
{
"code": null,
"e": 1477,
"s": 1209,
"text": "CREATE TABLE temp \n ( \n id INT, \n name VARCHAR(100) \n ); \n\nINSERT INTO temp VALUES (1, \"abc\"); \nINSERT INTO temp VALUES (2, \"abc\"); \nINSERT INTO temp VALUES (3, \"bcd\"); \nINSERT INTO temp VALUES (4, \"cde\"); \n\nSELECT Count(*) \nFROM temp \nGROUP BY name; \n"
},
{
"code": null,
"e": 1485,
"s": 1477,
"text": "Output:"
},
{
"code": null,
"e": 1510,
"s": 1485,
"text": "count(*)\n--------\n2\n1\n1\n"
},
{
"code": null,
"e": 1528,
"s": 1510,
"text": "Alternative way –"
},
{
"code": null,
"e": 1950,
"s": 1528,
"text": "Statement (P) “An SQL query can contain a HAVING clause even if it does not have a GROUP BY clause” is correct because Having caluse is applied after the aggregation phase and must be used if you want to filter aggregate results and Having doesn’t require Group By clause. A HAVING clause without a GROUP BY clause is valid and (arguably) useful syntax in Standard SQL. Consider this example, which is valid Standard SQL:"
},
{
"code": null,
"e": 2035,
"s": 1950,
"text": " SELECT 'T' AS result\n FROM Book\n HAVING MIN(NumberOfPages) < MAX(NumberOfPages);\n"
},
{
"code": null,
"e": 2246,
"s": 2035,
"text": "Statement (S) \"Not all attributes used in the GROUP BY clause need to appear in the SELECT clause\" is correct but if we use Group By clause must, there are limitations on what we can put into the Select clause."
},
{
"code": null,
"e": 2268,
"s": 2246,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 2281,
"s": 2268,
"text": "GATE-CS-2012"
},
{
"code": null,
"e": 2299,
"s": 2281,
"text": "GATE-GATE CS 2012"
},
{
"code": null,
"e": 2309,
"s": 2299,
"text": "DBMS Quiz"
}
] |
Lodash _.max() Method
|
02 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 _.max() method is used to find the maximum element from the array. If the array is empty then undefined is returned.
Syntax:
_.max( array )
Parameters: This method accepts a single parameter as mentioned above and described below:
array: It is the array that the method iterates over to get the maximum element.
Return Value: This method returns the maximum element from the array.
Example 1:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.max() method let max_val = _.max([]); // Printing the output console.log(max_val);
Output:
undefined
Example 2:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.max() method let max_val = _.max([15, 7, 38, 46, 82]); // Printing the output console.log(max_val);
Output:
82
Example 3:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.max() method let max_val = _.max([-15, 7, 38, -46, -82]); // Printing the output console.log(max_val);
Output:
38
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
How to append HTML code to a div using JavaScript ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 168,
"s": 28,
"text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc."
},
{
"code": null,
"e": 289,
"s": 168,
"text": "The _.max() method is used to find the maximum element from the array. If the array is empty then undefined is returned."
},
{
"code": null,
"e": 297,
"s": 289,
"text": "Syntax:"
},
{
"code": null,
"e": 312,
"s": 297,
"text": "_.max( array )"
},
{
"code": null,
"e": 403,
"s": 312,
"text": "Parameters: This method accepts a single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 484,
"s": 403,
"text": "array: It is the array that the method iterates over to get the maximum element."
},
{
"code": null,
"e": 554,
"s": 484,
"text": "Return Value: This method returns the maximum element from the array."
},
{
"code": null,
"e": 565,
"s": 554,
"text": "Example 1:"
},
{
"code": null,
"e": 576,
"s": 565,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.max() method let max_val = _.max([]); // Printing the output console.log(max_val);",
"e": 747,
"s": 576,
"text": null
},
{
"code": null,
"e": 755,
"s": 747,
"text": "Output:"
},
{
"code": null,
"e": 765,
"s": 755,
"text": "undefined"
},
{
"code": null,
"e": 778,
"s": 765,
"text": "Example 2: "
},
{
"code": null,
"e": 789,
"s": 778,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.max() method let max_val = _.max([15, 7, 38, 46, 82]); // Printing the output console.log(max_val);",
"e": 977,
"s": 789,
"text": null
},
{
"code": null,
"e": 985,
"s": 977,
"text": "Output:"
},
{
"code": null,
"e": 988,
"s": 985,
"text": "82"
},
{
"code": null,
"e": 1001,
"s": 988,
"text": "Example 3: "
},
{
"code": null,
"e": 1012,
"s": 1001,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.max() method let max_val = _.max([-15, 7, 38, -46, -82]); // Printing the output console.log(max_val);",
"e": 1203,
"s": 1012,
"text": null
},
{
"code": null,
"e": 1211,
"s": 1203,
"text": "Output:"
},
{
"code": null,
"e": 1214,
"s": 1211,
"text": "38"
},
{
"code": null,
"e": 1232,
"s": 1214,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 1243,
"s": 1232,
"text": "JavaScript"
},
{
"code": null,
"e": 1260,
"s": 1243,
"text": "Web Technologies"
},
{
"code": null,
"e": 1358,
"s": 1260,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1419,
"s": 1358,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1491,
"s": 1419,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1531,
"s": 1491,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1584,
"s": 1531,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 1636,
"s": 1584,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 1698,
"s": 1636,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1731,
"s": 1698,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1792,
"s": 1731,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1842,
"s": 1792,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
PHP | DOMXPath evaluate() Function
|
13 Jul, 2021
The DOMXPath::evaluate() function is an inbuilt function in PHP which is used to execute the given XPath expression which is a pattern defined to select a set of nodes.Syntax:
mixed DOMXPath::evaluate( string $expression,
DOMNode $contextnode, bool $registerNodeNS )
Parameters: This function accept three parameters as mentioned above and described below:
$expression: It specifies the XPath expression to execute.
$contextnode (Optional): It specifies the contextnode for doing relative XPath queries. By default, the queries are relative to the root element.
$registerNodeNS (Optional): It specifies whether to disable automatic registration of the context node.
Return Value: This function returns TRUE on success.Exceptions: This function throws DOMXPathException on error.Below examples illustrate the DOMXPath::evaluate() function in PHP:Example 1:
php
<?php // Create a new DOMDocument instance$document = new DOMDocument(); // Create a XML$xml = <<<XML<?xml version="1.0" encoding="utf-8"?><bookstore><book> <title lang="en">GeeksforGeeks</title> <price>400</price></book><book> <title lang="en">Intro to XML</title> <price>300</price></book></bookstore>XML; // Load the XML$document->loadXML($xml); // Create a new DOMXPath instance$xpath = new DOMXPath($document); // Get the$tbody = $document-> getElementsByTagName('bookstore')->item(0); // Query to get the number of titles with lang// attribute "en"$query = 'count(//title[@lang=\'en\'])'; // Evaluate the query$entries = $xpath->evaluate($query, $tbody);echo "Number of elements with lang = \"en\": $entries\n";?>
Output:
Number of elements with lang = "en": 2
Example 2:
php
<?php // Create a new DOMDocument instance$document = new DOMDocument(); // Create a XML$xml = <<<XML<?xml version="1.0" encoding="utf-8"?><GeeksforGeeks> Keep Learning.</GeeksforGeeks>XML; // Load the XML$document->loadXML($xml); // Create a new DOMXPath instance$xpath = new DOMXPath($document); // Get the$tbody = $document->getElementsByTagName('GeeksforGeeks')->item(0); // Get the element with name GeeksforGeeks$query = '//GeeksforGeeks'; // Evaluate the query$entries = $xpath->evaluate($query, $tbody);echo $entries[0]->nodeValue;?>
Output:
Keep Learning.
Reference: https://www.php.net/manual/en/domxpath.evaluate.php
sagar0719kumar
PHP-DOM
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Jul, 2021"
},
{
"code": null,
"e": 206,
"s": 28,
"text": "The DOMXPath::evaluate() function is an inbuilt function in PHP which is used to execute the given XPath expression which is a pattern defined to select a set of nodes.Syntax: "
},
{
"code": null,
"e": 308,
"s": 206,
"text": "mixed DOMXPath::evaluate( string $expression, \n DOMNode $contextnode, bool $registerNodeNS )"
},
{
"code": null,
"e": 400,
"s": 308,
"text": "Parameters: This function accept three parameters as mentioned above and described below: "
},
{
"code": null,
"e": 459,
"s": 400,
"text": "$expression: It specifies the XPath expression to execute."
},
{
"code": null,
"e": 605,
"s": 459,
"text": "$contextnode (Optional): It specifies the contextnode for doing relative XPath queries. By default, the queries are relative to the root element."
},
{
"code": null,
"e": 709,
"s": 605,
"text": "$registerNodeNS (Optional): It specifies whether to disable automatic registration of the context node."
},
{
"code": null,
"e": 901,
"s": 709,
"text": "Return Value: This function returns TRUE on success.Exceptions: This function throws DOMXPathException on error.Below examples illustrate the DOMXPath::evaluate() function in PHP:Example 1: "
},
{
"code": null,
"e": 905,
"s": 901,
"text": "php"
},
{
"code": "<?php // Create a new DOMDocument instance$document = new DOMDocument(); // Create a XML$xml = <<<XML<?xml version=\"1.0\" encoding=\"utf-8\"?><bookstore><book> <title lang=\"en\">GeeksforGeeks</title> <price>400</price></book><book> <title lang=\"en\">Intro to XML</title> <price>300</price></book></bookstore>XML; // Load the XML$document->loadXML($xml); // Create a new DOMXPath instance$xpath = new DOMXPath($document); // Get the$tbody = $document-> getElementsByTagName('bookstore')->item(0); // Query to get the number of titles with lang// attribute \"en\"$query = 'count(//title[@lang=\\'en\\'])'; // Evaluate the query$entries = $xpath->evaluate($query, $tbody);echo \"Number of elements with lang = \\\"en\\\": $entries\\n\";?>",
"e": 1639,
"s": 905,
"text": null
},
{
"code": null,
"e": 1649,
"s": 1639,
"text": "Output: "
},
{
"code": null,
"e": 1688,
"s": 1649,
"text": "Number of elements with lang = \"en\": 2"
},
{
"code": null,
"e": 1701,
"s": 1688,
"text": "Example 2: "
},
{
"code": null,
"e": 1705,
"s": 1701,
"text": "php"
},
{
"code": "<?php // Create a new DOMDocument instance$document = new DOMDocument(); // Create a XML$xml = <<<XML<?xml version=\"1.0\" encoding=\"utf-8\"?><GeeksforGeeks> Keep Learning.</GeeksforGeeks>XML; // Load the XML$document->loadXML($xml); // Create a new DOMXPath instance$xpath = new DOMXPath($document); // Get the$tbody = $document->getElementsByTagName('GeeksforGeeks')->item(0); // Get the element with name GeeksforGeeks$query = '//GeeksforGeeks'; // Evaluate the query$entries = $xpath->evaluate($query, $tbody);echo $entries[0]->nodeValue;?>",
"e": 2248,
"s": 1705,
"text": null
},
{
"code": null,
"e": 2258,
"s": 2248,
"text": "Output: "
},
{
"code": null,
"e": 2273,
"s": 2258,
"text": "Keep Learning."
},
{
"code": null,
"e": 2337,
"s": 2273,
"text": "Reference: https://www.php.net/manual/en/domxpath.evaluate.php "
},
{
"code": null,
"e": 2352,
"s": 2337,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 2360,
"s": 2352,
"text": "PHP-DOM"
},
{
"code": null,
"e": 2373,
"s": 2360,
"text": "PHP-function"
},
{
"code": null,
"e": 2377,
"s": 2373,
"text": "PHP"
},
{
"code": null,
"e": 2394,
"s": 2377,
"text": "Web Technologies"
},
{
"code": null,
"e": 2398,
"s": 2394,
"text": "PHP"
}
] |
ML | Naive Bayes Scratch Implementation using Python
|
06 Jun, 2021
Introduction to Naive Bayes Naive Bayes is among one of the very simple and powerful algorithms for classification based on Bayes Theorem with an assumption of independence among the predictors. The Naive Bayes classifier assumes that the presence of a feature in a class is not related to any other feature. Naive Bayes is a classification algorithm for binary and multi-class classification problems.Bayes Theorem
Based on prior knowledge of conditions that may be related to an event, Bayes theorem describes the probability of the event
conditional probability can be found this way
Assume we have a Hypothesis(H) and evidence(E), According to Bayes theorem, the relationship between the probability of Hypothesis before getting the evidence represented as P(H) and the probability of the hypothesis after getting the evidence represented as P(H|E) is:
P(H|E) = P(E|H)*P(H)/P(E)
Prior probability = P(H) is the probability before getting the evidence Posterior probability = P(H|E) is the probability after getting evidence
In general,
P(class|data) = (P(data|class) * P(class)) / P(data)
Bayes Theorem Example Assume we have to find the probability of the randomly picked card to be king given that it is a face card. There are 4 Kings in a Deck of Cards which implies that P(King) = 4/52 as all the Kings are face Cards so P(Face|King) = 1 there are 3 Face Cards in a Suit of 13 cards and there are 4 Suits in total so P(Face) = 12/52 Therefore,
P(King|face) = P(face|king)*P(king)/P(face) = 1/3
Download dataset here
Code : Implementing Naive Bayes algorithm from scratch using Python
Python3
# Importing libraryimport mathimport randomimport csv # the categorical class names are changed to numberic data# eg: yes and no encoded to 1 and 0def encode_class(mydata): classes = [] for i in range(len(mydata)): if mydata[i][-1] not in classes: classes.append(mydata[i][-1]) for i in range(len(classes)): for j in range(len(mydata)): if mydata[j][-1] == classes[i]: mydata[j][-1] = i return mydata # Splitting the datadef splitting(mydata, ratio): train_num = int(len(mydata) * ratio) train = [] # initially testset will have all the dataset test = list(mydata) while len(train) < train_num: # index generated randomly from range 0 # to length of testset index = random.randrange(len(test)) # from testset, pop data rows and put it in train train.append(test.pop(index)) return train, test # Group the data rows under each class yes or# no in dictionary eg: dict[yes] and dict[no]def groupUnderClass(mydata): dict = {} for i in range(len(mydata)): if (mydata[i][-1] not in dict): dict[mydata[i][-1]] = [] dict[mydata[i][-1]].append(mydata[i]) return dict # Calculating Meandef mean(numbers): return sum(numbers) / float(len(numbers)) # Calculating Standard Deviationdef std_dev(numbers): avg = mean(numbers) variance = sum([pow(x - avg, 2) for x in numbers]) / float(len(numbers) - 1) return math.sqrt(variance) def MeanAndStdDev(mydata): info = [(mean(attribute), std_dev(attribute)) for attribute in zip(*mydata)] # eg: list = [ [a, b, c], [m, n, o], [x, y, z]] # here mean of 1st attribute =(a + m+x), mean of 2nd attribute = (b + n+y)/3 # delete summaries of last class del info[-1] return info # find Mean and Standard Deviation under each classdef MeanAndStdDevForClass(mydata): info = {} dict = groupUnderClass(mydata) for classValue, instances in dict.items(): info[classValue] = MeanAndStdDev(instances) return info # Calculate Gaussian Probability Density Functiondef calculateGaussianProbability(x, mean, stdev): expo = math.exp(-(math.pow(x - mean, 2) / (2 * math.pow(stdev, 2)))) return (1 / (math.sqrt(2 * math.pi) * stdev)) * expo # Calculate Class Probabilitiesdef calculateClassProbabilities(info, test): probabilities = {} for classValue, classSummaries in info.items(): probabilities[classValue] = 1 for i in range(len(classSummaries)): mean, std_dev = classSummaries[i] x = test[i] probabilities[classValue] *= calculateGaussianProbability(x, mean, std_dev) return probabilities # Make prediction - highest probability is the predictiondef predict(info, test): probabilities = calculateClassProbabilities(info, test) bestLabel, bestProb = None, -1 for classValue, probability in probabilities.items(): if bestLabel is None or probability > bestProb: bestProb = probability bestLabel = classValue return bestLabel # returns predictions for a set of examplesdef getPredictions(info, test): predictions = [] for i in range(len(test)): result = predict(info, test[i]) predictions.append(result) return predictions # Accuracy scoredef accuracy_rate(test, predictions): correct = 0 for i in range(len(test)): if test[i][-1] == predictions[i]: correct += 1 return (correct / float(len(test))) * 100.0 # driver code # add the data path in your systemfilename = r'E:\user\MACHINE LEARNING\machine learning algos\Naive bayes\filedata.csv' # load the file and store it in mydata listmydata = csv.reader(open(filename, "rt"))mydata = list(mydata)mydata = encode_class(mydata)for i in range(len(mydata)): mydata[i] = [float(x) for x in mydata[i]] # split ratio = 0.7# 70% of data is training data and 30% is test data used for testingratio = 0.7train_data, test_data = splitting(mydata, ratio)print('Total number of examples are: ', len(mydata))print('Out of these, training examples are: ', len(train_data))print("Test examples are: ", len(test_data)) # prepare modelinfo = MeanAndStdDevForClass(train_data) # test modelpredictions = getPredictions(info, test_data)accuracy = accuracy_rate(test_data, predictions)print("Accuracy of your model is: ", accuracy)
Output:
Total number of examples are: 200
Out of these, training examples are: 140
Test examples are: 60
Accuracy of your model is: 71.2376788
surinderdawra388
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Tree Introduction with example
Search Algorithms in AI
Getting started with Machine Learning
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 472,
"s": 54,
"text": "Introduction to Naive Bayes Naive Bayes is among one of the very simple and powerful algorithms for classification based on Bayes Theorem with an assumption of independence among the predictors. The Naive Bayes classifier assumes that the presence of a feature in a class is not related to any other feature. Naive Bayes is a classification algorithm for binary and multi-class classification problems.Bayes Theorem "
},
{
"code": null,
"e": 597,
"s": 472,
"text": "Based on prior knowledge of conditions that may be related to an event, Bayes theorem describes the probability of the event"
},
{
"code": null,
"e": 643,
"s": 597,
"text": "conditional probability can be found this way"
},
{
"code": null,
"e": 914,
"s": 643,
"text": "Assume we have a Hypothesis(H) and evidence(E), According to Bayes theorem, the relationship between the probability of Hypothesis before getting the evidence represented as P(H) and the probability of the hypothesis after getting the evidence represented as P(H|E) is: "
},
{
"code": null,
"e": 940,
"s": 914,
"text": "P(H|E) = P(E|H)*P(H)/P(E)"
},
{
"code": null,
"e": 1085,
"s": 940,
"text": "Prior probability = P(H) is the probability before getting the evidence Posterior probability = P(H|E) is the probability after getting evidence"
},
{
"code": null,
"e": 1099,
"s": 1085,
"text": "In general, "
},
{
"code": null,
"e": 1152,
"s": 1099,
"text": "P(class|data) = (P(data|class) * P(class)) / P(data)"
},
{
"code": null,
"e": 1512,
"s": 1152,
"text": "Bayes Theorem Example Assume we have to find the probability of the randomly picked card to be king given that it is a face card. There are 4 Kings in a Deck of Cards which implies that P(King) = 4/52 as all the Kings are face Cards so P(Face|King) = 1 there are 3 Face Cards in a Suit of 13 cards and there are 4 Suits in total so P(Face) = 12/52 Therefore, "
},
{
"code": null,
"e": 1562,
"s": 1512,
"text": "P(King|face) = P(face|king)*P(king)/P(face) = 1/3"
},
{
"code": null,
"e": 1586,
"s": 1564,
"text": "Download dataset here"
},
{
"code": null,
"e": 1656,
"s": 1586,
"text": "Code : Implementing Naive Bayes algorithm from scratch using Python "
},
{
"code": null,
"e": 1664,
"s": 1656,
"text": "Python3"
},
{
"code": "# Importing libraryimport mathimport randomimport csv # the categorical class names are changed to numberic data# eg: yes and no encoded to 1 and 0def encode_class(mydata): classes = [] for i in range(len(mydata)): if mydata[i][-1] not in classes: classes.append(mydata[i][-1]) for i in range(len(classes)): for j in range(len(mydata)): if mydata[j][-1] == classes[i]: mydata[j][-1] = i return mydata # Splitting the datadef splitting(mydata, ratio): train_num = int(len(mydata) * ratio) train = [] # initially testset will have all the dataset test = list(mydata) while len(train) < train_num: # index generated randomly from range 0 # to length of testset index = random.randrange(len(test)) # from testset, pop data rows and put it in train train.append(test.pop(index)) return train, test # Group the data rows under each class yes or# no in dictionary eg: dict[yes] and dict[no]def groupUnderClass(mydata): dict = {} for i in range(len(mydata)): if (mydata[i][-1] not in dict): dict[mydata[i][-1]] = [] dict[mydata[i][-1]].append(mydata[i]) return dict # Calculating Meandef mean(numbers): return sum(numbers) / float(len(numbers)) # Calculating Standard Deviationdef std_dev(numbers): avg = mean(numbers) variance = sum([pow(x - avg, 2) for x in numbers]) / float(len(numbers) - 1) return math.sqrt(variance) def MeanAndStdDev(mydata): info = [(mean(attribute), std_dev(attribute)) for attribute in zip(*mydata)] # eg: list = [ [a, b, c], [m, n, o], [x, y, z]] # here mean of 1st attribute =(a + m+x), mean of 2nd attribute = (b + n+y)/3 # delete summaries of last class del info[-1] return info # find Mean and Standard Deviation under each classdef MeanAndStdDevForClass(mydata): info = {} dict = groupUnderClass(mydata) for classValue, instances in dict.items(): info[classValue] = MeanAndStdDev(instances) return info # Calculate Gaussian Probability Density Functiondef calculateGaussianProbability(x, mean, stdev): expo = math.exp(-(math.pow(x - mean, 2) / (2 * math.pow(stdev, 2)))) return (1 / (math.sqrt(2 * math.pi) * stdev)) * expo # Calculate Class Probabilitiesdef calculateClassProbabilities(info, test): probabilities = {} for classValue, classSummaries in info.items(): probabilities[classValue] = 1 for i in range(len(classSummaries)): mean, std_dev = classSummaries[i] x = test[i] probabilities[classValue] *= calculateGaussianProbability(x, mean, std_dev) return probabilities # Make prediction - highest probability is the predictiondef predict(info, test): probabilities = calculateClassProbabilities(info, test) bestLabel, bestProb = None, -1 for classValue, probability in probabilities.items(): if bestLabel is None or probability > bestProb: bestProb = probability bestLabel = classValue return bestLabel # returns predictions for a set of examplesdef getPredictions(info, test): predictions = [] for i in range(len(test)): result = predict(info, test[i]) predictions.append(result) return predictions # Accuracy scoredef accuracy_rate(test, predictions): correct = 0 for i in range(len(test)): if test[i][-1] == predictions[i]: correct += 1 return (correct / float(len(test))) * 100.0 # driver code # add the data path in your systemfilename = r'E:\\user\\MACHINE LEARNING\\machine learning algos\\Naive bayes\\filedata.csv' # load the file and store it in mydata listmydata = csv.reader(open(filename, \"rt\"))mydata = list(mydata)mydata = encode_class(mydata)for i in range(len(mydata)): mydata[i] = [float(x) for x in mydata[i]] # split ratio = 0.7# 70% of data is training data and 30% is test data used for testingratio = 0.7train_data, test_data = splitting(mydata, ratio)print('Total number of examples are: ', len(mydata))print('Out of these, training examples are: ', len(train_data))print(\"Test examples are: \", len(test_data)) # prepare modelinfo = MeanAndStdDevForClass(train_data) # test modelpredictions = getPredictions(info, test_data)accuracy = accuracy_rate(test_data, predictions)print(\"Accuracy of your model is: \", accuracy)",
"e": 6040,
"s": 1664,
"text": null
},
{
"code": null,
"e": 6050,
"s": 6040,
"text": "Output: "
},
{
"code": null,
"e": 6185,
"s": 6050,
"text": "Total number of examples are: 200\nOut of these, training examples are: 140\nTest examples are: 60\nAccuracy of your model is: 71.2376788"
},
{
"code": null,
"e": 6204,
"s": 6187,
"text": "surinderdawra388"
},
{
"code": null,
"e": 6221,
"s": 6204,
"text": "Machine Learning"
},
{
"code": null,
"e": 6228,
"s": 6221,
"text": "Python"
},
{
"code": null,
"e": 6245,
"s": 6228,
"text": "Machine Learning"
},
{
"code": null,
"e": 6343,
"s": 6245,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6383,
"s": 6343,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 6407,
"s": 6383,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 6445,
"s": 6407,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 6486,
"s": 6445,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 6519,
"s": 6486,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 6547,
"s": 6519,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 6569,
"s": 6547,
"text": "Python map() function"
},
{
"code": null,
"e": 6619,
"s": 6569,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 6637,
"s": 6619,
"text": "Python Dictionary"
}
] |
Shortest path in a graph from a source S to destination D with exactly K edges for multiple Queries
|
13 May, 2021
Given a graph with N nodes, a node S and Q queries each consisting of a node D and K, the task is to find the shortest path consisting of exactly K edges from node S to node D for each query. If no such path exists then print -1.
Note: K will always be lesser than 2 * N.
Examples:
Input: N = 3, edges[][] = {{1, 2, 5}, {2, 3, 3}, {3, 1, 4}}, S = 1, Q = {{1, 0}, {2, 1}, {3, 1}, {3, 2}, {3, 5}} Output: 0 5 -1 8 20 1. The shortest path from 1 to 1 using 0 edge will be 0. 2. The shortest path from 1 to 2 using 1 edge will be 5 i.e 1->2. 3. No path of 1 edge exists between nodes 1 and 3. 4. The shortest path from 1 to 3 using 2 edges will be 8 i.e 1->2->3. 5. The shortest path from 1 to 3 using 5 edges will be 20 i.e 1->2->3->1->2->3.
Input: N = 4, edges[][] = {{1, 2, 8}, {2, 3, 5}, {3, 4, 7}}, S = 1, Q = {{1, 0}, {2, 1}, {3, 1}, {3, 2}, {4, 5}} Output: 0 8 -1 13 -1
Approach:
This problem can be solved with the help of dynamic programming to create a linear solution.
Initialize a 2-d array, dp[N][2*N] with initial value as ‘inf’ except dp[S][0] as 0.
Pre-process the graph to find the shortest distance of each and every node from the source for every edge length between {0 to N-1}. The array dp[][] will be used to store the results of the pre-processing.
For the pre-processing, run a loop for J in the range [1, 2*N-1] to find the dp[X][J] for each edge in the graph, where dp[X][J] be the shortest path from node ‘S’ to node ‘X’ using exactly ‘J’ edges in total.
We can find dp[X][J+1] with the help of a recurrence relation:
dp[ edge.second ][ i ] = min(dp[ edge.second ][ i ], dp[ edge.first ][ i-1 ] + weight(edge))
For every query in Q, if(dp[X][k] == inf) then return -1, else return dp[X][k]
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach #include <bits/stdc++.h>using namespace std; #define inf 100000000 // Function to find the shortest path// between S and D with exactly K edgesvoid ansQueries(int s, vector<pair<pair<int, int>, int> > ed, int n, vector<pair<int, int> > q){ // To store the dp states int dp[n + 1][2 * n]; // Initialising the dp[][] array for (int i = 0; i <= n; i++) dp[i][0] = inf; dp[s][0] = 0; // Pre-Processing for (int i = 1; i <= 2 * n - 1; i++) { // Initialising current state for (int j = 0; j <= n; j++) dp[j][i] = inf; // Updating current state for (auto it : ed) { dp[it.first.second][i] = min( dp[it.first.second][i], dp[it.first.first][i - 1] + it.second); } } for (int i = 0; i < q.size(); i++) { if (dp[q[i].first][q[i].second] == inf) cout << -1 << endl; else cout << dp[q[i].first][q[i].second] << endl; }} // Driver codeint main(){ int n = 3; vector<pair<pair<int, int>, int> > ed; // Edges ed = { { { 1, 2 }, 5 }, { { 2, 3 }, 3 }, { { 3, 1 }, 4 } }; // Source int s = 1; // Queries vector<pair<int, int> > q = { { 1, 0 }, { 2, 1 }, { 3, 1 }, { 3, 2 }, { 3, 5 } }; // Function to answer queries ansQueries(s, ed, n, q); return 0;}
// Java implementation of the approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ static int inf = 100000000; // Function to find the shortest path// between S and D with exactly K edgesstatic void ansQueries(int s, int[][] ed, int n, int[][] q){ // To store the dp states int[][] dp = new int[n + 1][2 * n]; // Initialising the dp[][] array for(int i = 0; i <= n; i++) dp[i][0] = inf; dp[s][0] = 0; // Pre-Processing for(int i = 1; i <= 2 * n - 1; i++) { // Initialising current state for(int j = 0; j <= n; j++) dp[j][i] = inf; // Updating current state for(int[] it : ed) { dp[it[1]][i] = Math.min(dp[it[1]][i], dp[it[0]][i - 1] + it[2]); } } for(int i = 0; i < q.length; i++) { if (dp[q[i][0]][q[i][1]] == inf) System.out.println(-1); else System.out.println(dp[q[i][0]][q[i][1]]); }} // Driver codepublic static void main(String[] args){ int n = 3; // Edges int[][] ed = { { 1, 2, 5 }, { 2, 3, 3 }, { 3, 1, 4 } }; // Source int s = 1; // Queries int[][] q = { { 1, 0 }, { 2, 1 }, { 3, 1 }, { 3, 2 }, { 3, 5 } }; // Function to answer queries ansQueries(s, ed, n, q);}} // This code is contributed by offbeat
# Python3 implementation of the approachimport sys,numpy as np inf = sys.maxsize; # Function to find the shortest path# between S and D with exactly K edgesdef ansQueries(s, ed, n, q) : # To store the dp states dp = np.zeros((n + 1, 2 * n)); # Initialising the dp[][] array for i in range(n + 1) : dp[i][0] = inf; dp[s][0] = 0; # Pre-Processing for i in range( 1, 2 * n) : # Initialising current state for j in range( n + 1) : dp[j][i] = inf; # Updating current state for it in ed : dp[it[1]][i] = min( dp[it[1]][i], dp[it[0]][i - 1] + ed[it]); for i in range(len(q)) : if (dp[q[i][0]][q[i][1]] == inf) : print(-1); else : print(dp[q[i][0]][q[i][1]]); # Driver codeif __name__ == "__main__" : n = 3; # Edges ed = { ( 1, 2 ) : 5 , ( 2, 3 ) : 3 , ( 3, 1 ) : 4 }; # Source s = 1; # Queries q = [ ( 1, 0 ), ( 2, 1 ), ( 3, 1 ), ( 3, 2 ), ( 3, 5 ) ]; # Function to answer queries ansQueries(s, ed, n, q); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System;class GFG{ static int inf = 100000000; // Function to find the shortest path // between S and D with exactly K edges static void ansQueries(int s, int[][] ed, int n, int[][] q) { // To store the dp states int[, ] dp = new int[n + 1, 2 * n]; // Initialising the dp[][] array for (int i = 0; i <= n; i++) dp[i, 0] = inf; dp[s, 0] = 0; // Pre-Processing for (int i = 1; i <= 2 * n - 1; i++) { // Initialising current state for (int j = 0; j <= n; j++) dp[j, i] = inf; // Updating current state foreach (int[] it in ed) { dp[it[1], i] = Math.Min(dp[it[1], i], dp[it[0], i - 1] + it[2]); } } for (int i = 0; i < q.Length; i++) { if (dp[q[i][0], q[i][1]] == inf) Console.WriteLine(-1); else Console.WriteLine(dp[q[i][0], q[i][1]]); } } // Driver code public static void Main(string[] args) { int n = 3; // Edges int[][] ed = { new int[3]{1, 2, 5}, new int[3]{2, 3, 3}, new int[3]{3, 1, 4} }; // Source int s = 1; // Queries int[][] q = { new int[2]{1, 0}, new int[2]{2, 1}, new int[2]{3, 1}, new int[2]{3, 2}, new int[2]{3, 5} }; // Function to answer queries ansQueries(s, ed, n, q); }} // This code is contributed by sanjeev2552
<script> // Javascript implementation of the approachvar inf = 100000000; // Function to find the shortest path// between S and D with exactly K edgesfunction ansQueries( s, ed, n, q){ // To store the dp states var dp = Array.from(Array(n+1), ()=> Array(2*n)); // Initialising the dp[][] array for (var i = 0; i <= n; i++) dp[i][0] = inf; dp[s][0] = 0; // Pre-Processing for (var i = 1; i <= 2 * n - 1; i++) { // Initialising current state for (var j = 0; j <= n; j++) dp[j][i] = inf; // Updating current state for(var it =0; it<ed.length; it++) { dp[ed[it][0][1]][i] = Math.min( dp[ed[it][0][1]][i], dp[ed[it][0][0]][i - 1] + ed[it][1]); } } for (var i = 0; i < q.length; i++) { if (dp[q[i][0]][q[i][1]] == inf) document.write( -1+ "<br>" ); else document.write( dp[q[i][0]][q[i][1]]+ "<br>"); }} // Driver codevar n = 3;var ed;// Edgesed = [ [ [ 1, 2 ], 5 ], [ [ 2, 3 ], 3 ], [ [ 3, 1 ], 4 ] ];// Sourcevar s = 1;// Queriesvar q = [ [ 1, 0 ], [ 2, 1 ], [ 3, 1 ], [ 3, 2 ], [ 3, 5 ] ];// Function to answer queriesansQueries(s, ed, n, q); </script>
0
5
-1
8
20
Time Complexity: O(Q + N*E) Space Complexity: O(N*N)
ankthon
offbeat
sanjeev2552
rutvik_56
Graph
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find if there is a path between two vertices in a directed graph
Introduction to Data Structures
Find if there is a path between two vertices in an undirected graph
What is Data Structure: Types, Classifications and Applications
Top 50 Graph Coding Problems for Interviews
Detect Cycle in a Directed Graph using BFS
K Centers Problem | Set 1 (Greedy Approximate Algorithm)
Bridges in a graph
Water Jug problem using BFS
Real-time application of Data Structures
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 May, 2021"
},
{
"code": null,
"e": 259,
"s": 28,
"text": "Given a graph with N nodes, a node S and Q queries each consisting of a node D and K, the task is to find the shortest path consisting of exactly K edges from node S to node D for each query. If no such path exists then print -1. "
},
{
"code": null,
"e": 301,
"s": 259,
"text": "Note: K will always be lesser than 2 * N."
},
{
"code": null,
"e": 312,
"s": 301,
"text": "Examples: "
},
{
"code": null,
"e": 769,
"s": 312,
"text": "Input: N = 3, edges[][] = {{1, 2, 5}, {2, 3, 3}, {3, 1, 4}}, S = 1, Q = {{1, 0}, {2, 1}, {3, 1}, {3, 2}, {3, 5}} Output: 0 5 -1 8 20 1. The shortest path from 1 to 1 using 0 edge will be 0. 2. The shortest path from 1 to 2 using 1 edge will be 5 i.e 1->2. 3. No path of 1 edge exists between nodes 1 and 3. 4. The shortest path from 1 to 3 using 2 edges will be 8 i.e 1->2->3. 5. The shortest path from 1 to 3 using 5 edges will be 20 i.e 1->2->3->1->2->3."
},
{
"code": null,
"e": 905,
"s": 769,
"text": "Input: N = 4, edges[][] = {{1, 2, 8}, {2, 3, 5}, {3, 4, 7}}, S = 1, Q = {{1, 0}, {2, 1}, {3, 1}, {3, 2}, {4, 5}} Output: 0 8 -1 13 -1 "
},
{
"code": null,
"e": 917,
"s": 905,
"text": "Approach: "
},
{
"code": null,
"e": 1010,
"s": 917,
"text": "This problem can be solved with the help of dynamic programming to create a linear solution."
},
{
"code": null,
"e": 1095,
"s": 1010,
"text": "Initialize a 2-d array, dp[N][2*N] with initial value as ‘inf’ except dp[S][0] as 0."
},
{
"code": null,
"e": 1302,
"s": 1095,
"text": "Pre-process the graph to find the shortest distance of each and every node from the source for every edge length between {0 to N-1}. The array dp[][] will be used to store the results of the pre-processing."
},
{
"code": null,
"e": 1512,
"s": 1302,
"text": "For the pre-processing, run a loop for J in the range [1, 2*N-1] to find the dp[X][J] for each edge in the graph, where dp[X][J] be the shortest path from node ‘S’ to node ‘X’ using exactly ‘J’ edges in total."
},
{
"code": null,
"e": 1575,
"s": 1512,
"text": "We can find dp[X][J+1] with the help of a recurrence relation:"
},
{
"code": null,
"e": 1670,
"s": 1575,
"text": "dp[ edge.second ][ i ] = min(dp[ edge.second ][ i ], dp[ edge.first ][ i-1 ] + weight(edge)) "
},
{
"code": null,
"e": 1749,
"s": 1670,
"text": "For every query in Q, if(dp[X][k] == inf) then return -1, else return dp[X][k]"
},
{
"code": null,
"e": 1801,
"s": 1749,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1805,
"s": 1801,
"text": "C++"
},
{
"code": null,
"e": 1810,
"s": 1805,
"text": "Java"
},
{
"code": null,
"e": 1818,
"s": 1810,
"text": "Python3"
},
{
"code": null,
"e": 1821,
"s": 1818,
"text": "C#"
},
{
"code": null,
"e": 1832,
"s": 1821,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach #include <bits/stdc++.h>using namespace std; #define inf 100000000 // Function to find the shortest path// between S and D with exactly K edgesvoid ansQueries(int s, vector<pair<pair<int, int>, int> > ed, int n, vector<pair<int, int> > q){ // To store the dp states int dp[n + 1][2 * n]; // Initialising the dp[][] array for (int i = 0; i <= n; i++) dp[i][0] = inf; dp[s][0] = 0; // Pre-Processing for (int i = 1; i <= 2 * n - 1; i++) { // Initialising current state for (int j = 0; j <= n; j++) dp[j][i] = inf; // Updating current state for (auto it : ed) { dp[it.first.second][i] = min( dp[it.first.second][i], dp[it.first.first][i - 1] + it.second); } } for (int i = 0; i < q.size(); i++) { if (dp[q[i].first][q[i].second] == inf) cout << -1 << endl; else cout << dp[q[i].first][q[i].second] << endl; }} // Driver codeint main(){ int n = 3; vector<pair<pair<int, int>, int> > ed; // Edges ed = { { { 1, 2 }, 5 }, { { 2, 3 }, 3 }, { { 3, 1 }, 4 } }; // Source int s = 1; // Queries vector<pair<int, int> > q = { { 1, 0 }, { 2, 1 }, { 3, 1 }, { 3, 2 }, { 3, 5 } }; // Function to answer queries ansQueries(s, ed, n, q); return 0;}",
"e": 3427,
"s": 1832,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ static int inf = 100000000; // Function to find the shortest path// between S and D with exactly K edgesstatic void ansQueries(int s, int[][] ed, int n, int[][] q){ // To store the dp states int[][] dp = new int[n + 1][2 * n]; // Initialising the dp[][] array for(int i = 0; i <= n; i++) dp[i][0] = inf; dp[s][0] = 0; // Pre-Processing for(int i = 1; i <= 2 * n - 1; i++) { // Initialising current state for(int j = 0; j <= n; j++) dp[j][i] = inf; // Updating current state for(int[] it : ed) { dp[it[1]][i] = Math.min(dp[it[1]][i], dp[it[0]][i - 1] + it[2]); } } for(int i = 0; i < q.length; i++) { if (dp[q[i][0]][q[i][1]] == inf) System.out.println(-1); else System.out.println(dp[q[i][0]][q[i][1]]); }} // Driver codepublic static void main(String[] args){ int n = 3; // Edges int[][] ed = { { 1, 2, 5 }, { 2, 3, 3 }, { 3, 1, 4 } }; // Source int s = 1; // Queries int[][] q = { { 1, 0 }, { 2, 1 }, { 3, 1 }, { 3, 2 }, { 3, 5 } }; // Function to answer queries ansQueries(s, ed, n, q);}} // This code is contributed by offbeat",
"e": 5009,
"s": 3427,
"text": null
},
{
"code": "# Python3 implementation of the approachimport sys,numpy as np inf = sys.maxsize; # Function to find the shortest path# between S and D with exactly K edgesdef ansQueries(s, ed, n, q) : # To store the dp states dp = np.zeros((n + 1, 2 * n)); # Initialising the dp[][] array for i in range(n + 1) : dp[i][0] = inf; dp[s][0] = 0; # Pre-Processing for i in range( 1, 2 * n) : # Initialising current state for j in range( n + 1) : dp[j][i] = inf; # Updating current state for it in ed : dp[it[1]][i] = min( dp[it[1]][i], dp[it[0]][i - 1] + ed[it]); for i in range(len(q)) : if (dp[q[i][0]][q[i][1]] == inf) : print(-1); else : print(dp[q[i][0]][q[i][1]]); # Driver codeif __name__ == \"__main__\" : n = 3; # Edges ed = { ( 1, 2 ) : 5 , ( 2, 3 ) : 3 , ( 3, 1 ) : 4 }; # Source s = 1; # Queries q = [ ( 1, 0 ), ( 2, 1 ), ( 3, 1 ), ( 3, 2 ), ( 3, 5 ) ]; # Function to answer queries ansQueries(s, ed, n, q); # This code is contributed by AnkitRai01",
"e": 6208,
"s": 5009,
"text": null
},
{
"code": "// C# implementation of the approachusing System;class GFG{ static int inf = 100000000; // Function to find the shortest path // between S and D with exactly K edges static void ansQueries(int s, int[][] ed, int n, int[][] q) { // To store the dp states int[, ] dp = new int[n + 1, 2 * n]; // Initialising the dp[][] array for (int i = 0; i <= n; i++) dp[i, 0] = inf; dp[s, 0] = 0; // Pre-Processing for (int i = 1; i <= 2 * n - 1; i++) { // Initialising current state for (int j = 0; j <= n; j++) dp[j, i] = inf; // Updating current state foreach (int[] it in ed) { dp[it[1], i] = Math.Min(dp[it[1], i], dp[it[0], i - 1] + it[2]); } } for (int i = 0; i < q.Length; i++) { if (dp[q[i][0], q[i][1]] == inf) Console.WriteLine(-1); else Console.WriteLine(dp[q[i][0], q[i][1]]); } } // Driver code public static void Main(string[] args) { int n = 3; // Edges int[][] ed = { new int[3]{1, 2, 5}, new int[3]{2, 3, 3}, new int[3]{3, 1, 4} }; // Source int s = 1; // Queries int[][] q = { new int[2]{1, 0}, new int[2]{2, 1}, new int[2]{3, 1}, new int[2]{3, 2}, new int[2]{3, 5} }; // Function to answer queries ansQueries(s, ed, n, q); }} // This code is contributed by sanjeev2552",
"e": 7626,
"s": 6208,
"text": null
},
{
"code": "<script> // Javascript implementation of the approachvar inf = 100000000; // Function to find the shortest path// between S and D with exactly K edgesfunction ansQueries( s, ed, n, q){ // To store the dp states var dp = Array.from(Array(n+1), ()=> Array(2*n)); // Initialising the dp[][] array for (var i = 0; i <= n; i++) dp[i][0] = inf; dp[s][0] = 0; // Pre-Processing for (var i = 1; i <= 2 * n - 1; i++) { // Initialising current state for (var j = 0; j <= n; j++) dp[j][i] = inf; // Updating current state for(var it =0; it<ed.length; it++) { dp[ed[it][0][1]][i] = Math.min( dp[ed[it][0][1]][i], dp[ed[it][0][0]][i - 1] + ed[it][1]); } } for (var i = 0; i < q.length; i++) { if (dp[q[i][0]][q[i][1]] == inf) document.write( -1+ \"<br>\" ); else document.write( dp[q[i][0]][q[i][1]]+ \"<br>\"); }} // Driver codevar n = 3;var ed;// Edgesed = [ [ [ 1, 2 ], 5 ], [ [ 2, 3 ], 3 ], [ [ 3, 1 ], 4 ] ];// Sourcevar s = 1;// Queriesvar q = [ [ 1, 0 ], [ 2, 1 ], [ 3, 1 ], [ 3, 2 ], [ 3, 5 ] ];// Function to answer queriesansQueries(s, ed, n, q); </script>",
"e": 9001,
"s": 7626,
"text": null
},
{
"code": null,
"e": 9013,
"s": 9001,
"text": "0\n5\n-1\n8\n20"
},
{
"code": null,
"e": 9069,
"s": 9015,
"text": "Time Complexity: O(Q + N*E) Space Complexity: O(N*N) "
},
{
"code": null,
"e": 9077,
"s": 9069,
"text": "ankthon"
},
{
"code": null,
"e": 9085,
"s": 9077,
"text": "offbeat"
},
{
"code": null,
"e": 9097,
"s": 9085,
"text": "sanjeev2552"
},
{
"code": null,
"e": 9107,
"s": 9097,
"text": "rutvik_56"
},
{
"code": null,
"e": 9113,
"s": 9107,
"text": "Graph"
},
{
"code": null,
"e": 9119,
"s": 9113,
"text": "Graph"
},
{
"code": null,
"e": 9217,
"s": 9119,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9282,
"s": 9217,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 9314,
"s": 9282,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 9382,
"s": 9314,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 9446,
"s": 9382,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 9490,
"s": 9446,
"text": "Top 50 Graph Coding Problems for Interviews"
},
{
"code": null,
"e": 9533,
"s": 9490,
"text": "Detect Cycle in a Directed Graph using BFS"
},
{
"code": null,
"e": 9590,
"s": 9533,
"text": "K Centers Problem | Set 1 (Greedy Approximate Algorithm)"
},
{
"code": null,
"e": 9609,
"s": 9590,
"text": "Bridges in a graph"
},
{
"code": null,
"e": 9637,
"s": 9609,
"text": "Water Jug problem using BFS"
}
] |
Dart – Installation and Setup in Visual Studio Code
|
15 May, 2021
Dart is a client-optimized programming language that supports various areas like multi-platform application development, formatting, analyzing, and testing code. It is a programming language that forms the basic foundation of Flutter.
Flutter is an open-source UI – Software development kit that helps develop applications for Android, iOS, Linux, Mac, Windows, Google Fuchsia, and the web in a single code base.
Visual Studio Code is a code editor developed by Microsoft for Windows, Mac, and Linux with features like code debugging, syntax highlighting, code completion, code refactoring, etc.
Follow the below steps to install the dart SDK:
Step 1: Open “Get the Dart SDK” website.
Step 2: Scroll down to the bottom of the website and click “Downloading the SDK as a zip file”.
Step 3: Based on your device’s architecture, Click the “Dark SDK” for Windows or Mac or Linux, accordingly.
Step 4: Once the download is complete, go to the “Downloads” folder and unzip the newly downloaded Dart-SDK zip file.
Step 5: For unzipping the file, right-click on the file and click “Extract Here”.
Step 6: Now, a new “dart-sdk” folder will be created in the “Downloads” folder.
Step 7: Copy this file and paste it in the “Program Files” folder in the “C” drive.
Step 8: Open “dart-sdk” folder and you will find a folder named “bin”.
Step 9: Now, right-click on the “bin” folder and choose “Properties”.
Step 10: In the “bin Properties” window, go to “Security” and copy the “Object Name”, also known as the address of the file, and press “Ok”.
Installation of Dart SDK
Step 11: Open “This PC” folder, right-click inside this folder, and choose “Properties”.
Step 12: In the “System” window, select “Advanced system settings” that will be available on the left-hand side of the window.
Step 13: In the “Advanced” tab, press the “Environment Variables...” button.
Step 14: In the “Environment Variables” window, under “User Variables for...” check for the “Path” variable.
Step 15: If it’s available, then press the “Edit” button, press “New” button in the “Edit environment variable” window, add the copied address to it and save the made changes.
Step 16: If it’s unavailable, then create one by pressing the “New” button and entering the “Variable Name” as “Path” and “Variable Value” as the copied address, and press “Ok”.
Setting Environment variables for Dart SDK
Step 17: Now open the Command Prompt (cmd) and type “dart”.
Step 18: The output will be as follows.
Dart
╔════════════════════════════════════════════════════════════════════════════╗ ║ The Dart tool uses Google Analytics to anonymously report feature usage ║ ║ statistics and to send basic crash reports. This data is used to help ║ ║ improve the Dart platform and tools over time. ║ ║ ║ ║ To disable reporting of anonymous analytics, run: ║ ║ ║ ║ dart --disable-analytics ║ ║ ║ ╚════════════════════════════════════════════════════════════════════════════╝ A command-line utility for Dart development. Usage: dart [<vm-flags>] <command|dart-file> [<arguments>] Global options:-h, --help Print this usage information.-v, --verbose Show additional command output. --version Print the Dart SDK version. --enable-analytics Enable anonymous analytics. --disable-analytics Disable anonymous analytics. Available commands: analyze Analyze the project's Dart code. compile Compile Dart to various formats. create Create a new project. fix Apply automated fixes to Dart source code. format Idiomatically format Dart source code. migrate Perform a null safety migration on a project or package. pub Work with packages. run Run a Dart program. test Run tests in this package. Run "dart help <command>" for more information about a command.See https://dart.dev/tools/dart-tool for detailed documentation.
Step 19: If your output is just like above then, it signifies that dart has been installed successfully.
Follow the below steps to set up dart in VS Code:
Step 1: Open Visual Studio Code in your device.
Note: If unavailable then, open “Download Visual Studio Code” and download
the application based on your device’s architecture and configurations.
Step 2: Press “Ctrl + B” and select “Extensions” or directly Press “Ctrl + Shift + X”.
Step 3: In the search bar, type “dart” and open the first extension named “Dart” by “Dart Code” in the list. Press the “Install” button.
Installing Dart in Visual Studio Code
Step 4: Once the installation is complete, click “File” and “New File”.
Step 5: Again click “File”, “Save As” and name the file with a “.dart” extension like “gfg.dart”. This file should be saved under a folder, but not as a loose file. So, if needed to create a new folder named “Dart” and save this new file under this folder.
Now, let’s code our first Dart program.
Dart
void main() { print("Welcome to GeeksforGeeks!");}
Step 6: The above code helps us print the string “Welcome to GeeksforGeeks!”. Type or copy the above code in the coding area.
Step 7: Save the file by pressing “Ctrl + S” or by selecting “File” and “Save”.
Step 8: Now for running the code, press “Ctrl + Shift + D” and press “Run and Debug” button or open “Run” and select “Start Debugging”.
Step 9: Now a new file named “launch.json” will be created and it opens automatically in VS Code.
Dart
{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Dart & Flutter", "request": "launch", "type": "dart", "program" : "gfg.dart" } ]}
Step 10: In “launch.json” file, add “program value” inside the curly brackets ({}), like for example {“program” : “gfg.dart”} as shown above and save the file.
Note: If needed add a “,” (comma), to the previous value of "program" in the code of “launch.json” file.
Step 11: Now, press “Run” and then click “Run without Debugging”. The output of the dart file will be displayed in the “Debug Console”.
Dart
Welcome to GeeksforGeeks!Exited
Step 12: Now for running the code in a terminal, press “Terminal” and click “New terminal”.
Step 13: Now in the terminal, type “dart file_name” like “dart gfg.dart” and press “Enter”.
Step 14: The output of the file will get displayed in the terminal.
Dart
PS C:\Users\name\Dart> dart gfg.dartWelcome to GeeksforGeeks!
Output:
Dart
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ListView Class in Flutter
Flutter - Search Bar
Flutter - FutureBuilder Widget
Flutter - Dialogs
Flutter - Flexible Widget
How to Find the Wi-Fi Password Using CMD in Windows?
Docker - COPY Instruction
Setting up the environment in Java
How to Run a Python Script using Docker?
Running Python script on GPU.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 May, 2021"
},
{
"code": null,
"e": 288,
"s": 52,
"text": "Dart is a client-optimized programming language that supports various areas like multi-platform application development, formatting, analyzing, and testing code. It is a programming language that forms the basic foundation of Flutter. "
},
{
"code": null,
"e": 467,
"s": 288,
"text": " Flutter is an open-source UI – Software development kit that helps develop applications for Android, iOS, Linux, Mac, Windows, Google Fuchsia, and the web in a single code base."
},
{
"code": null,
"e": 650,
"s": 467,
"text": "Visual Studio Code is a code editor developed by Microsoft for Windows, Mac, and Linux with features like code debugging, syntax highlighting, code completion, code refactoring, etc."
},
{
"code": null,
"e": 698,
"s": 650,
"text": "Follow the below steps to install the dart SDK:"
},
{
"code": null,
"e": 739,
"s": 698,
"text": "Step 1: Open “Get the Dart SDK” website."
},
{
"code": null,
"e": 835,
"s": 739,
"text": "Step 2: Scroll down to the bottom of the website and click “Downloading the SDK as a zip file”."
},
{
"code": null,
"e": 943,
"s": 835,
"text": "Step 3: Based on your device’s architecture, Click the “Dark SDK” for Windows or Mac or Linux, accordingly."
},
{
"code": null,
"e": 1061,
"s": 943,
"text": "Step 4: Once the download is complete, go to the “Downloads” folder and unzip the newly downloaded Dart-SDK zip file."
},
{
"code": null,
"e": 1143,
"s": 1061,
"text": "Step 5: For unzipping the file, right-click on the file and click “Extract Here”."
},
{
"code": null,
"e": 1223,
"s": 1143,
"text": "Step 6: Now, a new “dart-sdk” folder will be created in the “Downloads” folder."
},
{
"code": null,
"e": 1307,
"s": 1223,
"text": "Step 7: Copy this file and paste it in the “Program Files” folder in the “C” drive."
},
{
"code": null,
"e": 1378,
"s": 1307,
"text": "Step 8: Open “dart-sdk” folder and you will find a folder named “bin”."
},
{
"code": null,
"e": 1448,
"s": 1378,
"text": "Step 9: Now, right-click on the “bin” folder and choose “Properties”."
},
{
"code": null,
"e": 1589,
"s": 1448,
"text": "Step 10: In the “bin Properties” window, go to “Security” and copy the “Object Name”, also known as the address of the file, and press “Ok”."
},
{
"code": null,
"e": 1614,
"s": 1589,
"text": "Installation of Dart SDK"
},
{
"code": null,
"e": 1705,
"s": 1614,
"text": "Step 11: Open “This PC” folder, right-click inside this folder, and choose “Properties”. "
},
{
"code": null,
"e": 1834,
"s": 1705,
"text": "Step 12: In the “System” window, select “Advanced system settings” that will be available on the left-hand side of the window. "
},
{
"code": null,
"e": 1911,
"s": 1834,
"text": "Step 13: In the “Advanced” tab, press the “Environment Variables...” button."
},
{
"code": null,
"e": 2020,
"s": 1911,
"text": "Step 14: In the “Environment Variables” window, under “User Variables for...” check for the “Path” variable."
},
{
"code": null,
"e": 2196,
"s": 2020,
"text": "Step 15: If it’s available, then press the “Edit” button, press “New” button in the “Edit environment variable” window, add the copied address to it and save the made changes."
},
{
"code": null,
"e": 2376,
"s": 2196,
"text": "Step 16: If it’s unavailable, then create one by pressing the “New” button and entering the “Variable Name” as “Path” and “Variable Value” as the copied address, and press “Ok”. "
},
{
"code": null,
"e": 2419,
"s": 2376,
"text": "Setting Environment variables for Dart SDK"
},
{
"code": null,
"e": 2479,
"s": 2419,
"text": "Step 17: Now open the Command Prompt (cmd) and type “dart”."
},
{
"code": null,
"e": 2519,
"s": 2479,
"text": "Step 18: The output will be as follows."
},
{
"code": null,
"e": 2524,
"s": 2519,
"text": "Dart"
},
{
"code": " ╔════════════════════════════════════════════════════════════════════════════╗ ║ The Dart tool uses Google Analytics to anonymously report feature usage ║ ║ statistics and to send basic crash reports. This data is used to help ║ ║ improve the Dart platform and tools over time. ║ ║ ║ ║ To disable reporting of anonymous analytics, run: ║ ║ ║ ║ dart --disable-analytics ║ ║ ║ ╚════════════════════════════════════════════════════════════════════════════╝ A command-line utility for Dart development. Usage: dart [<vm-flags>] <command|dart-file> [<arguments>] Global options:-h, --help Print this usage information.-v, --verbose Show additional command output. --version Print the Dart SDK version. --enable-analytics Enable anonymous analytics. --disable-analytics Disable anonymous analytics. Available commands: analyze Analyze the project's Dart code. compile Compile Dart to various formats. create Create a new project. fix Apply automated fixes to Dart source code. format Idiomatically format Dart source code. migrate Perform a null safety migration on a project or package. pub Work with packages. run Run a Dart program. test Run tests in this package. Run \"dart help <command>\" for more information about a command.See https://dart.dev/tools/dart-tool for detailed documentation.",
"e": 4268,
"s": 2524,
"text": null
},
{
"code": null,
"e": 4373,
"s": 4268,
"text": "Step 19: If your output is just like above then, it signifies that dart has been installed successfully."
},
{
"code": null,
"e": 4423,
"s": 4373,
"text": "Follow the below steps to set up dart in VS Code:"
},
{
"code": null,
"e": 4472,
"s": 4423,
"text": "Step 1: Open Visual Studio Code in your device. "
},
{
"code": null,
"e": 4626,
"s": 4472,
"text": "Note: If unavailable then, open “Download Visual Studio Code” and download\n the application based on your device’s architecture and configurations."
},
{
"code": null,
"e": 4713,
"s": 4626,
"text": "Step 2: Press “Ctrl + B” and select “Extensions” or directly Press “Ctrl + Shift + X”."
},
{
"code": null,
"e": 4850,
"s": 4713,
"text": "Step 3: In the search bar, type “dart” and open the first extension named “Dart” by “Dart Code” in the list. Press the “Install” button."
},
{
"code": null,
"e": 4888,
"s": 4850,
"text": "Installing Dart in Visual Studio Code"
},
{
"code": null,
"e": 4960,
"s": 4888,
"text": "Step 4: Once the installation is complete, click “File” and “New File”."
},
{
"code": null,
"e": 5217,
"s": 4960,
"text": "Step 5: Again click “File”, “Save As” and name the file with a “.dart” extension like “gfg.dart”. This file should be saved under a folder, but not as a loose file. So, if needed to create a new folder named “Dart” and save this new file under this folder."
},
{
"code": null,
"e": 5257,
"s": 5217,
"text": "Now, let’s code our first Dart program."
},
{
"code": null,
"e": 5262,
"s": 5257,
"text": "Dart"
},
{
"code": "void main() { print(\"Welcome to GeeksforGeeks!\");}",
"e": 5314,
"s": 5262,
"text": null
},
{
"code": null,
"e": 5440,
"s": 5314,
"text": "Step 6: The above code helps us print the string “Welcome to GeeksforGeeks!”. Type or copy the above code in the coding area."
},
{
"code": null,
"e": 5520,
"s": 5440,
"text": "Step 7: Save the file by pressing “Ctrl + S” or by selecting “File” and “Save”."
},
{
"code": null,
"e": 5656,
"s": 5520,
"text": "Step 8: Now for running the code, press “Ctrl + Shift + D” and press “Run and Debug” button or open “Run” and select “Start Debugging”."
},
{
"code": null,
"e": 5754,
"s": 5656,
"text": "Step 9: Now a new file named “launch.json” will be created and it opens automatically in VS Code."
},
{
"code": null,
"e": 5759,
"s": 5754,
"text": "Dart"
},
{
"code": "{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 \"version\": \"0.2.0\", \"configurations\": [ { \"name\": \"Dart & Flutter\", \"request\": \"launch\", \"type\": \"dart\", \"program\" : \"gfg.dart\" } ]}",
"e": 6159,
"s": 5759,
"text": null
},
{
"code": null,
"e": 6319,
"s": 6159,
"text": "Step 10: In “launch.json” file, add “program value” inside the curly brackets ({}), like for example {“program” : “gfg.dart”} as shown above and save the file."
},
{
"code": null,
"e": 6424,
"s": 6319,
"text": "Note: If needed add a “,” (comma), to the previous value of \"program\" in the code of “launch.json” file."
},
{
"code": null,
"e": 6560,
"s": 6424,
"text": "Step 11: Now, press “Run” and then click “Run without Debugging”. The output of the dart file will be displayed in the “Debug Console”."
},
{
"code": null,
"e": 6565,
"s": 6560,
"text": "Dart"
},
{
"code": "Welcome to GeeksforGeeks!Exited",
"e": 6597,
"s": 6565,
"text": null
},
{
"code": null,
"e": 6689,
"s": 6597,
"text": "Step 12: Now for running the code in a terminal, press “Terminal” and click “New terminal”."
},
{
"code": null,
"e": 6781,
"s": 6689,
"text": "Step 13: Now in the terminal, type “dart file_name” like “dart gfg.dart” and press “Enter”."
},
{
"code": null,
"e": 6849,
"s": 6781,
"text": "Step 14: The output of the file will get displayed in the terminal."
},
{
"code": null,
"e": 6854,
"s": 6849,
"text": "Dart"
},
{
"code": "PS C:\\Users\\name\\Dart> dart gfg.dartWelcome to GeeksforGeeks!",
"e": 6916,
"s": 6854,
"text": null
},
{
"code": null,
"e": 6924,
"s": 6916,
"text": "Output:"
},
{
"code": null,
"e": 6929,
"s": 6924,
"text": "Dart"
},
{
"code": null,
"e": 6938,
"s": 6929,
"text": "TechTips"
},
{
"code": null,
"e": 7036,
"s": 6938,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7062,
"s": 7036,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 7083,
"s": 7062,
"text": "Flutter - Search Bar"
},
{
"code": null,
"e": 7114,
"s": 7083,
"text": "Flutter - FutureBuilder Widget"
},
{
"code": null,
"e": 7132,
"s": 7114,
"text": "Flutter - Dialogs"
},
{
"code": null,
"e": 7158,
"s": 7132,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 7211,
"s": 7158,
"text": "How to Find the Wi-Fi Password Using CMD in Windows?"
},
{
"code": null,
"e": 7237,
"s": 7211,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 7272,
"s": 7237,
"text": "Setting up the environment in Java"
},
{
"code": null,
"e": 7313,
"s": 7272,
"text": "How to Run a Python Script using Docker?"
}
] |
How to programmatically fire a click event for a file input element in JavaScript ?
|
17 Feb, 2021
In this article, we will learn how to programmatically fire click events on the input file element.
Approach: Whenever you want to perform a click event programmatically, at your specific condition, just use JavaScript in-built click() function by DOM object. For example:
document.getElementById('your_input_type_file_element_id').click();
Example 1: We want to click the input file element automatically (programmatically). When the user clicks one button which is not the ‘file upload’ button of the input type file element, we can achieve it by using the following code.
HTML
<!DOCTYPE html><html><script type="text/javascript"> function open_file(){ document.getElementById('input_file').click(); }</script><body> <input type="file" name="" id='input_file' hidden> <button onclick="open_file()"> click event fire programmatically for input type file element </button></body></html>
Output:The input file type is hidden so whenever you run this code, you easily get the select dialog for file selection. After clicking the above button, we get the file select dialog box like the one below the image.
Example 2: For example, when a user registers for your service, it registers with email, username, and password, etc. Whenever a user registers successfully you give them one secret key by email or SMS. The user enters this secret in the input box on a specific page after which they are able to choose document/ image whatever needed for them.
HTML
<!DOCTYPE html><html> <head> <script type="text/javascript"> function open_file() { var secret_key = document.getElementById("secret_key").value; if (secret_key == "Geeksforgeeks") { // 'Geeksforgeeks' this value is just an example for // your understanding. document.getElementById("input_file").click(); } } </script> </head> <body> <p>Write down 'Geeksforgeeks'</p> <label>Enter Secret Key :</label> <input type="text" name="username" id="secret_key" oninput="open_file()" /> <input type="file" name="" id="input_file" hidden /> </body></html>
Output: After entering the correct secret key into the input box, the file select dialog box will pop up. AJAX request is generated and it matches that user key to the original key via backend files.
JavaScript-Questions
Picked
Technical Scripter 2020
JavaScript
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Feb, 2021"
},
{
"code": null,
"e": 154,
"s": 54,
"text": "In this article, we will learn how to programmatically fire click events on the input file element."
},
{
"code": null,
"e": 327,
"s": 154,
"text": "Approach: Whenever you want to perform a click event programmatically, at your specific condition, just use JavaScript in-built click() function by DOM object. For example:"
},
{
"code": null,
"e": 395,
"s": 327,
"text": "document.getElementById('your_input_type_file_element_id').click();"
},
{
"code": null,
"e": 629,
"s": 395,
"text": "Example 1: We want to click the input file element automatically (programmatically). When the user clicks one button which is not the ‘file upload’ button of the input type file element, we can achieve it by using the following code."
},
{
"code": null,
"e": 634,
"s": 629,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><script type=\"text/javascript\"> function open_file(){ document.getElementById('input_file').click(); }</script><body> <input type=\"file\" name=\"\" id='input_file' hidden> <button onclick=\"open_file()\"> click event fire programmatically for input type file element </button></body></html>",
"e": 968,
"s": 634,
"text": null
},
{
"code": null,
"e": 1186,
"s": 968,
"text": "Output:The input file type is hidden so whenever you run this code, you easily get the select dialog for file selection. After clicking the above button, we get the file select dialog box like the one below the image."
},
{
"code": null,
"e": 1531,
"s": 1186,
"text": "Example 2: For example, when a user registers for your service, it registers with email, username, and password, etc. Whenever a user registers successfully you give them one secret key by email or SMS. The user enters this secret in the input box on a specific page after which they are able to choose document/ image whatever needed for them."
},
{
"code": null,
"e": 1536,
"s": 1531,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script type=\"text/javascript\"> function open_file() { var secret_key = document.getElementById(\"secret_key\").value; if (secret_key == \"Geeksforgeeks\") { // 'Geeksforgeeks' this value is just an example for // your understanding. document.getElementById(\"input_file\").click(); } } </script> </head> <body> <p>Write down 'Geeksforgeeks'</p> <label>Enter Secret Key :</label> <input type=\"text\" name=\"username\" id=\"secret_key\" oninput=\"open_file()\" /> <input type=\"file\" name=\"\" id=\"input_file\" hidden /> </body></html>",
"e": 2261,
"s": 1536,
"text": null
},
{
"code": null,
"e": 2461,
"s": 2261,
"text": "Output: After entering the correct secret key into the input box, the file select dialog box will pop up. AJAX request is generated and it matches that user key to the original key via backend files."
},
{
"code": null,
"e": 2482,
"s": 2461,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 2489,
"s": 2482,
"text": "Picked"
},
{
"code": null,
"e": 2513,
"s": 2489,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2524,
"s": 2513,
"text": "JavaScript"
},
{
"code": null,
"e": 2543,
"s": 2524,
"text": "Technical Scripter"
}
] |
Python program to split and join a string
|
12 Jun, 2022
Python program to Split a string based on a delimiter and join the string using another delimiter. Split a string can be quite useful sometimes, especially when you need only certain parts of strings. A simple yet effective example is splitting the First-name and Last-name of a person. Another application is CSV(Comma Separated Files). We use split to get data from CSV and join to write data to CSV. In Python, we can use the function split() to split a string and join() to join a string. For detailed article on split() and join() functions, refer these : split() in Python and join() in Python. Examples :
Split the string into list of strings
Input : Geeks for Geeks
Output : ['Geeks', 'for', 'Geeks']
Join the list of strings into a string based on delimiter ('-')
Input : ['Geeks', 'for', 'Geeks']
Output : Geeks-for-Geeks
Below is Python code to Split and Join the string based on a delimiter :
Python3
# Python program to split a string and # join it using different delimiter def split_string(string): # Split the string based on space delimiter list_string = string.split(' ') return list_string def join_string(list_string): # Join the string based on '-' delimiter string = '-'.join(list_string) return string # Driver Functionif __name__ == '__main__': string = 'Geeks for Geeks' # Splitting a string list_string = split_string(string) print(list_string) # Join list of strings into one new_string = join_string(list_string) print(new_string)
['Geeks', 'for', 'Geeks']
Geeks-for-Geeks
Method: In Python, we can use the function split() to split a string and join() to join a string. the split() method in Python split a string into a list of strings after breaking the given string by the specified separator. Python String join() method is a string method and returns a string in which the elements of the sequence have been joined by the str separator.
Python3
# Python code# to split and join given string # input strings = 'Geeks for Geeks'# print the string after split methodprint(s.split(" "))# print the string after join methodprint("-".join(s.split())) # this code is contributed by gangarajula laxmi
['Geeks', 'for', 'Geeks']
Geeks-for-Geeks
Python Programming Tutorial | Program to split and join a string | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPython Programming Tutorial | Program to split and join a string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:02•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=aWab32mDz9Y" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
&t=1s
laxmigangarajula03
Python string-programs
python-string
Python
Python Programs
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()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n12 Jun, 2022"
},
{
"code": null,
"e": 665,
"s": 53,
"text": "Python program to Split a string based on a delimiter and join the string using another delimiter. Split a string can be quite useful sometimes, especially when you need only certain parts of strings. A simple yet effective example is splitting the First-name and Last-name of a person. Another application is CSV(Comma Separated Files). We use split to get data from CSV and join to write data to CSV. In Python, we can use the function split() to split a string and join() to join a string. For detailed article on split() and join() functions, refer these : split() in Python and join() in Python. Examples :"
},
{
"code": null,
"e": 890,
"s": 665,
"text": "Split the string into list of strings\n\nInput : Geeks for Geeks\nOutput : ['Geeks', 'for', 'Geeks']\n\n\nJoin the list of strings into a string based on delimiter ('-')\n\nInput : ['Geeks', 'for', 'Geeks']\nOutput : Geeks-for-Geeks"
},
{
"code": null,
"e": 964,
"s": 890,
"text": "Below is Python code to Split and Join the string based on a delimiter : "
},
{
"code": null,
"e": 972,
"s": 964,
"text": "Python3"
},
{
"code": "# Python program to split a string and # join it using different delimiter def split_string(string): # Split the string based on space delimiter list_string = string.split(' ') return list_string def join_string(list_string): # Join the string based on '-' delimiter string = '-'.join(list_string) return string # Driver Functionif __name__ == '__main__': string = 'Geeks for Geeks' # Splitting a string list_string = split_string(string) print(list_string) # Join list of strings into one new_string = join_string(list_string) print(new_string)",
"e": 1576,
"s": 972,
"text": null
},
{
"code": null,
"e": 1619,
"s": 1576,
"text": "['Geeks', 'for', 'Geeks']\nGeeks-for-Geeks\n"
},
{
"code": null,
"e": 1990,
"s": 1619,
"text": "Method: In Python, we can use the function split() to split a string and join() to join a string. the split() method in Python split a string into a list of strings after breaking the given string by the specified separator. Python String join() method is a string method and returns a string in which the elements of the sequence have been joined by the str separator. "
},
{
"code": null,
"e": 1998,
"s": 1990,
"text": "Python3"
},
{
"code": "# Python code# to split and join given string # input strings = 'Geeks for Geeks'# print the string after split methodprint(s.split(\" \"))# print the string after join methodprint(\"-\".join(s.split())) # this code is contributed by gangarajula laxmi",
"e": 2247,
"s": 1998,
"text": null
},
{
"code": null,
"e": 2290,
"s": 2247,
"text": "['Geeks', 'for', 'Geeks']\nGeeks-for-Geeks\n"
},
{
"code": null,
"e": 3236,
"s": 2290,
"text": "Python Programming Tutorial | Program to split and join a string | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPython Programming Tutorial | Program to split and join a string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:02•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=aWab32mDz9Y\" 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": 3242,
"s": 3236,
"text": "&t=1s"
},
{
"code": null,
"e": 3261,
"s": 3242,
"text": "laxmigangarajula03"
},
{
"code": null,
"e": 3284,
"s": 3261,
"text": "Python string-programs"
},
{
"code": null,
"e": 3298,
"s": 3284,
"text": "python-string"
},
{
"code": null,
"e": 3305,
"s": 3298,
"text": "Python"
},
{
"code": null,
"e": 3321,
"s": 3305,
"text": "Python Programs"
},
{
"code": null,
"e": 3419,
"s": 3321,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3437,
"s": 3419,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3479,
"s": 3437,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3501,
"s": 3479,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3536,
"s": 3501,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3562,
"s": 3536,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3605,
"s": 3562,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 3627,
"s": 3605,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3666,
"s": 3627,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3704,
"s": 3666,
"text": "Python | Convert a list to dictionary"
}
] |
Template Method Design Pattern
|
18 Oct, 2021
Template method design pattern is to define an algorithm as a skeleton of operations and leave the details to be implemented by the child classes. The overall structure and sequence of the algorithm are preserved by the parent class. Template means Preset format like HTML templates which has a fixed preset format. Similarly in the template method pattern, we have a preset structure method called template method which consists of steps. These steps can be an abstract method that will be implemented by its subclasses.This behavioral design pattern is one of the easiest to understand and implement. This design pattern is used popularly in framework development. This helps to avoid code duplication also.
Source: Wikipedia
AbstractClass contains the templateMethod() which should be made final so that it cannot be overridden. This template method makes use of other operations available in order to run the algorithm but is decoupled for the actual implementation of these methods. All operations used by this template method are made abstract, so their implementation is deferred to subclasses.
ConcreteClass implements all the operations required by the templateMethod that were defined as abstract in the parent class. There can be many different ConcreteClasses.
Let’s see an example of the template method pattern.
Java
abstract class OrderProcessTemplate{ public boolean isGift; public abstract void doSelect(); public abstract void doPayment(); public final void giftWrap() { try { System.out.println("Gift wrap successful"); } catch (Exception e) { System.out.println("Gift wrap unsuccessful"); } } public abstract void doDelivery(); public final void processOrder(boolean isGift) { doSelect(); doPayment(); if (isGift) { giftWrap(); } doDelivery(); }} class NetOrder extends OrderProcessTemplate{ @Override public void doSelect() { System.out.println("Item added to online shopping cart"); System.out.println("Get gift wrap preference"); System.out.println("Get delivery address."); } @Override public void doPayment() { System.out.println ("Online Payment through Netbanking, card or Paytm"); } @Override public void doDelivery() { System.out.println ("Ship the item through post to delivery address"); } } class StoreOrder extends OrderProcessTemplate{ @Override public void doSelect() { System.out.println("Customer chooses the item from shelf."); } @Override public void doPayment() { System.out.println("Pays at counter through cash/POS"); } @Override public void doDelivery() { System.out.println("Item delivered to in delivery counter."); } } class TemplateMethodPatternClient{ public static void main(String[] args) { OrderProcessTemplate netOrder = new NetOrder(); netOrder.processOrder(true); System.out.println(); OrderProcessTemplate storeOrder = new StoreOrder(); storeOrder.processOrder(true); }}
Output :
Item added to online shopping cart
Get gift wrap preference
Get delivery address.
Online Payment through Netbanking, card or Paytm
Gift wrap successful
Ship the item through post to delivery address
Customer chooses the item from shelf.
Pays at counter through cash/POS
Gift wrap successful
Item delivered to in delivery counter.
The above example deals with order processing flow. The OrderProcessTemplate class is an abstract class containing the algorithm skeleton. As shown on the note, processOrder() is the method that contains the process steps. We have two subclasses NetOrder and StoreOrder which have the same order processing steps.So the overall algorithm used to process an order is defined in the base class and used by the subclasses. But the way individual operations are performed varies depending on the subclass.
When to use template method
The template method is used in frameworks, where each implements the invariant parts of a domain’s architecture, leaving “placeholders” for customization options.The template method is used for the following reasons :
Let subclasses implement varying behavior (through method overriding)
Avoid duplication in the code, the general workflow structure is implemented once in the abstract class’s algorithm, and necessary variations are implemented in the subclasses.
Control at what points subclassing is allowed. As opposed to a simple polymorphic override, where the base method would be entirely rewritten allowing radical change to the workflow, only the specific details of the workflow are allowed to change.
Further Read – Template Method in PythonReference : WikipediaThis article is contributed by Saket Kumar. 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.
nidhi_biet
Pushpender007
Design Pattern
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Strategy Pattern | Set 1 (Introduction)
Design an online book reader system
State Design Pattern
Command Pattern
Observer Pattern | Set 2 (Implementation)
Visitor design pattern
Conceptual Model of the Unified Modeling Language (UML)
Decorator Pattern | Set 1 (Background)
Flyweight Design Pattern
Design a Logistics System
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 763,
"s": 52,
"text": "Template method design pattern is to define an algorithm as a skeleton of operations and leave the details to be implemented by the child classes. The overall structure and sequence of the algorithm are preserved by the parent class. Template means Preset format like HTML templates which has a fixed preset format. Similarly in the template method pattern, we have a preset structure method called template method which consists of steps. These steps can be an abstract method that will be implemented by its subclasses.This behavioral design pattern is one of the easiest to understand and implement. This design pattern is used popularly in framework development. This helps to avoid code duplication also. "
},
{
"code": null,
"e": 782,
"s": 763,
"text": "Source: Wikipedia "
},
{
"code": null,
"e": 1156,
"s": 782,
"text": "AbstractClass contains the templateMethod() which should be made final so that it cannot be overridden. This template method makes use of other operations available in order to run the algorithm but is decoupled for the actual implementation of these methods. All operations used by this template method are made abstract, so their implementation is deferred to subclasses."
},
{
"code": null,
"e": 1327,
"s": 1156,
"text": "ConcreteClass implements all the operations required by the templateMethod that were defined as abstract in the parent class. There can be many different ConcreteClasses."
},
{
"code": null,
"e": 1382,
"s": 1327,
"text": "Let’s see an example of the template method pattern. "
},
{
"code": null,
"e": 1387,
"s": 1382,
"text": "Java"
},
{
"code": "abstract class OrderProcessTemplate{ public boolean isGift; public abstract void doSelect(); public abstract void doPayment(); public final void giftWrap() { try { System.out.println(\"Gift wrap successful\"); } catch (Exception e) { System.out.println(\"Gift wrap unsuccessful\"); } } public abstract void doDelivery(); public final void processOrder(boolean isGift) { doSelect(); doPayment(); if (isGift) { giftWrap(); } doDelivery(); }} class NetOrder extends OrderProcessTemplate{ @Override public void doSelect() { System.out.println(\"Item added to online shopping cart\"); System.out.println(\"Get gift wrap preference\"); System.out.println(\"Get delivery address.\"); } @Override public void doPayment() { System.out.println (\"Online Payment through Netbanking, card or Paytm\"); } @Override public void doDelivery() { System.out.println (\"Ship the item through post to delivery address\"); } } class StoreOrder extends OrderProcessTemplate{ @Override public void doSelect() { System.out.println(\"Customer chooses the item from shelf.\"); } @Override public void doPayment() { System.out.println(\"Pays at counter through cash/POS\"); } @Override public void doDelivery() { System.out.println(\"Item delivered to in delivery counter.\"); } } class TemplateMethodPatternClient{ public static void main(String[] args) { OrderProcessTemplate netOrder = new NetOrder(); netOrder.processOrder(true); System.out.println(); OrderProcessTemplate storeOrder = new StoreOrder(); storeOrder.processOrder(true); }}",
"e": 3242,
"s": 1387,
"text": null
},
{
"code": null,
"e": 3253,
"s": 3242,
"text": "Output : "
},
{
"code": null,
"e": 3584,
"s": 3253,
"text": "Item added to online shopping cart\nGet gift wrap preference\nGet delivery address.\nOnline Payment through Netbanking, card or Paytm\nGift wrap successful\nShip the item through post to delivery address\n\nCustomer chooses the item from shelf.\nPays at counter through cash/POS\nGift wrap successful\nItem delivered to in delivery counter."
},
{
"code": null,
"e": 4087,
"s": 3584,
"text": "The above example deals with order processing flow. The OrderProcessTemplate class is an abstract class containing the algorithm skeleton. As shown on the note, processOrder() is the method that contains the process steps. We have two subclasses NetOrder and StoreOrder which have the same order processing steps.So the overall algorithm used to process an order is defined in the base class and used by the subclasses. But the way individual operations are performed varies depending on the subclass. "
},
{
"code": null,
"e": 4115,
"s": 4087,
"text": "When to use template method"
},
{
"code": null,
"e": 4334,
"s": 4115,
"text": "The template method is used in frameworks, where each implements the invariant parts of a domain’s architecture, leaving “placeholders” for customization options.The template method is used for the following reasons : "
},
{
"code": null,
"e": 4404,
"s": 4334,
"text": "Let subclasses implement varying behavior (through method overriding)"
},
{
"code": null,
"e": 4581,
"s": 4404,
"text": "Avoid duplication in the code, the general workflow structure is implemented once in the abstract class’s algorithm, and necessary variations are implemented in the subclasses."
},
{
"code": null,
"e": 4829,
"s": 4581,
"text": "Control at what points subclassing is allowed. As opposed to a simple polymorphic override, where the base method would be entirely rewritten allowing radical change to the workflow, only the specific details of the workflow are allowed to change."
},
{
"code": null,
"e": 5310,
"s": 4829,
"text": "Further Read – Template Method in PythonReference : WikipediaThis article is contributed by Saket Kumar. 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": 5321,
"s": 5310,
"text": "nidhi_biet"
},
{
"code": null,
"e": 5335,
"s": 5321,
"text": "Pushpender007"
},
{
"code": null,
"e": 5350,
"s": 5335,
"text": "Design Pattern"
},
{
"code": null,
"e": 5448,
"s": 5350,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5488,
"s": 5448,
"text": "Strategy Pattern | Set 1 (Introduction)"
},
{
"code": null,
"e": 5524,
"s": 5488,
"text": "Design an online book reader system"
},
{
"code": null,
"e": 5545,
"s": 5524,
"text": "State Design Pattern"
},
{
"code": null,
"e": 5561,
"s": 5545,
"text": "Command Pattern"
},
{
"code": null,
"e": 5603,
"s": 5561,
"text": "Observer Pattern | Set 2 (Implementation)"
},
{
"code": null,
"e": 5626,
"s": 5603,
"text": "Visitor design pattern"
},
{
"code": null,
"e": 5682,
"s": 5626,
"text": "Conceptual Model of the Unified Modeling Language (UML)"
},
{
"code": null,
"e": 5721,
"s": 5682,
"text": "Decorator Pattern | Set 1 (Background)"
},
{
"code": null,
"e": 5746,
"s": 5721,
"text": "Flyweight Design Pattern"
}
] |
Python | Pandas.Categorical()
|
10 Mar, 2022
pandas.Categorical(val, categories = None, ordered = None, dtype = None) : It represents a categorical variable. Categorical are a pandas data type that corresponds to the categorical variables in statistics. Such variables take on a fixed and limited number of possible values. For examples – grades, gender, blood group type etc. Also, in the case of categorical variables, logical order is not the same as categorical data e.g. “one”, “two”, “three”. But the sorting of these variables uses logical order.
Parameters- val : [list-like] The values of categorical.
categories : [index like] Unique categorisation of the categories.
ordered : [boolean] If false, then the categorical is treated as unordered.
dtype : [CategoricalDtype] an instance.
Error- ValueError : If the categories do not validate.
TypeError : If an explicit ordered = True but categorical can't be sorted.
Return- Categorical variable
Code:
Python3
# Python code explaining# numpy.pandas.Categorical() # importing librariesimport numpy as npimport pandas as pd # Categorical using dtypec = pd.Series(["a", "b", "d", "a", "d"], dtype ="category")print ("\nCategorical without pandas.Categorical() : \n", c) c1 = pd.Categorical([1, 2, 3, 1, 2, 3])print ("\n\nc1 : ", c1) c2 = pd.Categorical(['e', 'm', 'f', 'i', 'f', 'e', 'h', 'm' ])print ("\nc2 : ", c2)
Output :
Python3
# Ordered = Truec3 = pd.Categorical(['e', 'm', 'f', 'i', 'f', 'e', 'h', 'm' ], ordered = True)print ("\nc3 : ", c3)
Output :
Python3
# Mixed categoriesc4 = pd.Categorical(['a', 2, 3, 1, 2, 3])print ("\nc4 : ", c4) c5 = pd.Categorical(['a', 2, 3, 1, 2, 3], ordered = True)print ("\nc5 : ", c5)
Output :
Python3
# using categories attributec6 = pd.Categorical([1, 2, 3, 1, 2, 3], categories = [4, 1, 3, 5])print ("\nc6 : ", c6) print("\n\nSeries : \n", pd.Series(c6)) df = pd.DataFrame({"A":[1, 2, 3, 1, 2, 3]})df["B"] = c6print ("\n\nDataframe : \n", df)
Output :
sooda367
rkbhola5
Python pandas-datatypes
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Enumerate() in Python
Rotate axis tick labels in Seaborn and Matplotlib
Python Dictionary
Deque in Python
Stack in Python
Queue in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Mar, 2022"
},
{
"code": null,
"e": 539,
"s": 28,
"text": "pandas.Categorical(val, categories = None, ordered = None, dtype = None) : It represents a categorical variable. Categorical are a pandas data type that corresponds to the categorical variables in statistics. Such variables take on a fixed and limited number of possible values. For examples – grades, gender, blood group type etc. Also, in the case of categorical variables, logical order is not the same as categorical data e.g. “one”, “two”, “three”. But the sorting of these variables uses logical order. "
},
{
"code": null,
"e": 964,
"s": 539,
"text": "Parameters- val : [list-like] The values of categorical. \ncategories : [index like] Unique categorisation of the categories. \nordered : [boolean] If false, then the categorical is treated as unordered. \ndtype : [CategoricalDtype] an instance. \n\nError- ValueError : If the categories do not validate. \nTypeError : If an explicit ordered = True but categorical can't be sorted. \n\nReturn- Categorical variable"
},
{
"code": null,
"e": 971,
"s": 964,
"text": "Code: "
},
{
"code": null,
"e": 979,
"s": 971,
"text": "Python3"
},
{
"code": "# Python code explaining# numpy.pandas.Categorical() # importing librariesimport numpy as npimport pandas as pd # Categorical using dtypec = pd.Series([\"a\", \"b\", \"d\", \"a\", \"d\"], dtype =\"category\")print (\"\\nCategorical without pandas.Categorical() : \\n\", c) c1 = pd.Categorical([1, 2, 3, 1, 2, 3])print (\"\\n\\nc1 : \", c1) c2 = pd.Categorical(['e', 'm', 'f', 'i', 'f', 'e', 'h', 'm' ])print (\"\\nc2 : \", c2)",
"e": 1404,
"s": 979,
"text": null
},
{
"code": null,
"e": 1415,
"s": 1404,
"text": "Output : "
},
{
"code": null,
"e": 1427,
"s": 1419,
"text": "Python3"
},
{
"code": "# Ordered = Truec3 = pd.Categorical(['e', 'm', 'f', 'i', 'f', 'e', 'h', 'm' ], ordered = True)print (\"\\nc3 : \", c3)",
"e": 1563,
"s": 1427,
"text": null
},
{
"code": null,
"e": 1574,
"s": 1563,
"text": "Output : "
},
{
"code": null,
"e": 1586,
"s": 1578,
"text": "Python3"
},
{
"code": "# Mixed categoriesc4 = pd.Categorical(['a', 2, 3, 1, 2, 3])print (\"\\nc4 : \", c4) c5 = pd.Categorical(['a', 2, 3, 1, 2, 3], ordered = True)print (\"\\nc5 : \", c5)",
"e": 1746,
"s": 1586,
"text": null
},
{
"code": null,
"e": 1757,
"s": 1746,
"text": "Output : "
},
{
"code": null,
"e": 1769,
"s": 1761,
"text": "Python3"
},
{
"code": "# using categories attributec6 = pd.Categorical([1, 2, 3, 1, 2, 3], categories = [4, 1, 3, 5])print (\"\\nc6 : \", c6) print(\"\\n\\nSeries : \\n\", pd.Series(c6)) df = pd.DataFrame({\"A\":[1, 2, 3, 1, 2, 3]})df[\"B\"] = c6print (\"\\n\\nDataframe : \\n\", df)",
"e": 2013,
"s": 1769,
"text": null
},
{
"code": null,
"e": 2024,
"s": 2013,
"text": "Output : "
},
{
"code": null,
"e": 2035,
"s": 2026,
"text": "sooda367"
},
{
"code": null,
"e": 2044,
"s": 2035,
"text": "rkbhola5"
},
{
"code": null,
"e": 2068,
"s": 2044,
"text": "Python pandas-datatypes"
},
{
"code": null,
"e": 2082,
"s": 2068,
"text": "Python-pandas"
},
{
"code": null,
"e": 2089,
"s": 2082,
"text": "Python"
},
{
"code": null,
"e": 2187,
"s": 2089,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2232,
"s": 2187,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 2254,
"s": 2232,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2304,
"s": 2254,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 2322,
"s": 2304,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2338,
"s": 2322,
"text": "Deque in Python"
},
{
"code": null,
"e": 2354,
"s": 2338,
"text": "Stack in Python"
},
{
"code": null,
"e": 2370,
"s": 2354,
"text": "Queue in Python"
},
{
"code": null,
"e": 2392,
"s": 2370,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2434,
"s": 2392,
"text": "Different ways to create Pandas Dataframe"
}
] |
Lex code to count total number of tokens
|
21 May, 2019
Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lex in the C programming language.
Tokens: A token is a group of characters forming a basic atomic chunk of syntax i.e. token is a class of lexemes that matches a pattern. Eg – Keywords, identifier, operator, separator.
Example:
Input: int p=0, d=1, c=2;
Output:
total no. of tokens = 13
Below is the implementation of the above explanation:
/*Lex code to count total number of tokens */ %{ int n = 0 ; %} // rule section%% //count number of keywords"while"|"if"|"else" {n++;printf("\t keywords : %s", yytext);} // count number of keywords"int"|"float" {n++;printf("\t keywords : %s", yytext);} // count number of identifiers[a-zA-Z_][a-zA-Z0-9_]* {n++;printf("\t identifier : %s", yytext);} // count number of operators"<="|"=="|"="|"++"|"-"|"*"|"+" {n++;printf("\t operator : %s", yytext);} // count number of separators[(){}|, ;] {n++;printf("\t separator : %s", yytext);} // count number of floats[0-9]*"."[0-9]+ {n++;printf("\t float : %s", yytext);} // count number of integers[0-9]+ {n++;printf("\t integer : %s", yytext);} . ;%% int main() { yylex(); printf("\n total no. of token = %d\n", n); }
Output:
Ravimaurya2
Lex program
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Directed Acyclic graph in Compiler Design (with examples)
Type Checking in Compiler Design
Data flow analysis in Compiler
S - attributed and L - attributed SDTs in Syntax directed translation
Runtime Environments in Compiler Design
Compiler construction tools
Basic Blocks in Compiler Design
Token, Patterns, and Lexems
Compiler Design - Variants of Syntax Tree
Loop Optimization in Compiler Design
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n21 May, 2019"
},
{
"code": null,
"e": 293,
"s": 53,
"text": "Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lex in the C programming language."
},
{
"code": null,
"e": 478,
"s": 293,
"text": "Tokens: A token is a group of characters forming a basic atomic chunk of syntax i.e. token is a class of lexemes that matches a pattern. Eg – Keywords, identifier, operator, separator."
},
{
"code": null,
"e": 487,
"s": 478,
"text": "Example:"
},
{
"code": null,
"e": 549,
"s": 487,
"text": "Input: int p=0, d=1, c=2;\n\nOutput: \ntotal no. of tokens = 13\n"
},
{
"code": null,
"e": 603,
"s": 549,
"text": "Below is the implementation of the above explanation:"
},
{
"code": "/*Lex code to count total number of tokens */ %{ int n = 0 ; %} // rule section%% //count number of keywords\"while\"|\"if\"|\"else\" {n++;printf(\"\\t keywords : %s\", yytext);} // count number of keywords\"int\"|\"float\" {n++;printf(\"\\t keywords : %s\", yytext);} // count number of identifiers[a-zA-Z_][a-zA-Z0-9_]* {n++;printf(\"\\t identifier : %s\", yytext);} // count number of operators\"<=\"|\"==\"|\"=\"|\"++\"|\"-\"|\"*\"|\"+\" {n++;printf(\"\\t operator : %s\", yytext);} // count number of separators[(){}|, ;] {n++;printf(\"\\t separator : %s\", yytext);} // count number of floats[0-9]*\".\"[0-9]+ {n++;printf(\"\\t float : %s\", yytext);} // count number of integers[0-9]+ {n++;printf(\"\\t integer : %s\", yytext);} . ;%% int main() { yylex(); printf(\"\\n total no. of token = %d\\n\", n); } ",
"e": 1454,
"s": 603,
"text": null
},
{
"code": null,
"e": 1462,
"s": 1454,
"text": "Output:"
},
{
"code": null,
"e": 1474,
"s": 1462,
"text": "Ravimaurya2"
},
{
"code": null,
"e": 1486,
"s": 1474,
"text": "Lex program"
},
{
"code": null,
"e": 1502,
"s": 1486,
"text": "Compiler Design"
},
{
"code": null,
"e": 1600,
"s": 1502,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1658,
"s": 1600,
"text": "Directed Acyclic graph in Compiler Design (with examples)"
},
{
"code": null,
"e": 1691,
"s": 1658,
"text": "Type Checking in Compiler Design"
},
{
"code": null,
"e": 1722,
"s": 1691,
"text": "Data flow analysis in Compiler"
},
{
"code": null,
"e": 1792,
"s": 1722,
"text": "S - attributed and L - attributed SDTs in Syntax directed translation"
},
{
"code": null,
"e": 1832,
"s": 1792,
"text": "Runtime Environments in Compiler Design"
},
{
"code": null,
"e": 1860,
"s": 1832,
"text": "Compiler construction tools"
},
{
"code": null,
"e": 1892,
"s": 1860,
"text": "Basic Blocks in Compiler Design"
},
{
"code": null,
"e": 1920,
"s": 1892,
"text": "Token, Patterns, and Lexems"
},
{
"code": null,
"e": 1962,
"s": 1920,
"text": "Compiler Design - Variants of Syntax Tree"
}
] |
C program to find and replace a word in a File by another given word - GeeksforGeeks
|
09 Sep, 2021
Pre-requisite: File Handling in CGiven a file containing some text, and two strings wordToBeFind and wordToBeReplacedWith, the task is to find all occurrences of the given word ‘wordToBeFind’ in the file and replace them with the given word ‘wordToBeReplacedWith’.
Examples:
Input : File = "xxforxx xx for xx",
wordToBeFind = "xx",
wordToBeReplacedWith = "geeks"
Output : geeksforgeeks geeks for geeks
Approach: The idea here is to read the contents from the given file, process the find and replace, and then store the output in another file.
Make objects of FILE (ifp and ofp)Open two files, one for file input in read mode and another in write+ modeCheck for the file to be opened correctlyRead the contents of the existing input file word by wordAs using fgets takes the input of new line character(i.e. enter key) also we just copy the null character of the string one position back so that the newline is replaced with “\0”We run a loop till the end of file is reached and scan each word in the file and store it in a variable “read”.Then we compare “read” with “wordToBeFind” and if the result is true, we use “strcpy()” to replace “read” with “wordToBeReplacedWith”.Show the word replacement through printfNow again we shift the filepointer at the beginning of the file and print the file contents of the output file.
Make objects of FILE (ifp and ofp)
Open two files, one for file input in read mode and another in write+ mode
Check for the file to be opened correctly
Read the contents of the existing input file word by word
As using fgets takes the input of new line character(i.e. enter key) also we just copy the null character of the string one position back so that the newline is replaced with “\0”
We run a loop till the end of file is reached and scan each word in the file and store it in a variable “read”.
Then we compare “read” with “wordToBeFind” and if the result is true, we use “strcpy()” to replace “read” with “wordToBeReplacedWith”.
Show the word replacement through printf
Now again we shift the filepointer at the beginning of the file and print the file contents of the output file.
Below is the implementation of the above approach:
C
// C program to find and replace a word// in a File by another given word #include <stdio.h>#include <stdlib.h>#include <string.h> // Function to find and// replace a word in Filevoid findAndReplaceInFile(){ FILE *ifp, *ofp; char word[100], ch, read[100], replace[100]; int word_len, i, p = 0; ifp = fopen("file_search_input.txt", "r"); ofp = fopen("file_replace_output.txt", "w+"); if (ifp == NULL || ofp == NULL) { printf("Can't open file."); exit(0); } puts("THE CONTENTS OF THE FILE ARE SHOWN BELOW :\n"); // displaying file contents while (1) { ch = fgetc(ifp); if (ch == EOF) { break; } printf("%c", ch); } puts("\n\nEnter the word to find:"); fgets(word, 100, stdin); // removes the newline character from the string word[strlen(word) - 1] = word[strlen(word)]; puts("Enter the word to replace it with :"); fgets(replace, 100, stdin); // removes the newline character from the string replace[strlen(replace) - 1] = replace[strlen(replace)]; fprintf(ofp, "%s - %s\n", word, replace); // comparing word with file rewind(ifp); while (!feof(ifp)) { fscanf(ifp, "%s", read); if (strcmp(read, word) == 0) { // for deleting the word strcpy(read, replace); } // In last loop it runs twice fprintf(ofp, "%s ", read); } // Printing the content of the Output file rewind(ofp); while (1) { ch = fgetc(ofp); if (ch == EOF) { break; } printf("%c", ch); } fclose(ifp); fclose(ofp);} // Driver codevoid main(){ findAndReplaceInFile();}
How to execute the above code:
Copy the source code from here and paste it in an offline IDESave the program.Create a file named “file_search_input.txt” and save it in the folder where you saved the above-copied program.Now open the terminal or offline IDE and run the program
Copy the source code from here and paste it in an offline IDE
Save the program.
Create a file named “file_search_input.txt” and save it in the folder where you saved the above-copied program.
Now open the terminal or offline IDE and run the program
Output:
simmytarika5
C-File Handling
C Programs
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Header files in C/C++ and its uses
How to return multiple values from a function in C or C++?
How to Append a Character to a String in C
C program to sort an array in ascending order
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": 24442,
"s": 24414,
"text": "\n09 Sep, 2021"
},
{
"code": null,
"e": 24708,
"s": 24442,
"text": "Pre-requisite: File Handling in CGiven a file containing some text, and two strings wordToBeFind and wordToBeReplacedWith, the task is to find all occurrences of the given word ‘wordToBeFind’ in the file and replace them with the given word ‘wordToBeReplacedWith’. "
},
{
"code": null,
"e": 24719,
"s": 24708,
"text": "Examples: "
},
{
"code": null,
"e": 24864,
"s": 24719,
"text": "Input : File = \"xxforxx xx for xx\", \n wordToBeFind = \"xx\", \n wordToBeReplacedWith = \"geeks\"\nOutput : geeksforgeeks geeks for geeks"
},
{
"code": null,
"e": 25006,
"s": 24864,
"text": "Approach: The idea here is to read the contents from the given file, process the find and replace, and then store the output in another file."
},
{
"code": null,
"e": 25788,
"s": 25006,
"text": "Make objects of FILE (ifp and ofp)Open two files, one for file input in read mode and another in write+ modeCheck for the file to be opened correctlyRead the contents of the existing input file word by wordAs using fgets takes the input of new line character(i.e. enter key) also we just copy the null character of the string one position back so that the newline is replaced with “\\0”We run a loop till the end of file is reached and scan each word in the file and store it in a variable “read”.Then we compare “read” with “wordToBeFind” and if the result is true, we use “strcpy()” to replace “read” with “wordToBeReplacedWith”.Show the word replacement through printfNow again we shift the filepointer at the beginning of the file and print the file contents of the output file."
},
{
"code": null,
"e": 25823,
"s": 25788,
"text": "Make objects of FILE (ifp and ofp)"
},
{
"code": null,
"e": 25898,
"s": 25823,
"text": "Open two files, one for file input in read mode and another in write+ mode"
},
{
"code": null,
"e": 25940,
"s": 25898,
"text": "Check for the file to be opened correctly"
},
{
"code": null,
"e": 25998,
"s": 25940,
"text": "Read the contents of the existing input file word by word"
},
{
"code": null,
"e": 26178,
"s": 25998,
"text": "As using fgets takes the input of new line character(i.e. enter key) also we just copy the null character of the string one position back so that the newline is replaced with “\\0”"
},
{
"code": null,
"e": 26290,
"s": 26178,
"text": "We run a loop till the end of file is reached and scan each word in the file and store it in a variable “read”."
},
{
"code": null,
"e": 26425,
"s": 26290,
"text": "Then we compare “read” with “wordToBeFind” and if the result is true, we use “strcpy()” to replace “read” with “wordToBeReplacedWith”."
},
{
"code": null,
"e": 26466,
"s": 26425,
"text": "Show the word replacement through printf"
},
{
"code": null,
"e": 26578,
"s": 26466,
"text": "Now again we shift the filepointer at the beginning of the file and print the file contents of the output file."
},
{
"code": null,
"e": 26630,
"s": 26578,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26632,
"s": 26630,
"text": "C"
},
{
"code": "// C program to find and replace a word// in a File by another given word #include <stdio.h>#include <stdlib.h>#include <string.h> // Function to find and// replace a word in Filevoid findAndReplaceInFile(){ FILE *ifp, *ofp; char word[100], ch, read[100], replace[100]; int word_len, i, p = 0; ifp = fopen(\"file_search_input.txt\", \"r\"); ofp = fopen(\"file_replace_output.txt\", \"w+\"); if (ifp == NULL || ofp == NULL) { printf(\"Can't open file.\"); exit(0); } puts(\"THE CONTENTS OF THE FILE ARE SHOWN BELOW :\\n\"); // displaying file contents while (1) { ch = fgetc(ifp); if (ch == EOF) { break; } printf(\"%c\", ch); } puts(\"\\n\\nEnter the word to find:\"); fgets(word, 100, stdin); // removes the newline character from the string word[strlen(word) - 1] = word[strlen(word)]; puts(\"Enter the word to replace it with :\"); fgets(replace, 100, stdin); // removes the newline character from the string replace[strlen(replace) - 1] = replace[strlen(replace)]; fprintf(ofp, \"%s - %s\\n\", word, replace); // comparing word with file rewind(ifp); while (!feof(ifp)) { fscanf(ifp, \"%s\", read); if (strcmp(read, word) == 0) { // for deleting the word strcpy(read, replace); } // In last loop it runs twice fprintf(ofp, \"%s \", read); } // Printing the content of the Output file rewind(ofp); while (1) { ch = fgetc(ofp); if (ch == EOF) { break; } printf(\"%c\", ch); } fclose(ifp); fclose(ofp);} // Driver codevoid main(){ findAndReplaceInFile();}",
"e": 28315,
"s": 26632,
"text": null
},
{
"code": null,
"e": 28346,
"s": 28315,
"text": "How to execute the above code:"
},
{
"code": null,
"e": 28592,
"s": 28346,
"text": "Copy the source code from here and paste it in an offline IDESave the program.Create a file named “file_search_input.txt” and save it in the folder where you saved the above-copied program.Now open the terminal or offline IDE and run the program"
},
{
"code": null,
"e": 28654,
"s": 28592,
"text": "Copy the source code from here and paste it in an offline IDE"
},
{
"code": null,
"e": 28672,
"s": 28654,
"text": "Save the program."
},
{
"code": null,
"e": 28784,
"s": 28672,
"text": "Create a file named “file_search_input.txt” and save it in the folder where you saved the above-copied program."
},
{
"code": null,
"e": 28841,
"s": 28784,
"text": "Now open the terminal or offline IDE and run the program"
},
{
"code": null,
"e": 28849,
"s": 28841,
"text": "Output:"
},
{
"code": null,
"e": 28862,
"s": 28849,
"text": "simmytarika5"
},
{
"code": null,
"e": 28878,
"s": 28862,
"text": "C-File Handling"
},
{
"code": null,
"e": 28889,
"s": 28878,
"text": "C Programs"
},
{
"code": null,
"e": 28897,
"s": 28889,
"text": "Strings"
},
{
"code": null,
"e": 28905,
"s": 28897,
"text": "Strings"
},
{
"code": null,
"e": 29003,
"s": 28905,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29012,
"s": 29003,
"text": "Comments"
},
{
"code": null,
"e": 29025,
"s": 29012,
"text": "Old Comments"
},
{
"code": null,
"e": 29066,
"s": 29025,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 29101,
"s": 29066,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 29160,
"s": 29101,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 29203,
"s": 29160,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 29249,
"s": 29203,
"text": "C program to sort an array in ascending order"
},
{
"code": null,
"e": 29274,
"s": 29249,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 29320,
"s": 29274,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 29354,
"s": 29320,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 29369,
"s": 29354,
"text": "C++ Data Types"
}
] |
How to write Python Regular Expression find repeating digits in a number?
|
The following code using Python regex to find the repeating digits in given string
import re
result = re.search(r'(\d)\1{3}','54222267890' )
print result.group()
This gives the output
2222
|
[
{
"code": null,
"e": 1145,
"s": 1062,
"text": "The following code using Python regex to find the repeating digits in given string"
},
{
"code": null,
"e": 1224,
"s": 1145,
"text": "import re\nresult = re.search(r'(\\d)\\1{3}','54222267890' )\nprint result.group()"
},
{
"code": null,
"e": 1246,
"s": 1224,
"text": "This gives the output"
},
{
"code": null,
"e": 1251,
"s": 1246,
"text": "2222"
}
] |
Print prime factors of a given integer in decreasing order using Stack - GeeksforGeeks
|
18 Jun, 2021
Given an integer N, the task is to print prime factors of N in decreasing order using the stack data structure.
Examples:
Input: N = 34Output:17 2Explanation:The prime factors of the number 34 is 2 and 17.
Input: N = 8Output: 2
Approach: The idea is to use the Stack data structure to store all the prime factors of N and in the end, print all the values in the Stack. Follow the steps below to solve the problem:
Initialize a stack, say st.Run a loop while N != 1. From i = 2, for each value of i, run a loop until N % i == 0 and push i into the stack st and update N to N/i.Finally, print all the values from top to bottom of stack st.
Initialize a stack, say st.
Run a loop while N != 1. From i = 2, for each value of i, run a loop until N % i == 0 and push i into the stack st and update N to N/i.
Finally, print all the values from top to bottom of stack st.
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 print prime factors// of N in decreasing ordervoid PrimeFactors(int N){ // Stores prime factors of N // in decreasing order stack<int> st; int i = 2; while (N != 1) { if (N % i == 0) { // Insert i into stack st.push(i); while (N % i == 0) { // Update N N = N / i; } } // Update i i++; } // Print value of stack st while (!st.empty()) { printf("%d ", st.top()); st.pop(); }} // Driver Codeint main(){ int N = 8; // function Call PrimeFactors(N); return 0;}
// Java program for the above approach import java.util.*; class GFG{ // Function to print prime factors// of N in decreasing orderstatic void PrimeFactors(int N){ // Stores prime factors of N // in decreasing order Stack<Integer> st = new Stack<>(); int i = 2; while (N != 1) { if (N % i == 0) { // Insert i into stack st.push(i); while (N % i == 0) { // Update N N = N / i; } } // Update i i++; } // Print value of stack st while (!st.isEmpty()) { System.out.println(st.peek()); st.pop(); }} // Driver Code public static void main (String[] args) { int N = 8; // Function Call PrimeFactors(N);;}} // This code is contributed by susmitakundugoaldanga
# Python3 program for the above approach # Function to print prime factors# of N in decreasing orderdef PrimeFactors(N): # Stores prime factors of N # in decreasing order st = [] i = 2 while (N != 1): if (N % i == 0): # Insert i into stack st.append(i) while (N % i == 0): # Update N N = N // i # Update i i += 1 # Print value of stack st while (len(st) != 0): print(st[-1]) st.pop() # Driver Codeif __name__ == "__main__": N = 8 # function Call PrimeFactors(N) # This code is contributed by chitranayal.
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to print prime factors// of N in decreasing orderstatic void PrimeFactors(int N){ // Stores prime factors of N // in decreasing order Stack<int> st = new Stack<int>(); int i = 2; while (N != 1) { if (N % i == 0) { // Insert i into stack st.Push(i); while (N % i == 0) { // Update N N = N / i; } } // Update i i++; } // Print value of stack st while (st.Count != 0) { Console.Write(st.Peek()); st.Pop(); }} // Driver Code public static void Main () { int N = 8; // Function Call PrimeFactors(N);;}} // This code is contributed by code_hunt
<script> // JavaScript program for the above approach // Function to print prime factors// of N in decreasing orderfunction PrimeFactors(N){ // Stores prime factors of N // in decreasing order let st = []; let i = 2; while (N != 1) { if (N % i == 0) { // Insert i into stack st.push(i); while (N % i == 0) { // Update N N = Math.floor(N / i); } } // Update i i++; } // Print value of stack st while (st.length!=0) { document.write(st.pop()); }}// Driver Code let N = 8; // Function CallPrimeFactors(N); // This code is contributed by avanitrachhadiya2155 </script>
2
Time Complexity: O(sqrt(N))Auxiliary Space: O(1)
ukasp
susmitakundugoaldanga
code_hunt
avanitrachhadiya2155
cpp-stack-functions
prime-factor
Mathematical
Searching
Searching
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Modular multiplicative inverse
Fizz Buzz Implementation
Generate all permutation of a set in Python
How to check if a given point lies inside or outside a polygon?
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
Search an element in a sorted and rotated array
Find the Missing Number
|
[
{
"code": null,
"e": 26047,
"s": 26019,
"text": "\n18 Jun, 2021"
},
{
"code": null,
"e": 26159,
"s": 26047,
"text": "Given an integer N, the task is to print prime factors of N in decreasing order using the stack data structure."
},
{
"code": null,
"e": 26169,
"s": 26159,
"text": "Examples:"
},
{
"code": null,
"e": 26253,
"s": 26169,
"text": "Input: N = 34Output:17 2Explanation:The prime factors of the number 34 is 2 and 17."
},
{
"code": null,
"e": 26275,
"s": 26253,
"text": "Input: N = 8Output: 2"
},
{
"code": null,
"e": 26461,
"s": 26275,
"text": "Approach: The idea is to use the Stack data structure to store all the prime factors of N and in the end, print all the values in the Stack. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 26685,
"s": 26461,
"text": "Initialize a stack, say st.Run a loop while N != 1. From i = 2, for each value of i, run a loop until N % i == 0 and push i into the stack st and update N to N/i.Finally, print all the values from top to bottom of stack st."
},
{
"code": null,
"e": 26713,
"s": 26685,
"text": "Initialize a stack, say st."
},
{
"code": null,
"e": 26849,
"s": 26713,
"text": "Run a loop while N != 1. From i = 2, for each value of i, run a loop until N % i == 0 and push i into the stack st and update N to N/i."
},
{
"code": null,
"e": 26911,
"s": 26849,
"text": "Finally, print all the values from top to bottom of stack st."
},
{
"code": null,
"e": 26962,
"s": 26911,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26966,
"s": 26962,
"text": "C++"
},
{
"code": null,
"e": 26971,
"s": 26966,
"text": "Java"
},
{
"code": null,
"e": 26979,
"s": 26971,
"text": "Python3"
},
{
"code": null,
"e": 26982,
"s": 26979,
"text": "C#"
},
{
"code": null,
"e": 26993,
"s": 26982,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to print prime factors// of N in decreasing ordervoid PrimeFactors(int N){ // Stores prime factors of N // in decreasing order stack<int> st; int i = 2; while (N != 1) { if (N % i == 0) { // Insert i into stack st.push(i); while (N % i == 0) { // Update N N = N / i; } } // Update i i++; } // Print value of stack st while (!st.empty()) { printf(\"%d \", st.top()); st.pop(); }} // Driver Codeint main(){ int N = 8; // function Call PrimeFactors(N); return 0;}",
"e": 27710,
"s": 26993,
"text": null
},
{
"code": "// Java program for the above approach import java.util.*; class GFG{ // Function to print prime factors// of N in decreasing orderstatic void PrimeFactors(int N){ // Stores prime factors of N // in decreasing order Stack<Integer> st = new Stack<>(); int i = 2; while (N != 1) { if (N % i == 0) { // Insert i into stack st.push(i); while (N % i == 0) { // Update N N = N / i; } } // Update i i++; } // Print value of stack st while (!st.isEmpty()) { System.out.println(st.peek()); st.pop(); }} // Driver Code public static void main (String[] args) { int N = 8; // Function Call PrimeFactors(N);;}} // This code is contributed by susmitakundugoaldanga",
"e": 28602,
"s": 27710,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to print prime factors# of N in decreasing orderdef PrimeFactors(N): # Stores prime factors of N # in decreasing order st = [] i = 2 while (N != 1): if (N % i == 0): # Insert i into stack st.append(i) while (N % i == 0): # Update N N = N // i # Update i i += 1 # Print value of stack st while (len(st) != 0): print(st[-1]) st.pop() # Driver Codeif __name__ == \"__main__\": N = 8 # function Call PrimeFactors(N) # This code is contributed by chitranayal.",
"e": 29245,
"s": 28602,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to print prime factors// of N in decreasing orderstatic void PrimeFactors(int N){ // Stores prime factors of N // in decreasing order Stack<int> st = new Stack<int>(); int i = 2; while (N != 1) { if (N % i == 0) { // Insert i into stack st.Push(i); while (N % i == 0) { // Update N N = N / i; } } // Update i i++; } // Print value of stack st while (st.Count != 0) { Console.Write(st.Peek()); st.Pop(); }} // Driver Code public static void Main () { int N = 8; // Function Call PrimeFactors(N);;}} // This code is contributed by code_hunt",
"e": 30129,
"s": 29245,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to print prime factors// of N in decreasing orderfunction PrimeFactors(N){ // Stores prime factors of N // in decreasing order let st = []; let i = 2; while (N != 1) { if (N % i == 0) { // Insert i into stack st.push(i); while (N % i == 0) { // Update N N = Math.floor(N / i); } } // Update i i++; } // Print value of stack st while (st.length!=0) { document.write(st.pop()); }}// Driver Code let N = 8; // Function CallPrimeFactors(N); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 30916,
"s": 30129,
"text": null
},
{
"code": null,
"e": 30918,
"s": 30916,
"text": "2"
},
{
"code": null,
"e": 30969,
"s": 30920,
"text": "Time Complexity: O(sqrt(N))Auxiliary Space: O(1)"
},
{
"code": null,
"e": 30975,
"s": 30969,
"text": "ukasp"
},
{
"code": null,
"e": 30997,
"s": 30975,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 31007,
"s": 30997,
"text": "code_hunt"
},
{
"code": null,
"e": 31028,
"s": 31007,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 31048,
"s": 31028,
"text": "cpp-stack-functions"
},
{
"code": null,
"e": 31061,
"s": 31048,
"text": "prime-factor"
},
{
"code": null,
"e": 31074,
"s": 31061,
"text": "Mathematical"
},
{
"code": null,
"e": 31084,
"s": 31074,
"text": "Searching"
},
{
"code": null,
"e": 31094,
"s": 31084,
"text": "Searching"
},
{
"code": null,
"e": 31107,
"s": 31094,
"text": "Mathematical"
},
{
"code": null,
"e": 31205,
"s": 31107,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31249,
"s": 31205,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 31280,
"s": 31249,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 31305,
"s": 31280,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 31349,
"s": 31305,
"text": "Generate all permutation of a set in Python"
},
{
"code": null,
"e": 31413,
"s": 31349,
"text": "How to check if a given point lies inside or outside a polygon?"
},
{
"code": null,
"e": 31427,
"s": 31413,
"text": "Binary Search"
},
{
"code": null,
"e": 31495,
"s": 31427,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 31509,
"s": 31495,
"text": "Linear Search"
},
{
"code": null,
"e": 31557,
"s": 31509,
"text": "Search an element in a sorted and rotated array"
}
] |
VueJS - Components
|
Vue Components are one of the important features of VueJS that creates custom elements, which can be reused in HTML.
Let’s work with an example and create a component, that will give a better understanding on how components work with VueJS.
<html>
<head>
<title>VueJs Instance</title>
<script type = "text/javascript" src = "js/vue.js"></script>
</head>
<body>
<div id = "component_test">
<testcomponent></testcomponent>
</div>
<div id = "component_test1">
<testcomponent></testcomponent>
</div>
<script type = "text/javascript" src = "js/vue_component.js"></script>
</body>
</html>
vue_component.js
Vue.component('testcomponent',{
template : '<div><h1>This is coming from component</h1></div>'
});
var vm = new Vue({
el: '#component_test'
});
var vm1 = new Vue({
el: '#component_test1'
});
In the .html file, we have created two div with id component_test and component_test1. In the .js files shown above, two Vue instances are created with the div ids. We have created a common component to be used with both the view instances.
To create a component, following is the syntax.
Vue.component('nameofthecomponent',{ // options});
Once a component is created, the name of the component becomes the custom element and the same can be used in the Vue instance element created, i.e. inside the div with ids component_test and component_test1.
In the .js file, we have used a test component as the name of the component and the same name is used as the custom element inside the divs.
<div id = "component_test">
<testcomponent></testcomponent>
</div>
<div id = "component_test1">
<testcomponent></testcomponent>
</div>
In the component created in the .js file, we have added a template to which we have assigned a HTML code. This is a way of registering a global component, which can be made a part of any vue instance as shown in the following script.
Vue.component('testcomponent',{
template : '<div><h1>This is coming from component</h1></div>'
});
On execution, the same will be reflected in the browser.
The components are given the custom element tag, i.e. <testcomponent></testcomponent>. However, when we inspect the same in the browser, we will not notice the custom tag in plain HTML present in the template as shown in the following screenshot.
We have also directly made the components a part of vue instance as shown in the following script.
var vm = new Vue({
el: '#component_test',
components:{
'testcomponent': {
template : '<div><h1>This is coming from component</h1></div>'
}
}
});
This is called local registration and the components will be a part of only the vue instance created.
So far, we have seen the basic component with the basic options. Now, let’s add some more options such as data and methods to it. Just as Vue instance has data and methods, component also shares the same. Hence, we will extend the code, which we have already seen with data and methods.
<html>
<head>
<title>VueJs Instance</title>
<script type = "text/javascript" src = "js/vue.js"></script>
</head>
<body>
<div id = "component_test">
<testcomponent></testcomponent>
</div>
<div id = "component_test1">
<testcomponent></testcomponent>
</div>
<script type = "text/javascript" src = "js/vue_component.js"></script>
</body>
</html>
vue_component.js
Vue.component('testcomponent',{
template : '<div v-on:mouseover = "changename()" v-on:mouseout = "originalname();"><h1>Custom Component created by <span id = "name">{{name}}</span></h1></div>',
data: function() {
return {
name : "Ria"
}
},
methods:{
changename : function() {
this.name = "Ben";
},
originalname: function() {
this.name = "Ria";
}
}
});
var vm = new Vue({
el: '#component_test'
});
var vm1 = new Vue({
el: '#component_test1'
});
In the .js file above, we have added data that is a function, which returns an object. The object has a name property, which is assigned the value ‘Ria’. This is used in the following template.
template : '<div v-on:mouseover = "changename()" v-on:mouseout = "originalname();"><h1>Custom Component created by <span id = "name">{{name}}</span></h1></div>',
In spite of having data as a function in components, we can use its properties the same way as we use with direct Vue instance. Also, there are two methods added, changename and originalname. In changename, we are changing the name property, and in originalname we are resetting it back to the original name.
We have also added two events on the div, mouseover and mouseout. The details of the events will be discussed in the Events chapter. So for now, mouseover calls changename method and mouseout calls originalname method.
The display of the same is shown in the following browser.
As seen in the above browser, it displays the name assigned in the data property, which is the same name. We have also assigned a mouseover event on the div and also a mouseout. Let’s see what happens when we mouseover and mouseout.
On mouseover, we see the name of the first component is changed to Ben, however, the second one remains as it is. This is because the data component is a function and it returns an object. Thus, when it is changed in one place, the same is not overwritten in other cases.
Dynamic components are created using the keyword <component></component> and it is bound using a property as shown in the following example.
<html>
<head>
<title>VueJs Instance</title>
<script type = "text/javascript" src = "js/vue.js"></script>
</head>
<body>
<div id = "databinding">
<component v-bind:is = "view"></component>
</div>
<script type = "text/javascript">
var vm = new Vue({
el: '#databinding',
data: {
view: 'component1'
},
components: {
'component1': {
template: '<div><span style = "font-size:25;color:red;">Dynamic Component</span></div>'
}
}
});
</script>
</body>
</html>
Dynamic component is created using the following syntax.
<component v-bind:is = "view"></component>
It has v-bind:is = ”view”, and a value view is assigned to it. View is defined in the Vue instance as follows.
var vm = new Vue({
el: '#databinding',
data: {
view: 'component1'
},
components: {
'component1': {
template: '<div><span style = "font-size:25;color:red;">Dynamic Component</span></div>'
}
}
});
When executed, the template Dynamic Component is displayed in the browser.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2053,
"s": 1936,
"text": "Vue Components are one of the important features of VueJS that creates custom elements, which can be reused in HTML."
},
{
"code": null,
"e": 2177,
"s": 2053,
"text": "Let’s work with an example and create a component, that will give a better understanding on how components work with VueJS."
},
{
"code": null,
"e": 2591,
"s": 2177,
"text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"component_test\">\n <testcomponent></testcomponent>\n </div>\n <div id = \"component_test1\">\n <testcomponent></testcomponent>\n </div>\n <script type = \"text/javascript\" src = \"js/vue_component.js\"></script>\n </body>\n</html>"
},
{
"code": null,
"e": 2608,
"s": 2591,
"text": "vue_component.js"
},
{
"code": null,
"e": 2808,
"s": 2608,
"text": "Vue.component('testcomponent',{\n template : '<div><h1>This is coming from component</h1></div>'\n});\nvar vm = new Vue({\n el: '#component_test'\n});\nvar vm1 = new Vue({\n el: '#component_test1'\n});"
},
{
"code": null,
"e": 3049,
"s": 2808,
"text": "In the .html file, we have created two div with id component_test and component_test1. In the .js files shown above, two Vue instances are created with the div ids. We have created a common component to be used with both the view instances."
},
{
"code": null,
"e": 3097,
"s": 3049,
"text": "To create a component, following is the syntax."
},
{
"code": null,
"e": 3148,
"s": 3097,
"text": "Vue.component('nameofthecomponent',{ // options});"
},
{
"code": null,
"e": 3357,
"s": 3148,
"text": "Once a component is created, the name of the component becomes the custom element and the same can be used in the Vue instance element created, i.e. inside the div with ids component_test and component_test1."
},
{
"code": null,
"e": 3498,
"s": 3357,
"text": "In the .js file, we have used a test component as the name of the component and the same name is used as the custom element inside the divs."
},
{
"code": null,
"e": 3639,
"s": 3498,
"text": "<div id = \"component_test\">\n <testcomponent></testcomponent>\n</div>\n<div id = \"component_test1\">\n <testcomponent></testcomponent>\n</div>"
},
{
"code": null,
"e": 3873,
"s": 3639,
"text": "In the component created in the .js file, we have added a template to which we have assigned a HTML code. This is a way of registering a global component, which can be made a part of any vue instance as shown in the following script."
},
{
"code": null,
"e": 3975,
"s": 3873,
"text": "Vue.component('testcomponent',{\n template : '<div><h1>This is coming from component</h1></div>'\n});"
},
{
"code": null,
"e": 4032,
"s": 3975,
"text": "On execution, the same will be reflected in the browser."
},
{
"code": null,
"e": 4279,
"s": 4032,
"text": "The components are given the custom element tag, i.e. <testcomponent></testcomponent>. However, when we inspect the same in the browser, we will not notice the custom tag in plain HTML present in the template as shown in the following screenshot."
},
{
"code": null,
"e": 4378,
"s": 4279,
"text": "We have also directly made the components a part of vue instance as shown in the following script."
},
{
"code": null,
"e": 4553,
"s": 4378,
"text": "var vm = new Vue({\n el: '#component_test',\n components:{\n 'testcomponent': {\n template : '<div><h1>This is coming from component</h1></div>'\n }\n }\n});"
},
{
"code": null,
"e": 4655,
"s": 4553,
"text": "This is called local registration and the components will be a part of only the vue instance created."
},
{
"code": null,
"e": 4942,
"s": 4655,
"text": "So far, we have seen the basic component with the basic options. Now, let’s add some more options such as data and methods to it. Just as Vue instance has data and methods, component also shares the same. Hence, we will extend the code, which we have already seen with data and methods."
},
{
"code": null,
"e": 5356,
"s": 4942,
"text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"component_test\">\n <testcomponent></testcomponent>\n </div>\n <div id = \"component_test1\">\n <testcomponent></testcomponent>\n </div>\n <script type = \"text/javascript\" src = \"js/vue_component.js\"></script>\n </body>\n</html>"
},
{
"code": null,
"e": 5373,
"s": 5356,
"text": "vue_component.js"
},
{
"code": null,
"e": 5901,
"s": 5373,
"text": "Vue.component('testcomponent',{\n template : '<div v-on:mouseover = \"changename()\" v-on:mouseout = \"originalname();\"><h1>Custom Component created by <span id = \"name\">{{name}}</span></h1></div>',\n data: function() {\n return {\n name : \"Ria\"\n }\n },\n methods:{\n changename : function() {\n this.name = \"Ben\";\n },\n originalname: function() {\n this.name = \"Ria\";\n }\n }\n});\nvar vm = new Vue({\n el: '#component_test'\n});\nvar vm1 = new Vue({\n el: '#component_test1'\n});"
},
{
"code": null,
"e": 6095,
"s": 5901,
"text": "In the .js file above, we have added data that is a function, which returns an object. The object has a name property, which is assigned the value ‘Ria’. This is used in the following template."
},
{
"code": null,
"e": 6257,
"s": 6095,
"text": "template : '<div v-on:mouseover = \"changename()\" v-on:mouseout = \"originalname();\"><h1>Custom Component created by <span id = \"name\">{{name}}</span></h1></div>',"
},
{
"code": null,
"e": 6566,
"s": 6257,
"text": "In spite of having data as a function in components, we can use its properties the same way as we use with direct Vue instance. Also, there are two methods added, changename and originalname. In changename, we are changing the name property, and in originalname we are resetting it back to the original name."
},
{
"code": null,
"e": 6785,
"s": 6566,
"text": "We have also added two events on the div, mouseover and mouseout. The details of the events will be discussed in the Events chapter. So for now, mouseover calls changename method and mouseout calls originalname method."
},
{
"code": null,
"e": 6844,
"s": 6785,
"text": "The display of the same is shown in the following browser."
},
{
"code": null,
"e": 7077,
"s": 6844,
"text": "As seen in the above browser, it displays the name assigned in the data property, which is the same name. We have also assigned a mouseover event on the div and also a mouseout. Let’s see what happens when we mouseover and mouseout."
},
{
"code": null,
"e": 7349,
"s": 7077,
"text": "On mouseover, we see the name of the first component is changed to Ben, however, the second one remains as it is. This is because the data component is a function and it returns an object. Thus, when it is changed in one place, the same is not overwritten in other cases."
},
{
"code": null,
"e": 7490,
"s": 7349,
"text": "Dynamic components are created using the keyword <component></component> and it is bound using a property as shown in the following example."
},
{
"code": null,
"e": 8138,
"s": 7490,
"text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\">\n <component v-bind:is = \"view\"></component>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#databinding',\n data: {\n view: 'component1'\n },\n components: {\n 'component1': {\n template: '<div><span style = \"font-size:25;color:red;\">Dynamic Component</span></div>'\n }\n }\n });\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 8195,
"s": 8138,
"text": "Dynamic component is created using the following syntax."
},
{
"code": null,
"e": 8238,
"s": 8195,
"text": "<component v-bind:is = \"view\"></component>"
},
{
"code": null,
"e": 8349,
"s": 8238,
"text": "It has v-bind:is = ”view”, and a value view is assigned to it. View is defined in the Vue instance as follows."
},
{
"code": null,
"e": 8586,
"s": 8349,
"text": "var vm = new Vue({\n el: '#databinding',\n data: {\n view: 'component1'\n },\n components: {\n 'component1': {\n template: '<div><span style = \"font-size:25;color:red;\">Dynamic Component</span></div>'\n }\n }\n});"
},
{
"code": null,
"e": 8661,
"s": 8586,
"text": "When executed, the template Dynamic Component is displayed in the browser."
},
{
"code": null,
"e": 8668,
"s": 8661,
"text": " Print"
},
{
"code": null,
"e": 8679,
"s": 8668,
"text": " Add Notes"
}
] |
CSS - Scrollbars
|
There may be a case when an element's content might be larger than the amount of space allocated to it. For example, given width and height properties do not allow enough room to accommodate the content of the element.
CSS provides a property called overflow which tells the browser what to do if the box's contents is larger than the box itself. This property can take one of the following values −
visible
Allows the content to overflow the borders of its containing element.
hidden
The content of the nested element is simply cut off at the border of the containing element and no scrollbars is visible.
scroll
The size of the containing element does not change, but the scrollbars are added to allow the user to scroll to see the content.
auto
The purpose is the same as scroll, but the scrollbar will be shown only if the content does overflow.
Here is an example −
<html>
<head>
<style type = "text/css">
.scroll {
display:block;
border: 1px solid red;
padding:5px;
margin-top:5px;
width:300px;
height:50px;
overflow:scroll;
}
.auto {
display:block;
border: 1px solid red;
padding:5px;
margin-top:5px;
width:300px;
height:50px;
overflow:auto;
}
</style>
</head>
<body>
<p>Example of scroll value:</p>
<div class = "scroll">
I am going to keep lot of content here just to show you how
scrollbars works if there is an overflow in an element box.
This provides your horizontal as well as vertical scrollbars.
</div>
<br />
<p>Example of auto value:</p>
<div class = "auto">
I am going to keep lot of content here just to show you how
scrollbars works if there is an overflow in an element box.
This provides your horizontal as well as vertical scrollbars.
</div>
</body>
</html>
It will produce the following result −
Example of scroll value:
Example of auto value:
33 Lectures
2.5 hours
Anadi Sharma
26 Lectures
2.5 hours
Frahaan Hussain
44 Lectures
4.5 hours
DigiFisk (Programming Is Fun)
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
51 Lectures
7.5 hours
DigiFisk (Programming Is Fun)
52 Lectures
4 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2845,
"s": 2626,
"text": "There may be a case when an element's content might be larger than the amount of space allocated to it. For example, given width and height properties do not allow enough room to accommodate the content of the element."
},
{
"code": null,
"e": 3026,
"s": 2845,
"text": "CSS provides a property called overflow which tells the browser what to do if the box's contents is larger than the box itself. This property can take one of the following values −"
},
{
"code": null,
"e": 3034,
"s": 3026,
"text": "visible"
},
{
"code": null,
"e": 3104,
"s": 3034,
"text": "Allows the content to overflow the borders of its containing element."
},
{
"code": null,
"e": 3111,
"s": 3104,
"text": "hidden"
},
{
"code": null,
"e": 3233,
"s": 3111,
"text": "The content of the nested element is simply cut off at the border of the containing element and no scrollbars is visible."
},
{
"code": null,
"e": 3240,
"s": 3233,
"text": "scroll"
},
{
"code": null,
"e": 3369,
"s": 3240,
"text": "The size of the containing element does not change, but the scrollbars are added to allow the user to scroll to see the content."
},
{
"code": null,
"e": 3374,
"s": 3369,
"text": "auto"
},
{
"code": null,
"e": 3476,
"s": 3374,
"text": "The purpose is the same as scroll, but the scrollbar will be shown only if the content does overflow."
},
{
"code": null,
"e": 3497,
"s": 3476,
"text": "Here is an example −"
},
{
"code": null,
"e": 4652,
"s": 3497,
"text": "<html>\n <head>\n <style type = \"text/css\">\n .scroll {\n display:block;\n border: 1px solid red;\n padding:5px;\n margin-top:5px;\n width:300px;\n height:50px;\n overflow:scroll;\n }\n .auto {\n display:block;\n border: 1px solid red;\n padding:5px;\n margin-top:5px;\n width:300px;\n height:50px;\n overflow:auto;\n }\n </style>\n </head>\n\n <body>\n <p>Example of scroll value:</p>\n <div class = \"scroll\">\n I am going to keep lot of content here just to show you how \n scrollbars works if there is an overflow in an element box. \n This provides your horizontal as well as vertical scrollbars.\n </div>\n <br />\n \n <p>Example of auto value:</p>\n \n <div class = \"auto\">\n I am going to keep lot of content here just to show you how \n scrollbars works if there is an overflow in an element box. \n This provides your horizontal as well as vertical scrollbars.\n </div>\n </body>\n</html> "
},
{
"code": null,
"e": 4691,
"s": 4652,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 4716,
"s": 4691,
"text": "Example of scroll value:"
},
{
"code": null,
"e": 4739,
"s": 4716,
"text": "Example of auto value:"
},
{
"code": null,
"e": 4774,
"s": 4739,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4788,
"s": 4774,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4823,
"s": 4788,
"text": "\n 26 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4840,
"s": 4823,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4875,
"s": 4840,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4906,
"s": 4875,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4941,
"s": 4906,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4972,
"s": 4941,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5007,
"s": 4972,
"text": "\n 51 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5038,
"s": 5007,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5071,
"s": 5038,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5102,
"s": 5071,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5109,
"s": 5102,
"text": " Print"
},
{
"code": null,
"e": 5120,
"s": 5109,
"text": " Add Notes"
}
] |
Count of numbers with all digits same in a given range - GeeksforGeeks
|
27 Jan, 2022
Given two integers L and R denoting the starting and end values of a range, the task is to count all numbers in that range whose all digit are same, like 1, 22, 444, 3333, etc.Example:
Input: L = 12, R = 68 Output: 5 Explanation: { 22, 33, 44, 55, 66} are the numbers with same digits in the given range.Input: L = 1, R = 32 Output: 11
Naive Approach: Iterate through all the numbers from L to R and for each number, check if it has all its digits same. If yes, then increase the required count. Print this count at the end.Efficient Approach: The idea is based on the fact that the multiples (1 to 9) of 1, 11, 111, etc has all its digits same. For example:
1 times 1 = 1 (All digits are same)
2 times 1 = 2 (All digits are same)
3 times 1 = 3 (All digits are same)
.
.
9 times 1 = 9 (All digits are same)
Similarly
1 times 11 = 11 (All digits are same)
2 times 11 = 22 (All digits are same)
3 times 11 = 33 (All digits are same)
.
.
9 times 11 = 99 (All digits are same)
Same is the case for 111, 1111, etc.
Therefore, the steps can be defined as:
Find the number of digits in R. This will decide the length of consecutive 1s to be created, till which we have to check. For example, if R = 100, then length(R) = 3. Therefore we need to check only the multiples of 1, 11, and 111. For each length of consecutive 1s from 1 to length(R): Multiply them with all values from 2 to 9Check if it lies within the range [L, R] or not.If yes, then increment the count of required numbers.Print the required count of numbers.
Find the number of digits in R. This will decide the length of consecutive 1s to be created, till which we have to check. For example, if R = 100, then length(R) = 3. Therefore we need to check only the multiples of 1, 11, and 111.
For each length of consecutive 1s from 1 to length(R): Multiply them with all values from 2 to 9Check if it lies within the range [L, R] or not.If yes, then increment the count of required numbers.
Multiply them with all values from 2 to 9
Check if it lies within the range [L, R] or not.
If yes, then increment the count of required numbers.
Print the required count of numbers.
C++
Java
Python3
C#
Javascript
// C++ program to count the// total numbers in the range// L and R which have all the// digit same #include <bits/stdc++.h>using namespace std; // Function that count the// total numbersProgram between L// and R which have all the// digit sameint count_same_digit(int L, int R){ int tmp = 0, ans = 0; // length of R int n = log10(R) + 1; for (int i = 0; i < n; i++) { // tmp has all digits as 1 tmp = tmp * 10 + 1; // For each multiple // of tmp in range 1 to 9, // check if it present // in range [L, R] for (int j = 1; j <= 9; j++) { if (L <= (tmp * j) && (tmp * j) <= R) { // Increment the required count ans++; } } } return ans;} // Driver Programint main(){ int L = 12, R = 68; cout << count_same_digit(L, R) << endl; return 0;}
// Java program to count the// total numbers in the range// L and R which have all the// digit sameimport java.util.*; class GFG{ // Function that count the total// numbersProgram between L and// R which have all the digit samestatic int count_same_digit(int L, int R){ int tmp = 0, ans = 0; // Length of R int n = (int)Math.log10(R) + 1; for(int i = 0; i < n; i++) { // tmp has all digits as 1 tmp = tmp * 10 + 1; // For each multiple of tmp // in range 1 to 9, check if // it present in range [L, R] for(int j = 1; j <= 9; j++) { if (L <= (tmp * j) && (tmp * j) <= R) { // Increment the required count ans++; } } } return ans;} // Driver codepublic static void main(String[] args){ int L = 12, R = 68; System.out.println(count_same_digit(L, R));}} // This code is contributed by offbeat
# Python3 program to count the# total numbers in the range# L and R which have all the# digit sameimport math # Function that count the# total numbersProgram between L# and R which have all the# digit samedef count_same_digit(L, R): tmp = 0; ans = 0; # length of R n = int(math.log10(R) + 1); for i in range(0, n): # tmp has all digits as 1 tmp = tmp * 10 + 1; # For each multiple # of tmp in range 1 to 9, # check if it present # in range [L, R] for j in range(1, 9): if (L <= (tmp * j) and (tmp * j) <= R): # Increment the required count ans += 1; return ans; # Driver CodeL = 12; R = 68; print(count_same_digit(L, R)) # This code is contributed by Nidhi_biet
// C# program to count the// total numbers in the range// L and R which have all the// digit sameusing System; class GFG{ // Function that count the total// numbersProgram between L and// R which have all the digit samestatic int count_same_digit(int L, int R){ int tmp = 0, ans = 0; // Length of R int n = (int)Math.Log10(R) + 1; for(int i = 0; i < n; i++) { // tmp has all digits as 1 tmp = tmp * 10 + 1; // For each multiple of tmp // in range 1 to 9, check if // it present in range [L, R] for(int j = 1; j <= 9; j++) { if (L <= (tmp * j) && (tmp * j) <= R) { // Increment the required count ans++; } } } return ans;} // Driver codepublic static void Main(){ int L = 12, R = 68; Console.Write(count_same_digit(L, R));}} // This code is contributed by Code_Mech
<script> // JavaScript program to count the// total numbers in the range// L and R which have all the// digit same // Function that count the// total numbersProgram between L// and R which have all the// digit samefunction count_same_digit( L, R){ var tmp = 0, ans = 0; // length of R var n = Math.log10(R) + 1; for (let i = 0; i < n; i++) { // tmp has all digits as 1 tmp = tmp * 10 + 1; // For each multiple // of tmp in range 1 to 9, // check if it present // in range [L, R] for (let j = 1; j <= 9; j++) { if (L <= (tmp * j) && (tmp * j) <= R) { // Increment the required count ans++; } } } return ans;} // Driver Program var L = 12, R = 68; document.write( count_same_digit(L, R)); // This code is contributed by ukasp.</script>
offbeat
Code_Mech
nidhi_biet
ukasp
array-range-queries
number-digits
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Modular multiplicative inverse
Fizz Buzz Implementation
Check if a number is Palindrome
Generate all permutation of a set in Python
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects
|
[
{
"code": null,
"e": 25963,
"s": 25935,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 26150,
"s": 25963,
"text": "Given two integers L and R denoting the starting and end values of a range, the task is to count all numbers in that range whose all digit are same, like 1, 22, 444, 3333, etc.Example: "
},
{
"code": null,
"e": 26303,
"s": 26150,
"text": "Input: L = 12, R = 68 Output: 5 Explanation: { 22, 33, 44, 55, 66} are the numbers with same digits in the given range.Input: L = 1, R = 32 Output: 11 "
},
{
"code": null,
"e": 26630,
"s": 26305,
"text": "Naive Approach: Iterate through all the numbers from L to R and for each number, check if it has all its digits same. If yes, then increase the required count. Print this count at the end.Efficient Approach: The idea is based on the fact that the multiples (1 to 9) of 1, 11, 111, etc has all its digits same. For example: "
},
{
"code": null,
"e": 26983,
"s": 26630,
"text": "1 times 1 = 1 (All digits are same)\n2 times 1 = 2 (All digits are same)\n3 times 1 = 3 (All digits are same)\n.\n.\n9 times 1 = 9 (All digits are same)\n\nSimilarly\n1 times 11 = 11 (All digits are same)\n2 times 11 = 22 (All digits are same)\n3 times 11 = 33 (All digits are same)\n.\n.\n9 times 11 = 99 (All digits are same)\n\nSame is the case for 111, 1111, etc."
},
{
"code": null,
"e": 27025,
"s": 26983,
"text": "Therefore, the steps can be defined as: "
},
{
"code": null,
"e": 27492,
"s": 27025,
"text": "Find the number of digits in R. This will decide the length of consecutive 1s to be created, till which we have to check. For example, if R = 100, then length(R) = 3. Therefore we need to check only the multiples of 1, 11, and 111. For each length of consecutive 1s from 1 to length(R): Multiply them with all values from 2 to 9Check if it lies within the range [L, R] or not.If yes, then increment the count of required numbers.Print the required count of numbers."
},
{
"code": null,
"e": 27726,
"s": 27492,
"text": "Find the number of digits in R. This will decide the length of consecutive 1s to be created, till which we have to check. For example, if R = 100, then length(R) = 3. Therefore we need to check only the multiples of 1, 11, and 111. "
},
{
"code": null,
"e": 27924,
"s": 27726,
"text": "For each length of consecutive 1s from 1 to length(R): Multiply them with all values from 2 to 9Check if it lies within the range [L, R] or not.If yes, then increment the count of required numbers."
},
{
"code": null,
"e": 27966,
"s": 27924,
"text": "Multiply them with all values from 2 to 9"
},
{
"code": null,
"e": 28015,
"s": 27966,
"text": "Check if it lies within the range [L, R] or not."
},
{
"code": null,
"e": 28069,
"s": 28015,
"text": "If yes, then increment the count of required numbers."
},
{
"code": null,
"e": 28106,
"s": 28069,
"text": "Print the required count of numbers."
},
{
"code": null,
"e": 28110,
"s": 28106,
"text": "C++"
},
{
"code": null,
"e": 28115,
"s": 28110,
"text": "Java"
},
{
"code": null,
"e": 28123,
"s": 28115,
"text": "Python3"
},
{
"code": null,
"e": 28126,
"s": 28123,
"text": "C#"
},
{
"code": null,
"e": 28137,
"s": 28126,
"text": "Javascript"
},
{
"code": "// C++ program to count the// total numbers in the range// L and R which have all the// digit same #include <bits/stdc++.h>using namespace std; // Function that count the// total numbersProgram between L// and R which have all the// digit sameint count_same_digit(int L, int R){ int tmp = 0, ans = 0; // length of R int n = log10(R) + 1; for (int i = 0; i < n; i++) { // tmp has all digits as 1 tmp = tmp * 10 + 1; // For each multiple // of tmp in range 1 to 9, // check if it present // in range [L, R] for (int j = 1; j <= 9; j++) { if (L <= (tmp * j) && (tmp * j) <= R) { // Increment the required count ans++; } } } return ans;} // Driver Programint main(){ int L = 12, R = 68; cout << count_same_digit(L, R) << endl; return 0;}",
"e": 29035,
"s": 28137,
"text": null
},
{
"code": "// Java program to count the// total numbers in the range// L and R which have all the// digit sameimport java.util.*; class GFG{ // Function that count the total// numbersProgram between L and// R which have all the digit samestatic int count_same_digit(int L, int R){ int tmp = 0, ans = 0; // Length of R int n = (int)Math.log10(R) + 1; for(int i = 0; i < n; i++) { // tmp has all digits as 1 tmp = tmp * 10 + 1; // For each multiple of tmp // in range 1 to 9, check if // it present in range [L, R] for(int j = 1; j <= 9; j++) { if (L <= (tmp * j) && (tmp * j) <= R) { // Increment the required count ans++; } } } return ans;} // Driver codepublic static void main(String[] args){ int L = 12, R = 68; System.out.println(count_same_digit(L, R));}} // This code is contributed by offbeat",
"e": 29939,
"s": 29035,
"text": null
},
{
"code": "# Python3 program to count the# total numbers in the range# L and R which have all the# digit sameimport math # Function that count the# total numbersProgram between L# and R which have all the# digit samedef count_same_digit(L, R): tmp = 0; ans = 0; # length of R n = int(math.log10(R) + 1); for i in range(0, n): # tmp has all digits as 1 tmp = tmp * 10 + 1; # For each multiple # of tmp in range 1 to 9, # check if it present # in range [L, R] for j in range(1, 9): if (L <= (tmp * j) and (tmp * j) <= R): # Increment the required count ans += 1; return ans; # Driver CodeL = 12; R = 68; print(count_same_digit(L, R)) # This code is contributed by Nidhi_biet",
"e": 30726,
"s": 29939,
"text": null
},
{
"code": "// C# program to count the// total numbers in the range// L and R which have all the// digit sameusing System; class GFG{ // Function that count the total// numbersProgram between L and// R which have all the digit samestatic int count_same_digit(int L, int R){ int tmp = 0, ans = 0; // Length of R int n = (int)Math.Log10(R) + 1; for(int i = 0; i < n; i++) { // tmp has all digits as 1 tmp = tmp * 10 + 1; // For each multiple of tmp // in range 1 to 9, check if // it present in range [L, R] for(int j = 1; j <= 9; j++) { if (L <= (tmp * j) && (tmp * j) <= R) { // Increment the required count ans++; } } } return ans;} // Driver codepublic static void Main(){ int L = 12, R = 68; Console.Write(count_same_digit(L, R));}} // This code is contributed by Code_Mech",
"e": 31662,
"s": 30726,
"text": null
},
{
"code": "<script> // JavaScript program to count the// total numbers in the range// L and R which have all the// digit same // Function that count the// total numbersProgram between L// and R which have all the// digit samefunction count_same_digit( L, R){ var tmp = 0, ans = 0; // length of R var n = Math.log10(R) + 1; for (let i = 0; i < n; i++) { // tmp has all digits as 1 tmp = tmp * 10 + 1; // For each multiple // of tmp in range 1 to 9, // check if it present // in range [L, R] for (let j = 1; j <= 9; j++) { if (L <= (tmp * j) && (tmp * j) <= R) { // Increment the required count ans++; } } } return ans;} // Driver Program var L = 12, R = 68; document.write( count_same_digit(L, R)); // This code is contributed by ukasp.</script>",
"e": 32553,
"s": 31662,
"text": null
},
{
"code": null,
"e": 32561,
"s": 32553,
"text": "offbeat"
},
{
"code": null,
"e": 32571,
"s": 32561,
"text": "Code_Mech"
},
{
"code": null,
"e": 32582,
"s": 32571,
"text": "nidhi_biet"
},
{
"code": null,
"e": 32588,
"s": 32582,
"text": "ukasp"
},
{
"code": null,
"e": 32608,
"s": 32588,
"text": "array-range-queries"
},
{
"code": null,
"e": 32622,
"s": 32608,
"text": "number-digits"
},
{
"code": null,
"e": 32635,
"s": 32622,
"text": "Mathematical"
},
{
"code": null,
"e": 32654,
"s": 32635,
"text": "School Programming"
},
{
"code": null,
"e": 32667,
"s": 32654,
"text": "Mathematical"
},
{
"code": null,
"e": 32765,
"s": 32667,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32809,
"s": 32765,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 32840,
"s": 32809,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 32865,
"s": 32840,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 32897,
"s": 32865,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 32941,
"s": 32897,
"text": "Generate all permutation of a set in Python"
},
{
"code": null,
"e": 32959,
"s": 32941,
"text": "Python Dictionary"
},
{
"code": null,
"e": 32975,
"s": 32959,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 32994,
"s": 32975,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 33019,
"s": 32994,
"text": "Reverse a string in Java"
}
] |
Microsoft Expression Web - Images
|
Images are used heavily in webpages to make them look interesting and provide a better user experience. In this chapter, we will learn how to add images to the website. As usual, let’s go step by step and learn the process in detail.
Step 1 − To start adding images, let’s create a new one-page site and change the name of default.html file to index.html.
Step 2 − Now we need to include images to the website so that we can use those images in the webpage. Let’s create a new folder. In the folder list, right-click on the website name.
Step 3 − Currently, there are no images in this folder. To add images in this folder, simply select and drag images from your hard drive and drop them over the images folder.
You will see that the images are added to the website images folder, as shown in the following screenshot.
Step 4 − Now these images are included in your website but none of these are used in a webpage. A simple way to add an image to in the webpage is to drag the image from the images folder and drop in the code view where you want to add the image in the webpage.
Suppose we want to add an image below the heading. When your drop the image and release the mouse button, it will display the following dialog box.
Here you can specify the alternate text and long description. Then click OK and save the webpage. Now you can see that <img> tag is added with the alternate name and source of the image.
Step 5 − Follow the same process and add the second image along with its alternate name and source.
Now the index.html file will appear as follows −
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<meta content = "text/html; charset = utf-8" http-equiv = "Content-Type" />
</head>
<body>
<h1> Working with images </h1>
<img alt = "Beautiful Birds" src = "images/birds.jpg" />
<img alt = "Other Birds" src = "images/birds2.jpg" />
</body>
</html>
Step 6 − The Picture Properties dialog box gives you access to the most commonly used picture attributes. When you double-click an image, it will display the Picture Properties box.
In Expression Web, Picture Properties dialog has two tabs, General and Appearance.
Following are the options available on the General tab.
Picture − It contains the folder/file name of the graphic image.
Picture − It contains the folder/file name of the graphic image.
Alternate Text − Type the text you want to be displayed for pictures when the graphic is downloading, when it can't be found, or when a site visitor moves the pointer over it. This text will also be used by a screen reader if your viewer is using one.
Alternate Text − Type the text you want to be displayed for pictures when the graphic is downloading, when it can't be found, or when a site visitor moves the pointer over it. This text will also be used by a screen reader if your viewer is using one.
Long Description − There are times a few words may not be enough to describe your image. Charts and graphs are examples. Click Browse to select a file that contains a longer description of the picture.
Long Description − There are times a few words may not be enough to describe your image. Charts and graphs are examples. Click Browse to select a file that contains a longer description of the picture.
Location − If you want to link your image to a webpage or larger image, you insert the hyperlink here.
Location − If you want to link your image to a webpage or larger image, you insert the hyperlink here.
Target Frame − If the current page is a frames page, this option indicates which frame the link should be displayed in OR you can choose to have the image or page open in a new window.
Target Frame − If the current page is a frames page, this option indicates which frame the link should be displayed in OR you can choose to have the image or page open in a new window.
Following options are available on the Appearance tab.
Wrapping Style − Specify how the picture floats in the page, such as None, Left, or Right.
Wrapping Style − Specify how the picture floats in the page, such as None, Left, or Right.
Layout − In this section, you can set the alignment, border thickness, horizontal and vertical margins.
Layout − In this section, you can set the alignment, border thickness, horizontal and vertical margins.
Size − Expression Web automatically sets the width and height properties for the image based on the actual dimensions of the picture. Rather than resizing your image by changing these dimensions, resize the image using your graphic editor.
Size − Expression Web automatically sets the width and height properties for the image based on the actual dimensions of the picture. Rather than resizing your image by changing these dimensions, resize the image using your graphic editor.
Step 7 − Now, let’s preview the webpage in the browser; it will display the following output.
16 Lectures
11.5 hours
SHIVPRASAD KOIRALA
33 Lectures
3 hours
Abhishek And Pukhraj
33 Lectures
5.5 hours
Abhishek And Pukhraj
40 Lectures
6.5 hours
Syed Raza
15 Lectures
2 hours
Harshit Srivastava, Pranjal Srivastava
18 Lectures
1.5 hours
Pranjal Srivastava, Harshit Srivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2430,
"s": 2196,
"text": "Images are used heavily in webpages to make them look interesting and provide a better user experience. In this chapter, we will learn how to add images to the website. As usual, let’s go step by step and learn the process in detail."
},
{
"code": null,
"e": 2552,
"s": 2430,
"text": "Step 1 − To start adding images, let’s create a new one-page site and change the name of default.html file to index.html."
},
{
"code": null,
"e": 2734,
"s": 2552,
"text": "Step 2 − Now we need to include images to the website so that we can use those images in the webpage. Let’s create a new folder. In the folder list, right-click on the website name."
},
{
"code": null,
"e": 2909,
"s": 2734,
"text": "Step 3 − Currently, there are no images in this folder. To add images in this folder, simply select and drag images from your hard drive and drop them over the images folder."
},
{
"code": null,
"e": 3016,
"s": 2909,
"text": "You will see that the images are added to the website images folder, as shown in the following screenshot."
},
{
"code": null,
"e": 3277,
"s": 3016,
"text": "Step 4 − Now these images are included in your website but none of these are used in a webpage. A simple way to add an image to in the webpage is to drag the image from the images folder and drop in the code view where you want to add the image in the webpage."
},
{
"code": null,
"e": 3425,
"s": 3277,
"text": "Suppose we want to add an image below the heading. When your drop the image and release the mouse button, it will display the following dialog box."
},
{
"code": null,
"e": 3612,
"s": 3425,
"text": "Here you can specify the alternate text and long description. Then click OK and save the webpage. Now you can see that <img> tag is added with the alternate name and source of the image."
},
{
"code": null,
"e": 3712,
"s": 3612,
"text": "Step 5 − Follow the same process and add the second image along with its alternate name and source."
},
{
"code": null,
"e": 3761,
"s": 3712,
"text": "Now the index.html file will appear as follows −"
},
{
"code": null,
"e": 4243,
"s": 3761,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> \n<html xmlns = \"http://www.w3.org/1999/xhtml\"> \n <head> \n <meta content = \"text/html; charset = utf-8\" http-equiv = \"Content-Type\" /> \n </head> \n \n <body> \n <h1> Working with images </h1> \n <img alt = \"Beautiful Birds\" src = \"images/birds.jpg\" /> \n <img alt = \"Other Birds\" src = \"images/birds2.jpg\" /> \n </body> \n</html> "
},
{
"code": null,
"e": 4425,
"s": 4243,
"text": "Step 6 − The Picture Properties dialog box gives you access to the most commonly used picture attributes. When you double-click an image, it will display the Picture Properties box."
},
{
"code": null,
"e": 4508,
"s": 4425,
"text": "In Expression Web, Picture Properties dialog has two tabs, General and Appearance."
},
{
"code": null,
"e": 4564,
"s": 4508,
"text": "Following are the options available on the General tab."
},
{
"code": null,
"e": 4629,
"s": 4564,
"text": "Picture − It contains the folder/file name of the graphic image."
},
{
"code": null,
"e": 4694,
"s": 4629,
"text": "Picture − It contains the folder/file name of the graphic image."
},
{
"code": null,
"e": 4946,
"s": 4694,
"text": "Alternate Text − Type the text you want to be displayed for pictures when the graphic is downloading, when it can't be found, or when a site visitor moves the pointer over it. This text will also be used by a screen reader if your viewer is using one."
},
{
"code": null,
"e": 5198,
"s": 4946,
"text": "Alternate Text − Type the text you want to be displayed for pictures when the graphic is downloading, when it can't be found, or when a site visitor moves the pointer over it. This text will also be used by a screen reader if your viewer is using one."
},
{
"code": null,
"e": 5400,
"s": 5198,
"text": "Long Description − There are times a few words may not be enough to describe your image. Charts and graphs are examples. Click Browse to select a file that contains a longer description of the picture."
},
{
"code": null,
"e": 5602,
"s": 5400,
"text": "Long Description − There are times a few words may not be enough to describe your image. Charts and graphs are examples. Click Browse to select a file that contains a longer description of the picture."
},
{
"code": null,
"e": 5705,
"s": 5602,
"text": "Location − If you want to link your image to a webpage or larger image, you insert the hyperlink here."
},
{
"code": null,
"e": 5808,
"s": 5705,
"text": "Location − If you want to link your image to a webpage or larger image, you insert the hyperlink here."
},
{
"code": null,
"e": 5993,
"s": 5808,
"text": "Target Frame − If the current page is a frames page, this option indicates which frame the link should be displayed in OR you can choose to have the image or page open in a new window."
},
{
"code": null,
"e": 6178,
"s": 5993,
"text": "Target Frame − If the current page is a frames page, this option indicates which frame the link should be displayed in OR you can choose to have the image or page open in a new window."
},
{
"code": null,
"e": 6233,
"s": 6178,
"text": "Following options are available on the Appearance tab."
},
{
"code": null,
"e": 6324,
"s": 6233,
"text": "Wrapping Style − Specify how the picture floats in the page, such as None, Left, or Right."
},
{
"code": null,
"e": 6415,
"s": 6324,
"text": "Wrapping Style − Specify how the picture floats in the page, such as None, Left, or Right."
},
{
"code": null,
"e": 6519,
"s": 6415,
"text": "Layout − In this section, you can set the alignment, border thickness, horizontal and vertical margins."
},
{
"code": null,
"e": 6623,
"s": 6519,
"text": "Layout − In this section, you can set the alignment, border thickness, horizontal and vertical margins."
},
{
"code": null,
"e": 6863,
"s": 6623,
"text": "Size − Expression Web automatically sets the width and height properties for the image based on the actual dimensions of the picture. Rather than resizing your image by changing these dimensions, resize the image using your graphic editor."
},
{
"code": null,
"e": 7103,
"s": 6863,
"text": "Size − Expression Web automatically sets the width and height properties for the image based on the actual dimensions of the picture. Rather than resizing your image by changing these dimensions, resize the image using your graphic editor."
},
{
"code": null,
"e": 7197,
"s": 7103,
"text": "Step 7 − Now, let’s preview the webpage in the browser; it will display the following output."
},
{
"code": null,
"e": 7233,
"s": 7197,
"text": "\n 16 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 7253,
"s": 7233,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 7286,
"s": 7253,
"text": "\n 33 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 7308,
"s": 7286,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 7343,
"s": 7308,
"text": "\n 33 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7365,
"s": 7343,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 7400,
"s": 7365,
"text": "\n 40 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 7411,
"s": 7400,
"text": " Syed Raza"
},
{
"code": null,
"e": 7444,
"s": 7411,
"text": "\n 15 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7484,
"s": 7444,
"text": " Harshit Srivastava, Pranjal Srivastava"
},
{
"code": null,
"e": 7519,
"s": 7484,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7559,
"s": 7519,
"text": " Pranjal Srivastava, Harshit Srivastava"
},
{
"code": null,
"e": 7566,
"s": 7559,
"text": " Print"
},
{
"code": null,
"e": 7577,
"s": 7566,
"text": " Add Notes"
}
] |
Creating a Smart Contract that Returns Address and Balance of Owner using Solidity - GeeksforGeeks
|
28 Jul, 2020
Problem: Create a smart contract named MyContract having a state variable as owner. Create a constructor to fetch the address of the owner from msg and hold it into the state variable owner. Also, create a function getBalance() to show the current balance of the owner.
Solution: Every smart contract is owned by an address called as owner. A smart contract can know its owner’s address using sender property and its available balance using a special built-in object called msg.
Step 1: Open Remix-IDE.
Step 2: Select File Explorer from the left side icons and select Solidity in the environment. Click on New option below the Solidity environment. Enter the file name as MyContract.sol and Click on the OK button.
Step 3: Enter the following Solidity Code.
Solidity
// Solidity program to// retrieve address and// balance of ownerpragma solidity ^0.6.8; // Creating a contractcontract MyContract{ // Private state variable address private owner; // Defining a constructor constructor() public{ owner=msg.sender; } // Function to get // address of owner function getOwner( ) public view returns (address) { return owner; } // Function to return // current balance of owner function getBalance( ) public view returns(uint256){ return owner.balance; }}
Step 4: Compile the file MyContract.sol from the Solidity Compiler tab.
Step 5: Deploy the smart contract from the Deploy and Run Transaction tab and you will get the balance and address of the owner.
Step 6: The output below shows the address and the balance of the owner.
BlockChain
Solidity
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Dynamic Arrays and its Operations in Solidity
Steps to Execute Solidity Smart Contract using Remix IDE
Solidity - View and Pure Functions
Solidity - Error Handling
Solidity - Types
Solidity - Functions
What are Events in Solidity?
Solidity - Libraries
Flutter and Blockchain - Hello World Dapp
Random Number Generator in Solidity using keccak256
|
[
{
"code": null,
"e": 23525,
"s": 23497,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 23795,
"s": 23525,
"text": "Problem: Create a smart contract named MyContract having a state variable as owner. Create a constructor to fetch the address of the owner from msg and hold it into the state variable owner. Also, create a function getBalance() to show the current balance of the owner."
},
{
"code": null,
"e": 24004,
"s": 23795,
"text": "Solution: Every smart contract is owned by an address called as owner. A smart contract can know its owner’s address using sender property and its available balance using a special built-in object called msg."
},
{
"code": null,
"e": 24028,
"s": 24004,
"text": "Step 1: Open Remix-IDE."
},
{
"code": null,
"e": 24240,
"s": 24028,
"text": "Step 2: Select File Explorer from the left side icons and select Solidity in the environment. Click on New option below the Solidity environment. Enter the file name as MyContract.sol and Click on the OK button."
},
{
"code": null,
"e": 24284,
"s": 24240,
"text": "Step 3: Enter the following Solidity Code. "
},
{
"code": null,
"e": 24293,
"s": 24284,
"text": "Solidity"
},
{
"code": "// Solidity program to// retrieve address and// balance of ownerpragma solidity ^0.6.8; // Creating a contractcontract MyContract{ // Private state variable address private owner; // Defining a constructor constructor() public{ owner=msg.sender; } // Function to get // address of owner function getOwner( ) public view returns (address) { return owner; } // Function to return // current balance of owner function getBalance( ) public view returns(uint256){ return owner.balance; }}",
"e": 24869,
"s": 24293,
"text": null
},
{
"code": null,
"e": 24943,
"s": 24869,
"text": "Step 4: Compile the file MyContract.sol from the Solidity Compiler tab. "
},
{
"code": null,
"e": 25072,
"s": 24943,
"text": "Step 5: Deploy the smart contract from the Deploy and Run Transaction tab and you will get the balance and address of the owner."
},
{
"code": null,
"e": 25145,
"s": 25072,
"text": "Step 6: The output below shows the address and the balance of the owner."
},
{
"code": null,
"e": 25158,
"s": 25147,
"text": "BlockChain"
},
{
"code": null,
"e": 25167,
"s": 25158,
"text": "Solidity"
},
{
"code": null,
"e": 25265,
"s": 25167,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25274,
"s": 25265,
"text": "Comments"
},
{
"code": null,
"e": 25287,
"s": 25274,
"text": "Old Comments"
},
{
"code": null,
"e": 25333,
"s": 25287,
"text": "Dynamic Arrays and its Operations in Solidity"
},
{
"code": null,
"e": 25390,
"s": 25333,
"text": "Steps to Execute Solidity Smart Contract using Remix IDE"
},
{
"code": null,
"e": 25425,
"s": 25390,
"text": "Solidity - View and Pure Functions"
},
{
"code": null,
"e": 25451,
"s": 25425,
"text": "Solidity - Error Handling"
},
{
"code": null,
"e": 25468,
"s": 25451,
"text": "Solidity - Types"
},
{
"code": null,
"e": 25489,
"s": 25468,
"text": "Solidity - Functions"
},
{
"code": null,
"e": 25518,
"s": 25489,
"text": "What are Events in Solidity?"
},
{
"code": null,
"e": 25539,
"s": 25518,
"text": "Solidity - Libraries"
},
{
"code": null,
"e": 25581,
"s": 25539,
"text": "Flutter and Blockchain - Hello World Dapp"
}
] |
C++ Program to Display Prime Numbers Between Two Intervals Using Functions
|
A prime number is a whole number that is greater than one and the only factors of a prime number should be one and itself. Some of the first prime numbers are 2, 3, 5, 7, 11, 13 ,17 etc.
There can be many prime numbers between two intervals. For example, the prime numbers between the intervals 5 and 20 are 5, 7, 11, 13, 17 and 19.
The program to find and display the prime numbers between two intervals is given as follows.
Live Demo
#include <iostream>
using namespace std;
void primeNumbers (int lbound, int ubound) {
int flag, i;
while (lbound <= ubound) {
flag = 0;
for(i = 2; i <= lbound/2; i++) {
if(lbound % i == 0) {
flag = 1;
break;
}
}
if (flag == 0)
cout<<lbound<<" ";
lbound++;
}
}
int main() {
int lowerbound = 20, upperbound = 50;
cout<<"Prime numbers between "<<lowerbound<<" and "<<upperbound<<" are: ";
primeNumbers(lowerbound,upperbound);
return 0;
}
Prime numbers between 20 and 50 are: 23 29 31 37 41 43 47
In the above program, the function main() contains only the cout object and the function call to the function primeNumbers() with upperbound and lowerbound as arguments. This can be seen in the following code snippet.
cout<<"Prime numbers between "<<lowerbound<<" and "<<upperbound<<" are: ";
primeNumbers(lowerbound,upperbound);
In the function primeNumbers(), each number from lbound to ubound is tested to see if it is prime or not. If it is a prime number, it is displayed. This is done using a while loop.
In the while loop, initial value of flag=0. If the number is not prime, then the value of flag is set to 1 in the for loop. After the end of the for loop, if flag is still 0, then the number is prime and it is displayed. This can be observed from the following code snippet.
while (lbound <= ubound) {
flag = 0;
for(i = 2; i <= lbound/2; i++) {
if(lbound % i == 0) {
flag = 1;
break;
}
}
if (flag == 0)
cout<<lbound<<" ";
lbound++;
}
|
[
{
"code": null,
"e": 1249,
"s": 1062,
"text": "A prime number is a whole number that is greater than one and the only factors of a prime number should be one and itself. Some of the first prime numbers are 2, 3, 5, 7, 11, 13 ,17 etc."
},
{
"code": null,
"e": 1395,
"s": 1249,
"text": "There can be many prime numbers between two intervals. For example, the prime numbers between the intervals 5 and 20 are 5, 7, 11, 13, 17 and 19."
},
{
"code": null,
"e": 1488,
"s": 1395,
"text": "The program to find and display the prime numbers between two intervals is given as follows."
},
{
"code": null,
"e": 1499,
"s": 1488,
"text": " Live Demo"
},
{
"code": null,
"e": 2033,
"s": 1499,
"text": "#include <iostream>\nusing namespace std;\nvoid primeNumbers (int lbound, int ubound) {\n int flag, i;\n while (lbound <= ubound) {\n flag = 0;\n for(i = 2; i <= lbound/2; i++) {\n if(lbound % i == 0) {\n flag = 1;\n break;\n }\n }\n if (flag == 0)\n cout<<lbound<<\" \";\n lbound++;\n }\n}\nint main() {\n int lowerbound = 20, upperbound = 50;\n cout<<\"Prime numbers between \"<<lowerbound<<\" and \"<<upperbound<<\" are: \";\n primeNumbers(lowerbound,upperbound);\n return 0;\n}"
},
{
"code": null,
"e": 2091,
"s": 2033,
"text": "Prime numbers between 20 and 50 are: 23 29 31 37 41 43 47"
},
{
"code": null,
"e": 2309,
"s": 2091,
"text": "In the above program, the function main() contains only the cout object and the function call to the function primeNumbers() with upperbound and lowerbound as arguments. This can be seen in the following code snippet."
},
{
"code": null,
"e": 2421,
"s": 2309,
"text": "cout<<\"Prime numbers between \"<<lowerbound<<\" and \"<<upperbound<<\" are: \";\nprimeNumbers(lowerbound,upperbound);"
},
{
"code": null,
"e": 2602,
"s": 2421,
"text": "In the function primeNumbers(), each number from lbound to ubound is tested to see if it is prime or not. If it is a prime number, it is displayed. This is done using a while loop."
},
{
"code": null,
"e": 2877,
"s": 2602,
"text": "In the while loop, initial value of flag=0. If the number is not prime, then the value of flag is set to 1 in the for loop. After the end of the for loop, if flag is still 0, then the number is prime and it is displayed. This can be observed from the following code snippet."
},
{
"code": null,
"e": 3084,
"s": 2877,
"text": "while (lbound <= ubound) {\n flag = 0;\n for(i = 2; i <= lbound/2; i++) {\n if(lbound % i == 0) {\n flag = 1;\n break;\n }\n }\n if (flag == 0)\n cout<<lbound<<\" \";\n lbound++;\n}"
}
] |
Mean Shift Clustering Algorithm Example In Python | by Cory Maklin | Towards Data Science
|
Mean Shift is a hierarchical clustering algorithm. In contrast to supervised machine learning algorithms, clustering attempts to group data without having first been train on labeled data. Clustering is used in a wide variety of applications such as search engines, academic rankings and medicine. As opposed to K-Means, when using Mean Shift, you don’t need to know the number of categories (clusters) beforehand. The downside to Mean Shift is that it is computationally expensive — O(n2).
Define a window (bandwidth of the kernel) and place the window on a data point
Define a window (bandwidth of the kernel) and place the window on a data point
2. Calculate the mean for all the points in the window
3. Move the center of the window to the location of the mean
4. Repeat steps 2 and 3 until there is convergence
Let’s take a look at how we could go about labeling the data using the Mean Shift algorithm in python.
import numpy as npimport pandas as pdfrom sklearn.cluster import MeanShiftfrom sklearn.datasets.samples_generator import make_blobsfrom matplotlib import pyplot as pltfrom mpl_toolkits.mplot3d import Axes3D
We generate our own data using the make_blobs method.
clusters = [[1,1,1],[5,5,5],[3,10,10]]X, _ = make_blobs(n_samples = 150, centers = clusters, cluster_std = 0.60)
After training the model, we store the coordinates for the cluster centers.
ms = MeanShift()ms.fit(X)cluster_centers = ms.cluster_centers_
Finally, we plot the data points and centroids in a 3D graph.
fig = plt.figure()ax = fig.add_subplot(111, projection='3d')ax.scatter(X[:,0], X[:,1], X[:,2], marker='o')ax.scatter(cluster_centers[:,0], cluster_centers[:,1], cluster_centers[:,2], marker='x', color='red', s=300, linewidth=5, zorder=10)plt.show()
|
[
{
"code": null,
"e": 663,
"s": 172,
"text": "Mean Shift is a hierarchical clustering algorithm. In contrast to supervised machine learning algorithms, clustering attempts to group data without having first been train on labeled data. Clustering is used in a wide variety of applications such as search engines, academic rankings and medicine. As opposed to K-Means, when using Mean Shift, you don’t need to know the number of categories (clusters) beforehand. The downside to Mean Shift is that it is computationally expensive — O(n2)."
},
{
"code": null,
"e": 742,
"s": 663,
"text": "Define a window (bandwidth of the kernel) and place the window on a data point"
},
{
"code": null,
"e": 821,
"s": 742,
"text": "Define a window (bandwidth of the kernel) and place the window on a data point"
},
{
"code": null,
"e": 876,
"s": 821,
"text": "2. Calculate the mean for all the points in the window"
},
{
"code": null,
"e": 937,
"s": 876,
"text": "3. Move the center of the window to the location of the mean"
},
{
"code": null,
"e": 988,
"s": 937,
"text": "4. Repeat steps 2 and 3 until there is convergence"
},
{
"code": null,
"e": 1091,
"s": 988,
"text": "Let’s take a look at how we could go about labeling the data using the Mean Shift algorithm in python."
},
{
"code": null,
"e": 1298,
"s": 1091,
"text": "import numpy as npimport pandas as pdfrom sklearn.cluster import MeanShiftfrom sklearn.datasets.samples_generator import make_blobsfrom matplotlib import pyplot as pltfrom mpl_toolkits.mplot3d import Axes3D"
},
{
"code": null,
"e": 1352,
"s": 1298,
"text": "We generate our own data using the make_blobs method."
},
{
"code": null,
"e": 1465,
"s": 1352,
"text": "clusters = [[1,1,1],[5,5,5],[3,10,10]]X, _ = make_blobs(n_samples = 150, centers = clusters, cluster_std = 0.60)"
},
{
"code": null,
"e": 1541,
"s": 1465,
"text": "After training the model, we store the coordinates for the cluster centers."
},
{
"code": null,
"e": 1604,
"s": 1541,
"text": "ms = MeanShift()ms.fit(X)cluster_centers = ms.cluster_centers_"
},
{
"code": null,
"e": 1666,
"s": 1604,
"text": "Finally, we plot the data points and centroids in a 3D graph."
}
] |
Find LCA in Binary Tree using RMQ - GeeksforGeeks
|
11 Jun, 2021
The article describes an approach to solving the problem of finding the LCA of two nodes in a tree by reducing it to a RMQ problem.
Lowest Common Ancestor (LCA) of two nodes u and v in a rooted tree T is defined as the node located farthest from the root that has both u and v as descendants.For example, in below diagram, LCA of node 4 and node 9 is node 2.
There can be many approaches to solve the LCA problem. The approaches differ in their time and space complexities. Here is a link to a couple of them (these do not involve reduction to RMQ).
Range Minimum Query (RMQ) is used on arrays to find the position of an element with the minimum value between two specified indices. Different approaches for solving RMQ have been discussed here and here. In this article, Segment Tree based approach is discussed. With segment tree, preprocessing time is O(n) and time to for range minimum query is O(Logn). The extra space required is O(n) to store the segment tree.
Reduction of LCA to RMQ: The idea is to traverse the tree starting from root by an Euler tour (traversal without lifting pencil), which is a DFS-type traversal with preorder traversal characteristics.
Observation: The LCA of nodes 4 and 9 is node 2, which happens to be the node closest to the root amongst all those encountered between the visits of 4 and 9 during a DFS of T. This observation is the key to the reduction. Let’s rephrase: Our node is the node at the smallest level and the only node at that level amongst all the nodes that occur between consecutive occurrences (any) of u and v in the Euler tour of T.We require three arrays for implementation:
Nodes visited in order of Euler tour of TLevel of each node visited in Euler tour of TIndex of the first occurrence of a node in Euler tour of T (since any occurrence would be good, let’s track the first one)
Nodes visited in order of Euler tour of T
Level of each node visited in Euler tour of T
Index of the first occurrence of a node in Euler tour of T (since any occurrence would be good, let’s track the first one)
Algorithm:
Do a Euler tour on the tree, and fill the euler, level and first occurrence arrays.Using the first occurrence array, get the indices corresponding to the two nodes which will be the corners of the range in the level array that is fed to the RMQ algorithm for the minimum value.Once the algorithm return the index of the minimum level in the range, we use it to determine the LCA using Euler tour array.
Do a Euler tour on the tree, and fill the euler, level and first occurrence arrays.
Using the first occurrence array, get the indices corresponding to the two nodes which will be the corners of the range in the level array that is fed to the RMQ algorithm for the minimum value.
Once the algorithm return the index of the minimum level in the range, we use it to determine the LCA using Euler tour array.
Below is the implementation of above algorithm.
C++
Java
Python3
C#
Javascript
/* C++ Program to find LCA of u and v by reducing the problem to RMQ */#include<bits/stdc++.h>#define V 9 // number of nodes in input tree int euler[2*V - 1]; // For Euler tour sequenceint level[2*V - 1]; // Level of nodes in tour sequenceint firstOccurrence[V+1]; // First occurrences of nodes in tourint ind; // Variable to fill-in euler and level arrays // A Binary Tree nodestruct Node{ int key; struct Node *left, *right;}; // Utility function creates a new binary tree node with given keyNode * newNode(int k){ Node *temp = new Node; temp->key = k; temp->left = temp->right = NULL; return temp;} // log base 2 of xint Log2(int x){ int ans = 0 ; while (x>>=1) ans++; return ans ;} /* A recursive function to get the minimum value in a given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */int RMQUtil(int index, int ss, int se, int qs, int qe, int *st){ // If segment of this node is a part of given range, then return // the min of the segment if (qs <= ss && qe >= se) return st[index]; // If segment of this node is outside the given range else if (se < qs || ss > qe) return -1; // If a part of this segment overlaps with the given range int mid = (ss + se)/2; int q1 = RMQUtil(2*index+1, ss, mid, qs, qe, st); int q2 = RMQUtil(2*index+2, mid+1, se, qs, qe, st); if (q1==-1) return q2; else if (q2==-1) return q1; return (level[q1] < level[q2]) ? q1 : q2;} // Return minimum of elements in range from index qs (query start) to// qe (query end). It mainly uses RMQUtil()int RMQ(int *st, int n, int qs, int qe){ // Check for erroneous input values if (qs < 0 || qe > n-1 || qs > qe) { printf("Invalid Input"); return -1; } return RMQUtil(0, 0, n-1, qs, qe, st);} // A recursive function that constructs Segment Tree for array[ss..se].// si is index of current node in segment tree stvoid constructSTUtil(int si, int ss, int se, int arr[], int *st){ // If there is one element in array, store it in current node of // segment tree and return if (ss == se)st[si] = ss; else { // If there are more than one elements, then recur for left and // right subtrees and store the minimum of two values in this node int mid = (ss + se)/2; constructSTUtil(si*2+1, ss, mid, arr, st); constructSTUtil(si*2+2, mid+1, se, arr, st); if (arr[st[2*si+1]] < arr[st[2*si+2]]) st[si] = st[2*si+1]; else st[si] = st[2*si+2]; }} /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */int *constructST(int arr[], int n){ // Allocate memory for segment tree // Height of segment tree int x = Log2(n)+1; // Maximum size of segment tree int max_size = 2*(1<<x) - 1; // 2*pow(2,x) -1 int *st = new int[max_size]; // Fill the allocated memory st constructSTUtil(0, 0, n-1, arr, st); // Return the constructed segment tree return st;} // Recursive version of the Euler tour of Tvoid eulerTour(Node *root, int l){ /* if the passed node exists */ if (root) { euler[ind] = root->key; // insert in euler array level[ind] = l; // insert l in level array ind++; // increment index /* if unvisited, mark first occurrence */ if (firstOccurrence[root->key] == -1) firstOccurrence[root->key] = ind-1; /* tour left subtree if exists, and remark euler and level arrays for parent on return */ if (root->left) { eulerTour(root->left, l+1); euler[ind]=root->key; level[ind] = l; ind++; } /* tour right subtree if exists, and remark euler and level arrays for parent on return */ if (root->right) { eulerTour(root->right, l+1); euler[ind]=root->key; level[ind] = l; ind++; } }} // Returns LCA of nodes n1, n2 (assuming they are// present in the tree)int findLCA(Node *root, int u, int v){ /* Mark all nodes unvisited. Note that the size of firstOccurrence is 1 as node values which vary from 1 to 9 are used as indexes */ memset(firstOccurrence, -1, sizeof(int)*(V+1)); /* To start filling euler and level arrays from index 0 */ ind = 0; /* Start Euler tour with root node on level 0 */ eulerTour(root, 0); /* construct segment tree on level array */ int *st = constructST(level, 2*V-1); /* If v before u in Euler tour. For RMQ to work, first parameter 'u' must be smaller than second 'v' */ if (firstOccurrence[u]>firstOccurrence[v]) std::swap(u, v); // Starting and ending indexes of query range int qs = firstOccurrence[u]; int qe = firstOccurrence[v]; // query for index of LCA in tour int index = RMQ(st, 2*V-1, qs, qe); /* return LCA node */ return euler[index];} // Driver program to test above functionsint main(){ // Let us create the Binary Tree as shown in the diagram. Node * root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->right->left = newNode(8); root->left->right->right = newNode(9); int u = 4, v = 9; printf("The LCA of node %d and node %d is node %d.\n", u, v, findLCA(root, u, v)); return 0;}
// Java program to find LCA of u and v by reducing problem to RMQ import java.util.*; // A binary tree nodeclass Node{ Node left, right; int data; Node(int item) { data = item; left = right = null; }} class St_class{ int st; int stt[] = new int[10000];} class BinaryTree{ Node root; int v = 9; // v is the highest value of node in our tree int euler[] = new int[2 * v - 1]; // for euler tour sequence int level[] = new int[2 * v - 1]; // level of nodes in tour sequence int f_occur[] = new int[2 * v - 1]; // to store 1st occurrence of nodes int fill; // variable to fill euler and level arrays St_class sc = new St_class(); // log base 2 of x int Log2(int x) { int ans = 0; int y = x >>= 1; while (y-- != 0) ans++; return ans; } int swap(int a, int b) { return a; } /* A recursive function to get the minimum value in a given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */ int RMQUtil(int index, int ss, int se, int qs, int qe, St_class st) { // If segment of this node is a part of given range, then return // the min of the segment if (qs <= ss && qe >= se) return st.stt[index]; // If segment of this node is outside the given range else if (se < qs || ss > qe) return -1; // If a part of this segment overlaps with the given range int mid = (ss + se) / 2; int q1 = RMQUtil(2 * index + 1, ss, mid, qs, qe, st); int q2 = RMQUtil(2 * index + 2, mid + 1, se, qs, qe, st); if (q1 == -1) return q2; else if (q2 == -1) return q1; return (level[q1] < level[q2]) ? q1 : q2; } // Return minimum of elements in range from index qs (query start) to // qe (query end). It mainly uses RMQUtil() int RMQ(St_class st, int n, int qs, int qe) { // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { System.out.println("Invalid input"); return -1; } return RMQUtil(0, 0, n - 1, qs, qe, st); } // A recursive function that constructs Segment Tree for array[ss..se]. // si is index of current node in segment tree st void constructSTUtil(int si, int ss, int se, int arr[], St_class st) { // If there is one element in array, store it in current node of // segment tree and return if (ss == se) st.stt[si] = ss; else { // If there are more than one elements, then recur for left and // right subtrees and store the minimum of two values in this node int mid = (ss + se) / 2; constructSTUtil(si * 2 + 1, ss, mid, arr, st); constructSTUtil(si * 2 + 2, mid + 1, se, arr, st); if (arr[st.stt[2 * si + 1]] < arr[st.stt[2 * si + 2]]) st.stt[si] = st.stt[2 * si + 1]; else st.stt[si] = st.stt[2 * si + 2]; } } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ int constructST(int arr[], int n) { // Allocate memory for segment tree // Height of segment tree int x = Log2(n) + 1; // Maximum size of segment tree int max_size = 2 * (1 << x) - 1; // 2*pow(2,x) -1 sc.stt = new int[max_size]; // Fill the allocated memory st constructSTUtil(0, 0, n - 1, arr, sc); // Return the constructed segment tree return sc.st; } // Recursive version of the Euler tour of T void eulerTour(Node node, int l) { /* if the passed node exists */ if (node != null) { euler[fill] = node.data; // insert in euler array level[fill] = l; // insert l in level array fill++; // increment index /* if unvisited, mark first occurrence */ if (f_occur[node.data] == -1) f_occur[node.data] = fill - 1; /* tour left subtree if exists, and remark euler and level arrays for parent on return */ if (node.left != null) { eulerTour(node.left, l + 1); euler[fill] = node.data; level[fill] = l; fill++; } /* tour right subtree if exists, and remark euler and level arrays for parent on return */ if (node.right != null) { eulerTour(node.right, l + 1); euler[fill] = node.data; level[fill] = l; fill++; } } } // returns LCA of node n1 and n2 assuming they are present in tree int findLCA(Node node, int u, int v) { /* Mark all nodes unvisited. Note that the size of firstOccurrence is 1 as node values which vary from 1 to 9 are used as indexes */ Arrays.fill(f_occur, -1); /* To start filling euler and level arrays from index 0 */ fill = 0; /* Start Euler tour with root node on level 0 */ eulerTour(root, 0); /* construct segment tree on level array */ sc.st = constructST(level, 2 * v - 1); /* If v before u in Euler tour. For RMQ to work, first parameter 'u' must be smaller than second 'v' */ if (f_occur[u] > f_occur[v]) u = swap(u, u = v); // Starting and ending indexes of query range int qs = f_occur[u]; int qe = f_occur[v]; // query for index of LCA in tour int index = RMQ(sc, 2 * v - 1, qs, qe); /* return LCA node */ return euler[index]; } // Driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); // Let us create the Binary Tree as shown in the diagram. tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.left.right.left = new Node(8); tree.root.left.right.right = new Node(9); int u = 4, v = 9; System.out.println("The LCA of node " + u + " and " + v + " is " + tree.findLCA(tree.root, u, v)); } } // This code has been contributed by Mayank Jaiswal
# Python3 program to find LCA of u and v by# reducing the problem to RMQfrom math import log2, floorfrom typing import List class Node: def __init__(self, val: int): self.val, self.left, self.right = val, None, None class BinaryTree: def __init__(self, root: Node): self.root = root self.val_max = self._get_max_val() self.euler = [0] * (2 * self.val_max - 1) self.level = [0] * (2 * self.val_max - 1) self.f_occur = [-1] * (self.val_max + 1) self.fill = 0 self.segment_tree = [] def _get_max_val(self): stack = [self.root] max_val = -1 while stack: x = stack.pop() if x.val > max_val: max_val = x.val if x.left: stack.append(x.left) if x.right: stack.append(x.right) return max_val ''' A recursive function to get the minimum value in a given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range ''' def rmq_util(self, index, ss, se, qs, qe) -> int: # If segment of this node is part of given range # then return the min of the segment if qs <= ss and qe >= se: return self.segment_tree[index] # If segment of this node is outside # the given range elif se < qs or ss > qe: return -1 # If part of this segment overlaps with # given range mid = (ss + se) // 2 q1 = self.rmq_util(2 * index + 1, ss, mid, qs, qe) q2 = self.rmq_util(2 * index + 2, mid + 1, se, qs, qe) if q1 == -1: return q2 if q2 == -1: return q1 return (q1 if self.level[q1] < self.level[q2] else q2) # Return minimum of elements in range from # index qs (query start) to qe (query end). # It mainly uses rmq_util() def rmq(self, n: int, qs: int, qe: int) -> int: if qs < 0 or qe > n - 1 or qs > qe: print('invalid input') return -1 return self.rmq_util(0, 0, n - 1, qs, qe) # A recursive function that constructs Segment # Tree for array[ss..se]. si is index of # current node in segment tree st def construct_segment_tree_util(self, si, ss, se, arr): # If there is one element in array, # store it in current node of segment tree # and return if ss == se: self.segment_tree[si] = ss else: # If there are more than one elements, # then recur for left and right subtrees and # store the min of two values in this node mid = (ss + se) // 2 index_left, index_right = si * 2 + 1, si * 2 + 2 self.construct_segment_tree_util( index_left, ss, mid, arr) self.construct_segment_tree_util( index_right, mid+1, se, arr) if (arr[self.segment_tree[index_left]] < arr[self.segment_tree[index_right]]): self.segment_tree[si] = self.segment_tree[index_left] else: self.segment_tree[si] = self.segment_tree[index_right] # Function to construct segment tree from given # array. This function allocates memory for segment # tree and calls construct_segment_tree_util() # to fill the allocated memory def construct_segment_tree(self, arr: List, n: int): # Height of segment tree x = floor(log2(n) + 1) # Maximum size of segment tree max_size = 2 * (1 << x) - 1 # 2*pow(2,x) -1 self.segment_tree = [0] * max_size # Fill the allocated memory st self.construct_segment_tree_util( 0, 0, n - 1, arr) # Recursive version of the Euler tour of T def euler_tour(self, node: Node, lev: int): # If the passed node exists if node is not None: self.euler[self.fill] = node.val self.level[self.fill] = lev self.fill += 1 # If unvisited, mark first occurence if self.f_occur[node.val] == -1: self.f_occur[node.val] = self.fill - 1 # Tour left subtree if exists and remark # euler and level arrays for parent on # return if node.left is not None: self.euler_tour(node.left, lev + 1) self.euler[self.fill] = node.val self.level[self.fill] = lev self.fill += 1 # Tour right subtree if exists and # remark euler and level arrays for # parent on return if node.right is not None: self.euler_tour(node.right, lev + 1) self.euler[self.fill] = node.val self.level[self.fill] = lev self.fill += 1 # Returns LCA of nodes n1, n2 (assuming they are # present in the tree) def find_lca(self, u: int, v: int): # Start euler tour with root node on level 0 self.euler_tour(self.root, 0) # Construct segment tree on level array self.construct_segment_tree(self.level, 2 * self.val_max - 1) # For rmq to work, u must be smaller than v if self.f_occur[u] > self.f_occur[v]: u, v = v, u # Start and end of query range qs = self.f_occur[u] qe = self.f_occur[v] # Query for index of lca in tour index = self.rmq(2 * self.val_max - 1, qs, qe) # Return lca node return self.euler[index] # Driver codeif __name__ == "__main__": root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) root.left.right.left = Node(8) root.left.right.right = Node(9) tree = BinaryTree(root) u, v = 4, 9 print('The lca of node {} and {} is node {}'.format( u, v, tree.find_lca(u, v))) # This code is contributed by Rajat Srivastava
// C# program to find LCA of u and// v by reducing problem to RMQusing System; // A binary tree nodeclass Node{ public Node left, right; public int data; public Node(int item) { data = item; left = right = null; }} class St_class{ public int st; public int []stt = new int[10000];} public class BinaryTree{ Node root; static int v = 9; // v is the highest value of node in our tree int []euler = new int[2 * v - 1]; // for euler tour sequence int []level = new int[2 * v - 1]; // level of nodes in tour sequence int []f_occur = new int[2 * v - 1]; // to store 1st occurrence of nodes int fill; // variable to fill euler and level arrays St_class sc = new St_class(); // log base 2 of x int Log2(int x) { int ans = 0; int y = x >>= 1; while (y-- != 0) ans++; return ans; } int swap(int a, int b) { return a; } /* A recursive function to get the minimum value in a given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */ int RMQUtil(int index, int ss, int se, int qs, int qe, St_class st) { // If segment of this node is a part // of given range, then return // the min of the segment if (qs <= ss && qe >= se) return st.stt[index]; // If segment of this node is // outside the given range else if (se < qs || ss > qe) return -1; // If a part of this segment // overlaps with the given range int mid = (ss + se) / 2; int q1 = RMQUtil(2 * index + 1, ss, mid, qs, qe, st); int q2 = RMQUtil(2 * index + 2, mid + 1, se, qs, qe, st); if (q1 == -1) return q2; else if (q2 == -1) return q1; return (level[q1] < level[q2]) ? q1 : q2; } // Return minimum of elements in // range from index qs (query start) to // qe (query end). It mainly uses RMQUtil() int RMQ(St_class st, int n, int qs, int qe) { // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { Console.WriteLine("Invalid input"); return -1; } return RMQUtil(0, 0, n - 1, qs, qe, st); } // A recursive function that constructs // Segment Tree for array[ss..se]. // si is index of current node in segment tree st void constructSTUtil(int si, int ss, int se, int []arr, St_class st) { // If there is one element in array, // store it in current node of // segment tree and return if (ss == se) st.stt[si] = ss; else { // If there are more than one elements, // then recur for left and right subtrees // and store the minimum of two values in this node int mid = (ss + se) / 2; constructSTUtil(si * 2 + 1, ss, mid, arr, st); constructSTUtil(si * 2 + 2, mid + 1, se, arr, st); if (arr[st.stt[2 * si + 1]] < arr[st.stt[2 * si + 2]]) st.stt[si] = st.stt[2 * si + 1]; else st.stt[si] = st.stt[2 * si + 2]; } } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ int constructST(int []arr, int n) { // Allocate memory for segment tree // Height of segment tree int x = Log2(n) + 1; // Maximum size of segment tree int max_size = 2 * (1 << x) - 1; // 2*pow(2,x) -1 sc.stt = new int[max_size]; // Fill the allocated memory st constructSTUtil(0, 0, n - 1, arr, sc); // Return the constructed segment tree return sc.st; } // Recursive version of the Euler tour of T void eulerTour(Node node, int l) { /* if the passed node exists */ if (node != null) { euler[fill] = node.data; // insert in euler array level[fill] = l; // insert l in level array fill++; // increment index /* if unvisited, mark first occurrence */ if (f_occur[node.data] == -1) f_occur[node.data] = fill - 1; /* tour left subtree if exists, and remark euler and level arrays for parent on return */ if (node.left != null) { eulerTour(node.left, l + 1); euler[fill] = node.data; level[fill] = l; fill++; } /* tour right subtree if exists, and remark euler and level arrays for parent on return */ if (node.right != null) { eulerTour(node.right, l + 1); euler[fill] = node.data; level[fill] = l; fill++; } } } // returns LCA of node n1 and n2 // assuming they are present in tree int findLCA(Node node, int u, int v) { /* Mark all nodes unvisited. Note that the size of firstOccurrence is 1 as node values which vary from 1 to 9 are used as indexes */ //Arrays.fill(f_occur, -1); for(int i = 0; i < f_occur.Length; i++) f_occur[i] = -1; /* To start filling euler and level arrays from index 0 */ fill = 0; /* Start Euler tour with root node on level 0 */ eulerTour(root, 0); /* construct segment tree on level array */ sc.st = constructST(level, 2 * v - 1); /* If v before u in Euler tour. For RMQ to work, first parameter 'u' must be smaller than second 'v' */ if (f_occur[u] > f_occur[v]) u = swap(u, u = v); // Starting and ending indexes of query range int qs = f_occur[u]; int qe = f_occur[v]; // query for index of LCA in tour int index = RMQ(sc, 2 * v - 1, qs, qe); /* return LCA node */ return euler[index]; } // Driver program to test above functions public static void Main(String []args) { BinaryTree tree = new BinaryTree(); // Let us create the Binary Tree // as shown in the diagram. tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.left.right.left = new Node(8); tree.root.left.right.right = new Node(9); int u = 4, v = 9; Console.WriteLine("The LCA of node " + u + " and " + v + " is " + tree.findLCA(tree.root, u, v)); }} // This code is contributed by 29AjayKumar
<script> // JavaScript program to find LCA of u and v// by reducing problem to RMQ // A binary tree nodeclass Node{ constructor(item) { this.data=item; this.left = this.right = null; }} class St_class{ st; stt=new Array(10000);} let root;// v is the highest value of node in our treelet v = 9;// for euler tour sequencelet euler = new Array(2 * v - 1);// level of nodes in tour sequencelet level = new Array(2 * v - 1);// to store 1st occurrence of nodeslet f_occur = new Array(2 * v - 1); let fill; // variable to fill euler and level arrayslet sc = new St_class(); // log base 2 of xfunction Log2(x){ let ans = 0; let y = x >>= 1; while (y-- != 0) ans++; return ans;} function swap(a,b){ return a;} /* A recursive function to get the minimum value in a given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */function RMQUtil(index,ss,se,qs,qe,st){ // If segment of this node is a part // of given range, then return // the min of the segment if (qs <= ss && qe >= se) return st.stt[index]; // If segment of this node is // outside the given range else if (se < qs || ss > qe) return -1; // If a part of this segment overlaps // with the given range let mid = Math.floor((ss + se) / 2); let q1 = RMQUtil(2 * index + 1, ss, mid, qs, qe, st); let q2 = RMQUtil(2 * index + 2, mid + 1, se, qs, qe, st); if (q1 == -1) return q2; else if (q2 == -1) return q1; return (level[q1] < level[q2]) ? q1 : q2;} // Return minimum of elements in range// from index qs (query start) to // qe (query end). It mainly uses RMQUtil()function RMQ(st,n,qs,qe){ // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { document.write("Invalid input"); return -1; } return RMQUtil(0, 0, n - 1, qs, qe, st);} // A recursive function that constructs// Segment Tree for array[ss..se]. // si is index of current node in segment tree stfunction constructSTUtil(si,ss,se,arr,st){ // If there is one element in array, // store it in current node of // segment tree and return if (ss == se) st.stt[si] = ss; else { // If there are more than one elements, // then recur for left and // right subtrees and store the minimum // of two values in this node let mid = Math.floor((ss + se) / 2); constructSTUtil(si * 2 + 1, ss, mid, arr, st); constructSTUtil(si * 2 + 2, mid + 1, se, arr, st); if (arr[st.stt[2 * si + 1]] < arr[st.stt[2 * si + 2]]) st.stt[si] = st.stt[2 * si + 1]; else st.stt[si] = st.stt[2 * si + 2]; }} /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */function constructST(arr,n){ // Allocate memory for segment tree // Height of segment tree let x = Log2(n) + 1; // Maximum size of segment tree let max_size = 2 * (1 << x) - 1; // 2*pow(2,x) -1 sc.stt = new Array(max_size); // Fill the allocated memory st constructSTUtil(0, 0, n - 1, arr, sc); // Return the constructed segment tree return sc.st;} // Recursive version of the Euler tour of Tfunction eulerTour(node,l){ /* if the passed node exists */ if (node != null) { euler[fill] = node.data; // insert in euler array level[fill] = l; // insert l in level array fill++; // increment index /* if unvisited, mark first occurrence */ if (f_occur[node.data] == -1) f_occur[node.data] = fill - 1; /* tour left subtree if exists, and remark euler and level arrays for parent on return */ if (node.left != null) { eulerTour(node.left, l + 1); euler[fill] = node.data; level[fill] = l; fill++; } /* tour right subtree if exists, and remark euler and level arrays for parent on return */ if (node.right != null) { eulerTour(node.right, l + 1); euler[fill] = node.data; level[fill] = l; fill++; } }} // returns LCA of node n1 and n2// assuming they are present in treefunction findLCA(node,u,v){ /* Mark all nodes unvisited. Note that the size of firstOccurrence is 1 as node values which vary from 1 to 9 are used as indexes */ for(let i=0;i<f_occur.length;i++) { f_occur[i]=-1; } /* To start filling euler and level arrays from index 0 */ fill = 0; /* Start Euler tour with root node on level 0 */ eulerTour(root, 0); /* construct segment tree on level array */ sc.st = constructST(level, 2 * v - 1); /* If v before u in Euler tour. For RMQ to work, first parameter 'u' must be smaller than second 'v' */ if (f_occur[u] > f_occur[v]) u = swap(u, u = v); // Starting and ending indexes of query range let qs = f_occur[u]; let qe = f_occur[v]; // query for index of LCA in tour let index = RMQ(sc, 2 * v - 1, qs, qe); /* return LCA node */ return euler[index];} // Driver program to test above functions // Let us create the Binary Tree as shown in the diagram.root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.left = new Node(6);root.right.right = new Node(7);root.left.right.left = new Node(8);root.left.right.right = new Node(9); u = 4, v = 9;document.write("The LCA of node " + u +" and node " + v + " is node "+ findLCA(root, u, v)); // This code is contributed by rag2127 </script>
Output:
The LCA of node 4 and node 9 is node 2.
Note:
We assume that the nodes queried are present in the tree.We also assumed that if there are V nodes in tree, then keys (or data) of these nodes are in range from 1 to V.
We assume that the nodes queried are present in the tree.
We also assumed that if there are V nodes in tree, then keys (or data) of these nodes are in range from 1 to V.
Time complexity:
Euler tour: Number of nodes is V. For a tree, E = V-1. Euler tour (DFS) will take O(V+E) which is O(2*V) which can be written as O(V).Segment Tree construction : O(n) where n = V + E = 2*V – 1.Range Minimum query: O(log(n))
Euler tour: Number of nodes is V. For a tree, E = V-1. Euler tour (DFS) will take O(V+E) which is O(2*V) which can be written as O(V).
Segment Tree construction : O(n) where n = V + E = 2*V – 1.
Range Minimum query: O(log(n))
Overall this method takes O(n) time for preprocssing, but takes O(Log n) time for query. Therefore, it can be useful when we have a single tree on which we want to perform large number of LCA queries (Note that LCA is useful for finding shortest path between two nodes of Binary Tree)
Auxiliary Space:
Euler tour array: O(n) where n = 2*V – 1Node Levels array: O(n)First Occurrences array: O(V)Segment Tree: O(n)
Euler tour array: O(n) where n = 2*V – 1
Node Levels array: O(n)
First Occurrences array: O(V)
Segment Tree: O(n)
Overall: O(n)Another observation is that the adjacent elements in level array differ by 1. This can be used to convert a RMQ problem to a LCA problem.This article is contributed by Yash Varyani. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
29AjayKumar
nidhi_biet
ManasChhabra2
rajatsri94
rag2127
LCA
Segment-Tree
Advanced Data Structure
Tree
Tree
Segment-Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
AVL Tree | Set 1 (Insertion)
Trie | (Insert and Search)
LRU Cache Implementation
Red-Black Tree | Set 1 (Introduction)
Introduction of B-Tree
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
AVL Tree | Set 1 (Insertion)
Inorder Tree Traversal without Recursion
|
[
{
"code": null,
"e": 35766,
"s": 35738,
"text": "\n11 Jun, 2021"
},
{
"code": null,
"e": 35898,
"s": 35766,
"text": "The article describes an approach to solving the problem of finding the LCA of two nodes in a tree by reducing it to a RMQ problem."
},
{
"code": null,
"e": 36127,
"s": 35898,
"text": "Lowest Common Ancestor (LCA) of two nodes u and v in a rooted tree T is defined as the node located farthest from the root that has both u and v as descendants.For example, in below diagram, LCA of node 4 and node 9 is node 2. "
},
{
"code": null,
"e": 36318,
"s": 36127,
"text": "There can be many approaches to solve the LCA problem. The approaches differ in their time and space complexities. Here is a link to a couple of them (these do not involve reduction to RMQ)."
},
{
"code": null,
"e": 36736,
"s": 36318,
"text": "Range Minimum Query (RMQ) is used on arrays to find the position of an element with the minimum value between two specified indices. Different approaches for solving RMQ have been discussed here and here. In this article, Segment Tree based approach is discussed. With segment tree, preprocessing time is O(n) and time to for range minimum query is O(Logn). The extra space required is O(n) to store the segment tree."
},
{
"code": null,
"e": 36939,
"s": 36736,
"text": "Reduction of LCA to RMQ: The idea is to traverse the tree starting from root by an Euler tour (traversal without lifting pencil), which is a DFS-type traversal with preorder traversal characteristics. "
},
{
"code": null,
"e": 37403,
"s": 36939,
"text": "Observation: The LCA of nodes 4 and 9 is node 2, which happens to be the node closest to the root amongst all those encountered between the visits of 4 and 9 during a DFS of T. This observation is the key to the reduction. Let’s rephrase: Our node is the node at the smallest level and the only node at that level amongst all the nodes that occur between consecutive occurrences (any) of u and v in the Euler tour of T.We require three arrays for implementation: "
},
{
"code": null,
"e": 37612,
"s": 37403,
"text": "Nodes visited in order of Euler tour of TLevel of each node visited in Euler tour of TIndex of the first occurrence of a node in Euler tour of T (since any occurrence would be good, let’s track the first one)"
},
{
"code": null,
"e": 37654,
"s": 37612,
"text": "Nodes visited in order of Euler tour of T"
},
{
"code": null,
"e": 37700,
"s": 37654,
"text": "Level of each node visited in Euler tour of T"
},
{
"code": null,
"e": 37823,
"s": 37700,
"text": "Index of the first occurrence of a node in Euler tour of T (since any occurrence would be good, let’s track the first one)"
},
{
"code": null,
"e": 37835,
"s": 37823,
"text": "Algorithm: "
},
{
"code": null,
"e": 38238,
"s": 37835,
"text": "Do a Euler tour on the tree, and fill the euler, level and first occurrence arrays.Using the first occurrence array, get the indices corresponding to the two nodes which will be the corners of the range in the level array that is fed to the RMQ algorithm for the minimum value.Once the algorithm return the index of the minimum level in the range, we use it to determine the LCA using Euler tour array."
},
{
"code": null,
"e": 38322,
"s": 38238,
"text": "Do a Euler tour on the tree, and fill the euler, level and first occurrence arrays."
},
{
"code": null,
"e": 38517,
"s": 38322,
"text": "Using the first occurrence array, get the indices corresponding to the two nodes which will be the corners of the range in the level array that is fed to the RMQ algorithm for the minimum value."
},
{
"code": null,
"e": 38643,
"s": 38517,
"text": "Once the algorithm return the index of the minimum level in the range, we use it to determine the LCA using Euler tour array."
},
{
"code": null,
"e": 38691,
"s": 38643,
"text": "Below is the implementation of above algorithm."
},
{
"code": null,
"e": 38695,
"s": 38691,
"text": "C++"
},
{
"code": null,
"e": 38700,
"s": 38695,
"text": "Java"
},
{
"code": null,
"e": 38708,
"s": 38700,
"text": "Python3"
},
{
"code": null,
"e": 38711,
"s": 38708,
"text": "C#"
},
{
"code": null,
"e": 38722,
"s": 38711,
"text": "Javascript"
},
{
"code": "/* C++ Program to find LCA of u and v by reducing the problem to RMQ */#include<bits/stdc++.h>#define V 9 // number of nodes in input tree int euler[2*V - 1]; // For Euler tour sequenceint level[2*V - 1]; // Level of nodes in tour sequenceint firstOccurrence[V+1]; // First occurrences of nodes in tourint ind; // Variable to fill-in euler and level arrays // A Binary Tree nodestruct Node{ int key; struct Node *left, *right;}; // Utility function creates a new binary tree node with given keyNode * newNode(int k){ Node *temp = new Node; temp->key = k; temp->left = temp->right = NULL; return temp;} // log base 2 of xint Log2(int x){ int ans = 0 ; while (x>>=1) ans++; return ans ;} /* A recursive function to get the minimum value in a given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */int RMQUtil(int index, int ss, int se, int qs, int qe, int *st){ // If segment of this node is a part of given range, then return // the min of the segment if (qs <= ss && qe >= se) return st[index]; // If segment of this node is outside the given range else if (se < qs || ss > qe) return -1; // If a part of this segment overlaps with the given range int mid = (ss + se)/2; int q1 = RMQUtil(2*index+1, ss, mid, qs, qe, st); int q2 = RMQUtil(2*index+2, mid+1, se, qs, qe, st); if (q1==-1) return q2; else if (q2==-1) return q1; return (level[q1] < level[q2]) ? q1 : q2;} // Return minimum of elements in range from index qs (query start) to// qe (query end). It mainly uses RMQUtil()int RMQ(int *st, int n, int qs, int qe){ // Check for erroneous input values if (qs < 0 || qe > n-1 || qs > qe) { printf(\"Invalid Input\"); return -1; } return RMQUtil(0, 0, n-1, qs, qe, st);} // A recursive function that constructs Segment Tree for array[ss..se].// si is index of current node in segment tree stvoid constructSTUtil(int si, int ss, int se, int arr[], int *st){ // If there is one element in array, store it in current node of // segment tree and return if (ss == se)st[si] = ss; else { // If there are more than one elements, then recur for left and // right subtrees and store the minimum of two values in this node int mid = (ss + se)/2; constructSTUtil(si*2+1, ss, mid, arr, st); constructSTUtil(si*2+2, mid+1, se, arr, st); if (arr[st[2*si+1]] < arr[st[2*si+2]]) st[si] = st[2*si+1]; else st[si] = st[2*si+2]; }} /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */int *constructST(int arr[], int n){ // Allocate memory for segment tree // Height of segment tree int x = Log2(n)+1; // Maximum size of segment tree int max_size = 2*(1<<x) - 1; // 2*pow(2,x) -1 int *st = new int[max_size]; // Fill the allocated memory st constructSTUtil(0, 0, n-1, arr, st); // Return the constructed segment tree return st;} // Recursive version of the Euler tour of Tvoid eulerTour(Node *root, int l){ /* if the passed node exists */ if (root) { euler[ind] = root->key; // insert in euler array level[ind] = l; // insert l in level array ind++; // increment index /* if unvisited, mark first occurrence */ if (firstOccurrence[root->key] == -1) firstOccurrence[root->key] = ind-1; /* tour left subtree if exists, and remark euler and level arrays for parent on return */ if (root->left) { eulerTour(root->left, l+1); euler[ind]=root->key; level[ind] = l; ind++; } /* tour right subtree if exists, and remark euler and level arrays for parent on return */ if (root->right) { eulerTour(root->right, l+1); euler[ind]=root->key; level[ind] = l; ind++; } }} // Returns LCA of nodes n1, n2 (assuming they are// present in the tree)int findLCA(Node *root, int u, int v){ /* Mark all nodes unvisited. Note that the size of firstOccurrence is 1 as node values which vary from 1 to 9 are used as indexes */ memset(firstOccurrence, -1, sizeof(int)*(V+1)); /* To start filling euler and level arrays from index 0 */ ind = 0; /* Start Euler tour with root node on level 0 */ eulerTour(root, 0); /* construct segment tree on level array */ int *st = constructST(level, 2*V-1); /* If v before u in Euler tour. For RMQ to work, first parameter 'u' must be smaller than second 'v' */ if (firstOccurrence[u]>firstOccurrence[v]) std::swap(u, v); // Starting and ending indexes of query range int qs = firstOccurrence[u]; int qe = firstOccurrence[v]; // query for index of LCA in tour int index = RMQ(st, 2*V-1, qs, qe); /* return LCA node */ return euler[index];} // Driver program to test above functionsint main(){ // Let us create the Binary Tree as shown in the diagram. Node * root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->right->left = newNode(8); root->left->right->right = newNode(9); int u = 4, v = 9; printf(\"The LCA of node %d and node %d is node %d.\\n\", u, v, findLCA(root, u, v)); return 0;}",
"e": 44713,
"s": 38722,
"text": null
},
{
"code": "// Java program to find LCA of u and v by reducing problem to RMQ import java.util.*; // A binary tree nodeclass Node{ Node left, right; int data; Node(int item) { data = item; left = right = null; }} class St_class{ int st; int stt[] = new int[10000];} class BinaryTree{ Node root; int v = 9; // v is the highest value of node in our tree int euler[] = new int[2 * v - 1]; // for euler tour sequence int level[] = new int[2 * v - 1]; // level of nodes in tour sequence int f_occur[] = new int[2 * v - 1]; // to store 1st occurrence of nodes int fill; // variable to fill euler and level arrays St_class sc = new St_class(); // log base 2 of x int Log2(int x) { int ans = 0; int y = x >>= 1; while (y-- != 0) ans++; return ans; } int swap(int a, int b) { return a; } /* A recursive function to get the minimum value in a given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */ int RMQUtil(int index, int ss, int se, int qs, int qe, St_class st) { // If segment of this node is a part of given range, then return // the min of the segment if (qs <= ss && qe >= se) return st.stt[index]; // If segment of this node is outside the given range else if (se < qs || ss > qe) return -1; // If a part of this segment overlaps with the given range int mid = (ss + se) / 2; int q1 = RMQUtil(2 * index + 1, ss, mid, qs, qe, st); int q2 = RMQUtil(2 * index + 2, mid + 1, se, qs, qe, st); if (q1 == -1) return q2; else if (q2 == -1) return q1; return (level[q1] < level[q2]) ? q1 : q2; } // Return minimum of elements in range from index qs (query start) to // qe (query end). It mainly uses RMQUtil() int RMQ(St_class st, int n, int qs, int qe) { // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { System.out.println(\"Invalid input\"); return -1; } return RMQUtil(0, 0, n - 1, qs, qe, st); } // A recursive function that constructs Segment Tree for array[ss..se]. // si is index of current node in segment tree st void constructSTUtil(int si, int ss, int se, int arr[], St_class st) { // If there is one element in array, store it in current node of // segment tree and return if (ss == se) st.stt[si] = ss; else { // If there are more than one elements, then recur for left and // right subtrees and store the minimum of two values in this node int mid = (ss + se) / 2; constructSTUtil(si * 2 + 1, ss, mid, arr, st); constructSTUtil(si * 2 + 2, mid + 1, se, arr, st); if (arr[st.stt[2 * si + 1]] < arr[st.stt[2 * si + 2]]) st.stt[si] = st.stt[2 * si + 1]; else st.stt[si] = st.stt[2 * si + 2]; } } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ int constructST(int arr[], int n) { // Allocate memory for segment tree // Height of segment tree int x = Log2(n) + 1; // Maximum size of segment tree int max_size = 2 * (1 << x) - 1; // 2*pow(2,x) -1 sc.stt = new int[max_size]; // Fill the allocated memory st constructSTUtil(0, 0, n - 1, arr, sc); // Return the constructed segment tree return sc.st; } // Recursive version of the Euler tour of T void eulerTour(Node node, int l) { /* if the passed node exists */ if (node != null) { euler[fill] = node.data; // insert in euler array level[fill] = l; // insert l in level array fill++; // increment index /* if unvisited, mark first occurrence */ if (f_occur[node.data] == -1) f_occur[node.data] = fill - 1; /* tour left subtree if exists, and remark euler and level arrays for parent on return */ if (node.left != null) { eulerTour(node.left, l + 1); euler[fill] = node.data; level[fill] = l; fill++; } /* tour right subtree if exists, and remark euler and level arrays for parent on return */ if (node.right != null) { eulerTour(node.right, l + 1); euler[fill] = node.data; level[fill] = l; fill++; } } } // returns LCA of node n1 and n2 assuming they are present in tree int findLCA(Node node, int u, int v) { /* Mark all nodes unvisited. Note that the size of firstOccurrence is 1 as node values which vary from 1 to 9 are used as indexes */ Arrays.fill(f_occur, -1); /* To start filling euler and level arrays from index 0 */ fill = 0; /* Start Euler tour with root node on level 0 */ eulerTour(root, 0); /* construct segment tree on level array */ sc.st = constructST(level, 2 * v - 1); /* If v before u in Euler tour. For RMQ to work, first parameter 'u' must be smaller than second 'v' */ if (f_occur[u] > f_occur[v]) u = swap(u, u = v); // Starting and ending indexes of query range int qs = f_occur[u]; int qe = f_occur[v]; // query for index of LCA in tour int index = RMQ(sc, 2 * v - 1, qs, qe); /* return LCA node */ return euler[index]; } // Driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); // Let us create the Binary Tree as shown in the diagram. tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.left.right.left = new Node(8); tree.root.left.right.right = new Node(9); int u = 4, v = 9; System.out.println(\"The LCA of node \" + u + \" and \" + v + \" is \" + tree.findLCA(tree.root, u, v)); } } // This code has been contributed by Mayank Jaiswal",
"e": 51726,
"s": 44713,
"text": null
},
{
"code": "# Python3 program to find LCA of u and v by# reducing the problem to RMQfrom math import log2, floorfrom typing import List class Node: def __init__(self, val: int): self.val, self.left, self.right = val, None, None class BinaryTree: def __init__(self, root: Node): self.root = root self.val_max = self._get_max_val() self.euler = [0] * (2 * self.val_max - 1) self.level = [0] * (2 * self.val_max - 1) self.f_occur = [-1] * (self.val_max + 1) self.fill = 0 self.segment_tree = [] def _get_max_val(self): stack = [self.root] max_val = -1 while stack: x = stack.pop() if x.val > max_val: max_val = x.val if x.left: stack.append(x.left) if x.right: stack.append(x.right) return max_val ''' A recursive function to get the minimum value in a given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range ''' def rmq_util(self, index, ss, se, qs, qe) -> int: # If segment of this node is part of given range # then return the min of the segment if qs <= ss and qe >= se: return self.segment_tree[index] # If segment of this node is outside # the given range elif se < qs or ss > qe: return -1 # If part of this segment overlaps with # given range mid = (ss + se) // 2 q1 = self.rmq_util(2 * index + 1, ss, mid, qs, qe) q2 = self.rmq_util(2 * index + 2, mid + 1, se, qs, qe) if q1 == -1: return q2 if q2 == -1: return q1 return (q1 if self.level[q1] < self.level[q2] else q2) # Return minimum of elements in range from # index qs (query start) to qe (query end). # It mainly uses rmq_util() def rmq(self, n: int, qs: int, qe: int) -> int: if qs < 0 or qe > n - 1 or qs > qe: print('invalid input') return -1 return self.rmq_util(0, 0, n - 1, qs, qe) # A recursive function that constructs Segment # Tree for array[ss..se]. si is index of # current node in segment tree st def construct_segment_tree_util(self, si, ss, se, arr): # If there is one element in array, # store it in current node of segment tree # and return if ss == se: self.segment_tree[si] = ss else: # If there are more than one elements, # then recur for left and right subtrees and # store the min of two values in this node mid = (ss + se) // 2 index_left, index_right = si * 2 + 1, si * 2 + 2 self.construct_segment_tree_util( index_left, ss, mid, arr) self.construct_segment_tree_util( index_right, mid+1, se, arr) if (arr[self.segment_tree[index_left]] < arr[self.segment_tree[index_right]]): self.segment_tree[si] = self.segment_tree[index_left] else: self.segment_tree[si] = self.segment_tree[index_right] # Function to construct segment tree from given # array. This function allocates memory for segment # tree and calls construct_segment_tree_util() # to fill the allocated memory def construct_segment_tree(self, arr: List, n: int): # Height of segment tree x = floor(log2(n) + 1) # Maximum size of segment tree max_size = 2 * (1 << x) - 1 # 2*pow(2,x) -1 self.segment_tree = [0] * max_size # Fill the allocated memory st self.construct_segment_tree_util( 0, 0, n - 1, arr) # Recursive version of the Euler tour of T def euler_tour(self, node: Node, lev: int): # If the passed node exists if node is not None: self.euler[self.fill] = node.val self.level[self.fill] = lev self.fill += 1 # If unvisited, mark first occurence if self.f_occur[node.val] == -1: self.f_occur[node.val] = self.fill - 1 # Tour left subtree if exists and remark # euler and level arrays for parent on # return if node.left is not None: self.euler_tour(node.left, lev + 1) self.euler[self.fill] = node.val self.level[self.fill] = lev self.fill += 1 # Tour right subtree if exists and # remark euler and level arrays for # parent on return if node.right is not None: self.euler_tour(node.right, lev + 1) self.euler[self.fill] = node.val self.level[self.fill] = lev self.fill += 1 # Returns LCA of nodes n1, n2 (assuming they are # present in the tree) def find_lca(self, u: int, v: int): # Start euler tour with root node on level 0 self.euler_tour(self.root, 0) # Construct segment tree on level array self.construct_segment_tree(self.level, 2 * self.val_max - 1) # For rmq to work, u must be smaller than v if self.f_occur[u] > self.f_occur[v]: u, v = v, u # Start and end of query range qs = self.f_occur[u] qe = self.f_occur[v] # Query for index of lca in tour index = self.rmq(2 * self.val_max - 1, qs, qe) # Return lca node return self.euler[index] # Driver codeif __name__ == \"__main__\": root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) root.left.right.left = Node(8) root.left.right.right = Node(9) tree = BinaryTree(root) u, v = 4, 9 print('The lca of node {} and {} is node {}'.format( u, v, tree.find_lca(u, v))) # This code is contributed by Rajat Srivastava",
"e": 58442,
"s": 51726,
"text": null
},
{
"code": "// C# program to find LCA of u and// v by reducing problem to RMQusing System; // A binary tree nodeclass Node{ public Node left, right; public int data; public Node(int item) { data = item; left = right = null; }} class St_class{ public int st; public int []stt = new int[10000];} public class BinaryTree{ Node root; static int v = 9; // v is the highest value of node in our tree int []euler = new int[2 * v - 1]; // for euler tour sequence int []level = new int[2 * v - 1]; // level of nodes in tour sequence int []f_occur = new int[2 * v - 1]; // to store 1st occurrence of nodes int fill; // variable to fill euler and level arrays St_class sc = new St_class(); // log base 2 of x int Log2(int x) { int ans = 0; int y = x >>= 1; while (y-- != 0) ans++; return ans; } int swap(int a, int b) { return a; } /* A recursive function to get the minimum value in a given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */ int RMQUtil(int index, int ss, int se, int qs, int qe, St_class st) { // If segment of this node is a part // of given range, then return // the min of the segment if (qs <= ss && qe >= se) return st.stt[index]; // If segment of this node is // outside the given range else if (se < qs || ss > qe) return -1; // If a part of this segment // overlaps with the given range int mid = (ss + se) / 2; int q1 = RMQUtil(2 * index + 1, ss, mid, qs, qe, st); int q2 = RMQUtil(2 * index + 2, mid + 1, se, qs, qe, st); if (q1 == -1) return q2; else if (q2 == -1) return q1; return (level[q1] < level[q2]) ? q1 : q2; } // Return minimum of elements in // range from index qs (query start) to // qe (query end). It mainly uses RMQUtil() int RMQ(St_class st, int n, int qs, int qe) { // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { Console.WriteLine(\"Invalid input\"); return -1; } return RMQUtil(0, 0, n - 1, qs, qe, st); } // A recursive function that constructs // Segment Tree for array[ss..se]. // si is index of current node in segment tree st void constructSTUtil(int si, int ss, int se, int []arr, St_class st) { // If there is one element in array, // store it in current node of // segment tree and return if (ss == se) st.stt[si] = ss; else { // If there are more than one elements, // then recur for left and right subtrees // and store the minimum of two values in this node int mid = (ss + se) / 2; constructSTUtil(si * 2 + 1, ss, mid, arr, st); constructSTUtil(si * 2 + 2, mid + 1, se, arr, st); if (arr[st.stt[2 * si + 1]] < arr[st.stt[2 * si + 2]]) st.stt[si] = st.stt[2 * si + 1]; else st.stt[si] = st.stt[2 * si + 2]; } } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ int constructST(int []arr, int n) { // Allocate memory for segment tree // Height of segment tree int x = Log2(n) + 1; // Maximum size of segment tree int max_size = 2 * (1 << x) - 1; // 2*pow(2,x) -1 sc.stt = new int[max_size]; // Fill the allocated memory st constructSTUtil(0, 0, n - 1, arr, sc); // Return the constructed segment tree return sc.st; } // Recursive version of the Euler tour of T void eulerTour(Node node, int l) { /* if the passed node exists */ if (node != null) { euler[fill] = node.data; // insert in euler array level[fill] = l; // insert l in level array fill++; // increment index /* if unvisited, mark first occurrence */ if (f_occur[node.data] == -1) f_occur[node.data] = fill - 1; /* tour left subtree if exists, and remark euler and level arrays for parent on return */ if (node.left != null) { eulerTour(node.left, l + 1); euler[fill] = node.data; level[fill] = l; fill++; } /* tour right subtree if exists, and remark euler and level arrays for parent on return */ if (node.right != null) { eulerTour(node.right, l + 1); euler[fill] = node.data; level[fill] = l; fill++; } } } // returns LCA of node n1 and n2 // assuming they are present in tree int findLCA(Node node, int u, int v) { /* Mark all nodes unvisited. Note that the size of firstOccurrence is 1 as node values which vary from 1 to 9 are used as indexes */ //Arrays.fill(f_occur, -1); for(int i = 0; i < f_occur.Length; i++) f_occur[i] = -1; /* To start filling euler and level arrays from index 0 */ fill = 0; /* Start Euler tour with root node on level 0 */ eulerTour(root, 0); /* construct segment tree on level array */ sc.st = constructST(level, 2 * v - 1); /* If v before u in Euler tour. For RMQ to work, first parameter 'u' must be smaller than second 'v' */ if (f_occur[u] > f_occur[v]) u = swap(u, u = v); // Starting and ending indexes of query range int qs = f_occur[u]; int qe = f_occur[v]; // query for index of LCA in tour int index = RMQ(sc, 2 * v - 1, qs, qe); /* return LCA node */ return euler[index]; } // Driver program to test above functions public static void Main(String []args) { BinaryTree tree = new BinaryTree(); // Let us create the Binary Tree // as shown in the diagram. tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.left.right.left = new Node(8); tree.root.left.right.right = new Node(9); int u = 4, v = 9; Console.WriteLine(\"The LCA of node \" + u + \" and \" + v + \" is \" + tree.findLCA(tree.root, u, v)); }} // This code is contributed by 29AjayKumar",
"e": 65741,
"s": 58442,
"text": null
},
{
"code": "<script> // JavaScript program to find LCA of u and v// by reducing problem to RMQ // A binary tree nodeclass Node{ constructor(item) { this.data=item; this.left = this.right = null; }} class St_class{ st; stt=new Array(10000);} let root;// v is the highest value of node in our treelet v = 9;// for euler tour sequencelet euler = new Array(2 * v - 1);// level of nodes in tour sequencelet level = new Array(2 * v - 1);// to store 1st occurrence of nodeslet f_occur = new Array(2 * v - 1); let fill; // variable to fill euler and level arrayslet sc = new St_class(); // log base 2 of xfunction Log2(x){ let ans = 0; let y = x >>= 1; while (y-- != 0) ans++; return ans;} function swap(a,b){ return a;} /* A recursive function to get the minimum value in a given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */function RMQUtil(index,ss,se,qs,qe,st){ // If segment of this node is a part // of given range, then return // the min of the segment if (qs <= ss && qe >= se) return st.stt[index]; // If segment of this node is // outside the given range else if (se < qs || ss > qe) return -1; // If a part of this segment overlaps // with the given range let mid = Math.floor((ss + se) / 2); let q1 = RMQUtil(2 * index + 1, ss, mid, qs, qe, st); let q2 = RMQUtil(2 * index + 2, mid + 1, se, qs, qe, st); if (q1 == -1) return q2; else if (q2 == -1) return q1; return (level[q1] < level[q2]) ? q1 : q2;} // Return minimum of elements in range// from index qs (query start) to // qe (query end). It mainly uses RMQUtil()function RMQ(st,n,qs,qe){ // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { document.write(\"Invalid input\"); return -1; } return RMQUtil(0, 0, n - 1, qs, qe, st);} // A recursive function that constructs// Segment Tree for array[ss..se]. // si is index of current node in segment tree stfunction constructSTUtil(si,ss,se,arr,st){ // If there is one element in array, // store it in current node of // segment tree and return if (ss == se) st.stt[si] = ss; else { // If there are more than one elements, // then recur for left and // right subtrees and store the minimum // of two values in this node let mid = Math.floor((ss + se) / 2); constructSTUtil(si * 2 + 1, ss, mid, arr, st); constructSTUtil(si * 2 + 2, mid + 1, se, arr, st); if (arr[st.stt[2 * si + 1]] < arr[st.stt[2 * si + 2]]) st.stt[si] = st.stt[2 * si + 1]; else st.stt[si] = st.stt[2 * si + 2]; }} /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */function constructST(arr,n){ // Allocate memory for segment tree // Height of segment tree let x = Log2(n) + 1; // Maximum size of segment tree let max_size = 2 * (1 << x) - 1; // 2*pow(2,x) -1 sc.stt = new Array(max_size); // Fill the allocated memory st constructSTUtil(0, 0, n - 1, arr, sc); // Return the constructed segment tree return sc.st;} // Recursive version of the Euler tour of Tfunction eulerTour(node,l){ /* if the passed node exists */ if (node != null) { euler[fill] = node.data; // insert in euler array level[fill] = l; // insert l in level array fill++; // increment index /* if unvisited, mark first occurrence */ if (f_occur[node.data] == -1) f_occur[node.data] = fill - 1; /* tour left subtree if exists, and remark euler and level arrays for parent on return */ if (node.left != null) { eulerTour(node.left, l + 1); euler[fill] = node.data; level[fill] = l; fill++; } /* tour right subtree if exists, and remark euler and level arrays for parent on return */ if (node.right != null) { eulerTour(node.right, l + 1); euler[fill] = node.data; level[fill] = l; fill++; } }} // returns LCA of node n1 and n2// assuming they are present in treefunction findLCA(node,u,v){ /* Mark all nodes unvisited. Note that the size of firstOccurrence is 1 as node values which vary from 1 to 9 are used as indexes */ for(let i=0;i<f_occur.length;i++) { f_occur[i]=-1; } /* To start filling euler and level arrays from index 0 */ fill = 0; /* Start Euler tour with root node on level 0 */ eulerTour(root, 0); /* construct segment tree on level array */ sc.st = constructST(level, 2 * v - 1); /* If v before u in Euler tour. For RMQ to work, first parameter 'u' must be smaller than second 'v' */ if (f_occur[u] > f_occur[v]) u = swap(u, u = v); // Starting and ending indexes of query range let qs = f_occur[u]; let qe = f_occur[v]; // query for index of LCA in tour let index = RMQ(sc, 2 * v - 1, qs, qe); /* return LCA node */ return euler[index];} // Driver program to test above functions // Let us create the Binary Tree as shown in the diagram.root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.left = new Node(6);root.right.right = new Node(7);root.left.right.left = new Node(8);root.left.right.right = new Node(9); u = 4, v = 9;document.write(\"The LCA of node \" + u +\" and node \" + v + \" is node \"+ findLCA(root, u, v)); // This code is contributed by rag2127 </script>",
"e": 72339,
"s": 65741,
"text": null
},
{
"code": null,
"e": 72348,
"s": 72339,
"text": "Output: "
},
{
"code": null,
"e": 72388,
"s": 72348,
"text": "The LCA of node 4 and node 9 is node 2."
},
{
"code": null,
"e": 72395,
"s": 72388,
"text": "Note: "
},
{
"code": null,
"e": 72564,
"s": 72395,
"text": "We assume that the nodes queried are present in the tree.We also assumed that if there are V nodes in tree, then keys (or data) of these nodes are in range from 1 to V."
},
{
"code": null,
"e": 72622,
"s": 72564,
"text": "We assume that the nodes queried are present in the tree."
},
{
"code": null,
"e": 72734,
"s": 72622,
"text": "We also assumed that if there are V nodes in tree, then keys (or data) of these nodes are in range from 1 to V."
},
{
"code": null,
"e": 72752,
"s": 72734,
"text": "Time complexity: "
},
{
"code": null,
"e": 72976,
"s": 72752,
"text": "Euler tour: Number of nodes is V. For a tree, E = V-1. Euler tour (DFS) will take O(V+E) which is O(2*V) which can be written as O(V).Segment Tree construction : O(n) where n = V + E = 2*V – 1.Range Minimum query: O(log(n))"
},
{
"code": null,
"e": 73111,
"s": 72976,
"text": "Euler tour: Number of nodes is V. For a tree, E = V-1. Euler tour (DFS) will take O(V+E) which is O(2*V) which can be written as O(V)."
},
{
"code": null,
"e": 73171,
"s": 73111,
"text": "Segment Tree construction : O(n) where n = V + E = 2*V – 1."
},
{
"code": null,
"e": 73202,
"s": 73171,
"text": "Range Minimum query: O(log(n))"
},
{
"code": null,
"e": 73487,
"s": 73202,
"text": "Overall this method takes O(n) time for preprocssing, but takes O(Log n) time for query. Therefore, it can be useful when we have a single tree on which we want to perform large number of LCA queries (Note that LCA is useful for finding shortest path between two nodes of Binary Tree)"
},
{
"code": null,
"e": 73506,
"s": 73487,
"text": "Auxiliary Space: "
},
{
"code": null,
"e": 73617,
"s": 73506,
"text": "Euler tour array: O(n) where n = 2*V – 1Node Levels array: O(n)First Occurrences array: O(V)Segment Tree: O(n)"
},
{
"code": null,
"e": 73658,
"s": 73617,
"text": "Euler tour array: O(n) where n = 2*V – 1"
},
{
"code": null,
"e": 73682,
"s": 73658,
"text": "Node Levels array: O(n)"
},
{
"code": null,
"e": 73712,
"s": 73682,
"text": "First Occurrences array: O(V)"
},
{
"code": null,
"e": 73731,
"s": 73712,
"text": "Segment Tree: O(n)"
},
{
"code": null,
"e": 74051,
"s": 73731,
"text": "Overall: O(n)Another observation is that the adjacent elements in level array differ by 1. This can be used to convert a RMQ problem to a LCA problem.This article is contributed by Yash Varyani. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 74063,
"s": 74051,
"text": "29AjayKumar"
},
{
"code": null,
"e": 74074,
"s": 74063,
"text": "nidhi_biet"
},
{
"code": null,
"e": 74088,
"s": 74074,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 74099,
"s": 74088,
"text": "rajatsri94"
},
{
"code": null,
"e": 74107,
"s": 74099,
"text": "rag2127"
},
{
"code": null,
"e": 74111,
"s": 74107,
"text": "LCA"
},
{
"code": null,
"e": 74124,
"s": 74111,
"text": "Segment-Tree"
},
{
"code": null,
"e": 74148,
"s": 74124,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 74153,
"s": 74148,
"text": "Tree"
},
{
"code": null,
"e": 74158,
"s": 74153,
"text": "Tree"
},
{
"code": null,
"e": 74171,
"s": 74158,
"text": "Segment-Tree"
},
{
"code": null,
"e": 74269,
"s": 74171,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 74278,
"s": 74269,
"text": "Comments"
},
{
"code": null,
"e": 74291,
"s": 74278,
"text": "Old Comments"
},
{
"code": null,
"e": 74320,
"s": 74291,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 74347,
"s": 74320,
"text": "Trie | (Insert and Search)"
},
{
"code": null,
"e": 74372,
"s": 74347,
"text": "LRU Cache Implementation"
},
{
"code": null,
"e": 74410,
"s": 74372,
"text": "Red-Black Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 74433,
"s": 74410,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 74483,
"s": 74433,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 74518,
"s": 74483,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 74552,
"s": 74518,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 74581,
"s": 74552,
"text": "AVL Tree | Set 1 (Insertion)"
}
] |
AWT Label Class
|
Label is a passive control because it does not create any event when accessed by the user. The label control is an object of Label. A label displays a single line of read-only text. However the text can be changed by the application programmer but cannot be changed by the end user in any way.
Following is the declaration for java.awt.Label class:
public class Label
extends Component
implements Accessible
Following are the fields for java.awt.Component class:
static int CENTER -- Indicates that the label should be centered.
static int CENTER -- Indicates that the label should be centered.
static int LEFT -- Indicates that the label should be left justified.
static int LEFT -- Indicates that the label should be left justified.
static int RIGHT -- Indicates that the label should be right justified.
static int RIGHT -- Indicates that the label should be right justified.
Label()
Constructs an empty label.
Label(String text)
Constructs a new label with the specified string of text, left justified.
Label(String text, int alignment)
Constructs a new label that presents the specified string of text with the specified alignment.
void addNotify()
Creates the peer for this label.
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Label.
int getAlignment()
Gets the current alignment of this label.
String getText()
Gets the text of this label.
protected String paramString()
Returns a string representing the state of this Label.
void setAlignment(int alignment)
Sets the alignment for this label to the specified alignment.
void setText(String text)
Sets the text for this label to the specified text.
This class inherits methods from the following classes:
java.awt.Component
java.awt.Component
java.lang.Object
java.lang.Object
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtControlDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtControlDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showLabelDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showLabelDemo(){
headerLabel.setText("Control in action: Label");
Label label = new Label();
label.setText("Welcome to TutorialsPoint AWT Tutorial.");
label.setAlignment(Label.CENTER);
label.setBackground(Color.GRAY);
label.setForeground(Color.WHITE);
controlPanel.add(label);
mainFrame.setVisible(true);
}
}
Compile the program using command prompt. Go to D:/ > AWT and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtControlDemo
Verify the following output
13 Lectures
2 hours
EduOLC
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2041,
"s": 1747,
"text": "Label is a passive control because it does not create any event when accessed by the user. The label control is an object of Label. A label displays a single line of read-only text. However the text can be changed by the application programmer but cannot be changed by the end user in any way."
},
{
"code": null,
"e": 2096,
"s": 2041,
"text": "Following is the declaration for java.awt.Label class:"
},
{
"code": null,
"e": 2164,
"s": 2096,
"text": "public class Label\n extends Component\n implements Accessible"
},
{
"code": null,
"e": 2219,
"s": 2164,
"text": "Following are the fields for java.awt.Component class:"
},
{
"code": null,
"e": 2286,
"s": 2219,
"text": "static int CENTER -- Indicates that the label should be centered."
},
{
"code": null,
"e": 2353,
"s": 2286,
"text": "static int CENTER -- Indicates that the label should be centered."
},
{
"code": null,
"e": 2423,
"s": 2353,
"text": "static int LEFT -- Indicates that the label should be left justified."
},
{
"code": null,
"e": 2493,
"s": 2423,
"text": "static int LEFT -- Indicates that the label should be left justified."
},
{
"code": null,
"e": 2565,
"s": 2493,
"text": "static int RIGHT -- Indicates that the label should be right justified."
},
{
"code": null,
"e": 2637,
"s": 2565,
"text": "static int RIGHT -- Indicates that the label should be right justified."
},
{
"code": null,
"e": 2645,
"s": 2637,
"text": "Label()"
},
{
"code": null,
"e": 2672,
"s": 2645,
"text": "Constructs an empty label."
},
{
"code": null,
"e": 2692,
"s": 2672,
"text": "Label(String text) "
},
{
"code": null,
"e": 2766,
"s": 2692,
"text": "Constructs a new label with the specified string of text, left justified."
},
{
"code": null,
"e": 2800,
"s": 2766,
"text": "Label(String text, int alignment)"
},
{
"code": null,
"e": 2896,
"s": 2800,
"text": "Constructs a new label that presents the specified string of text with the specified alignment."
},
{
"code": null,
"e": 2914,
"s": 2896,
"text": "void addNotify() "
},
{
"code": null,
"e": 2947,
"s": 2914,
"text": "Creates the peer for this label."
},
{
"code": null,
"e": 2988,
"s": 2947,
"text": "AccessibleContext getAccessibleContext()"
},
{
"code": null,
"e": 3043,
"s": 2988,
"text": "Gets the AccessibleContext associated with this Label."
},
{
"code": null,
"e": 3062,
"s": 3043,
"text": "int getAlignment()"
},
{
"code": null,
"e": 3104,
"s": 3062,
"text": "Gets the current alignment of this label."
},
{
"code": null,
"e": 3122,
"s": 3104,
"text": "String getText() "
},
{
"code": null,
"e": 3151,
"s": 3122,
"text": "Gets the text of this label."
},
{
"code": null,
"e": 3183,
"s": 3151,
"text": "protected String paramString() "
},
{
"code": null,
"e": 3238,
"s": 3183,
"text": "Returns a string representing the state of this Label."
},
{
"code": null,
"e": 3271,
"s": 3238,
"text": "void setAlignment(int alignment)"
},
{
"code": null,
"e": 3333,
"s": 3271,
"text": "Sets the alignment for this label to the specified alignment."
},
{
"code": null,
"e": 3359,
"s": 3333,
"text": "void setText(String text)"
},
{
"code": null,
"e": 3411,
"s": 3359,
"text": "Sets the text for this label to the specified text."
},
{
"code": null,
"e": 3467,
"s": 3411,
"text": "This class inherits methods from the following classes:"
},
{
"code": null,
"e": 3486,
"s": 3467,
"text": "java.awt.Component"
},
{
"code": null,
"e": 3505,
"s": 3486,
"text": "java.awt.Component"
},
{
"code": null,
"e": 3522,
"s": 3505,
"text": "java.lang.Object"
},
{
"code": null,
"e": 3539,
"s": 3522,
"text": "java.lang.Object"
},
{
"code": null,
"e": 3653,
"s": 3539,
"text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >"
},
{
"code": null,
"e": 5245,
"s": 3653,
"text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class AwtControlDemo {\n\n private Frame mainFrame;\n private Label headerLabel;\n private Label statusLabel;\n private Panel controlPanel;\n\n public AwtControlDemo(){\n prepareGUI();\n }\n\n public static void main(String[] args){\n AwtControlDemo awtControlDemo = new AwtControlDemo();\n awtControlDemo.showLabelDemo();\n }\n\n private void prepareGUI(){\n mainFrame = new Frame(\"Java AWT Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new Label();\n headerLabel.setAlignment(Label.CENTER);\n statusLabel = new Label(); \n statusLabel.setAlignment(Label.CENTER);\n statusLabel.setSize(350,100);\n\n controlPanel = new Panel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n\n private void showLabelDemo(){\n headerLabel.setText(\"Control in action: Label\"); \n\n Label label = new Label();\n label.setText(\"Welcome to TutorialsPoint AWT Tutorial.\");\n label.setAlignment(Label.CENTER);\n label.setBackground(Color.GRAY);\n label.setForeground(Color.WHITE);\n controlPanel.add(label);\n \n mainFrame.setVisible(true); \n }\n}"
},
{
"code": null,
"e": 5336,
"s": 5245,
"text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command."
},
{
"code": null,
"e": 5392,
"s": 5336,
"text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AwtControlDemo.java"
},
{
"code": null,
"e": 5489,
"s": 5392,
"text": "If no error comes that means compilation is successful. Run the program using following command."
},
{
"code": null,
"e": 5539,
"s": 5489,
"text": "D:\\AWT>java com.tutorialspoint.gui.AwtControlDemo"
},
{
"code": null,
"e": 5567,
"s": 5539,
"text": "Verify the following output"
},
{
"code": null,
"e": 5600,
"s": 5567,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5608,
"s": 5600,
"text": " EduOLC"
},
{
"code": null,
"e": 5615,
"s": 5608,
"text": " Print"
},
{
"code": null,
"e": 5626,
"s": 5615,
"text": " Add Notes"
}
] |
getopt() function in C to parse command line arguments
|
The getopt() is one of the built-in C function that are used for taking the command line options. The syntax of this function is like below −
getopt(int argc, char *const argv[], const char *optstring)
The opstring is a list of characters. Each of them representing a single character option.
This function returns many values. These are like below −
If the option takes a value, then that value will be pointed by optarg.
It will return -1, when no more options to proces
Returns ‘?’ to show that this is an unrecognized option, it stores it to optopt.
Sometimes some options need some value, If the option is present but the values are not there, then also it will return ‘?’. We can use ‘:’ as the first character of the optstring, so in that time, it will return ‘:’ instead of ‘?’ if no value is given.
#include <stdio.h>
#include <unistd.h>
main(int argc, char *argv[]) {
int option;
// put ':' at the starting of the string so compiler can distinguish between '?' and ':'
while((option = getopt(argc, argv, ":if:lrx")) != -1){ //get option from the getopt() method
switch(option){
//For option i, r, l, print that these are options
case 'i':
case 'l':
case 'r':
printf("Given Option: %c\n", option);
break;
case 'f': //here f is used for some file name
printf("Given File: %s\n", optarg);
break;
case ':':
printf("option needs a value\n");
break;
case '?': //used for some unknown options
printf("unknown option: %c\n", optopt);
break;
}
}
for(; optind < argc; optind++){ //when some extra arguments are passed
printf("Given extra arguments: %s\n", argv[optind]);
}
}
Given Option: i
Given File: test_file.c
Given Option: l
Given Option: r
Given extra arguments: hello
|
[
{
"code": null,
"e": 1204,
"s": 1062,
"text": "The getopt() is one of the built-in C function that are used for taking the command line options. The syntax of this function is like below −"
},
{
"code": null,
"e": 1264,
"s": 1204,
"text": "getopt(int argc, char *const argv[], const char *optstring)"
},
{
"code": null,
"e": 1355,
"s": 1264,
"text": "The opstring is a list of characters. Each of them representing a single character option."
},
{
"code": null,
"e": 1413,
"s": 1355,
"text": "This function returns many values. These are like below −"
},
{
"code": null,
"e": 1485,
"s": 1413,
"text": "If the option takes a value, then that value will be pointed by optarg."
},
{
"code": null,
"e": 1535,
"s": 1485,
"text": "It will return -1, when no more options to proces"
},
{
"code": null,
"e": 1616,
"s": 1535,
"text": "Returns ‘?’ to show that this is an unrecognized option, it stores it to optopt."
},
{
"code": null,
"e": 1870,
"s": 1616,
"text": "Sometimes some options need some value, If the option is present but the values are not there, then also it will return ‘?’. We can use ‘:’ as the first character of the optstring, so in that time, it will return ‘:’ instead of ‘?’ if no value is given."
},
{
"code": null,
"e": 2833,
"s": 1870,
"text": "#include <stdio.h>\n#include <unistd.h>\n\nmain(int argc, char *argv[]) {\n int option;\n // put ':' at the starting of the string so compiler can distinguish between '?' and ':'\n while((option = getopt(argc, argv, \":if:lrx\")) != -1){ //get option from the getopt() method\n switch(option){\n //For option i, r, l, print that these are options\n case 'i':\n case 'l':\n case 'r':\n printf(\"Given Option: %c\\n\", option);\n break;\n case 'f': //here f is used for some file name\n printf(\"Given File: %s\\n\", optarg);\n break;\n case ':':\n printf(\"option needs a value\\n\");\n break;\n case '?': //used for some unknown options\n printf(\"unknown option: %c\\n\", optopt);\n break;\n }\n }\n for(; optind < argc; optind++){ //when some extra arguments are passed\n printf(\"Given extra arguments: %s\\n\", argv[optind]);\n }\n}"
},
{
"code": null,
"e": 2934,
"s": 2833,
"text": "Given Option: i\nGiven File: test_file.c\nGiven Option: l\nGiven Option: r\nGiven extra arguments: hello"
}
] |
How do I add a simple onClick event handler to an HTML5 canvas element?
|
The elements that are drawn in canvas element have no representation. Their only representation is the pixels they use and their color. Drawing to a canvas element means drawing a bitmap in immediate mode. To get a click event on a canvas element (shape), you need to capture click events on the canvas HTML element and determine which element was clicked. This requires storing the element’s width and height.
To add a click event to your canvas element, use the below-given code
canvas.addEventListener('click', function() { }, false);
To determine what element was clicked, use the following code snippet −
var e = document.getElementById('myCanvas'),
elemLeft = e.offsetLeft,
elemTop = e.offsetTop,
context = e.getContext('2d'),
elements = [];
// event listener for click event
e.addEventListener('click', function(event) {
var xVal = event.pageX - elemLeft,
yVal = event.pageY - elemTop;
console.log(xVal, yVal);
elements.forEach(function(ele) {
if (yVal > ele.top && yVal < ele.top + ele.height && xVal > ele.left && xVal < ele.left + ele.width) {
alert(‘element clicked');
}
});
}, false);
elements.push({
colour: '#1C2128’,
width: 250,
height: 200,
top: 30,
left: 20
});
elements.forEach(function(ele) {
context.fillStyle = element.colour;
context.fillRect(ele.left, ele.top, ele.width, ele.height);
});
|
[
{
"code": null,
"e": 1473,
"s": 1062,
"text": "The elements that are drawn in canvas element have no representation. Their only representation is the pixels they use and their color. Drawing to a canvas element means drawing a bitmap in immediate mode. To get a click event on a canvas element (shape), you need to capture click events on the canvas HTML element and determine which element was clicked. This requires storing the element’s width and height."
},
{
"code": null,
"e": 1543,
"s": 1473,
"text": "To add a click event to your canvas element, use the below-given code"
},
{
"code": null,
"e": 1600,
"s": 1543,
"text": "canvas.addEventListener('click', function() { }, false);"
},
{
"code": null,
"e": 1672,
"s": 1600,
"text": "To determine what element was clicked, use the following code snippet −"
},
{
"code": null,
"e": 2444,
"s": 1672,
"text": "var e = document.getElementById('myCanvas'),\n elemLeft = e.offsetLeft,\n elemTop = e.offsetTop,\n context = e.getContext('2d'),\n elements = [];\n\n// event listener for click event\ne.addEventListener('click', function(event) {\n var xVal = event.pageX - elemLeft,\n yVal = event.pageY - elemTop;\n console.log(xVal, yVal);\n elements.forEach(function(ele) {\n if (yVal > ele.top && yVal < ele.top + ele.height && xVal > ele.left && xVal < ele.left + ele.width) {\n alert(‘element clicked');\n }\n });\n}, false);\nelements.push({\n colour: '#1C2128’,\n width: 250,\n height: 200,\n top: 30,\n left: 20\n});\nelements.forEach(function(ele) {\n context.fillStyle = element.colour;\n context.fillRect(ele.left, ele.top, ele.width, ele.height);\n});"
}
] |
Field setByte() method in Java with Examples - GeeksforGeeks
|
28 Aug, 2019
setByte() method of java.lang.reflect.Field used to set the value of a field as a byte on the specified object. When you need to set the value of a field of an object as byte then you can use this method to set value over an Object.
Syntax:
public void setByte(Object obj, byte b)
throws IllegalArgumentException,
IllegalAccessException
Parameters: This method accepts accepts two parameters:
obj: which is the object whose field should be modified and
b: which is the new value for the field of obj being modified.
Return: This method returns nothing.
Exception: This method throws the following Exception:
IllegalAccessException: if this Field object is enforcing Java language access control and the underlying field is either inaccessible or final.
IllegalArgumentException: if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof), or if an unwrapping conversion fails.
NullPointerException: if the specified object is null and the field is an instance field.
ExceptionInInitializerError: if the initialization provoked by this method fails.
Below programs illustrate setByte() method:Program 1:
// Java program to illustrate setByte() method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws Exception { // create user object Employee emp = new Employee(); // print value of leaveLeft System.out.println( "Value of leaveLeft before " + "applying setByte is " + emp.leaveLeft); // Get the marks field object Field field = Employee.class .getField("leaveLeft"); // Apply setByte Method field.setByte(emp, (byte)2); // print value of leaveLeft System.out.println( "Value of leaveLeft after " + "applying setByte is " + emp.leaveLeft); // print value of age System.out.println( "Value of age before " + "applying setByte is " + emp.age); // Get the marks field object field = Employee.class.getField("age"); // Apply setByte Method field.setByte(emp, (byte)56); // print value of age System.out.println( "Value of age after " + "applying setByte is " + emp.age); }} // sample classclass Employee { // static byte values public static byte age = 45; public static byte leaveLeft = 12;}
Value of leaveLeft before applying setByte is 12
Value of leaveLeft after applying setByte is 2
Value of age before applying setByte is 45
Value of age after applying setByte is 56
Program 2:
// Java program to illustrate setByte() method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws Exception { // create user object User user = new User(); // Get the id field object Field field = User.class .getField("id"); // Apply setByte Method field.setByte(user, (byte)20); // print value of isActive System.out.println( "Value after " + "applying setByte is " + user.id); }} // sample User classclass User { // static byte values public static byte id = 2;}
Value after applying setByte is 20
Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#setByte-java.lang.Object-byte-
Java-Field
Java-Functions
java-lang-reflect-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
Different ways of Reading a text file in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
Introduction to Java
HashMap get() Method in Java
Strings in Java
|
[
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n28 Aug, 2019"
},
{
"code": null,
"e": 24181,
"s": 23948,
"text": "setByte() method of java.lang.reflect.Field used to set the value of a field as a byte on the specified object. When you need to set the value of a field of an object as byte then you can use this method to set value over an Object."
},
{
"code": null,
"e": 24189,
"s": 24181,
"text": "Syntax:"
},
{
"code": null,
"e": 24317,
"s": 24189,
"text": "public void setByte(Object obj, byte b)\n throws IllegalArgumentException,\n IllegalAccessException\n"
},
{
"code": null,
"e": 24373,
"s": 24317,
"text": "Parameters: This method accepts accepts two parameters:"
},
{
"code": null,
"e": 24433,
"s": 24373,
"text": "obj: which is the object whose field should be modified and"
},
{
"code": null,
"e": 24496,
"s": 24433,
"text": "b: which is the new value for the field of obj being modified."
},
{
"code": null,
"e": 24533,
"s": 24496,
"text": "Return: This method returns nothing."
},
{
"code": null,
"e": 24588,
"s": 24533,
"text": "Exception: This method throws the following Exception:"
},
{
"code": null,
"e": 24733,
"s": 24588,
"text": "IllegalAccessException: if this Field object is enforcing Java language access control and the underlying field is either inaccessible or final."
},
{
"code": null,
"e": 24937,
"s": 24733,
"text": "IllegalArgumentException: if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof), or if an unwrapping conversion fails."
},
{
"code": null,
"e": 25027,
"s": 24937,
"text": "NullPointerException: if the specified object is null and the field is an instance field."
},
{
"code": null,
"e": 25109,
"s": 25027,
"text": "ExceptionInInitializerError: if the initialization provoked by this method fails."
},
{
"code": null,
"e": 25163,
"s": 25109,
"text": "Below programs illustrate setByte() method:Program 1:"
},
{
"code": "// Java program to illustrate setByte() method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws Exception { // create user object Employee emp = new Employee(); // print value of leaveLeft System.out.println( \"Value of leaveLeft before \" + \"applying setByte is \" + emp.leaveLeft); // Get the marks field object Field field = Employee.class .getField(\"leaveLeft\"); // Apply setByte Method field.setByte(emp, (byte)2); // print value of leaveLeft System.out.println( \"Value of leaveLeft after \" + \"applying setByte is \" + emp.leaveLeft); // print value of age System.out.println( \"Value of age before \" + \"applying setByte is \" + emp.age); // Get the marks field object field = Employee.class.getField(\"age\"); // Apply setByte Method field.setByte(emp, (byte)56); // print value of age System.out.println( \"Value of age after \" + \"applying setByte is \" + emp.age); }} // sample classclass Employee { // static byte values public static byte age = 45; public static byte leaveLeft = 12;}",
"e": 26532,
"s": 25163,
"text": null
},
{
"code": null,
"e": 26714,
"s": 26532,
"text": "Value of leaveLeft before applying setByte is 12\nValue of leaveLeft after applying setByte is 2\nValue of age before applying setByte is 45\nValue of age after applying setByte is 56\n"
},
{
"code": null,
"e": 26725,
"s": 26714,
"text": "Program 2:"
},
{
"code": "// Java program to illustrate setByte() method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws Exception { // create user object User user = new User(); // Get the id field object Field field = User.class .getField(\"id\"); // Apply setByte Method field.setByte(user, (byte)20); // print value of isActive System.out.println( \"Value after \" + \"applying setByte is \" + user.id); }} // sample User classclass User { // static byte values public static byte id = 2;}",
"e": 27387,
"s": 26725,
"text": null
},
{
"code": null,
"e": 27423,
"s": 27387,
"text": "Value after applying setByte is 20\n"
},
{
"code": null,
"e": 27536,
"s": 27423,
"text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#setByte-java.lang.Object-byte-"
},
{
"code": null,
"e": 27547,
"s": 27536,
"text": "Java-Field"
},
{
"code": null,
"e": 27562,
"s": 27547,
"text": "Java-Functions"
},
{
"code": null,
"e": 27588,
"s": 27562,
"text": "java-lang-reflect-package"
},
{
"code": null,
"e": 27593,
"s": 27588,
"text": "Java"
},
{
"code": null,
"e": 27598,
"s": 27593,
"text": "Java"
},
{
"code": null,
"e": 27696,
"s": 27598,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27711,
"s": 27696,
"text": "Stream In Java"
},
{
"code": null,
"e": 27732,
"s": 27711,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27778,
"s": 27732,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27797,
"s": 27778,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27827,
"s": 27797,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27844,
"s": 27827,
"text": "Generics in Java"
},
{
"code": null,
"e": 27887,
"s": 27844,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27908,
"s": 27887,
"text": "Introduction to Java"
},
{
"code": null,
"e": 27937,
"s": 27908,
"text": "HashMap get() Method in Java"
}
] |
time.Unix() Function in Golang with Examples
|
21 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Unix() function in Go language is used to yield the local time which is related to the stated Unix time from January 1, 1970, in UTC. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func Unix(sec int64, nsec int64) Time
Here, “sec” is seconds which is of type int64 and “nsec” is nanoseconds which is also of type int64.
Note: It is reasonable to permit “nsec” outside the range [0, 999999999]. However, not every “sec” values have a equivalent time value and one analogous value is 1<<63-1, which is the largest int64 value.
Return value: It returns the local time which is equivalent to the stated Unix time from January 1, 1970 in UTC.
Example 1:
// Golang program to illustrate the usage of// time.Unix() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Calling Unix method with 275 seconds // and zero nanoseconds and also // printing output fmt.Println(time.Unix(275, 0).UTC()) // Calling Unix method with 0 seconds and // 566 nanoseconds and also printing // output fmt.Println(time.Unix(0, 566).UTC()) // Calling Unix method with 456 seconds and // -67 nanoseconds and also printing // output fmt.Println(time.Unix(456, -67).UTC())}
Output:
1970-01-01 00:04:35 +0000 UTC
1970-01-01 00:00:00.000000566 +0000 UTC
1970-01-01 00:07:35.999999933 +0000 UTC
Example 2:
// Golang program to illustrate the usage of// time.Unix() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Calling Unix method with 2e1 seconds // and zero nanoseconds and also // printing output fmt.Println(time.Unix(2e1, 0).UTC()) // Calling Unix method with 0 seconds and // 1e13 nanoseconds and also printing // output fmt.Println(time.Unix(0, 1e13).UTC()) // Calling Unix method with 1e1 seconds and // -1e15 nanoseconds and also printing // output fmt.Println(time.Unix(1e1, -1e15).UTC())}
Output:
1970-01-01 00:00:20 +0000 UTC
1970-01-01 02:46:40 +0000 UTC
1969-12-20 10:13:30 +0000 UTC
Here, the parameters of the Unix() method stated in the above code have values that contain a constant “e” which is converted in usual range while conversion.
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
Arrays in Go
Golang Maps
How to Split a String in Golang?
Interfaces in Golang
Slices in Golang
How to Parse JSON in Golang?
How to Trim a String in Golang?
How to convert a string in lower case in Golang?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 396,
"s": 28,
"text": "In Go language, time packages supplies functionality for determining as well as viewing time. The Unix() function in Go language is used to yield the local time which is related to the stated Unix time from January 1, 1970, in UTC. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions."
},
{
"code": null,
"e": 404,
"s": 396,
"text": "Syntax:"
},
{
"code": null,
"e": 443,
"s": 404,
"text": "func Unix(sec int64, nsec int64) Time\n"
},
{
"code": null,
"e": 544,
"s": 443,
"text": "Here, “sec” is seconds which is of type int64 and “nsec” is nanoseconds which is also of type int64."
},
{
"code": null,
"e": 749,
"s": 544,
"text": "Note: It is reasonable to permit “nsec” outside the range [0, 999999999]. However, not every “sec” values have a equivalent time value and one analogous value is 1<<63-1, which is the largest int64 value."
},
{
"code": null,
"e": 862,
"s": 749,
"text": "Return value: It returns the local time which is equivalent to the stated Unix time from January 1, 1970 in UTC."
},
{
"code": null,
"e": 873,
"s": 862,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate the usage of// time.Unix() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Calling Unix method with 275 seconds // and zero nanoseconds and also // printing output fmt.Println(time.Unix(275, 0).UTC()) // Calling Unix method with 0 seconds and // 566 nanoseconds and also printing // output fmt.Println(time.Unix(0, 566).UTC()) // Calling Unix method with 456 seconds and // -67 nanoseconds and also printing // output fmt.Println(time.Unix(456, -67).UTC())}",
"e": 1490,
"s": 873,
"text": null
},
{
"code": null,
"e": 1498,
"s": 1490,
"text": "Output:"
},
{
"code": null,
"e": 1609,
"s": 1498,
"text": "1970-01-01 00:04:35 +0000 UTC\n1970-01-01 00:00:00.000000566 +0000 UTC\n1970-01-01 00:07:35.999999933 +0000 UTC\n"
},
{
"code": null,
"e": 1620,
"s": 1609,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate the usage of// time.Unix() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Calling Unix method with 2e1 seconds // and zero nanoseconds and also // printing output fmt.Println(time.Unix(2e1, 0).UTC()) // Calling Unix method with 0 seconds and // 1e13 nanoseconds and also printing // output fmt.Println(time.Unix(0, 1e13).UTC()) // Calling Unix method with 1e1 seconds and // -1e15 nanoseconds and also printing // output fmt.Println(time.Unix(1e1, -1e15).UTC())}",
"e": 2243,
"s": 1620,
"text": null
},
{
"code": null,
"e": 2251,
"s": 2243,
"text": "Output:"
},
{
"code": null,
"e": 2342,
"s": 2251,
"text": "1970-01-01 00:00:20 +0000 UTC\n1970-01-01 02:46:40 +0000 UTC\n1969-12-20 10:13:30 +0000 UTC\n"
},
{
"code": null,
"e": 2501,
"s": 2342,
"text": "Here, the parameters of the Unix() method stated in the above code have values that contain a constant “e” which is converted in usual range while conversion."
},
{
"code": null,
"e": 2513,
"s": 2501,
"text": "GoLang-time"
},
{
"code": null,
"e": 2525,
"s": 2513,
"text": "Go Language"
},
{
"code": null,
"e": 2623,
"s": 2525,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2674,
"s": 2623,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 2721,
"s": 2674,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 2734,
"s": 2721,
"text": "Arrays in Go"
},
{
"code": null,
"e": 2746,
"s": 2734,
"text": "Golang Maps"
},
{
"code": null,
"e": 2779,
"s": 2746,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 2800,
"s": 2779,
"text": "Interfaces in Golang"
},
{
"code": null,
"e": 2817,
"s": 2800,
"text": "Slices in Golang"
},
{
"code": null,
"e": 2846,
"s": 2817,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 2878,
"s": 2846,
"text": "How to Trim a String in Golang?"
}
] |
Python | Get email alert when the website is up
|
11 Sep, 2020
In this article, we are going to learn how to check whether any website is running or it’s down with a simple Python script. We will use Python’s requests library for sending ‘get’ request and ‘smtplib’ library for sending email notification when the website is up.It means we don’t need to check every time. Our Python program will notify us via email when the site is running.This script simply checks whether a website is up or not. If it is up then it will send an email about this, if it is down then it will keep checking and when the site will be up, it will send an email and terminate.Installation: Go to command prompt and write this command:
pip install requests, smtplib
Below are the steps:
Put the entire code into a try block, to handle the exception.
Send a get request to the website we want.
If website is not running, then we don’t get a response thus throwing an exception.
Then in except block we just print that website is not running.
If there is no exception thrown, then it means we got the response and website is running.
Now Create SMTP session for login through gmail.
Enter your correct gmail id and password.
Send the mail and done.
Below is the implementation:
Python3
import smtplib, requests, timefrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipart while(1): try: # Replace the url for your desired website url = "https://www.facebook.com/" # Send the get request to the website r = requests.get(url) # creates SMTP session s = smtplib.SMTP("smtp.gmail.com", 587) # start TLS for security s.starttls() # Authentication s.login("sender_gmail_id", "sender_password") # Instance of MIMEMultipart msg = MIMEMultipart("alternative") # Write the subject msg["Subject"]= url + " is working now." msg["From"]="sender_gmail_id" msg["To"]="receiver_gmail_id" # Plain text body of the mail text = url + " is running now." # Attach the Plain body with the msg instance msg.attach(MIMEText(text, "plain")) # HTML body of the mail html ="<h2>Your site is running now.</h2><br/><a href ='" + url + "'>Click here to visit.</a>" # Attach the HTML body with the msg instance msg.attach(MIMEText(html, "html")) # Sending the mail s.sendmail("sender_gmail_id", "receiver_gmail_id", msg.as_string()) s.quit() print('sent') break except: print('site is down yet...') print('sleeping...') # Sleeping for 60 seconds. We can change this interval. time.sleep(60) print('Trying again') continue
gjaiswal108
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Sep, 2020"
},
{
"code": null,
"e": 707,
"s": 52,
"text": "In this article, we are going to learn how to check whether any website is running or it’s down with a simple Python script. We will use Python’s requests library for sending ‘get’ request and ‘smtplib’ library for sending email notification when the website is up.It means we don’t need to check every time. Our Python program will notify us via email when the site is running.This script simply checks whether a website is up or not. If it is up then it will send an email about this, if it is down then it will keep checking and when the site will be up, it will send an email and terminate.Installation: Go to command prompt and write this command: "
},
{
"code": null,
"e": 738,
"s": 707,
"text": "pip install requests, smtplib\n"
},
{
"code": null,
"e": 760,
"s": 738,
"text": "Below are the steps: "
},
{
"code": null,
"e": 825,
"s": 762,
"text": "Put the entire code into a try block, to handle the exception."
},
{
"code": null,
"e": 868,
"s": 825,
"text": "Send a get request to the website we want."
},
{
"code": null,
"e": 952,
"s": 868,
"text": "If website is not running, then we don’t get a response thus throwing an exception."
},
{
"code": null,
"e": 1016,
"s": 952,
"text": "Then in except block we just print that website is not running."
},
{
"code": null,
"e": 1107,
"s": 1016,
"text": "If there is no exception thrown, then it means we got the response and website is running."
},
{
"code": null,
"e": 1156,
"s": 1107,
"text": "Now Create SMTP session for login through gmail."
},
{
"code": null,
"e": 1198,
"s": 1156,
"text": "Enter your correct gmail id and password."
},
{
"code": null,
"e": 1222,
"s": 1198,
"text": "Send the mail and done."
},
{
"code": null,
"e": 1252,
"s": 1222,
"text": "Below is the implementation: "
},
{
"code": null,
"e": 1262,
"s": 1254,
"text": "Python3"
},
{
"code": "import smtplib, requests, timefrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipart while(1): try: # Replace the url for your desired website url = \"https://www.facebook.com/\" # Send the get request to the website r = requests.get(url) # creates SMTP session s = smtplib.SMTP(\"smtp.gmail.com\", 587) # start TLS for security s.starttls() # Authentication s.login(\"sender_gmail_id\", \"sender_password\") # Instance of MIMEMultipart msg = MIMEMultipart(\"alternative\") # Write the subject msg[\"Subject\"]= url + \" is working now.\" msg[\"From\"]=\"sender_gmail_id\" msg[\"To\"]=\"receiver_gmail_id\" # Plain text body of the mail text = url + \" is running now.\" # Attach the Plain body with the msg instance msg.attach(MIMEText(text, \"plain\")) # HTML body of the mail html =\"<h2>Your site is running now.</h2><br/><a href ='\" + url + \"'>Click here to visit.</a>\" # Attach the HTML body with the msg instance msg.attach(MIMEText(html, \"html\")) # Sending the mail s.sendmail(\"sender_gmail_id\", \"receiver_gmail_id\", msg.as_string()) s.quit() print('sent') break except: print('site is down yet...') print('sleeping...') # Sleeping for 60 seconds. We can change this interval. time.sleep(60) print('Trying again') continue",
"e": 2770,
"s": 1262,
"text": null
},
{
"code": null,
"e": 2782,
"s": 2770,
"text": "gjaiswal108"
},
{
"code": null,
"e": 2797,
"s": 2782,
"text": "python-utility"
},
{
"code": null,
"e": 2804,
"s": 2797,
"text": "Python"
},
{
"code": null,
"e": 2902,
"s": 2804,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2934,
"s": 2902,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2961,
"s": 2934,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2982,
"s": 2961,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3005,
"s": 2982,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3061,
"s": 3005,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3092,
"s": 3061,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3134,
"s": 3092,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3176,
"s": 3134,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3215,
"s": 3176,
"text": "Python | Get unique values from a list"
}
] |
Python Program for ShellSort
|
16 Jun, 2022
In shellSort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sublists of every h\’th element is sorted.
Python
# Python program for implementation of Shell Sort def shellSort(arr): # Start with a big gap, then reduce the gap n = len(arr) gap = n/2 # Do a gapped insertion sort for this gap size. # The first gap elements a[0..gap-1] are already in gapped # order keep adding one more element until the entire array # is gap sorted while gap > 0: for i in range(gap,n): # add a[i] to the elements that have been gap sorted # save a[i] in temp and make a hole at position i temp = arr[i] # shift earlier gap-sorted elements up until the correct # location for a[i] is found j = i while j >= gap and arr[j-gap] >temp: arr[j] = arr[j-gap] j -= gap # put temp (the original a[i]) in its correct location arr[j] = temp gap /= 2 # Driver code to test abovearr = [ 12, 34, 54, 2, 3] n = len(arr)print ("Array before sorting:")for i in range(n): print(arr[i]), shellSort(arr) print ("\nArray after sorting:")for i in range(n): print(arr[i]), # This code is contributed by Mohit Kumra
Output:
Array before sorting:
12 34 54 2 3
Array after sorting:
2 3 12 34 54
Time Complexity: O(n2)
Auxiliary Space: O(1)
Please refer complete article on ShellSort for more details!
chandramauliguptach
python sorting-exercises
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 252,
"s": 52,
"text": "In shellSort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sublists of every h\\’th element is sorted. "
},
{
"code": null,
"e": 259,
"s": 252,
"text": "Python"
},
{
"code": "# Python program for implementation of Shell Sort def shellSort(arr): # Start with a big gap, then reduce the gap n = len(arr) gap = n/2 # Do a gapped insertion sort for this gap size. # The first gap elements a[0..gap-1] are already in gapped # order keep adding one more element until the entire array # is gap sorted while gap > 0: for i in range(gap,n): # add a[i] to the elements that have been gap sorted # save a[i] in temp and make a hole at position i temp = arr[i] # shift earlier gap-sorted elements up until the correct # location for a[i] is found j = i while j >= gap and arr[j-gap] >temp: arr[j] = arr[j-gap] j -= gap # put temp (the original a[i]) in its correct location arr[j] = temp gap /= 2 # Driver code to test abovearr = [ 12, 34, 54, 2, 3] n = len(arr)print (\"Array before sorting:\")for i in range(n): print(arr[i]), shellSort(arr) print (\"\\nArray after sorting:\")for i in range(n): print(arr[i]), # This code is contributed by Mohit Kumra",
"e": 1404,
"s": 259,
"text": null
},
{
"code": null,
"e": 1412,
"s": 1404,
"text": "Output:"
},
{
"code": null,
"e": 1482,
"s": 1412,
"text": "Array before sorting:\n12 34 54 2 3 \nArray after sorting:\n2 3 12 34 54"
},
{
"code": null,
"e": 1505,
"s": 1482,
"text": "Time Complexity: O(n2)"
},
{
"code": null,
"e": 1527,
"s": 1505,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1588,
"s": 1527,
"text": "Please refer complete article on ShellSort for more details!"
},
{
"code": null,
"e": 1608,
"s": 1588,
"text": "chandramauliguptach"
},
{
"code": null,
"e": 1633,
"s": 1608,
"text": "python sorting-exercises"
},
{
"code": null,
"e": 1649,
"s": 1633,
"text": "Python Programs"
}
] |
Python – Multiple Sets Intersection
|
02 Feb, 2021
In this article given List of sets, the task is to write a Python program to perform their intersection.
Examples:
Input : test_list = [{5, 3, 6, 7}, {1, 3, 5, 2}, {7, 3, 8, 5}, {8, 4, 5, 3}]
Output : {3, 5}
Explanation : 3 and 5 is present in all the sets.
Input : test_list = [{5, 3, 6, 7}, {1, 3, 5, 2}, {7, 3, 8, 5}, {8, 4, 5, 4}]
Output : {5}
Explanation : 5 is present in all the sets.
Method #1 : Using intersection() + * operator
In this, we perform tasks of getting intersection using intersection() and * operator is used to pack all the sets together.
Python3
# Python3 code to demonstrate working of# Multiple Sets Intersection# Using intersection() + * operator # initializing listtest_list = [{5, 3, 6, 7}, {1, 3, 5, 2}, {7, 3, 8, 5}, {8, 4, 5, 3}] # printing original listprint("The original list is : " + str(test_list)) # getting all sets intersection using intersection()res = set.intersection(*test_list) # printing resultprint("Intersected Sets : " + str(res))
Output:
The original list is : [{3, 5, 6, 7}, {1, 2, 3, 5}, {8, 3, 5, 7}, {8, 3, 4, 5}]
Intersected Sets : {3, 5}
Method #2 : Using reduce() + and_ operator
In this, we perform task of intersection using and_ operator and reduce() does the task of getting all the sets packed together for required operation.
Python3
# Python3 code to demonstrate working of# Multiple Sets Intersection# Using reduce() + and_ operatorfrom operator import and_from functools import reduce # initializing listtest_list = [{5, 3, 6, 7}, {1, 3, 5, 2}, {7, 3, 8, 5}, {8, 4, 5, 3}] # printing original listprint("The original list is : " + str(test_list)) # getting all sets intersection using and_ operatorres = set(reduce(and_, test_list)) # printing resultprint("Intersected Sets : " + str(res))
Output:
The original list is : [{3, 5, 6, 7}, {1, 2, 3, 5}, {8, 3, 5, 7}, {8, 3, 4, 5}]
Intersected Sets : {3, 5}
Python set-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Defaultdict in Python
Python program to add two numbers
Python | Get dictionary keys as a list
Python Program for Fibonacci numbers
Python Program for factorial of a number
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Feb, 2021"
},
{
"code": null,
"e": 133,
"s": 28,
"text": "In this article given List of sets, the task is to write a Python program to perform their intersection."
},
{
"code": null,
"e": 143,
"s": 133,
"text": "Examples:"
},
{
"code": null,
"e": 220,
"s": 143,
"text": "Input : test_list = [{5, 3, 6, 7}, {1, 3, 5, 2}, {7, 3, 8, 5}, {8, 4, 5, 3}]"
},
{
"code": null,
"e": 236,
"s": 220,
"text": "Output : {3, 5}"
},
{
"code": null,
"e": 286,
"s": 236,
"text": "Explanation : 3 and 5 is present in all the sets."
},
{
"code": null,
"e": 363,
"s": 286,
"text": "Input : test_list = [{5, 3, 6, 7}, {1, 3, 5, 2}, {7, 3, 8, 5}, {8, 4, 5, 4}]"
},
{
"code": null,
"e": 376,
"s": 363,
"text": "Output : {5}"
},
{
"code": null,
"e": 420,
"s": 376,
"text": "Explanation : 5 is present in all the sets."
},
{
"code": null,
"e": 466,
"s": 420,
"text": "Method #1 : Using intersection() + * operator"
},
{
"code": null,
"e": 591,
"s": 466,
"text": "In this, we perform tasks of getting intersection using intersection() and * operator is used to pack all the sets together."
},
{
"code": null,
"e": 599,
"s": 591,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Multiple Sets Intersection# Using intersection() + * operator # initializing listtest_list = [{5, 3, 6, 7}, {1, 3, 5, 2}, {7, 3, 8, 5}, {8, 4, 5, 3}] # printing original listprint(\"The original list is : \" + str(test_list)) # getting all sets intersection using intersection()res = set.intersection(*test_list) # printing resultprint(\"Intersected Sets : \" + str(res))",
"e": 1013,
"s": 599,
"text": null
},
{
"code": null,
"e": 1021,
"s": 1013,
"text": "Output:"
},
{
"code": null,
"e": 1101,
"s": 1021,
"text": "The original list is : [{3, 5, 6, 7}, {1, 2, 3, 5}, {8, 3, 5, 7}, {8, 3, 4, 5}]"
},
{
"code": null,
"e": 1127,
"s": 1101,
"text": "Intersected Sets : {3, 5}"
},
{
"code": null,
"e": 1170,
"s": 1127,
"text": "Method #2 : Using reduce() + and_ operator"
},
{
"code": null,
"e": 1322,
"s": 1170,
"text": "In this, we perform task of intersection using and_ operator and reduce() does the task of getting all the sets packed together for required operation."
},
{
"code": null,
"e": 1330,
"s": 1322,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Multiple Sets Intersection# Using reduce() + and_ operatorfrom operator import and_from functools import reduce # initializing listtest_list = [{5, 3, 6, 7}, {1, 3, 5, 2}, {7, 3, 8, 5}, {8, 4, 5, 3}] # printing original listprint(\"The original list is : \" + str(test_list)) # getting all sets intersection using and_ operatorres = set(reduce(and_, test_list)) # printing resultprint(\"Intersected Sets : \" + str(res))",
"e": 1793,
"s": 1330,
"text": null
},
{
"code": null,
"e": 1801,
"s": 1793,
"text": "Output:"
},
{
"code": null,
"e": 1881,
"s": 1801,
"text": "The original list is : [{3, 5, 6, 7}, {1, 2, 3, 5}, {8, 3, 5, 7}, {8, 3, 4, 5}]"
},
{
"code": null,
"e": 1907,
"s": 1881,
"text": "Intersected Sets : {3, 5}"
},
{
"code": null,
"e": 1927,
"s": 1907,
"text": "Python set-programs"
},
{
"code": null,
"e": 1934,
"s": 1927,
"text": "Python"
},
{
"code": null,
"e": 1950,
"s": 1934,
"text": "Python Programs"
},
{
"code": null,
"e": 2048,
"s": 1950,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2093,
"s": 2048,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 2143,
"s": 2093,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 2159,
"s": 2143,
"text": "Deque in Python"
},
{
"code": null,
"e": 2175,
"s": 2159,
"text": "Queue in Python"
},
{
"code": null,
"e": 2197,
"s": 2175,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2219,
"s": 2197,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2253,
"s": 2219,
"text": "Python program to add two numbers"
},
{
"code": null,
"e": 2292,
"s": 2253,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2329,
"s": 2292,
"text": "Python Program for Fibonacci numbers"
}
] |
KnockoutJS - Quick Guide
|
KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites. The model separates the application's Model (stored data), View (UI) and View Model (JavaScript Representation of model).
KnockoutJS was developed and is maintained as an open source project by Steve Sanderson, a Microsoft employee on July 5, 2010. KO is an abbreviation used for KnockoutJS. KO supports all mainstream browsers - IE 6+, Firefox 3.5+, Chrome, Opera, Safari (desktop/mobile).
Here is a list of some of the most prominent features of KnockoutJS −
Declarative Binding − HTML DOM elements are connected to the model through data-bind attribute using a very simple syntax. It is made easy to achieve responsiveness using this feature.
Declarative Binding − HTML DOM elements are connected to the model through data-bind attribute using a very simple syntax. It is made easy to achieve responsiveness using this feature.
Automatic UI Refresh − Any changes made to view the model data are reflected in the UI automatically and vice-versa. No need of writing extra code.
Automatic UI Refresh − Any changes made to view the model data are reflected in the UI automatically and vice-versa. No need of writing extra code.
Dependency Tracking − Relationship between KO attributes and KO library functions/components is transparent. Automatically tracks data changes in KO attribute and updates respective affected areas.
Dependency Tracking − Relationship between KO attributes and KO library functions/components is transparent. Automatically tracks data changes in KO attribute and updates respective affected areas.
Templating − Templates are a simple and convenient way to build complex UI structures - with the possibility of repeating or nesting blocks - as a function of view model data.
Templating − Templates are a simple and convenient way to build complex UI structures - with the possibility of repeating or nesting blocks - as a function of view model data.
Extensible − Extends custom behavior very easily.
Extensible − Extends custom behavior very easily.
KnockoutJS library provides an easy and clean way to handle complex data-driven interfaces. One can create self-updating UIs for Javascript objects.
KnockoutJS library provides an easy and clean way to handle complex data-driven interfaces. One can create self-updating UIs for Javascript objects.
It is pure JavaScript Library and works with any web framework. It's not a replacement of JQuery but can work as a supplement providing smart features.
It is pure JavaScript Library and works with any web framework. It's not a replacement of JQuery but can work as a supplement providing smart features.
KnockoutJS library file is very small and lightweight.
KnockoutJS library file is very small and lightweight.
KnockoutJS is independent of any other framework. It is compatible with other client or server side technologies.
KnockoutJS is independent of any other framework. It is compatible with other client or server side technologies.
Most important of all KnockoutJS is open source and hence free for use.
Most important of all KnockoutJS is open source and hence free for use.
KnockoutJS is fully documented. The official site has full documentation including API docs, live examples, and interactive tutorials.
KnockoutJS is fully documented. The official site has full documentation including API docs, live examples, and interactive tutorials.
It is very easy to use KnockoutJS. Simply refer the JavaScript file using <script> tag in HTML pages.
Knockout.js can be accessed in the following ways −
You can download production build of Knockout.js from its official website
A page as in the following image will be displayed. Click on download link and you will get the latest knockout.js file.
You can download production build of Knockout.js from its official website
A page as in the following image will be displayed. Click on download link and you will get the latest knockout.js file.
Now refer the file as shown in the following code.
<script type = 'text/javascript' src = 'knockout-3.3.0.js'></script>
Update the src attribute to match the location where the downloaded files are kept.
You can refer to the KnockoutJS library from CDNs −
You can refer to the KnockoutJS library from CDNs −
You can refer KnockoutJS library from Microsoft Ajax CDN in your code as follows −
You can refer KnockoutJS library from Microsoft Ajax CDN in your code as follows −
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type = "text/javascript"></script>
Alternatively you can refer to a minified version of KnockoutJS library from CDNJS as follows −
Alternatively you can refer to a minified version of KnockoutJS library from CDNJS as follows −
<script src = "https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"
type = "text/javascript"></script>
Note − In all the chapters for this tutorial, we have referred to CDN version of the KnockoutJS library.
KnockoutJS is based on Model-View-ViewModel (MVVM) pattern. We will study this pattern in depth in chapter KnockoutJS - MVVM Framework. First let's take a look at a simple example of KnockoutJS.
<!DOCTYPE html>
<head>
<title>KnockoutJS Simple Example</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type = "text/javascript"></script>
</head>
<body>
<!-- This is called "view" of HTML markup that defines the appearance of UI -->
<p>First String: <input data-bind = "value: firstString" /></p>
<p>Second String: <input data-bind = "value: secondString" /></p>
<p>First String: <strong data-bind = "text: firstString">Hi</strong></p>
<p>Second String: <strong data-bind = "text: secondString">There</strong></p>
<p>Derived String: <strong data-bind = "text: thirdString"></strong></p>
<script>
<!-- This is called "viewmodel". This javascript section defines the data and
behavior of UI -->
function AppViewModel() {
this.firstString = ko.observable("Enter First String");
this.secondString = ko.observable("Enter Second String");
this.thirdString = ko.computed(function() {
return this.firstString() + " " + this.secondString();
}, this);
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
</script>
</body>
</html>
The following line refers to KnockoutJS library.
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type = "text/javascript"> </script>
This line refers KnockoutJS library.
We have two input boxes: First String and Second String. These 2 variables are initialized with values Enter First String and Enter Second String respectively in ViewModel.
<p>First String: < input data-bind = "value: firstString" /> </p>
This is how we are binding values from ViewModel to HTML elements using 'data-bind' attribute in the body section.
Here, 'firstString' refers to ViewModel variable.
this.firstString = ko.observable("Enter First String");
ko.observable is a concept which keeps an eye on the value changes so that it can update the underlying ViewModel data.
To understand this better, let's update the first input box to "Hello" and the second input box to "TutorialsPoint". You will see the values are updated simultaneously. We will study more about this concept in KnockoutJS - Observables chapter.
this.thirdString = ko.computed(function() {
return this.firstString() + " " + this.secondString();
}, this);
Next, we have computed function in viewmodel. This function derives the third string based on 2 strings mentioned earlier. Thus, any updates made to these strings automatically get reflected in this derived string. There is no need of writing an extra code to accomplish this. This is just a simple example. We will study about this concept in KnockoutJS - Computed Observables chapter.
Save the above code as my_first_knockoutjs_program.html. Open this file in your browser and you will see an output as the following.
Modify strings to "Hello" and "TutorialsPoint" and the output changes as follows.
KnockoutJS is widely used for Single Page Applications - A website created with the ability to retrieve all necessary data dynamically with a single page load reducing server round trips.
KnockoutJS is a client-side framework. This is a JavaScript library which makes it very easy to bind HTML to domain data. It implements a pattern called Model-View-ViewModel (MVVM). Observables is the magic ingredient of KnockoutJS. All data remains in sync because of Observable attribute.
View is nothing but user interface created using HTML elements and CSS styling.
You can bind HTML DOM elements to data model using KnockoutJS. It provides 2-way data binding between View and ViewModel using 'data-bind' concept, which means any updates done in the UI are reflected in the data model and any changes done in the data model are reflected in the UI. One can create self-updating UI with the help of knockoutJS.
ViewModel is a JavaScript object, which contains necessary properties and functions to represent data. View and ViewModel are connected together with declarative data-bind concept used in HTML. This makes it easy to change HTML without changing ViewModel. KnockoutJS takes care of automatic data refresh between them through the use of Observables.
Synchronization of data is achieved through binding DOM elements to Data Model, first using data-bind and then refreshing these 2 components through the use of Observables. Dependency tracking is done automatically due to this synchronization of data. No extra coding is required to achieve it. KnockoutJS allows to create direct connection between the display and underlying data.
You can create your own bindings called as custom bindings for application specific behaviors. This way Knockout gives direct control of how you want to transform your data into HTML.
Model is the domain data on the server and it gets manipulated as and when the request is sent/received from ViewModel.
The data could be stored in database, cookie, or other form of persistent storage. KnockoutJS does not worry about how it is stored. It is up to the programmer to communicate between the stored data and KnockoutJS.
Most of the times, data is saved and loaded via an Ajax call.
Model-View-ViewModel (MVVM) is an architectural design pattern for developing software applications. MVVM was developed by Microsoft Architect John Gossman in 2005. This pattern is derived from Model-View-Controller (MVC) pattern. The advantage of MVVM is that it separates the application layer's graphical user interface from business logic. MVVM is responsible for handling data from the underlying model in such a way that it is represented and managed very easily. ViewModel in MVVM represents an abstract version of View's state and actions.
The view classes do not know that Model and ViewModel classes exists, also Model and ViewModel does not know that View exists. Model is also unaware that ViewModel and View exists.
View is a Graphical User Interface created using markup language to represent data. View binds to properties of a ViewModel through data-bind concept, which indirectly connects to the model data. View need not be changed for any alteration done in ViewModel. Changes made to data in ViewModel is automatically propagated in View due to binding.
Model is domain data or business object, which holds real-time data. Model does not carry behaviors. Behavior is mostly implemented in business logic.
ViewModel is the center place, where data from Model and View's display logic are bundled together. ViewModel holds the dynamic state of data. There is an implicit binder in between View and ViewModel to communicate with each other. This binding is inclusive of declarative data and command binding. Synchronization of View and ViewModel is achieved through this binding. Any change made in View is reflected in ViewModel, and similarly any change in ViewModel gets automatically reflected in View. Existence of this 2-way binding mechanism is a key aspect of this MVVM pattern.
KnockoutJS is build upon the following 3 important concepts.
Observables and dependency tracking between them - DOM elements are connected to ViewModel via 'data-bind'. They exchange information through Observables. This automatically takes care of dependency tracking.
Observables and dependency tracking between them - DOM elements are connected to ViewModel via 'data-bind'. They exchange information through Observables. This automatically takes care of dependency tracking.
Declarative Bindings between UI and ViewModel - DOM elements are connected to ViewModel via 'data-bind' concept.
Declarative Bindings between UI and ViewModel - DOM elements are connected to ViewModel via 'data-bind' concept.
Templating to create re-usable components - Templating provides a robust way to create complex web applications.
Templating to create re-usable components - Templating provides a robust way to create complex web applications.
We will study Observables in this chapter.
As the name specifies, when you declare a ViewModel data/property as Observable, any data modification each time automatically gets reflected at all places the data is used. This also includes refreshing the related dependencies. KO takes care of these things and there is no need to write extra code to achieve this.
Using Observable, it becomes very easy to make UI and ViewModel communicate dynamically.
You just need to declare ViewModel property with function ko.observable() to make it Observable.
this.property = ko.observable('value');
Let's take a look at the following example which demonstrates the use of Observable.
<!DOCTYPE html>
<head>
<title>KnockoutJS Observable Example</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type = "text/javascript"></script>
</head>
<body>
<!-- This is called "view" of HTML markup that defines the appearance of UI -->
<p>Enter your name: <input data-bind = "value: yourName" /></p>
<p>Hi <strong data-bind = "text: yourName"></strong> Good Morning!!!</p>
<script>
<!-- This is called "viewmodel". This javascript section defines the data and behavior of UI -->
function AppViewModel() {
this.yourName = ko.observable("");
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
</script>
</body>
</html>
The following line is for the input box. As can be seen, we have used data-bind attribute to bind yourName value to ViewModel.
<p>Enter your name: <input data-bind = "value: yourName" /> <p>
The following line just prints the value of yourName. Note, that here data-bind type is the text as we are simply reading the value.
<p>Hi <strong data-bind = "text: yourName"></strong> Good Morning!!!</p>
In the following line, ko.observable keeps an eye on yourName variable for any modification in data. Once there is a modification, the corresponding places also get updated with the modified value. When you run the following code, an input box will appear. As and when you update that input box, the new value will get reflected or refreshed in places wherever it is used.
this.yourName = ko.observable("");
Let's carry out the following steps to see how the above code works −
Save the above code in first_observable_pgm.htm file.
Save the above code in first_observable_pgm.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Enter the name as Scott and observe that the name is reflected in the output.
Enter the name as Scott and observe that the name is reflected in the output.
Enter your name:
Hi Good Morning!!!
Data modification can take place either from the UI or from ViewModel. Irrespective of from where the data is changed, the UI and ViewModel keeps synchronization among them. This makes it a two-way-binding mechanism. In the above example, when you change your name in the input box, ViewModel gets a new value. When you change yourName property from inside ViewModel, then the UI receives a new value.
Following table lists the read and write operations which can be performed on Observables.
Read
To read value just call Observable property without parameters like: AppViewModel.yourName();
Write
To write/update value in Observable property, just pass the desired value in parameter like: AppViewModel.yourName('Bob');
Write multiple
Multiple ViewModel properties can be updated in a single row with the help of chaining-syntax like: AppViewModel.yourName('Bob').yourAge(45);
Observable declaration takes care of data modifications of a single object. ObservableArray works with the collection of objects. This is a very useful feature when you are dealing with complex applications containing multiple type of values and changing their status frequently based on the user actions.
this.arrayName = ko.observableArray(); // It's an empty array
Observable array only tracks which objects in it are added or removed. It does not notify if the individual object's properties are modified.
You can initialize your array and at the same time you can declare it as Observable by passing the initial values to the constructor as follows.
this.arrayName = ko.observableArray(['scott','jack']);
You can access Observable array elements as follows.
alert('The second element is ' + arrayName()[1]);
KnockoutJS has its own set of Observable array functions. They are convenient because −
These functions work on all browsers.
These functions work on all browsers.
These functions will take care of dependency tracking automatically.
These functions will take care of dependency tracking automatically.
Syntax is easy to use. For example, to insert an element into an array, you just need to use arrayName.push('value') instead of arrayName().push('value').
Syntax is easy to use. For example, to insert an element into an array, you just need to use arrayName.push('value') instead of arrayName().push('value').
Following is the list of various Observable Array methods.
Inserts a new item at the end of array.
Removes the last item from the array and returns it.
Inserts a new value at the beginning of the array.
Removes the first item from the array and returns it.
Reverses the order of the array.
Sorts array items in an ascending order.
Accepts 2 parameters - start-index and end-index - removes items starting from start to end index and returns them as an array.
This function returns the index of the first occurrence of parameter provided.
This method slices out a piece of an array. Returns the items from start-index up to end-index.
Removes all items and returns them as an array.
Removes items that match the parameter and returns as an array.
Removes items which are satisfying the condition and returns them as an array.
Removes items that match with a given set of values.
destroyAll()
Marks all items in an array with property _destroy with value true.
destroy('value')
Searches for an item equal to the parameter and mark it with a special property _destroy with value true.
destroy(function(item) { condition})
Finds all items which are satisfying the condition, marks them with property _destroy with true value.
destroy([set of values])
Finds the items that match with a given set of values, marks them as _destroy with true value.
Note − Destroy and DestroyAll Functions from ObservableArrays are mostly for 'Ruby on Rails' developers only.
When you use destroy method, the corresponding items are not really deleted from array at that moment but are made hidden by marking them with property _destroy with true value so that they can't be read by UI. Items marked as _destroy equal to true are deleted later while dealing with JSON object graph.
Computed Observable is a function which is dependent on one or more Observables and automatically updates whenever its underlying Observables (dependencies) change.
Computed Observables can be chained.
this.varName = ko.computed(function(){
...
... // function code
...
},this);
Let us look at the following example which demonstrates the use of Computed Observables.
<!DOCTYPE html>
<head >
<title>KnockoutJS Computed Observables</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"></script>
</head>
<body>
<p>Enter first number: <input data-bind = "value: a" /></p>
<p>Enter second number: <input data-bind = "value: b"/></p>
<p>Average := <span data-bind="text: totalAvg"></span></p>
<script>
function MyViewModel() {
this.a = ko.observable(10);
this.b = ko.observable(40);
this.totalAvg = ko.computed(function() {
if(typeof(this.a()) !== "number" || typeof(this.b()) !== "number") {
this.a(Number(this.a())); //convert string to Number
this.b(Number(this.b())); //convert string to Number
}
total = (this.a() + this.b())/2 ;
return total;
},this);
}
ko.applyBindings(new MyViewModel());
</script>
</body>
</html>
In the following lines, first two are for accepting input values. Third line prints the average of these two numbers.
<p>Enter first number: <input data-bind = "value: a" /></p>
<p>Enter second number: <input data-bind = "value: b"/></p>
<p>Average := <span data-bind = "text: totalAvg"></span></p>
In the following lines, type of Observables a and b is number when they are initialized for the first time inside ViewModel. However, in KO every input accepted from UI is by default in the String format. So they need to be converted to Number so as to perform arithmetic operation on them.
this.totalAvg = ko.computed(function() {
if(typeof(this.a()) !== "number" || typeof(this.b()) !== "number") {
this.a(Number(this.a())); //convert string to Number
this.b(Number(this.b())); //convert string to Number
}
total = (this.a() + this.b())/2 ;
return total;
},this);
In the following line, the calculated average is displayed in the UI. Note that data-bind type of totalAvg is just text.
<p>Average := <span data-bind = "text: totalAvg"></span></p>
Let's carry out the following steps to see how the above code works −
Save the above code in computed-observable.htm file.
Save the above code in computed-observable.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Enter any 2 numbers in the text boxes and observe that the average is calculated.
Enter any 2 numbers in the text boxes and observe that the average is calculated.
Enter first number:
Enter second number:
Average := 25
Note that in the above example, the second parameter is provided as this to Computed function. It is not possible to refer to Observables a() and b() without providing this.
To overcome this, self variable is used which holds the reference of this. Doing so, there is no need to track this throughout the code. Instead, self can be used.
Following ViewModel code is rewritten for the above example using self.
function MyViewModel(){
self = this;
self.a = ko.observable(10);
self.b = ko.observable(40);
this.totalAvg = ko.computed(function() {
if(typeof(self.a()) !== "number" || typeof(self.b()) !== "number") {
self.a(Number(self.a())); //convert string to Number
self.b(Number(self.b())); //convert string to Number
}
total = (self.a() + self.b())/2 ;
return total;
});
}
A Computed Observable should be declared as Pure Computed Observable if that Observable is simply calculating and returning the value and not directly modifying the other objects or state. Pure Computed Observables helps Knockout to manage reevaluation and memory usage efficiently.
When a Computed Observable is returning primitive data type value (String, Boolean, Null, and Number) then its subscribers are notified if and only if the actual value change takes place. It means if an Observable has received the value same as the previous value, then its subscribers are not notified.
You can make Computed Observables always explicitly notify the observers, even though the new value is the same as the old by using the notify syntax as follows.
myViewModel.property = ko.pureComputed(function() {
return ...; // code logic goes here
}).extend({ notify: 'always' });
Too many expensive updates can result in performance issues. You can limit the number of notifications to be received from Observable using rateLimit attribute as follows.
// make sure there are updates no more than once per 100-millisecond period
myViewModel.property.extend({ rateLimit: 100 });
In certain situations, it might be necessary to find out if a property is a Computed Observable. Following functions can be used to identify the types of Observables.
ko.isComputed
Returns true if the property is Computed Observable.
ko.isObservable
Returns true if the property is Observable, Observable array, or Computed Observable.
ko.isWritableObservable
Returns true if Observable, Observable array, or Writable Computed Observable. (This is also called as ko.isWriteableObservable)
Computed Observable is derived from one or multiple other Observables, so it is read only. However, it is possible that one can make Computed Observable writable. For this you need to provide callback function that works on written values.
These writable Computed Observables work just like regular Observables. In addition, they require custom logic to be built for interfering read and write actions.
One can assign values to many Observables or Computed Observable properties using the chaining syntax as follows.
myViewModel.fullName('Tom Smith').age(45)
Following example demonstrates the use of Writable Computable Observable.
<!DOCTYPE html>
<head >
<title>KnockoutJS Writable Computed Observable</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"></script>
</head>
<body>
<p>Enter your birth Date: <input type = "date" data-bind = "value: rawDate" ></p>
<p><span data-bind = "text: yourAge"></span></p>
<script>
function MyViewModel() {
this.yourAge = ko.observable();
today = new Date();
rawDate = ko.observable();
this.rawDate = ko.pureComputed ({
read: function() {
return this.yourAge;
},
write: function(value) {
var b = Date.parse(value); // convert birth date into milliseconds
var t = Date.parse(today); // convert todays date into milliseconds
diff = t - b; // take difference
var y = Math.floor(diff/31449600000); // difference is converted
// into years. 31449600000
//milliseconds form a year.
var m = Math.floor((diff % 31449600000)/604800000/4.3); // calculating
// months.
// 604800000
// milliseconds
// form a week.
this.yourAge("You are " + y + " year(s) " + m +" months old.");
},
owner: this
});
}
ko.applyBindings(new MyViewModel());
</script>
</body>
</html>
In the above code, rawDate is pureComputed property accepted from UI. yourAge Observable is derived from rawDate.
Dates in JavaScript are manipulated in milliseconds. Hence, both the dates (today date and birth date) are converted into milliseconds and then the difference between them is converted back in years and months.
Let's carry out the following steps to see how the above code works −
Save the above code in writable_computed_observable.htm file.
Save the above code in writable_computed_observable.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Enter any birth date and observe that the age is calculated.
Enter any birth date and observe that the age is calculated.
Enter your birth Date:
Declarative binding in KnockoutJS provides a powerful way to connect data to UI.
It is important to understand the relationship between bindings and Observables. Technically, these two are different. You can use normal JavaScript object as ViewModel and KnockoutJS can process View's binding correctly.
Without Observable, the property from the UI will be processed only for the first time. In this case, it cannot update automatically based on the underlying data update. To achieve this, bindings must be referred to Observable properties.
The binding consists of 2 items, the binding name and value. Following is a simple example −
Today is : <span data-bind = "text: whatDay"></span>
Here, text is the binding name and whatDay is the binding value. You can have multiple bindings separated by comma, as shown in the following syntax.
Your name: <input data-bind = "value: yourName, valueUpdate: 'afterkeydown'" />
Here, value is updated after each key is pressed.
The binding value can be a single value, literal, a variable or can be a JavaScript expression. If the binding refers to some invalid expression or reference, then KO will produce an error and stop processing the binding.
Following are few examples of bindings.
<!-- simple text binding -->
<p>Enter employee name: <input -bind = 'value: empName' /></p>
<!-- click binding, call a specific function -->
<button data-bind="click: sortEmpArray">Sort Array</button>
<!-- options binding -->
<select multiple = "true" size = "8" data-bind = "options: empArray ,
selectedOptions: chosenItem"> </select>
Note the following points −
Whitespaces do not make any difference.
Whitespaces do not make any difference.
Starting from KO 3.0, you can skip the binding value which will give binding an undefined value.
Starting from KO 3.0, you can skip the binding value which will give binding an undefined value.
The data that is being used in current bindings can be referenced by an object. This object is called binding context.
Context hierarchy is created and managed by KnockoutJS automatically. Following table lists the different types of binding contexts provided by KO.
$root
This always refers to top level ViewModel. This makes it possible to access top level methods for manipulating ViewModel. This is usually the object, which is passed to ko.applyBindings.
$data
This property is lot like this keyword in Javascript object. $data property in a binding context refers to ViewModel object for the current context.
$index
This property contains index of a current item of an array inside a foreach loop. The value of $index will change automatically as and when the underlying Observable array is updated. Obviously, this context is available only for foreach bindings.
$parent
This property refers to parent ViewModel object. This is useful when you want to access outer ViewModel properties from inside of a nested loop.
$parentContext
The context object which is bound at the parent level is called $parentContext. This is different from $parent. $parent refers to data. Whereas, $parentContext refers to binding context. E.g. you might need to access the index of outer foreach item from an inner context.
$rawdata
This context holds raw ViewModel value in the current situation. This resembles $data but the difference is, if ViewModel is wrapped in Observable, then $data becomes just unwrapped. ViewModel and $rawdata becomes actual Observable data.
$component
This context is used to refer to ViewModel of that component, when you are inside a particular component. E.g. you might want to access some property from ViewModel instead of current data in the template section of component.
$componentTemplateNodes
This represents an array of DOM nodes passed to that particular component when you are within a specific component template.
Following terms are also available in binding but are not actually binding context.
$context − This is nothing but existing binding context object.
$context − This is nothing but existing binding context object.
$element − This object refers to an element in DOM in the current binding.
$element − This object refers to an element in DOM in the current binding.
Following is a list of binding types provided by KO to deal with text and visual appearances.
To show or hide HTML DOM element depending on certain conditions.
To set the content of an HTML DOM element.
To set the HTML markup contents of a DOM element.
To apply CSS classes to an element.
To define the inline style attribute of an element.
To add attributes to an element dynamically.
Following is a list of Control Flow Binding types provided by KO.
In this binding, each array item is referenced in HTML markup in a loop.
If the condition is true, then the given HTML markup will be processed. Else, it will be removed from DOM.
Negation of If. If the condition is true, then the given HTML markup will be processed. Else, it will be removed from DOM.
This binding is used to bind the child elements of an object in the specified object's context.
This binding is used to insert a component into DOM elements and pass the parameters optionally.
Following is the list of Form Fields Binding types provided by KO.
This binding is used to invoke a JavaScript function associated with a DOM element based on a click.
This binding is used to listen to the specified DOM events and call associated handler functions based on them.
This binding is used to invoke a JavaScript function when the associated DOM element is submitted.
This binding is used to enable certain DOM elements based on a specified condition.
This binding disables the associated DOM element when the parameter evaluates to true.
This binding is used to link respective DOM element's value into ViewModel property.
This binding is used to create 2-way binding between text box or textarea and ViewModel property.
This binding is used to manually set the focus of a HTML DOM element through a ViewModel property.
This binding is used to create a link between a checkable form element and ViewModel property.
This binding is used to define the options for a select element.
This binding is used to work with elements which are selected currently in multi list select form control.
This binding is used to generate a unique name for a DOM element.
KnockoutJs automatically tracks the dependencies when the values get updated. It has a single object called dependency tracker (ko.dependencyDetection) which acts as an intermediate between the two parties for subscribing the dependencies.
Following is the algorithm for dependency tracking.
Step 1 − Whenever you declare a computed observable, KO immediately invokes its evaluator function to get its initial value.
Step 2 − Subscription is set up to any observable that the evaluator reads. In an application, the old subscriptions which are no longer used are disposed.
Step 3 − KO finally notifies the updated computed observable.
Example
<!DOCTYPE html>
<html>
<head>
<title>KnockoutJS How Dependency Tracking Works</title>
<!-- CDN's-->
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type = "text/javascript"></script>
</head>
<body>
<div>
<form data-bind = "submit: addFruits">
<b>Add Fruits:</b>
<input data-bind = 'value: fruitToAdd, valueUpdate: "afterkeydown"'/>
<button type = "submit" data-bind = "enable: fruitToAdd().length > 0">Add</button>
<p><b>Your fruits list:</b></p>
<select multiple = "multiple" width = "50" data-bind = "options: fruits"> </select>
</form>
</div>
<script>
var Addfruit = function(fruits) {
this.fruits = ko.observableArray(fruits);
this.fruitToAdd = ko.observable("");
this.addFruits = function() {
if (this.fruitToAdd() != "") {
this.fruits.push(this.fruitToAdd()); // Adds a fruit
this.fruitToAdd(""); // Clears the text box
}
}.bind(this); // "this" is the view model
};
ko.applyBindings(new Addfruit(["Apple", "Orange", "Banana"]));
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works −
Save the above code in dependency_tracking.htm file.
Save the above code in dependency_tracking.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Enter any fruit name and click the Add button.
Enter any fruit name and click the Add button.
Your fruits list:
The Computed Observable can be accessed without creating a dependency, by using the peek function. It controls the Observable by updating the computed property.
Example
<!DOCTYPE html>
<html>
<head>
<title>KnockoutJs Controlling Dependencies Using Peek</title>
<!-- CDN's-->
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type = "text/javascript"></script>
</head>
<body>
<div class = "logblock">
<h3>Computed Log</h3>
<pre class = "log" data-bind = "html: computedLog"></pre>
</div>
<script>
function AppData() {
this.firstName = ko.observable('John');
this.lastName = ko.observable('Burns');
this.computedLog = ko.observable('Log: ');
this.fullName = ko.computed(function () {
var value = this.firstName() + " " + this.lastName();
this.computedLog(this.computedLog.peek() + value + '; <br/>');
return value;
}, this);
this.step = ko.observable(0);
this.next = function () {
this.step(this.step() === 2 ? 0 : this.step()+1);
};
};
ko.applyBindings(new AppData());
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works −
Save the above code in dependency_tracking_peek.htm file.
Save the above code in dependency_tracking_peek.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Log: John Burns;
The ko.ignoreDependencies function helps ignore those dependencies that you don't want to track within the computed dependencies. Following is its syntax.
ko.ignoreDependencies( callback, callbackTarget, callbackArgs );
If KO is evaluating a Computed Observable, then it will not restart an evaluation of the dependent Computed Observable. Hence, it doesn't make sense to include cycles in your dependency chains.
Template is a set of DOM elements which can be used repetitively. Templating makes it easy to build complex applications due to its property of minimizing duplication of DOM elements.
There are 2 ways of creating templates.
Native templating − This method supports the control flow bindings such as foreach, with, and if. These bindings capture HTML markup existing in the element and use it as template for random items. No external library is required for this templating.
Native templating − This method supports the control flow bindings such as foreach, with, and if. These bindings capture HTML markup existing in the element and use it as template for random items. No external library is required for this templating.
String-based templating − KO connects to the third party engine to pass ViewModel values into it and injects the resulting markup into the document. For example, JQuery.tmpl and Underscore Engine.
String-based templating − KO connects to the third party engine to pass ViewModel values into it and injects the resulting markup into the document. For example, JQuery.tmpl and Underscore Engine.
Syntax
template: <parameter-value>
<script type = "text/html" id = "template-name">
...
... // DOM elemets to be processed
...
</script>
Note that type is provided as text/html in the script block to notify KO that, it is not an executable block rather just a template block which needs to be rendered.
Parameters
Combination of the following properties can be sent as parameter-value to template.
name − This represents the name of the template.
name − This represents the name of the template.
nodes − This represents an array of DOM nodes to be used as the template. This parameter is ignored if the name parameter is passed.
nodes − This represents an array of DOM nodes to be used as the template. This parameter is ignored if the name parameter is passed.
data − This is nothing but data to be shown via the template.
data − This is nothing but data to be shown via the template.
if − Template will be served if the given condition results in true or true-like value.
if − Template will be served if the given condition results in true or true-like value.
foreach − To serve template in foreach format.
foreach − To serve template in foreach format.
as − This is just to create an alias in foreach element.
as − This is just to create an alias in foreach element.
afterAdd, afterRender, beforeRemove − These are all to represent callable functions to be executed depending on the operation performed.
afterAdd, afterRender, beforeRemove − These are all to represent callable functions to be executed depending on the operation performed.
Templates are defined implicitly by HTML markup inside DOM when used with control flow bindings. However if you want to, you can factor out templates into a separate element and then reference them by name.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS Templating - Named Template</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type = "text/javascript"></script>
</head>
<body>
<h2>Friends List</h2>
Here are the Friends from your contact page:
<div data-bind = "template: { name: 'friend-template', data: friend1 }"></div>
<div data-bind = "template: { name: 'friend-template', data: friend2 }"></div>
<script type = "text/html" id = "friend-template">
<h3 data-bind = "text: name"></h3>
<p>Contact Number: <span data-bind = "text: contactNumber"></span></p>
<p>Email-id: <span data-bind = "text: email"></span></p>
</script>
<script type = "text/javascript">
function MyViewModel() {
this.friend1 = {
name: 'Smith',
contactNumber: 4556750345,
email: '[email protected]'
};
this.friend2 = {
name: 'Jack',
contactNumber: 6789358001,
email: '[email protected]'
};
}
var vm = new MyViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works −
Save the above code in template-named.htm file.
Save the above code in template-named.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Here, friend-template is used 2 times.
Here, friend-template is used 2 times.
Contact Number: 4556750345
Email-id: [email protected]
Contact Number: 6789358001
Email-id: [email protected]
Following is an example of using foreach parameter along with the template name.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS Templating - foreach used with Template</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type = "text/javascript"></script>
</head>
<body>
<h2>Friends List</h2>
Here are the Friends from your contact page:
<div data-bind = "template: { name: 'friend-template', foreach: friends }"></div>
<script type = "text/html" id = "friend-template">
<h3 data-bind = "text: name"></h3>
<p>Contact Number: <span data-bind = "text: contactNumber"></span></p>
<p>Email-id: <span data-bind = "text: email"></span></p>
</script>
<script type = "text/javascript">
function MyViewModel() {
this.friends = [
{ name: 'Smith', contactNumber: 4556750345, email: '[email protected]' },
{ name: 'Jack', contactNumber: 6789358001, email: '[email protected]' },
{ name: 'Lisa', contactNumber: 4567893131, email: '[email protected]' }
]
}
var vm = new MyViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works −
Save the above code in template-foreach.htm file.
Save the above code in template-foreach.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Here, foreach control is used in template binding.
Here, foreach control is used in template binding.
Contact Number: 4556750345
Email-id: [email protected]
Contact Number: 6789358001
Email-id: [email protected]
Contact Number: 4567893131
Email-id: [email protected]
Following is how an alias can be created for a foreach item −
<div data-bind = "template: {
name: 'friend-template',
foreach: friends,
as: 'frnz'
}"></div>
It becomes easy to refer to parent objects from inside of foreach loops by creating alias. This feature is useful when the code is complex and nested at multiple levels.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS Templating - using alias in Template</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type = "text/javascript"></script>
</head>
<body>
<h2>Friends List</h2>
Here are the Friends from your contact page:
<ul data-bind = "template: {
name: 'friend-template',
foreach: friends,
as: 'frnz'
}"></ul>
<script type = "text/html" id = "friend-template">
<li>
<h3 data-bind = "text: name"></h3>
<span>Contact Numbers</span>
<ul data-bind = "template: {
name : 'contacts-template',
foreach:contactNumber,
as: 'cont'
} "></ul>
<p>Email-id: <span data-bind = "text: email"></span></p>
</li>
</script>
<script type = "text/html" id = "contacts-template">
<li>
<p><span data-bind = "text: cont"></span></p>
</li>
</script>
<script type = "text/javascript">
function MyViewModel() {
this.friends = ko.observableArray ( [
{
name: 'Smith',
contactNumber: [ 4556750345, 4356787934 ],
email: '[email protected]'
},
{
name: 'Jack',
contactNumber: [ 6789358001, 3456895445 ],
email: '[email protected]'
},
{
name: 'Lisa',
contactNumber: [ 4567893131, 9876456783, 1349873445 ],
email: '[email protected]'
}
]);
}
var vm = new MyViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works −
Save the above code in template-as-alias.htm file.
Save the above code in template-as-alias.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Alias is used instead of full name of arrays.
Alias is used instead of full name of arrays.
Smith
Contact Numbers
4556750345
4356787934
Email-id: [email protected]
4556750345
4556750345
4356787934
4356787934
Email-id: [email protected]
Jack
Contact Numbers
6789358001
3456895445
Email-id: [email protected]
6789358001
6789358001
3456895445
3456895445
Email-id: [email protected]
Lisa
Contact Numbers
4567893131
9876456783
1349873445
Email-id: [email protected]
4567893131
4567893131
9876456783
9876456783
1349873445
1349873445
Email-id: [email protected]
There are situations wherein extra custom logic needs to be run on DOM elements created by the template. In such case, following callbacks can be used. Consider that you are using foreach element then −
afterAdd − This function is invoked when a new item is added to the array mentioned in foreach.
beforeRemove − This function is invoked just before removing the item from an array mentioned in foreach.
afterRender − Function mentioned here is invoked every time foreach is rendered and new entries are added to the array.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS Templating - Use of afterRender Template</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type = "text/javascript"></script>
<script src = "https://code.jquery.com/jquery-2.1.3.min.js"
type = "text/javascript"></script>
</head>
<body>
<h2>Friends List</h2>
Here are the Friends from your contact page:
<div data-bind = "template: {
name: 'friend-template',
foreach: friends ,
afterRender: afterProcess
}"></div>
<script type = "text/html" id = "friend-template">
<h3 data-bind = "text: name"></h3>
<p>Contact Number: <span data-bind = "text: contactNumber"></span></p>
<p>Email-id: <span data-bind = "text: email"></span></p>
<button data-bind = "click: $root.removeContact">remove </button>
</script>
<script type = "text/javascript">
function MyViewModel() {
self = this;
this.friends = ko.observableArray ([
{ name: 'Smith', contactNumber: 4556750345, email: '[email protected]' },
{ name: 'Jack', contactNumber: 6789358001, email: '[email protected]' },
])
this.afterProcess = function(elements, data){
$(elements).css({color: 'magenta' });
}
self.removeContact = function() {
self.friends.remove(this);
}
}
var vm = new MyViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works −
Save the above code in template-afterrender.htm file.
Save the above code in template-afterrender.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Here, afterProcess function is executed every time foreach is rendered.
Here, afterProcess function is executed every time foreach is rendered.
Contact Number: 4556750345
Email-id: [email protected]
Contact Number: 6789358001
Email-id: [email protected]
If there are multiple templates available, then one can be chosen dynamically by making the name as observable parameter. Hence, the template value will be re-evaluated as the name parameter changes and in turn data will be re-rendered.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS Templating - Dynamic Template</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type = "text/javascript"></script>
</head>
<body>
<h2>Friends List</h2>
Here are the Friends from your contact page:
<div data-bind = "template: {
name: whichTemplate,
foreach: friends
}"></div>
<script type = "text/html" id = "only-phon">
<h3 data-bind = "text: name"></h3>
<p>Contact Number: <span data-bind = "text: contactNumber"></span></p>
</script>
<script type = "text/html" id = "only-email">
<h3 data-bind = "text: name"></h3>
<p>Email-id: <span data-bind = "text: email"></span></p>
</script>
<script type = "text/javascript">
function MyViewModel() {
this.friends = ko.observableArray ([
{
name: 'Smith',
contactNumber: 4556750345,
email: '[email protected]',
active: ko.observable(true)
},
{
name: 'Jack',
contactNumber: 6789358001,
email: '[email protected]',
active: ko.observable(false)
},
]);
this.whichTemplate = function(friends) {
return friends.active() ? "only-phon" : "only-email";
}
}
var vm = new MyViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works −
Save the above code in template-dynamic.htm file.
Save the above code in template-dynamic.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Template to be used is decided depending on the active flag value.
Template to be used is decided depending on the active flag value.
Contact Number: 4556750345
Email-id: [email protected]
Native templating works perfectly with various control flow elements even with nested code blocks. KO also offers a way to integrate with external templating library such as Underscore templating Engine or JQuery.tmpl.
As mentioned on the official site JQuery.tmpl is no longer under active development since December 2011. Hence, KO's native templating is only recommended instead of JQuery.tmpl or any other string-based template engine.
Please refer to the official site for more details on this.
Components are a huge way of organizing the UI code for structuring a large application and promoting code reusability.
It is inherited or nested from other component. For loading and configuration, it defines its own conventions or logic.
It is packaged to reuse throughout the application or the project. Represents the complete sections of application or small controls/widgets. It can be loaded or preloaded on demand.
Components can register using the ko.components.register() API. It helps to load and represent the components in KO. Component name with configuration is expected for registration. The configuration specifies how to determine the viewModel and template.
Syntax
Components can be registered as follows −
ko.components.register('component-name', {
viewModel: {...}, //function code
template: {....) //function code
});
The component-name can be any nonempty string.
The component-name can be any nonempty string.
viewModel is optional, and can take any of the viewModel formats listed in the next sections.
viewModel is optional, and can take any of the viewModel formats listed in the next sections.
template is required, and can take any of the template formats listed in the next sections.
template is required, and can take any of the template formats listed in the next sections.
Following table lists the viewModel formats that can be used to register the components.
constructor function
It creates a separate viewModel object for each component. The object or function is used to bind in components view.
function SomeComponentViewModel(params) {
this.someProperty = params.something;
}
ko.components.register('component name', {
viewModel: SomeComponentViewModel,
template: ...
});
shared object instance
The viewModel object instance is shared. The instance property is passed to use the object directly.
var sharedViewModelInstance = { ... };
ko.components.register('component name', {
viewModel: { instance: sharedViewModelInstance },
template: ...
});
createViewModel
It calls a function which acts as a factory and can be used as view model that can return an object.
ko.components.register('component name', {
viewModel: {
createViewModel: function (params, componentInfo) {
... //function code
...
}
},
template: ....
});
AMD module
It is a module format for defining modules where module and dependencies both are loaded asynchronously.
ko.components.register('component name', {
viewModel: { require: 'some/module/name' },
template: ...
});
define(['knockout'], function(ko) {
function MyViewModel() {
// ...
}
return MyViewModel;
});
Following table lists the template formats that can be used to register the components.
element ID
ko.components.register('component name', {
template: { element: 'component-template' },
viewModel: ...
});
element instance
var elemInstance = document.getElementById('component-template');
ko.components.register('component name', {
template: { element: elemInstance },
viewModel: ...
});
string of markup
ko.components.register('component name', {
template: '<input data-bind = "value: yourName" />\
<button data-bind = "click: addEmp">Add Emp </button>',
viewModel: ...
});
DOM nodes
var emp = [
document.getElementById('node 1'),
document.getElementById('node 2'),
];
ko.components.register('component name', {
template: emp,
viewModel: ...
});
document fragement
ko.components.register('component name', {
template: someDocumentFragmentInstance,
viewModel: ...
});
AMD module
ko.components.register('component name', {
template: { require: 'some/template' },
viewModel: ...
});
The AMD module can register a component by itself without using viewModel/template pair.
ko.components.register('component name',{ require: 'some/module'});
There are two ways of component binding.
Full syntax − It passes the parameter and object to the component. It can pass using the following properties.
name − It adds the component name.
params − It can pass multiple parameters in object on the component.
Full syntax − It passes the parameter and object to the component. It can pass using the following properties.
name − It adds the component name.
name − It adds the component name.
params − It can pass multiple parameters in object on the component.
params − It can pass multiple parameters in object on the component.
<div data-bind='component: {
name: "tutorials point",
params: { mode: "detailed-list", items: productsList }
}'>
</div>
Shorthand syntax − It passes the string as a component name and it does not include parameter in it.
Shorthand syntax − It passes the string as a component name and it does not include parameter in it.
<div data-bind = 'component: "component name"'></div>
Template-only components − Components can only define template without specifing the viewModel.
Template-only components − Components can only define template without specifing the viewModel.
ko.components.register('component name', {
template:'<input data-bind = "value: someName" />,
});
Using Component without a container element − Components can be used without using extra container element. This can be done using containerless flow control which is similar as the comment tag.
Using Component without a container element − Components can be used without using extra container element. This can be done using containerless flow control which is similar as the comment tag.
<!--ko.component: ""-->
<!--/ko-->
Custom element is a way for rendering a component. Here, you can directly write a selfdescriptive markup element name instead of defining a placeholder, where the components are binded through it.
<products-list params = "name: userName, type: userType"></products-list>
params attribute is used to pass the parameter to component viewModel. It is similar to data-bind attribute. The contents of the params attribute are interpreted like a JavaScript object literal (just like a data-bind attribute), so you can pass arbitrary values of any type. It can pass the parameter in following ways −
Communication between parent and child components − The component is not instantiated by itself so the viewmodel properties are referred from outside of the component and thus would be received by child component viewmodel. For example, you can see in the following syntax that ModelValue is the parent viewmodel, which is received by child viewModel constructor ModelProperty.
Communication between parent and child components − The component is not instantiated by itself so the viewmodel properties are referred from outside of the component and thus would be received by child component viewmodel. For example, you can see in the following syntax that ModelValue is the parent viewmodel, which is received by child viewModel constructor ModelProperty.
Passing observable expressions − It has three values in params parameter.
simpleExpression − It is a numeric value. It does not involve any observables.
simpleObservable − It is an instance that is defined on parent viewModel. The parent viewModel will automatically get the changes on observable done by child viewModel.
observableExpression − Expression reads the observable when the expression is evaluated by itself. When the observable value changes, then the result of expression can also changs over time.
Passing observable expressions − It has three values in params parameter.
simpleExpression − It is a numeric value. It does not involve any observables.
simpleExpression − It is a numeric value. It does not involve any observables.
simpleObservable − It is an instance that is defined on parent viewModel. The parent viewModel will automatically get the changes on observable done by child viewModel.
simpleObservable − It is an instance that is defined on parent viewModel. The parent viewModel will automatically get the changes on observable done by child viewModel.
observableExpression − Expression reads the observable when the expression is evaluated by itself. When the observable value changes, then the result of expression can also changs over time.
observableExpression − Expression reads the observable when the expression is evaluated by itself. When the observable value changes, then the result of expression can also changs over time.
We can pass the parameters as follows −
<some-component
params = 'simpleExpression: 1 + 1,
simpleObservable: myObservable,
observableExpression: myObservable() + 1'>
</some-component>
We can pass the parameters in viewModel as follows −
<some-component
params = 'objectValue:{a: 3, b: 2},
dateValue: new date(),
stringValue: "Hi",
numericValue:123,
boolValue: true/false,
ModelProperty: ModelValue'>
</some-component>
The received markup is used to create a component and is selected as a part of the output. Following nodes are passed as part of the output in the component template.
template: { nodes: $componentTemplateNodes }
The names which you register in the components using ko.components.register, the same name corresponds to the custom element tag names. We can change the custom element tag names by overriding it to control using getComponentNameForNode.
ko.components.getComponentNameForNode = function(node) {
...
... //function code
...
}
The custom elements can be made available immediately, if the default component loader is used and hence the component is registered using ko.components.register. If we are not using the ko.components.register and implementing the custom component loader, then the custom element can be used by defining any element name of choice. There is no need to specify configuration when you are using ko.components.register as the custom component loader does not use it anymore.
ko.components.register('custom-element', { ......... });
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS Components</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
</head>
<body>
<!--params attribute is used to pass the parameter to component viewModel.-->
<click params = "a: a, b: b"></click>
<!--template is used for a component by specifying its ID -->
<template id = "click-l">
<div data-bind = "text: a"></div>
<!--Use data-bind attribute to bind click:function() to ViewModel. -->
<button data-bind = "click:function(){callback(1)}">Increase</button>
<button data-bind = "click:function(){callback(-1)}">Decrease</button>
</template>
<script>
//Here components are registered
ko.components.register('click', {
viewModel: function(params) {
self = this;
this.a = params.a;
this.b = params.b;
this.callback = function(num) {
self.b(parseInt(num));
self.a( self.a() + parseInt(num) );
};
},
template: { element: 'click-l' }
});
//keeps an eye on variable for any modification in data
function viewModel() {
this.a = ko.observable(2);
this.b = ko.observable(0);
}
ko.applyBindings(new viewModel() );
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works −
Save the above code in component_register.htm file.
Save the above code in component_register.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
Component loaders are used to pass the template/viewModel pair asynchronously for the given component name.
The default component loader depends on the explicitly registered configuration. Each component is registered before using the component.
ko.components.defaultLoader
The default component loader can read and write using the following functions.
ko.components.register(name, configuration)
Component is registered.
ko.components.isRegistered(name)
If the particular component name is already registered, then it returns as true else false.
ko.components.unregister(name)
The component name is removed from the registry.
ko.components.get(name, callback)
This function goes turn by turn to each registered loader to find who has passed the viewModel/template definition for component name as first. Then it returns viewModel/template declaration by invoking callback. If the registered loader could not find anything about the component, then it invokes callback(null).
ko.components.clearCachedDefinition(name)
This function can be called when we want to clear the given component cache entry. If the component is needed next time, again the loaders will be consulted.
The custom component loader can be implemented in the following ways −
getConfig(name, callback) − Depending on the names, we can pass configurations programatically. We can call callback(componentConfig) to pass the configurations, where the object componentConfig can be used by the loadComponent or any other loader.
getConfig(name, callback) − Depending on the names, we can pass configurations programatically. We can call callback(componentConfig) to pass the configurations, where the object componentConfig can be used by the loadComponent or any other loader.
loadComponent(name, componentConfig, callback) − This function resolves the viewModel and the template portion of config depending upon the way it is configured. We can call callback(result) to pass the viewmodel/template pair, where the object result is defined by the following properties.
template − Required. Return array of DOM nodes.
createViewModel(params, componentInfo) − Optional. Returns the viewModel Object depending on how the viewModel property was configured.
loadComponent(name, componentConfig, callback) − This function resolves the viewModel and the template portion of config depending upon the way it is configured. We can call callback(result) to pass the viewmodel/template pair, where the object result is defined by the following properties.
template − Required. Return array of DOM nodes.
template − Required. Return array of DOM nodes.
createViewModel(params, componentInfo) − Optional. Returns the viewModel Object depending on how the viewModel property was configured.
createViewModel(params, componentInfo) − Optional. Returns the viewModel Object depending on how the viewModel property was configured.
loadTemplate(name, templateConfig, callback) − DOM nodes is passed in a template using custom logic. The object templateConfig is a property of the template from an object componentConfig. callback(domNodeArray) is called to pass an array of DOM nodes.
loadTemplate(name, templateConfig, callback) − DOM nodes is passed in a template using custom logic. The object templateConfig is a property of the template from an object componentConfig. callback(domNodeArray) is called to pass an array of DOM nodes.
loadViewModel(name, templateConfig, callback) − viewModel factory is passed in a viewModel configuration using custom logic.
loadViewModel(name, templateConfig, callback) − viewModel factory is passed in a viewModel configuration using custom logic.
|
[
{
"code": null,
"e": 2245,
"s": 1986,
"text": "KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites. The model separates the application's Model (stored data), View (UI) and View Model (JavaScript Representation of model)."
},
{
"code": null,
"e": 2514,
"s": 2245,
"text": "KnockoutJS was developed and is maintained as an open source project by Steve Sanderson, a Microsoft employee on July 5, 2010. KO is an abbreviation used for KnockoutJS. KO supports all mainstream browsers - IE 6+, Firefox 3.5+, Chrome, Opera, Safari (desktop/mobile)."
},
{
"code": null,
"e": 2584,
"s": 2514,
"text": "Here is a list of some of the most prominent features of KnockoutJS −"
},
{
"code": null,
"e": 2769,
"s": 2584,
"text": "Declarative Binding − HTML DOM elements are connected to the model through data-bind attribute using a very simple syntax. It is made easy to achieve responsiveness using this feature."
},
{
"code": null,
"e": 2954,
"s": 2769,
"text": "Declarative Binding − HTML DOM elements are connected to the model through data-bind attribute using a very simple syntax. It is made easy to achieve responsiveness using this feature."
},
{
"code": null,
"e": 3102,
"s": 2954,
"text": "Automatic UI Refresh − Any changes made to view the model data are reflected in the UI automatically and vice-versa. No need of writing extra code."
},
{
"code": null,
"e": 3250,
"s": 3102,
"text": "Automatic UI Refresh − Any changes made to view the model data are reflected in the UI automatically and vice-versa. No need of writing extra code."
},
{
"code": null,
"e": 3448,
"s": 3250,
"text": "Dependency Tracking − Relationship between KO attributes and KO library functions/components is transparent. Automatically tracks data changes in KO attribute and updates respective affected areas."
},
{
"code": null,
"e": 3646,
"s": 3448,
"text": "Dependency Tracking − Relationship between KO attributes and KO library functions/components is transparent. Automatically tracks data changes in KO attribute and updates respective affected areas."
},
{
"code": null,
"e": 3822,
"s": 3646,
"text": "Templating − Templates are a simple and convenient way to build complex UI structures - with the possibility of repeating or nesting blocks - as a function of view model data."
},
{
"code": null,
"e": 3998,
"s": 3822,
"text": "Templating − Templates are a simple and convenient way to build complex UI structures - with the possibility of repeating or nesting blocks - as a function of view model data."
},
{
"code": null,
"e": 4048,
"s": 3998,
"text": "Extensible − Extends custom behavior very easily."
},
{
"code": null,
"e": 4098,
"s": 4048,
"text": "Extensible − Extends custom behavior very easily."
},
{
"code": null,
"e": 4247,
"s": 4098,
"text": "KnockoutJS library provides an easy and clean way to handle complex data-driven interfaces. One can create self-updating UIs for Javascript objects."
},
{
"code": null,
"e": 4396,
"s": 4247,
"text": "KnockoutJS library provides an easy and clean way to handle complex data-driven interfaces. One can create self-updating UIs for Javascript objects."
},
{
"code": null,
"e": 4548,
"s": 4396,
"text": "It is pure JavaScript Library and works with any web framework. It's not a replacement of JQuery but can work as a supplement providing smart features."
},
{
"code": null,
"e": 4700,
"s": 4548,
"text": "It is pure JavaScript Library and works with any web framework. It's not a replacement of JQuery but can work as a supplement providing smart features."
},
{
"code": null,
"e": 4755,
"s": 4700,
"text": "KnockoutJS library file is very small and lightweight."
},
{
"code": null,
"e": 4810,
"s": 4755,
"text": "KnockoutJS library file is very small and lightweight."
},
{
"code": null,
"e": 4924,
"s": 4810,
"text": "KnockoutJS is independent of any other framework. It is compatible with other client or server side technologies."
},
{
"code": null,
"e": 5038,
"s": 4924,
"text": "KnockoutJS is independent of any other framework. It is compatible with other client or server side technologies."
},
{
"code": null,
"e": 5110,
"s": 5038,
"text": "Most important of all KnockoutJS is open source and hence free for use."
},
{
"code": null,
"e": 5182,
"s": 5110,
"text": "Most important of all KnockoutJS is open source and hence free for use."
},
{
"code": null,
"e": 5317,
"s": 5182,
"text": "KnockoutJS is fully documented. The official site has full documentation including API docs, live examples, and interactive tutorials."
},
{
"code": null,
"e": 5452,
"s": 5317,
"text": "KnockoutJS is fully documented. The official site has full documentation including API docs, live examples, and interactive tutorials."
},
{
"code": null,
"e": 5554,
"s": 5452,
"text": "It is very easy to use KnockoutJS. Simply refer the JavaScript file using <script> tag in HTML pages."
},
{
"code": null,
"e": 5606,
"s": 5554,
"text": "Knockout.js can be accessed in the following ways −"
},
{
"code": null,
"e": 5802,
"s": 5606,
"text": "You can download production build of Knockout.js from its official website\nA page as in the following image will be displayed. Click on download link and you will get the latest knockout.js file."
},
{
"code": null,
"e": 5877,
"s": 5802,
"text": "You can download production build of Knockout.js from its official website"
},
{
"code": null,
"e": 5998,
"s": 5877,
"text": "A page as in the following image will be displayed. Click on download link and you will get the latest knockout.js file."
},
{
"code": null,
"e": 6049,
"s": 5998,
"text": "Now refer the file as shown in the following code."
},
{
"code": null,
"e": 6118,
"s": 6049,
"text": "<script type = 'text/javascript' src = 'knockout-3.3.0.js'></script>"
},
{
"code": null,
"e": 6202,
"s": 6118,
"text": "Update the src attribute to match the location where the downloaded files are kept."
},
{
"code": null,
"e": 6254,
"s": 6202,
"text": "You can refer to the KnockoutJS library from CDNs −"
},
{
"code": null,
"e": 6306,
"s": 6254,
"text": "You can refer to the KnockoutJS library from CDNs −"
},
{
"code": null,
"e": 6389,
"s": 6306,
"text": "You can refer KnockoutJS library from Microsoft Ajax CDN in your code as follows −"
},
{
"code": null,
"e": 6472,
"s": 6389,
"text": "You can refer KnockoutJS library from Microsoft Ajax CDN in your code as follows −"
},
{
"code": null,
"e": 6586,
"s": 6472,
"text": "<script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js\" \n type = \"text/javascript\"></script>"
},
{
"code": null,
"e": 6682,
"s": 6586,
"text": "Alternatively you can refer to a minified version of KnockoutJS library from CDNJS as follows −"
},
{
"code": null,
"e": 6778,
"s": 6682,
"text": "Alternatively you can refer to a minified version of KnockoutJS library from CDNJS as follows −"
},
{
"code": null,
"e": 6903,
"s": 6778,
"text": "<script src = \"https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js\" \n type = \"text/javascript\"></script>"
},
{
"code": null,
"e": 7008,
"s": 6903,
"text": "Note − In all the chapters for this tutorial, we have referred to CDN version of the KnockoutJS library."
},
{
"code": null,
"e": 7203,
"s": 7008,
"text": "KnockoutJS is based on Model-View-ViewModel (MVVM) pattern. We will study this pattern in depth in chapter KnockoutJS - MVVM Framework. First let's take a look at a simple example of KnockoutJS."
},
{
"code": null,
"e": 8484,
"s": 7203,
"text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS Simple Example</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js\" \n type = \"text/javascript\"></script>\n </head>\n\n <body>\n <!-- This is called \"view\" of HTML markup that defines the appearance of UI -->\n\n <p>First String: <input data-bind = \"value: firstString\" /></p>\n <p>Second String: <input data-bind = \"value: secondString\" /></p>\n\n <p>First String: <strong data-bind = \"text: firstString\">Hi</strong></p>\n <p>Second String: <strong data-bind = \"text: secondString\">There</strong></p>\n\n <p>Derived String: <strong data-bind = \"text: thirdString\"></strong></p>\n\n <script>\n <!-- This is called \"viewmodel\". This javascript section defines the data and \n behavior of UI -->\n\n function AppViewModel() {\n this.firstString = ko.observable(\"Enter First String\");\n this.secondString = ko.observable(\"Enter Second String\");\n\n this.thirdString = ko.computed(function() {\n return this.firstString() + \" \" + this.secondString();\n }, this);\n }\n\n // Activates knockout.js\n ko.applyBindings(new AppViewModel());\n </script>\n\n </body>\n</html>"
},
{
"code": null,
"e": 8533,
"s": 8484,
"text": "The following line refers to KnockoutJS library."
},
{
"code": null,
"e": 8648,
"s": 8533,
"text": "<script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js\" \n type = \"text/javascript\"> </script>"
},
{
"code": null,
"e": 8685,
"s": 8648,
"text": "This line refers KnockoutJS library."
},
{
"code": null,
"e": 8858,
"s": 8685,
"text": "We have two input boxes: First String and Second String. These 2 variables are initialized with values Enter First String and Enter Second String respectively in ViewModel."
},
{
"code": null,
"e": 8924,
"s": 8858,
"text": "<p>First String: < input data-bind = \"value: firstString\" /> </p>"
},
{
"code": null,
"e": 9039,
"s": 8924,
"text": "This is how we are binding values from ViewModel to HTML elements using 'data-bind' attribute in the body section."
},
{
"code": null,
"e": 9089,
"s": 9039,
"text": "Here, 'firstString' refers to ViewModel variable."
},
{
"code": null,
"e": 9145,
"s": 9089,
"text": "this.firstString = ko.observable(\"Enter First String\");"
},
{
"code": null,
"e": 9265,
"s": 9145,
"text": "ko.observable is a concept which keeps an eye on the value changes so that it can update the underlying ViewModel data."
},
{
"code": null,
"e": 9509,
"s": 9265,
"text": "To understand this better, let's update the first input box to \"Hello\" and the second input box to \"TutorialsPoint\". You will see the values are updated simultaneously. We will study more about this concept in KnockoutJS - Observables chapter."
},
{
"code": null,
"e": 9621,
"s": 9509,
"text": "this.thirdString = ko.computed(function() {\n return this.firstString() + \" \" + this.secondString();\n}, this);"
},
{
"code": null,
"e": 10008,
"s": 9621,
"text": "Next, we have computed function in viewmodel. This function derives the third string based on 2 strings mentioned earlier. Thus, any updates made to these strings automatically get reflected in this derived string. There is no need of writing an extra code to accomplish this. This is just a simple example. We will study about this concept in KnockoutJS - Computed Observables chapter."
},
{
"code": null,
"e": 10141,
"s": 10008,
"text": "Save the above code as my_first_knockoutjs_program.html. Open this file in your browser and you will see an output as the following."
},
{
"code": null,
"e": 10223,
"s": 10141,
"text": "Modify strings to \"Hello\" and \"TutorialsPoint\" and the output changes as follows."
},
{
"code": null,
"e": 10411,
"s": 10223,
"text": "KnockoutJS is widely used for Single Page Applications - A website created with the ability to retrieve all necessary data dynamically with a single page load reducing server round trips."
},
{
"code": null,
"e": 10702,
"s": 10411,
"text": "KnockoutJS is a client-side framework. This is a JavaScript library which makes it very easy to bind HTML to domain data. It implements a pattern called Model-View-ViewModel (MVVM). Observables is the magic ingredient of KnockoutJS. All data remains in sync because of Observable attribute."
},
{
"code": null,
"e": 10782,
"s": 10702,
"text": "View is nothing but user interface created using HTML elements and CSS styling."
},
{
"code": null,
"e": 11126,
"s": 10782,
"text": "You can bind HTML DOM elements to data model using KnockoutJS. It provides 2-way data binding between View and ViewModel using 'data-bind' concept, which means any updates done in the UI are reflected in the data model and any changes done in the data model are reflected in the UI. One can create self-updating UI with the help of knockoutJS."
},
{
"code": null,
"e": 11475,
"s": 11126,
"text": "ViewModel is a JavaScript object, which contains necessary properties and functions to represent data. View and ViewModel are connected together with declarative data-bind concept used in HTML. This makes it easy to change HTML without changing ViewModel. KnockoutJS takes care of automatic data refresh between them through the use of Observables."
},
{
"code": null,
"e": 11857,
"s": 11475,
"text": "Synchronization of data is achieved through binding DOM elements to Data Model, first using data-bind and then refreshing these 2 components through the use of Observables. Dependency tracking is done automatically due to this synchronization of data. No extra coding is required to achieve it. KnockoutJS allows to create direct connection between the display and underlying data."
},
{
"code": null,
"e": 12041,
"s": 11857,
"text": "You can create your own bindings called as custom bindings for application specific behaviors. This way Knockout gives direct control of how you want to transform your data into HTML."
},
{
"code": null,
"e": 12161,
"s": 12041,
"text": "Model is the domain data on the server and it gets manipulated as and when the request is sent/received from ViewModel."
},
{
"code": null,
"e": 12376,
"s": 12161,
"text": "The data could be stored in database, cookie, or other form of persistent storage. KnockoutJS does not worry about how it is stored. It is up to the programmer to communicate between the stored data and KnockoutJS."
},
{
"code": null,
"e": 12438,
"s": 12376,
"text": "Most of the times, data is saved and loaded via an Ajax call."
},
{
"code": null,
"e": 12986,
"s": 12438,
"text": "Model-View-ViewModel (MVVM) is an architectural design pattern for developing software applications. MVVM was developed by Microsoft Architect John Gossman in 2005. This pattern is derived from Model-View-Controller (MVC) pattern. The advantage of MVVM is that it separates the application layer's graphical user interface from business logic. MVVM is responsible for handling data from the underlying model in such a way that it is represented and managed very easily. ViewModel in MVVM represents an abstract version of View's state and actions."
},
{
"code": null,
"e": 13167,
"s": 12986,
"text": "The view classes do not know that Model and ViewModel classes exists, also Model and ViewModel does not know that View exists. Model is also unaware that ViewModel and View exists."
},
{
"code": null,
"e": 13512,
"s": 13167,
"text": "View is a Graphical User Interface created using markup language to represent data. View binds to properties of a ViewModel through data-bind concept, which indirectly connects to the model data. View need not be changed for any alteration done in ViewModel. Changes made to data in ViewModel is automatically propagated in View due to binding."
},
{
"code": null,
"e": 13663,
"s": 13512,
"text": "Model is domain data or business object, which holds real-time data. Model does not carry behaviors. Behavior is mostly implemented in business logic."
},
{
"code": null,
"e": 14242,
"s": 13663,
"text": "ViewModel is the center place, where data from Model and View's display logic are bundled together. ViewModel holds the dynamic state of data. There is an implicit binder in between View and ViewModel to communicate with each other. This binding is inclusive of declarative data and command binding. Synchronization of View and ViewModel is achieved through this binding. Any change made in View is reflected in ViewModel, and similarly any change in ViewModel gets automatically reflected in View. Existence of this 2-way binding mechanism is a key aspect of this MVVM pattern."
},
{
"code": null,
"e": 14303,
"s": 14242,
"text": "KnockoutJS is build upon the following 3 important concepts."
},
{
"code": null,
"e": 14512,
"s": 14303,
"text": "Observables and dependency tracking between them - DOM elements are connected to ViewModel via 'data-bind'. They exchange information through Observables. This automatically takes care of dependency tracking."
},
{
"code": null,
"e": 14721,
"s": 14512,
"text": "Observables and dependency tracking between them - DOM elements are connected to ViewModel via 'data-bind'. They exchange information through Observables. This automatically takes care of dependency tracking."
},
{
"code": null,
"e": 14834,
"s": 14721,
"text": "Declarative Bindings between UI and ViewModel - DOM elements are connected to ViewModel via 'data-bind' concept."
},
{
"code": null,
"e": 14947,
"s": 14834,
"text": "Declarative Bindings between UI and ViewModel - DOM elements are connected to ViewModel via 'data-bind' concept."
},
{
"code": null,
"e": 15060,
"s": 14947,
"text": "Templating to create re-usable components - Templating provides a robust way to create complex web applications."
},
{
"code": null,
"e": 15173,
"s": 15060,
"text": "Templating to create re-usable components - Templating provides a robust way to create complex web applications."
},
{
"code": null,
"e": 15216,
"s": 15173,
"text": "We will study Observables in this chapter."
},
{
"code": null,
"e": 15534,
"s": 15216,
"text": "As the name specifies, when you declare a ViewModel data/property as Observable, any data modification each time automatically gets reflected at all places the data is used. This also includes refreshing the related dependencies. KO takes care of these things and there is no need to write extra code to achieve this."
},
{
"code": null,
"e": 15623,
"s": 15534,
"text": "Using Observable, it becomes very easy to make UI and ViewModel communicate dynamically."
},
{
"code": null,
"e": 15720,
"s": 15623,
"text": "You just need to declare ViewModel property with function ko.observable() to make it Observable."
},
{
"code": null,
"e": 15761,
"s": 15720,
"text": "this.property = ko.observable('value');\n"
},
{
"code": null,
"e": 15846,
"s": 15761,
"text": "Let's take a look at the following example which demonstrates the use of Observable."
},
{
"code": null,
"e": 16643,
"s": 15846,
"text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS Observable Example</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js\" \n type = \"text/javascript\"></script>\n </head>\n \n <body>\n <!-- This is called \"view\" of HTML markup that defines the appearance of UI -->\n\n <p>Enter your name: <input data-bind = \"value: yourName\" /></p>\n <p>Hi <strong data-bind = \"text: yourName\"></strong> Good Morning!!!</p>\n\n <script>\n <!-- This is called \"viewmodel\". This javascript section defines the data and behavior of UI -->\n\n function AppViewModel() {\n this.yourName = ko.observable(\"\");\n }\n\n // Activates knockout.js\n ko.applyBindings(new AppViewModel());\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 16770,
"s": 16643,
"text": "The following line is for the input box. As can be seen, we have used data-bind attribute to bind yourName value to ViewModel."
},
{
"code": null,
"e": 16834,
"s": 16770,
"text": "<p>Enter your name: <input data-bind = \"value: yourName\" /> <p>"
},
{
"code": null,
"e": 16967,
"s": 16834,
"text": "The following line just prints the value of yourName. Note, that here data-bind type is the text as we are simply reading the value."
},
{
"code": null,
"e": 17040,
"s": 16967,
"text": "<p>Hi <strong data-bind = \"text: yourName\"></strong> Good Morning!!!</p>"
},
{
"code": null,
"e": 17413,
"s": 17040,
"text": "In the following line, ko.observable keeps an eye on yourName variable for any modification in data. Once there is a modification, the corresponding places also get updated with the modified value. When you run the following code, an input box will appear. As and when you update that input box, the new value will get reflected or refreshed in places wherever it is used."
},
{
"code": null,
"e": 17448,
"s": 17413,
"text": "this.yourName = ko.observable(\"\");"
},
{
"code": null,
"e": 17518,
"s": 17448,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 17572,
"s": 17518,
"text": "Save the above code in first_observable_pgm.htm file."
},
{
"code": null,
"e": 17626,
"s": 17572,
"text": "Save the above code in first_observable_pgm.htm file."
},
{
"code": null,
"e": 17660,
"s": 17626,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 17694,
"s": 17660,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 17772,
"s": 17694,
"text": "Enter the name as Scott and observe that the name is reflected in the output."
},
{
"code": null,
"e": 17850,
"s": 17772,
"text": "Enter the name as Scott and observe that the name is reflected in the output."
},
{
"code": null,
"e": 17868,
"s": 17850,
"text": "Enter your name: "
},
{
"code": null,
"e": 17888,
"s": 17868,
"text": "Hi Good Morning!!!"
},
{
"code": null,
"e": 18290,
"s": 17888,
"text": "Data modification can take place either from the UI or from ViewModel. Irrespective of from where the data is changed, the UI and ViewModel keeps synchronization among them. This makes it a two-way-binding mechanism. In the above example, when you change your name in the input box, ViewModel gets a new value. When you change yourName property from inside ViewModel, then the UI receives a new value."
},
{
"code": null,
"e": 18381,
"s": 18290,
"text": "Following table lists the read and write operations which can be performed on Observables."
},
{
"code": null,
"e": 18386,
"s": 18381,
"text": "Read"
},
{
"code": null,
"e": 18481,
"s": 18386,
"text": "To read value just call Observable property without parameters like: AppViewModel.yourName();"
},
{
"code": null,
"e": 18487,
"s": 18481,
"text": "Write"
},
{
"code": null,
"e": 18611,
"s": 18487,
"text": "To write/update value in Observable property, just pass the desired value in parameter like: AppViewModel.yourName('Bob');"
},
{
"code": null,
"e": 18626,
"s": 18611,
"text": "Write multiple"
},
{
"code": null,
"e": 18769,
"s": 18626,
"text": "Multiple ViewModel properties can be updated in a single row with the help of chaining-syntax like: AppViewModel.yourName('Bob').yourAge(45);"
},
{
"code": null,
"e": 19075,
"s": 18769,
"text": "Observable declaration takes care of data modifications of a single object. ObservableArray works with the collection of objects. This is a very useful feature when you are dealing with complex applications containing multiple type of values and changing their status frequently based on the user actions."
},
{
"code": null,
"e": 19141,
"s": 19075,
"text": "this.arrayName = ko.observableArray(); // It's an empty array\n"
},
{
"code": null,
"e": 19283,
"s": 19141,
"text": "Observable array only tracks which objects in it are added or removed. It does not notify if the individual object's properties are modified."
},
{
"code": null,
"e": 19428,
"s": 19283,
"text": "You can initialize your array and at the same time you can declare it as Observable by passing the initial values to the constructor as follows."
},
{
"code": null,
"e": 19483,
"s": 19428,
"text": "this.arrayName = ko.observableArray(['scott','jack']);"
},
{
"code": null,
"e": 19536,
"s": 19483,
"text": "You can access Observable array elements as follows."
},
{
"code": null,
"e": 19586,
"s": 19536,
"text": "alert('The second element is ' + arrayName()[1]);"
},
{
"code": null,
"e": 19674,
"s": 19586,
"text": "KnockoutJS has its own set of Observable array functions. They are convenient because −"
},
{
"code": null,
"e": 19712,
"s": 19674,
"text": "These functions work on all browsers."
},
{
"code": null,
"e": 19750,
"s": 19712,
"text": "These functions work on all browsers."
},
{
"code": null,
"e": 19819,
"s": 19750,
"text": "These functions will take care of dependency tracking automatically."
},
{
"code": null,
"e": 19888,
"s": 19819,
"text": "These functions will take care of dependency tracking automatically."
},
{
"code": null,
"e": 20043,
"s": 19888,
"text": "Syntax is easy to use. For example, to insert an element into an array, you just need to use arrayName.push('value') instead of arrayName().push('value')."
},
{
"code": null,
"e": 20198,
"s": 20043,
"text": "Syntax is easy to use. For example, to insert an element into an array, you just need to use arrayName.push('value') instead of arrayName().push('value')."
},
{
"code": null,
"e": 20257,
"s": 20198,
"text": "Following is the list of various Observable Array methods."
},
{
"code": null,
"e": 20297,
"s": 20257,
"text": "Inserts a new item at the end of array."
},
{
"code": null,
"e": 20350,
"s": 20297,
"text": "Removes the last item from the array and returns it."
},
{
"code": null,
"e": 20401,
"s": 20350,
"text": "Inserts a new value at the beginning of the array."
},
{
"code": null,
"e": 20455,
"s": 20401,
"text": "Removes the first item from the array and returns it."
},
{
"code": null,
"e": 20488,
"s": 20455,
"text": "Reverses the order of the array."
},
{
"code": null,
"e": 20529,
"s": 20488,
"text": "Sorts array items in an ascending order."
},
{
"code": null,
"e": 20657,
"s": 20529,
"text": "Accepts 2 parameters - start-index and end-index - removes items starting from start to end index and returns them as an array."
},
{
"code": null,
"e": 20736,
"s": 20657,
"text": "This function returns the index of the first occurrence of parameter provided."
},
{
"code": null,
"e": 20832,
"s": 20736,
"text": "This method slices out a piece of an array. Returns the items from start-index up to end-index."
},
{
"code": null,
"e": 20880,
"s": 20832,
"text": "Removes all items and returns them as an array."
},
{
"code": null,
"e": 20944,
"s": 20880,
"text": "Removes items that match the parameter and returns as an array."
},
{
"code": null,
"e": 21023,
"s": 20944,
"text": "Removes items which are satisfying the condition and returns them as an array."
},
{
"code": null,
"e": 21076,
"s": 21023,
"text": "Removes items that match with a given set of values."
},
{
"code": null,
"e": 21089,
"s": 21076,
"text": "destroyAll()"
},
{
"code": null,
"e": 21157,
"s": 21089,
"text": "Marks all items in an array with property _destroy with value true."
},
{
"code": null,
"e": 21174,
"s": 21157,
"text": "destroy('value')"
},
{
"code": null,
"e": 21280,
"s": 21174,
"text": "Searches for an item equal to the parameter and mark it with a special property _destroy with value true."
},
{
"code": null,
"e": 21317,
"s": 21280,
"text": "destroy(function(item) { condition})"
},
{
"code": null,
"e": 21420,
"s": 21317,
"text": "Finds all items which are satisfying the condition, marks them with property _destroy with true value."
},
{
"code": null,
"e": 21445,
"s": 21420,
"text": "destroy([set of values])"
},
{
"code": null,
"e": 21540,
"s": 21445,
"text": "Finds the items that match with a given set of values, marks them as _destroy with true value."
},
{
"code": null,
"e": 21650,
"s": 21540,
"text": "Note − Destroy and DestroyAll Functions from ObservableArrays are mostly for 'Ruby on Rails' developers only."
},
{
"code": null,
"e": 21956,
"s": 21650,
"text": "When you use destroy method, the corresponding items are not really deleted from array at that moment but are made hidden by marking them with property _destroy with true value so that they can't be read by UI. Items marked as _destroy equal to true are deleted later while dealing with JSON object graph."
},
{
"code": null,
"e": 22121,
"s": 21956,
"text": "Computed Observable is a function which is dependent on one or more Observables and automatically updates whenever its underlying Observables (dependencies) change."
},
{
"code": null,
"e": 22158,
"s": 22121,
"text": "Computed Observables can be chained."
},
{
"code": null,
"e": 22246,
"s": 22158,
"text": "this.varName = ko.computed(function(){\n ...\n ... // function code\n ...\n},this);\n"
},
{
"code": null,
"e": 22335,
"s": 22246,
"text": "Let us look at the following example which demonstrates the use of Computed Observables."
},
{
"code": null,
"e": 23351,
"s": 22335,
"text": "<!DOCTYPE html>\n <head >\n <title>KnockoutJS Computed Observables</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js\"></script>\n </head>\n\n <body>\n <p>Enter first number: <input data-bind = \"value: a\" /></p>\n <p>Enter second number: <input data-bind = \"value: b\"/></p>\n <p>Average := <span data-bind=\"text: totalAvg\"></span></p>\n\n <script>\n function MyViewModel() {\n this.a = ko.observable(10);\n this.b = ko.observable(40);\n\n this.totalAvg = ko.computed(function() {\n\n if(typeof(this.a()) !== \"number\" || typeof(this.b()) !== \"number\") {\n this.a(Number(this.a())); //convert string to Number\n this.b(Number(this.b())); //convert string to Number\n }\n\n total = (this.a() + this.b())/2 ;\n return total;\n },this);\n }\n\n ko.applyBindings(new MyViewModel());\n </script>\n\n </body>\n</html>"
},
{
"code": null,
"e": 23469,
"s": 23351,
"text": "In the following lines, first two are for accepting input values. Third line prints the average of these two numbers."
},
{
"code": null,
"e": 23650,
"s": 23469,
"text": "<p>Enter first number: <input data-bind = \"value: a\" /></p>\n<p>Enter second number: <input data-bind = \"value: b\"/></p>\n<p>Average := <span data-bind = \"text: totalAvg\"></span></p>"
},
{
"code": null,
"e": 23941,
"s": 23650,
"text": "In the following lines, type of Observables a and b is number when they are initialized for the first time inside ViewModel. However, in KO every input accepted from UI is by default in the String format. So they need to be converted to Number so as to perform arithmetic operation on them."
},
{
"code": null,
"e": 24252,
"s": 23941,
"text": "this.totalAvg = ko.computed(function() {\n \n if(typeof(this.a()) !== \"number\" || typeof(this.b()) !== \"number\") {\n this.a(Number(this.a())); //convert string to Number\n this.b(Number(this.b())); //convert string to Number\n }\n \n total = (this.a() + this.b())/2 ;\n return total;\n},this);"
},
{
"code": null,
"e": 24373,
"s": 24252,
"text": "In the following line, the calculated average is displayed in the UI. Note that data-bind type of totalAvg is just text."
},
{
"code": null,
"e": 24434,
"s": 24373,
"text": "<p>Average := <span data-bind = \"text: totalAvg\"></span></p>"
},
{
"code": null,
"e": 24504,
"s": 24434,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 24557,
"s": 24504,
"text": "Save the above code in computed-observable.htm file."
},
{
"code": null,
"e": 24610,
"s": 24557,
"text": "Save the above code in computed-observable.htm file."
},
{
"code": null,
"e": 24644,
"s": 24610,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 24678,
"s": 24644,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 24760,
"s": 24678,
"text": "Enter any 2 numbers in the text boxes and observe that the average is calculated."
},
{
"code": null,
"e": 24842,
"s": 24760,
"text": "Enter any 2 numbers in the text boxes and observe that the average is calculated."
},
{
"code": null,
"e": 24863,
"s": 24842,
"text": "Enter first number: "
},
{
"code": null,
"e": 24885,
"s": 24863,
"text": "Enter second number: "
},
{
"code": null,
"e": 24899,
"s": 24885,
"text": "Average := 25"
},
{
"code": null,
"e": 25073,
"s": 24899,
"text": "Note that in the above example, the second parameter is provided as this to Computed function. It is not possible to refer to Observables a() and b() without providing this."
},
{
"code": null,
"e": 25237,
"s": 25073,
"text": "To overcome this, self variable is used which holds the reference of this. Doing so, there is no need to track this throughout the code. Instead, self can be used."
},
{
"code": null,
"e": 25309,
"s": 25237,
"text": "Following ViewModel code is rewritten for the above example using self."
},
{
"code": null,
"e": 25750,
"s": 25309,
"text": "function MyViewModel(){\n self = this;\n self.a = ko.observable(10);\n self.b = ko.observable(40);\n\n this.totalAvg = ko.computed(function() {\n \n if(typeof(self.a()) !== \"number\" || typeof(self.b()) !== \"number\") {\n self.a(Number(self.a())); //convert string to Number\n self.b(Number(self.b())); //convert string to Number\n }\n \n total = (self.a() + self.b())/2 ;\n return total;\n });\n}"
},
{
"code": null,
"e": 26033,
"s": 25750,
"text": "A Computed Observable should be declared as Pure Computed Observable if that Observable is simply calculating and returning the value and not directly modifying the other objects or state. Pure Computed Observables helps Knockout to manage reevaluation and memory usage efficiently."
},
{
"code": null,
"e": 26337,
"s": 26033,
"text": "When a Computed Observable is returning primitive data type value (String, Boolean, Null, and Number) then its subscribers are notified if and only if the actual value change takes place. It means if an Observable has received the value same as the previous value, then its subscribers are not notified."
},
{
"code": null,
"e": 26499,
"s": 26337,
"text": "You can make Computed Observables always explicitly notify the observers, even though the new value is the same as the old by using the notify syntax as follows."
},
{
"code": null,
"e": 26627,
"s": 26499,
"text": "myViewModel.property = ko.pureComputed(function() {\n return ...; // code logic goes here\n}).extend({ notify: 'always' });\n"
},
{
"code": null,
"e": 26799,
"s": 26627,
"text": "Too many expensive updates can result in performance issues. You can limit the number of notifications to be received from Observable using rateLimit attribute as follows."
},
{
"code": null,
"e": 26924,
"s": 26799,
"text": "// make sure there are updates no more than once per 100-millisecond period\nmyViewModel.property.extend({ rateLimit: 100 });"
},
{
"code": null,
"e": 27091,
"s": 26924,
"text": "In certain situations, it might be necessary to find out if a property is a Computed Observable. Following functions can be used to identify the types of Observables."
},
{
"code": null,
"e": 27105,
"s": 27091,
"text": "ko.isComputed"
},
{
"code": null,
"e": 27158,
"s": 27105,
"text": "Returns true if the property is Computed Observable."
},
{
"code": null,
"e": 27174,
"s": 27158,
"text": "ko.isObservable"
},
{
"code": null,
"e": 27260,
"s": 27174,
"text": "Returns true if the property is Observable, Observable array, or Computed Observable."
},
{
"code": null,
"e": 27284,
"s": 27260,
"text": "ko.isWritableObservable"
},
{
"code": null,
"e": 27413,
"s": 27284,
"text": "Returns true if Observable, Observable array, or Writable Computed Observable. (This is also called as ko.isWriteableObservable)"
},
{
"code": null,
"e": 27653,
"s": 27413,
"text": "Computed Observable is derived from one or multiple other Observables, so it is read only. However, it is possible that one can make Computed Observable writable. For this you need to provide callback function that works on written values."
},
{
"code": null,
"e": 27816,
"s": 27653,
"text": "These writable Computed Observables work just like regular Observables. In addition, they require custom logic to be built for interfering read and write actions."
},
{
"code": null,
"e": 27930,
"s": 27816,
"text": "One can assign values to many Observables or Computed Observable properties using the chaining syntax as follows."
},
{
"code": null,
"e": 27973,
"s": 27930,
"text": "myViewModel.fullName('Tom Smith').age(45)\n"
},
{
"code": null,
"e": 28047,
"s": 27973,
"text": "Following example demonstrates the use of Writable Computable Observable."
},
{
"code": null,
"e": 29927,
"s": 28047,
"text": "<!DOCTYPE html>\n <head >\n <title>KnockoutJS Writable Computed Observable</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js\"></script>\n </head>\n\n <body>\n <p>Enter your birth Date: <input type = \"date\" data-bind = \"value: rawDate\" ></p>\n <p><span data-bind = \"text: yourAge\"></span></p>\n\n <script>\n function MyViewModel() {\n this.yourAge = ko.observable();\n today = new Date();\n rawDate = ko.observable();\n\n this.rawDate = ko.pureComputed ({\n\n read: function() {\n return this.yourAge;\n },\n\n write: function(value) {\n var b = Date.parse(value); // convert birth date into milliseconds\n var t = Date.parse(today); // convert todays date into milliseconds\n diff = t - b; // take difference\n var y = Math.floor(diff/31449600000); // difference is converted\n // into years. 31449600000\n //milliseconds form a year.\n\n var m = Math.floor((diff % 31449600000)/604800000/4.3); // calculating\n // months.\n // 604800000\n // milliseconds\n // form a week.\n\n this.yourAge(\"You are \" + y + \" year(s) \" + m +\" months old.\");\n },\n owner: this\n });\n }\n\n ko.applyBindings(new MyViewModel());\n </script>\n\n </body>\n</html>"
},
{
"code": null,
"e": 30041,
"s": 29927,
"text": "In the above code, rawDate is pureComputed property accepted from UI. yourAge Observable is derived from rawDate."
},
{
"code": null,
"e": 30252,
"s": 30041,
"text": "Dates in JavaScript are manipulated in milliseconds. Hence, both the dates (today date and birth date) are converted into milliseconds and then the difference between them is converted back in years and months."
},
{
"code": null,
"e": 30322,
"s": 30252,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 30384,
"s": 30322,
"text": "Save the above code in writable_computed_observable.htm file."
},
{
"code": null,
"e": 30446,
"s": 30384,
"text": "Save the above code in writable_computed_observable.htm file."
},
{
"code": null,
"e": 30480,
"s": 30446,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 30514,
"s": 30480,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 30575,
"s": 30514,
"text": "Enter any birth date and observe that the age is calculated."
},
{
"code": null,
"e": 30636,
"s": 30575,
"text": "Enter any birth date and observe that the age is calculated."
},
{
"code": null,
"e": 30661,
"s": 30636,
"text": "Enter your birth Date: "
},
{
"code": null,
"e": 30744,
"s": 30663,
"text": "Declarative binding in KnockoutJS provides a powerful way to connect data to UI."
},
{
"code": null,
"e": 30966,
"s": 30744,
"text": "It is important to understand the relationship between bindings and Observables. Technically, these two are different. You can use normal JavaScript object as ViewModel and KnockoutJS can process View's binding correctly."
},
{
"code": null,
"e": 31205,
"s": 30966,
"text": "Without Observable, the property from the UI will be processed only for the first time. In this case, it cannot update automatically based on the underlying data update. To achieve this, bindings must be referred to Observable properties."
},
{
"code": null,
"e": 31298,
"s": 31205,
"text": "The binding consists of 2 items, the binding name and value. Following is a simple example −"
},
{
"code": null,
"e": 31352,
"s": 31298,
"text": "Today is : <span data-bind = \"text: whatDay\"></span>\n"
},
{
"code": null,
"e": 31502,
"s": 31352,
"text": "Here, text is the binding name and whatDay is the binding value. You can have multiple bindings separated by comma, as shown in the following syntax."
},
{
"code": null,
"e": 31583,
"s": 31502,
"text": "Your name: <input data-bind = \"value: yourName, valueUpdate: 'afterkeydown'\" />\n"
},
{
"code": null,
"e": 31633,
"s": 31583,
"text": "Here, value is updated after each key is pressed."
},
{
"code": null,
"e": 31855,
"s": 31633,
"text": "The binding value can be a single value, literal, a variable or can be a JavaScript expression. If the binding refers to some invalid expression or reference, then KO will produce an error and stop processing the binding."
},
{
"code": null,
"e": 31895,
"s": 31855,
"text": "Following are few examples of bindings."
},
{
"code": null,
"e": 32239,
"s": 31895,
"text": "<!-- simple text binding -->\n<p>Enter employee name: <input -bind = 'value: empName' /></p>\n\n<!-- click binding, call a specific function -->\n<button data-bind=\"click: sortEmpArray\">Sort Array</button>\n\n<!-- options binding -->\n<select multiple = \"true\" size = \"8\" data-bind = \"options: empArray , \n selectedOptions: chosenItem\"> </select>"
},
{
"code": null,
"e": 32267,
"s": 32239,
"text": "Note the following points −"
},
{
"code": null,
"e": 32307,
"s": 32267,
"text": "Whitespaces do not make any difference."
},
{
"code": null,
"e": 32347,
"s": 32307,
"text": "Whitespaces do not make any difference."
},
{
"code": null,
"e": 32444,
"s": 32347,
"text": "Starting from KO 3.0, you can skip the binding value which will give binding an undefined value."
},
{
"code": null,
"e": 32541,
"s": 32444,
"text": "Starting from KO 3.0, you can skip the binding value which will give binding an undefined value."
},
{
"code": null,
"e": 32660,
"s": 32541,
"text": "The data that is being used in current bindings can be referenced by an object. This object is called binding context."
},
{
"code": null,
"e": 32809,
"s": 32660,
"text": "Context hierarchy is created and managed by KnockoutJS automatically. Following table lists the different types of binding contexts provided by KO. "
},
{
"code": null,
"e": 32815,
"s": 32809,
"text": "$root"
},
{
"code": null,
"e": 33002,
"s": 32815,
"text": "This always refers to top level ViewModel. This makes it possible to access top level methods for manipulating ViewModel. This is usually the object, which is passed to ko.applyBindings."
},
{
"code": null,
"e": 33008,
"s": 33002,
"text": "$data"
},
{
"code": null,
"e": 33157,
"s": 33008,
"text": "This property is lot like this keyword in Javascript object. $data property in a binding context refers to ViewModel object for the current context."
},
{
"code": null,
"e": 33164,
"s": 33157,
"text": "$index"
},
{
"code": null,
"e": 33412,
"s": 33164,
"text": "This property contains index of a current item of an array inside a foreach loop. The value of $index will change automatically as and when the underlying Observable array is updated. Obviously, this context is available only for foreach bindings."
},
{
"code": null,
"e": 33420,
"s": 33412,
"text": "$parent"
},
{
"code": null,
"e": 33565,
"s": 33420,
"text": "This property refers to parent ViewModel object. This is useful when you want to access outer ViewModel properties from inside of a nested loop."
},
{
"code": null,
"e": 33580,
"s": 33565,
"text": "$parentContext"
},
{
"code": null,
"e": 33852,
"s": 33580,
"text": "The context object which is bound at the parent level is called $parentContext. This is different from $parent. $parent refers to data. Whereas, $parentContext refers to binding context. E.g. you might need to access the index of outer foreach item from an inner context."
},
{
"code": null,
"e": 33861,
"s": 33852,
"text": "$rawdata"
},
{
"code": null,
"e": 34099,
"s": 33861,
"text": "This context holds raw ViewModel value in the current situation. This resembles $data but the difference is, if ViewModel is wrapped in Observable, then $data becomes just unwrapped. ViewModel and $rawdata becomes actual Observable data."
},
{
"code": null,
"e": 34110,
"s": 34099,
"text": "$component"
},
{
"code": null,
"e": 34337,
"s": 34110,
"text": "This context is used to refer to ViewModel of that component, when you are inside a particular component. E.g. you might want to access some property from ViewModel instead of current data in the template section of component."
},
{
"code": null,
"e": 34361,
"s": 34337,
"text": "$componentTemplateNodes"
},
{
"code": null,
"e": 34486,
"s": 34361,
"text": "This represents an array of DOM nodes passed to that particular component when you are within a specific component template."
},
{
"code": null,
"e": 34570,
"s": 34486,
"text": "Following terms are also available in binding but are not actually binding context."
},
{
"code": null,
"e": 34634,
"s": 34570,
"text": "$context − This is nothing but existing binding context object."
},
{
"code": null,
"e": 34698,
"s": 34634,
"text": "$context − This is nothing but existing binding context object."
},
{
"code": null,
"e": 34773,
"s": 34698,
"text": "$element − This object refers to an element in DOM in the current binding."
},
{
"code": null,
"e": 34848,
"s": 34773,
"text": "$element − This object refers to an element in DOM in the current binding."
},
{
"code": null,
"e": 34942,
"s": 34848,
"text": "Following is a list of binding types provided by KO to deal with text and visual appearances."
},
{
"code": null,
"e": 35008,
"s": 34942,
"text": "To show or hide HTML DOM element depending on certain conditions."
},
{
"code": null,
"e": 35051,
"s": 35008,
"text": "To set the content of an HTML DOM element."
},
{
"code": null,
"e": 35101,
"s": 35051,
"text": "To set the HTML markup contents of a DOM element."
},
{
"code": null,
"e": 35137,
"s": 35101,
"text": "To apply CSS classes to an element."
},
{
"code": null,
"e": 35189,
"s": 35137,
"text": "To define the inline style attribute of an element."
},
{
"code": null,
"e": 35234,
"s": 35189,
"text": "To add attributes to an element dynamically."
},
{
"code": null,
"e": 35300,
"s": 35234,
"text": "Following is a list of Control Flow Binding types provided by KO."
},
{
"code": null,
"e": 35373,
"s": 35300,
"text": "In this binding, each array item is referenced in HTML markup in a loop."
},
{
"code": null,
"e": 35480,
"s": 35373,
"text": "If the condition is true, then the given HTML markup will be processed. Else, it will be removed from DOM."
},
{
"code": null,
"e": 35603,
"s": 35480,
"text": "Negation of If. If the condition is true, then the given HTML markup will be processed. Else, it will be removed from DOM."
},
{
"code": null,
"e": 35699,
"s": 35603,
"text": "This binding is used to bind the child elements of an object in the specified object's context."
},
{
"code": null,
"e": 35796,
"s": 35699,
"text": "This binding is used to insert a component into DOM elements and pass the parameters optionally."
},
{
"code": null,
"e": 35863,
"s": 35796,
"text": "Following is the list of Form Fields Binding types provided by KO."
},
{
"code": null,
"e": 35964,
"s": 35863,
"text": "This binding is used to invoke a JavaScript function associated with a DOM element based on a click."
},
{
"code": null,
"e": 36076,
"s": 35964,
"text": "This binding is used to listen to the specified DOM events and call associated handler functions based on them."
},
{
"code": null,
"e": 36175,
"s": 36076,
"text": "This binding is used to invoke a JavaScript function when the associated DOM element is submitted."
},
{
"code": null,
"e": 36259,
"s": 36175,
"text": "This binding is used to enable certain DOM elements based on a specified condition."
},
{
"code": null,
"e": 36346,
"s": 36259,
"text": "This binding disables the associated DOM element when the parameter evaluates to true."
},
{
"code": null,
"e": 36431,
"s": 36346,
"text": "This binding is used to link respective DOM element's value into ViewModel property."
},
{
"code": null,
"e": 36529,
"s": 36431,
"text": "This binding is used to create 2-way binding between text box or textarea and ViewModel property."
},
{
"code": null,
"e": 36628,
"s": 36529,
"text": "This binding is used to manually set the focus of a HTML DOM element through a ViewModel property."
},
{
"code": null,
"e": 36723,
"s": 36628,
"text": "This binding is used to create a link between a checkable form element and ViewModel property."
},
{
"code": null,
"e": 36788,
"s": 36723,
"text": "This binding is used to define the options for a select element."
},
{
"code": null,
"e": 36895,
"s": 36788,
"text": "This binding is used to work with elements which are selected currently in multi list select form control."
},
{
"code": null,
"e": 36961,
"s": 36895,
"text": "This binding is used to generate a unique name for a DOM element."
},
{
"code": null,
"e": 37201,
"s": 36961,
"text": "KnockoutJs automatically tracks the dependencies when the values get updated. It has a single object called dependency tracker (ko.dependencyDetection) which acts as an intermediate between the two parties for subscribing the dependencies."
},
{
"code": null,
"e": 37253,
"s": 37201,
"text": "Following is the algorithm for dependency tracking."
},
{
"code": null,
"e": 37378,
"s": 37253,
"text": "Step 1 − Whenever you declare a computed observable, KO immediately invokes its evaluator function to get its initial value."
},
{
"code": null,
"e": 37534,
"s": 37378,
"text": "Step 2 − Subscription is set up to any observable that the evaluator reads. In an application, the old subscriptions which are no longer used are disposed."
},
{
"code": null,
"e": 37596,
"s": 37534,
"text": "Step 3 − KO finally notifies the updated computed observable."
},
{
"code": null,
"e": 37604,
"s": 37596,
"text": "Example"
},
{
"code": null,
"e": 38991,
"s": 37604,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>KnockoutJS How Dependency Tracking Works</title>\n <!-- CDN's-->\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js\"\n type = \"text/javascript\"></script>\n </head>\n \n <body>\n <div>\n <form data-bind = \"submit: addFruits\">\n <b>Add Fruits:</b>\n <input data-bind = 'value: fruitToAdd, valueUpdate: \"afterkeydown\"'/>\n <button type = \"submit\" data-bind = \"enable: fruitToAdd().length > 0\">Add</button>\n <p><b>Your fruits list:</b></p>\n <select multiple = \"multiple\" width = \"50\" data-bind = \"options: fruits\"> </select>\n </form>\n </div>\n \n <script>\n var Addfruit = function(fruits) {\n this.fruits = ko.observableArray(fruits);\n this.fruitToAdd = ko.observable(\"\");\n \n this.addFruits = function() {\n \n if (this.fruitToAdd() != \"\") {\n this.fruits.push(this.fruitToAdd()); // Adds a fruit\n this.fruitToAdd(\"\"); // Clears the text box\n }\n \n }.bind(this); // \"this\" is the view model\n };\n\n ko.applyBindings(new Addfruit([\"Apple\", \"Orange\", \"Banana\"]));\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 38998,
"s": 38991,
"text": "Output"
},
{
"code": null,
"e": 39068,
"s": 38998,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 39121,
"s": 39068,
"text": "Save the above code in dependency_tracking.htm file."
},
{
"code": null,
"e": 39174,
"s": 39121,
"text": "Save the above code in dependency_tracking.htm file."
},
{
"code": null,
"e": 39208,
"s": 39174,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 39242,
"s": 39208,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 39289,
"s": 39242,
"text": "Enter any fruit name and click the Add button."
},
{
"code": null,
"e": 39336,
"s": 39289,
"text": "Enter any fruit name and click the Add button."
},
{
"code": null,
"e": 39354,
"s": 39336,
"text": "Your fruits list:"
},
{
"code": null,
"e": 39515,
"s": 39354,
"text": "The Computed Observable can be accessed without creating a dependency, by using the peek function. It controls the Observable by updating the computed property."
},
{
"code": null,
"e": 39523,
"s": 39515,
"text": "Example"
},
{
"code": null,
"e": 40673,
"s": 39523,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>KnockoutJs Controlling Dependencies Using Peek</title>\n <!-- CDN's-->\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js\"\n type = \"text/javascript\"></script>\n </head>\n \n <body>\n <div class = \"logblock\">\n <h3>Computed Log</h3>\n <pre class = \"log\" data-bind = \"html: computedLog\"></pre>\n </div>\n\n <script>\n function AppData() {\n this.firstName = ko.observable('John');\n this.lastName = ko.observable('Burns');\n this.computedLog = ko.observable('Log: ');\n \n this.fullName = ko.computed(function () {\n var value = this.firstName() + \" \" + this.lastName();\n this.computedLog(this.computedLog.peek() + value + '; <br/>');\n return value;\n }, this);\n\n this.step = ko.observable(0);\n this.next = function () {\n this.step(this.step() === 2 ? 0 : this.step()+1);\n };\n };\n \n ko.applyBindings(new AppData());\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 40680,
"s": 40673,
"text": "Output"
},
{
"code": null,
"e": 40750,
"s": 40680,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 40808,
"s": 40750,
"text": "Save the above code in dependency_tracking_peek.htm file."
},
{
"code": null,
"e": 40866,
"s": 40808,
"text": "Save the above code in dependency_tracking_peek.htm file."
},
{
"code": null,
"e": 40900,
"s": 40866,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 40934,
"s": 40900,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 40952,
"s": 40934,
"text": "Log: John Burns; "
},
{
"code": null,
"e": 41107,
"s": 40952,
"text": "The ko.ignoreDependencies function helps ignore those dependencies that you don't want to track within the computed dependencies. Following is its syntax."
},
{
"code": null,
"e": 41173,
"s": 41107,
"text": "ko.ignoreDependencies( callback, callbackTarget, callbackArgs );\n"
},
{
"code": null,
"e": 41367,
"s": 41173,
"text": "If KO is evaluating a Computed Observable, then it will not restart an evaluation of the dependent Computed Observable. Hence, it doesn't make sense to include cycles in your dependency chains."
},
{
"code": null,
"e": 41551,
"s": 41367,
"text": "Template is a set of DOM elements which can be used repetitively. Templating makes it easy to build complex applications due to its property of minimizing duplication of DOM elements."
},
{
"code": null,
"e": 41591,
"s": 41551,
"text": "There are 2 ways of creating templates."
},
{
"code": null,
"e": 41842,
"s": 41591,
"text": "Native templating − This method supports the control flow bindings such as foreach, with, and if. These bindings capture HTML markup existing in the element and use it as template for random items. No external library is required for this templating."
},
{
"code": null,
"e": 42093,
"s": 41842,
"text": "Native templating − This method supports the control flow bindings such as foreach, with, and if. These bindings capture HTML markup existing in the element and use it as template for random items. No external library is required for this templating."
},
{
"code": null,
"e": 42292,
"s": 42093,
"text": "String-based templating − KO connects to the third party engine to pass ViewModel values into it and injects the resulting markup into the document. For example, JQuery.tmpl and Underscore Engine."
},
{
"code": null,
"e": 42491,
"s": 42292,
"text": "String-based templating − KO connects to the third party engine to pass ViewModel values into it and injects the resulting markup into the document. For example, JQuery.tmpl and Underscore Engine."
},
{
"code": null,
"e": 42498,
"s": 42491,
"text": "Syntax"
},
{
"code": null,
"e": 42641,
"s": 42498,
"text": "template: <parameter-value>\n\n<script type = \"text/html\" id = \"template-name\">\n ...\n ... // DOM elemets to be processed\n ...\n</script>\n"
},
{
"code": null,
"e": 42807,
"s": 42641,
"text": "Note that type is provided as text/html in the script block to notify KO that, it is not an executable block rather just a template block which needs to be rendered."
},
{
"code": null,
"e": 42818,
"s": 42807,
"text": "Parameters"
},
{
"code": null,
"e": 42902,
"s": 42818,
"text": "Combination of the following properties can be sent as parameter-value to template."
},
{
"code": null,
"e": 42951,
"s": 42902,
"text": "name − This represents the name of the template."
},
{
"code": null,
"e": 43000,
"s": 42951,
"text": "name − This represents the name of the template."
},
{
"code": null,
"e": 43133,
"s": 43000,
"text": "nodes − This represents an array of DOM nodes to be used as the template. This parameter is ignored if the name parameter is passed."
},
{
"code": null,
"e": 43266,
"s": 43133,
"text": "nodes − This represents an array of DOM nodes to be used as the template. This parameter is ignored if the name parameter is passed."
},
{
"code": null,
"e": 43328,
"s": 43266,
"text": "data − This is nothing but data to be shown via the template."
},
{
"code": null,
"e": 43390,
"s": 43328,
"text": "data − This is nothing but data to be shown via the template."
},
{
"code": null,
"e": 43478,
"s": 43390,
"text": "if − Template will be served if the given condition results in true or true-like value."
},
{
"code": null,
"e": 43566,
"s": 43478,
"text": "if − Template will be served if the given condition results in true or true-like value."
},
{
"code": null,
"e": 43613,
"s": 43566,
"text": "foreach − To serve template in foreach format."
},
{
"code": null,
"e": 43660,
"s": 43613,
"text": "foreach − To serve template in foreach format."
},
{
"code": null,
"e": 43717,
"s": 43660,
"text": "as − This is just to create an alias in foreach element."
},
{
"code": null,
"e": 43774,
"s": 43717,
"text": "as − This is just to create an alias in foreach element."
},
{
"code": null,
"e": 43911,
"s": 43774,
"text": "afterAdd, afterRender, beforeRemove − These are all to represent callable functions to be executed depending on the operation performed."
},
{
"code": null,
"e": 44048,
"s": 43911,
"text": "afterAdd, afterRender, beforeRemove − These are all to represent callable functions to be executed depending on the operation performed."
},
{
"code": null,
"e": 44255,
"s": 44048,
"text": "Templates are defined implicitly by HTML markup inside DOM when used with control flow bindings. However if you want to, you can factor out templates into a separate element and then reference them by name."
},
{
"code": null,
"e": 44263,
"s": 44255,
"text": "Example"
},
{
"code": null,
"e": 45543,
"s": 44263,
"text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS Templating - Named Template</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js\"\n type = \"text/javascript\"></script>\n </head>\n\n <body>\n <h2>Friends List</h2>\n Here are the Friends from your contact page:\n <div data-bind = \"template: { name: 'friend-template', data: friend1 }\"></div>\n <div data-bind = \"template: { name: 'friend-template', data: friend2 }\"></div>\n\n <script type = \"text/html\" id = \"friend-template\">\n <h3 data-bind = \"text: name\"></h3>\n <p>Contact Number: <span data-bind = \"text: contactNumber\"></span></p>\n <p>Email-id: <span data-bind = \"text: email\"></span></p>\n </script>\n\n <script type = \"text/javascript\">\n function MyViewModel() {\n this.friend1 = { \n name: 'Smith', \n contactNumber: 4556750345, \n email: '[email protected]' \n };\n \n this.friend2 = { \n name: 'Jack', \n contactNumber: 6789358001, \n email: '[email protected]' \n };\n }\n\n var vm = new MyViewModel();\n ko.applyBindings(vm);\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 45550,
"s": 45543,
"text": "Output"
},
{
"code": null,
"e": 45620,
"s": 45550,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 45668,
"s": 45620,
"text": "Save the above code in template-named.htm file."
},
{
"code": null,
"e": 45716,
"s": 45668,
"text": "Save the above code in template-named.htm file."
},
{
"code": null,
"e": 45750,
"s": 45716,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 45784,
"s": 45750,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 45823,
"s": 45784,
"text": "Here, friend-template is used 2 times."
},
{
"code": null,
"e": 45862,
"s": 45823,
"text": "Here, friend-template is used 2 times."
},
{
"code": null,
"e": 45889,
"s": 45862,
"text": "Contact Number: 4556750345"
},
{
"code": null,
"e": 45918,
"s": 45889,
"text": "Email-id: [email protected]"
},
{
"code": null,
"e": 45945,
"s": 45918,
"text": "Contact Number: 6789358001"
},
{
"code": null,
"e": 45973,
"s": 45945,
"text": "Email-id: [email protected]"
},
{
"code": null,
"e": 46054,
"s": 45973,
"text": "Following is an example of using foreach parameter along with the template name."
},
{
"code": null,
"e": 46062,
"s": 46054,
"text": "Example"
},
{
"code": null,
"e": 47243,
"s": 46062,
"text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS Templating - foreach used with Template</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js\"\n type = \"text/javascript\"></script>\n </head>\n\n <body>\n <h2>Friends List</h2>\n Here are the Friends from your contact page:\n <div data-bind = \"template: { name: 'friend-template', foreach: friends }\"></div>\n\n <script type = \"text/html\" id = \"friend-template\">\n <h3 data-bind = \"text: name\"></h3>\n <p>Contact Number: <span data-bind = \"text: contactNumber\"></span></p>\n <p>Email-id: <span data-bind = \"text: email\"></span></p>\n </script>\n\n <script type = \"text/javascript\">\n function MyViewModel() {\n this.friends = [\n { name: 'Smith', contactNumber: 4556750345, email: '[email protected]' },\n { name: 'Jack', contactNumber: 6789358001, email: '[email protected]' },\n { name: 'Lisa', contactNumber: 4567893131, email: '[email protected]' }\n ]\n }\n\n var vm = new MyViewModel();\n ko.applyBindings(vm);\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 47250,
"s": 47243,
"text": "Output"
},
{
"code": null,
"e": 47320,
"s": 47250,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 47370,
"s": 47320,
"text": "Save the above code in template-foreach.htm file."
},
{
"code": null,
"e": 47420,
"s": 47370,
"text": "Save the above code in template-foreach.htm file."
},
{
"code": null,
"e": 47454,
"s": 47420,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 47488,
"s": 47454,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 47539,
"s": 47488,
"text": "Here, foreach control is used in template binding."
},
{
"code": null,
"e": 47590,
"s": 47539,
"text": "Here, foreach control is used in template binding."
},
{
"code": null,
"e": 47617,
"s": 47590,
"text": "Contact Number: 4556750345"
},
{
"code": null,
"e": 47646,
"s": 47617,
"text": "Email-id: [email protected]"
},
{
"code": null,
"e": 47673,
"s": 47646,
"text": "Contact Number: 6789358001"
},
{
"code": null,
"e": 47701,
"s": 47673,
"text": "Email-id: [email protected]"
},
{
"code": null,
"e": 47728,
"s": 47701,
"text": "Contact Number: 4567893131"
},
{
"code": null,
"e": 47756,
"s": 47728,
"text": "Email-id: [email protected]"
},
{
"code": null,
"e": 47818,
"s": 47756,
"text": "Following is how an alias can be created for a foreach item −"
},
{
"code": null,
"e": 47925,
"s": 47818,
"text": "<div data-bind = \"template: { \n name: 'friend-template', \n foreach: friends, \n as: 'frnz' \n}\"></div>"
},
{
"code": null,
"e": 48095,
"s": 47925,
"text": "It becomes easy to refer to parent objects from inside of foreach loops by creating alias. This feature is useful when the code is complex and nested at multiple levels."
},
{
"code": null,
"e": 48103,
"s": 48095,
"text": "Example"
},
{
"code": null,
"e": 49995,
"s": 48103,
"text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS Templating - using alias in Template</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js\"\n type = \"text/javascript\"></script>\n </head>\n\n <body>\n <h2>Friends List</h2>\n Here are the Friends from your contact page:\n <ul data-bind = \"template: { \n name: 'friend-template', \n foreach: friends, \n as: 'frnz' \n }\"></ul>\n\n <script type = \"text/html\" id = \"friend-template\">\n <li>\n <h3 data-bind = \"text: name\"></h3>\n <span>Contact Numbers</span>\n <ul data-bind = \"template: { \n name : 'contacts-template', \n foreach:contactNumber, \n as: 'cont'\n } \"></ul>\n <p>Email-id: <span data-bind = \"text: email\"></span></p>\n </li>\n </script>\n\n <script type = \"text/html\" id = \"contacts-template\">\n <li>\n <p><span data-bind = \"text: cont\"></span></p>\n </li>\n </script>\n\n <script type = \"text/javascript\">\n function MyViewModel() {\n this.friends = ko.observableArray ( [\n { \n name: 'Smith', \n contactNumber: [ 4556750345, 4356787934 ], \n email: '[email protected]' \n },\n \n { \n name: 'Jack', \n contactNumber: [ 6789358001, 3456895445 ], \n email: '[email protected]' \n },\n \n { \n name: 'Lisa', \n contactNumber: [ 4567893131, 9876456783, 1349873445 ], \n email: '[email protected]' \n }\n ]);\n }\n\n var vm = new MyViewModel();\n ko.applyBindings(vm);\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 50002,
"s": 49995,
"text": "Output"
},
{
"code": null,
"e": 50072,
"s": 50002,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 50123,
"s": 50072,
"text": "Save the above code in template-as-alias.htm file."
},
{
"code": null,
"e": 50174,
"s": 50123,
"text": "Save the above code in template-as-alias.htm file."
},
{
"code": null,
"e": 50208,
"s": 50174,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 50242,
"s": 50208,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 50288,
"s": 50242,
"text": "Alias is used instead of full name of arrays."
},
{
"code": null,
"e": 50334,
"s": 50288,
"text": "Alias is used instead of full name of arrays."
},
{
"code": null,
"e": 50416,
"s": 50334,
"text": "\nSmith\nContact Numbers\n\n\n4556750345\n\n\n\n4356787934\n\n\nEmail-id: [email protected]\n"
},
{
"code": null,
"e": 50429,
"s": 50416,
"text": "\n4556750345\n"
},
{
"code": null,
"e": 50440,
"s": 50429,
"text": "4556750345"
},
{
"code": null,
"e": 50453,
"s": 50440,
"text": "\n4356787934\n"
},
{
"code": null,
"e": 50464,
"s": 50453,
"text": "4356787934"
},
{
"code": null,
"e": 50493,
"s": 50464,
"text": "Email-id: [email protected]"
},
{
"code": null,
"e": 50573,
"s": 50493,
"text": "\nJack\nContact Numbers\n\n\n6789358001\n\n\n\n3456895445\n\n\nEmail-id: [email protected]\n"
},
{
"code": null,
"e": 50586,
"s": 50573,
"text": "\n6789358001\n"
},
{
"code": null,
"e": 50597,
"s": 50586,
"text": "6789358001"
},
{
"code": null,
"e": 50610,
"s": 50597,
"text": "\n3456895445\n"
},
{
"code": null,
"e": 50621,
"s": 50610,
"text": "3456895445"
},
{
"code": null,
"e": 50649,
"s": 50621,
"text": "Email-id: [email protected]"
},
{
"code": null,
"e": 50743,
"s": 50649,
"text": "\nLisa\nContact Numbers\n\n\n4567893131\n\n\n\n9876456783\n\n\n\n1349873445\n\n\nEmail-id: [email protected]\n"
},
{
"code": null,
"e": 50756,
"s": 50743,
"text": "\n4567893131\n"
},
{
"code": null,
"e": 50767,
"s": 50756,
"text": "4567893131"
},
{
"code": null,
"e": 50780,
"s": 50767,
"text": "\n9876456783\n"
},
{
"code": null,
"e": 50791,
"s": 50780,
"text": "9876456783"
},
{
"code": null,
"e": 50804,
"s": 50791,
"text": "\n1349873445\n"
},
{
"code": null,
"e": 50815,
"s": 50804,
"text": "1349873445"
},
{
"code": null,
"e": 50843,
"s": 50815,
"text": "Email-id: [email protected]"
},
{
"code": null,
"e": 51046,
"s": 50843,
"text": "There are situations wherein extra custom logic needs to be run on DOM elements created by the template. In such case, following callbacks can be used. Consider that you are using foreach element then −"
},
{
"code": null,
"e": 51142,
"s": 51046,
"text": "afterAdd − This function is invoked when a new item is added to the array mentioned in foreach."
},
{
"code": null,
"e": 51248,
"s": 51142,
"text": "beforeRemove − This function is invoked just before removing the item from an array mentioned in foreach."
},
{
"code": null,
"e": 51368,
"s": 51248,
"text": "afterRender − Function mentioned here is invoked every time foreach is rendered and new entries are added to the array."
},
{
"code": null,
"e": 51376,
"s": 51368,
"text": "Example"
},
{
"code": null,
"e": 52988,
"s": 51376,
"text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS Templating - Use of afterRender Template</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js\"\n type = \"text/javascript\"></script>\n <script src = \"https://code.jquery.com/jquery-2.1.3.min.js\"\n type = \"text/javascript\"></script>\n </head>\n\n <body>\n <h2>Friends List</h2>\n Here are the Friends from your contact page:\n <div data-bind = \"template: { \n name: 'friend-template', \n foreach: friends , \n afterRender: afterProcess\n }\"></div>\n\n <script type = \"text/html\" id = \"friend-template\">\n <h3 data-bind = \"text: name\"></h3>\n <p>Contact Number: <span data-bind = \"text: contactNumber\"></span></p>\n <p>Email-id: <span data-bind = \"text: email\"></span></p>\n <button data-bind = \"click: $root.removeContact\">remove </button>\n </script>\n\n <script type = \"text/javascript\">\n function MyViewModel() {\n self = this;\n this.friends = ko.observableArray ([\n { name: 'Smith', contactNumber: 4556750345, email: '[email protected]' },\n { name: 'Jack', contactNumber: 6789358001, email: '[email protected]' },\n ])\n\n this.afterProcess = function(elements, data){\n $(elements).css({color: 'magenta' });\n }\n\n self.removeContact = function() {\n self.friends.remove(this);\n }\n }\n\n var vm = new MyViewModel();\n ko.applyBindings(vm);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 52995,
"s": 52988,
"text": "Output"
},
{
"code": null,
"e": 53065,
"s": 52995,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 53119,
"s": 53065,
"text": "Save the above code in template-afterrender.htm file."
},
{
"code": null,
"e": 53173,
"s": 53119,
"text": "Save the above code in template-afterrender.htm file."
},
{
"code": null,
"e": 53207,
"s": 53173,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 53241,
"s": 53207,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 53313,
"s": 53241,
"text": "Here, afterProcess function is executed every time foreach is rendered."
},
{
"code": null,
"e": 53385,
"s": 53313,
"text": "Here, afterProcess function is executed every time foreach is rendered."
},
{
"code": null,
"e": 53412,
"s": 53385,
"text": "Contact Number: 4556750345"
},
{
"code": null,
"e": 53441,
"s": 53412,
"text": "Email-id: [email protected]"
},
{
"code": null,
"e": 53468,
"s": 53441,
"text": "Contact Number: 6789358001"
},
{
"code": null,
"e": 53496,
"s": 53468,
"text": "Email-id: [email protected]"
},
{
"code": null,
"e": 53733,
"s": 53496,
"text": "If there are multiple templates available, then one can be chosen dynamically by making the name as observable parameter. Hence, the template value will be re-evaluated as the name parameter changes and in turn data will be re-rendered."
},
{
"code": null,
"e": 53741,
"s": 53733,
"text": "Example"
},
{
"code": null,
"e": 55376,
"s": 53741,
"text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS Templating - Dynamic Template</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js\"\n type = \"text/javascript\"></script>\n </head>\n \n <body>\n <h2>Friends List</h2>\n Here are the Friends from your contact page:\n <div data-bind = \"template: { \n name: whichTemplate, \n foreach: friends \n }\"></div>\n\n <script type = \"text/html\" id = \"only-phon\">\n <h3 data-bind = \"text: name\"></h3>\n <p>Contact Number: <span data-bind = \"text: contactNumber\"></span></p>\n </script>\n\n <script type = \"text/html\" id = \"only-email\">\n <h3 data-bind = \"text: name\"></h3>\n <p>Email-id: <span data-bind = \"text: email\"></span></p>\n </script>\n\n <script type = \"text/javascript\">\n function MyViewModel() {\n \n this.friends = ko.observableArray ([\n {\n name: 'Smith', \n contactNumber: 4556750345, \n email: '[email protected]', \n active: ko.observable(true)\n },\n \n {\n name: 'Jack', \n contactNumber: 6789358001, \n email: '[email protected]', \n active: ko.observable(false)\n },\n ]);\n\n this.whichTemplate = function(friends) {\n return friends.active() ? \"only-phon\" : \"only-email\";\n }\n }\n\n var vm = new MyViewModel();\n ko.applyBindings(vm);\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 55383,
"s": 55376,
"text": "Output"
},
{
"code": null,
"e": 55453,
"s": 55383,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 55503,
"s": 55453,
"text": "Save the above code in template-dynamic.htm file."
},
{
"code": null,
"e": 55553,
"s": 55503,
"text": "Save the above code in template-dynamic.htm file."
},
{
"code": null,
"e": 55587,
"s": 55553,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 55621,
"s": 55587,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 55688,
"s": 55621,
"text": "Template to be used is decided depending on the active flag value."
},
{
"code": null,
"e": 55755,
"s": 55688,
"text": "Template to be used is decided depending on the active flag value."
},
{
"code": null,
"e": 55782,
"s": 55755,
"text": "Contact Number: 4556750345"
},
{
"code": null,
"e": 55810,
"s": 55782,
"text": "Email-id: [email protected]"
},
{
"code": null,
"e": 56029,
"s": 55810,
"text": "Native templating works perfectly with various control flow elements even with nested code blocks. KO also offers a way to integrate with external templating library such as Underscore templating Engine or JQuery.tmpl."
},
{
"code": null,
"e": 56250,
"s": 56029,
"text": "As mentioned on the official site JQuery.tmpl is no longer under active development since December 2011. Hence, KO's native templating is only recommended instead of JQuery.tmpl or any other string-based template engine."
},
{
"code": null,
"e": 56310,
"s": 56250,
"text": "Please refer to the official site for more details on this."
},
{
"code": null,
"e": 56430,
"s": 56310,
"text": "Components are a huge way of organizing the UI code for structuring a large application and promoting code reusability."
},
{
"code": null,
"e": 56550,
"s": 56430,
"text": "It is inherited or nested from other component. For loading and configuration, it defines its own conventions or logic."
},
{
"code": null,
"e": 56733,
"s": 56550,
"text": "It is packaged to reuse throughout the application or the project. Represents the complete sections of application or small controls/widgets. It can be loaded or preloaded on demand."
},
{
"code": null,
"e": 56987,
"s": 56733,
"text": "Components can register using the ko.components.register() API. It helps to load and represent the components in KO. Component name with configuration is expected for registration. The configuration specifies how to determine the viewModel and template."
},
{
"code": null,
"e": 56994,
"s": 56987,
"text": "Syntax"
},
{
"code": null,
"e": 57036,
"s": 56994,
"text": "Components can be registered as follows −"
},
{
"code": null,
"e": 57159,
"s": 57036,
"text": "ko.components.register('component-name', {\n viewModel: {...}, //function code\n template: {....)\t//function code\n});"
},
{
"code": null,
"e": 57206,
"s": 57159,
"text": "The component-name can be any nonempty string."
},
{
"code": null,
"e": 57253,
"s": 57206,
"text": "The component-name can be any nonempty string."
},
{
"code": null,
"e": 57347,
"s": 57253,
"text": "viewModel is optional, and can take any of the viewModel formats listed in the next sections."
},
{
"code": null,
"e": 57441,
"s": 57347,
"text": "viewModel is optional, and can take any of the viewModel formats listed in the next sections."
},
{
"code": null,
"e": 57533,
"s": 57441,
"text": "template is required, and can take any of the template formats listed in the next sections."
},
{
"code": null,
"e": 57625,
"s": 57533,
"text": "template is required, and can take any of the template formats listed in the next sections."
},
{
"code": null,
"e": 57714,
"s": 57625,
"text": "Following table lists the viewModel formats that can be used to register the components."
},
{
"code": null,
"e": 57735,
"s": 57714,
"text": "constructor function"
},
{
"code": null,
"e": 57853,
"s": 57735,
"text": "It creates a separate viewModel object for each component. The object or function is used to bind in components view."
},
{
"code": null,
"e": 58040,
"s": 57853,
"text": "function SomeComponentViewModel(params) {\n this.someProperty = params.something;\n}\nko.components.register('component name', {\n viewModel: SomeComponentViewModel,\n template: ...\n});"
},
{
"code": null,
"e": 58063,
"s": 58040,
"text": "shared object instance"
},
{
"code": null,
"e": 58164,
"s": 58063,
"text": "The viewModel object instance is shared. The instance property is passed to use the object directly."
},
{
"code": null,
"e": 58321,
"s": 58164,
"text": "var sharedViewModelInstance = { ... };\n\nko.components.register('component name', {\n viewModel: { instance: sharedViewModelInstance },\n template: ...\n});"
},
{
"code": null,
"e": 58337,
"s": 58321,
"text": "createViewModel"
},
{
"code": null,
"e": 58438,
"s": 58337,
"text": "It calls a function which acts as a factory and can be used as view model that can return an object."
},
{
"code": null,
"e": 58653,
"s": 58438,
"text": "ko.components.register('component name', { \n viewModel: { \n createViewModel: function (params, componentInfo) { \n ... //function code \n ...\n } \n }, \n template: .... \n});"
},
{
"code": null,
"e": 58664,
"s": 58653,
"text": "AMD module"
},
{
"code": null,
"e": 58769,
"s": 58664,
"text": "It is a module format for defining modules where module and dependencies both are loaded asynchronously."
},
{
"code": null,
"e": 58991,
"s": 58769,
"text": "ko.components.register('component name', {\n viewModel: { require: 'some/module/name' },\n template: ...\n});\n\ndefine(['knockout'], function(ko) {\n function MyViewModel() {\n // ...\n }\n\n return MyViewModel;\n});"
},
{
"code": null,
"e": 59079,
"s": 58991,
"text": "Following table lists the template formats that can be used to register the components."
},
{
"code": null,
"e": 59090,
"s": 59079,
"text": "element ID"
},
{
"code": null,
"e": 59203,
"s": 59090,
"text": "ko.components.register('component name', {\n template: { element: 'component-template' },\n viewModel: ...\n});"
},
{
"code": null,
"e": 59220,
"s": 59203,
"text": "element instance"
},
{
"code": null,
"e": 59392,
"s": 59220,
"text": "var elemInstance = document.getElementById('component-template');\n\nko.components.register('component name', {\n template: { element: elemInstance },\n viewModel: ...\n});"
},
{
"code": null,
"e": 59409,
"s": 59392,
"text": "string of markup"
},
{
"code": null,
"e": 59591,
"s": 59409,
"text": "ko.components.register('component name', {\n template: '<input data-bind = \"value: yourName\" />\\\n <button data-bind = \"click: addEmp\">Add Emp </button>',\n viewModel: ...\n});"
},
{
"code": null,
"e": 59601,
"s": 59591,
"text": "DOM nodes"
},
{
"code": null,
"e": 59776,
"s": 59601,
"text": "var emp = [\n document.getElementById('node 1'),\n document.getElementById('node 2'),\n];\n\nko.components.register('component name', {\n template: emp,\n viewModel: ...\n});"
},
{
"code": null,
"e": 59795,
"s": 59776,
"text": "document fragement"
},
{
"code": null,
"e": 59903,
"s": 59795,
"text": "ko.components.register('component name', {\n template: someDocumentFragmentInstance,\n viewModel: ...\n});"
},
{
"code": null,
"e": 59914,
"s": 59903,
"text": "AMD module"
},
{
"code": null,
"e": 60022,
"s": 59914,
"text": "ko.components.register('component name', {\n template: { require: 'some/template' },\n viewModel: ...\n});"
},
{
"code": null,
"e": 60111,
"s": 60022,
"text": "The AMD module can register a component by itself without using viewModel/template pair."
},
{
"code": null,
"e": 60179,
"s": 60111,
"text": "ko.components.register('component name',{ require: 'some/module'});"
},
{
"code": null,
"e": 60220,
"s": 60179,
"text": "There are two ways of component binding."
},
{
"code": null,
"e": 60438,
"s": 60220,
"text": "Full syntax − It passes the parameter and object to the component. It can pass using the following properties.\n\nname − It adds the component name.\nparams − It can pass multiple parameters in object on the component.\n\n"
},
{
"code": null,
"e": 60549,
"s": 60438,
"text": "Full syntax − It passes the parameter and object to the component. It can pass using the following properties."
},
{
"code": null,
"e": 60584,
"s": 60549,
"text": "name − It adds the component name."
},
{
"code": null,
"e": 60619,
"s": 60584,
"text": "name − It adds the component name."
},
{
"code": null,
"e": 60688,
"s": 60619,
"text": "params − It can pass multiple parameters in object on the component."
},
{
"code": null,
"e": 60757,
"s": 60688,
"text": "params − It can pass multiple parameters in object on the component."
},
{
"code": null,
"e": 60883,
"s": 60757,
"text": "<div data-bind='component: {\n name: \"tutorials point\",\n params: { mode: \"detailed-list\", items: productsList }\n}'>\n</div>"
},
{
"code": null,
"e": 60984,
"s": 60883,
"text": "Shorthand syntax − It passes the string as a component name and it does not include parameter in it."
},
{
"code": null,
"e": 61085,
"s": 60984,
"text": "Shorthand syntax − It passes the string as a component name and it does not include parameter in it."
},
{
"code": null,
"e": 61140,
"s": 61085,
"text": "<div data-bind = 'component: \"component name\"'></div>\n"
},
{
"code": null,
"e": 61236,
"s": 61140,
"text": "Template-only components − Components can only define template without specifing the viewModel."
},
{
"code": null,
"e": 61332,
"s": 61236,
"text": "Template-only components − Components can only define template without specifing the viewModel."
},
{
"code": null,
"e": 61433,
"s": 61332,
"text": "ko.components.register('component name', {\n template:'<input data-bind = \"value: someName\" />,\n});"
},
{
"code": null,
"e": 61628,
"s": 61433,
"text": "Using Component without a container element − Components can be used without using extra container element. This can be done using containerless flow control which is similar as the comment tag."
},
{
"code": null,
"e": 61823,
"s": 61628,
"text": "Using Component without a container element − Components can be used without using extra container element. This can be done using containerless flow control which is similar as the comment tag."
},
{
"code": null,
"e": 61859,
"s": 61823,
"text": "<!--ko.component: \"\"-->\n<!--/ko-->\n"
},
{
"code": null,
"e": 62056,
"s": 61859,
"text": "Custom element is a way for rendering a component. Here, you can directly write a selfdescriptive markup element name instead of defining a placeholder, where the components are binded through it."
},
{
"code": null,
"e": 62130,
"s": 62056,
"text": "<products-list params = \"name: userName, type: userType\"></products-list>"
},
{
"code": null,
"e": 62452,
"s": 62130,
"text": "params attribute is used to pass the parameter to component viewModel. It is similar to data-bind attribute. The contents of the params attribute are interpreted like a JavaScript object literal (just like a data-bind attribute), so you can pass arbitrary values of any type. It can pass the parameter in following ways −"
},
{
"code": null,
"e": 62830,
"s": 62452,
"text": "Communication between parent and child components − The component is not instantiated by itself so the viewmodel properties are referred from outside of the component and thus would be received by child component viewmodel. For example, you can see in the following syntax that ModelValue is the parent viewmodel, which is received by child viewModel constructor ModelProperty."
},
{
"code": null,
"e": 63208,
"s": 62830,
"text": "Communication between parent and child components − The component is not instantiated by itself so the viewmodel properties are referred from outside of the component and thus would be received by child component viewmodel. For example, you can see in the following syntax that ModelValue is the parent viewmodel, which is received by child viewModel constructor ModelProperty."
},
{
"code": null,
"e": 63724,
"s": 63208,
"text": "Passing observable expressions − It has three values in params parameter.\n\nsimpleExpression − It is a numeric value. It does not involve any observables.\nsimpleObservable − It is an instance that is defined on parent viewModel. The parent viewModel will automatically get the changes on observable done by child viewModel.\nobservableExpression − Expression reads the observable when the expression is evaluated by itself. When the observable value changes, then the result of expression can also changs over time.\n\n"
},
{
"code": null,
"e": 63798,
"s": 63724,
"text": "Passing observable expressions − It has three values in params parameter."
},
{
"code": null,
"e": 63877,
"s": 63798,
"text": "simpleExpression − It is a numeric value. It does not involve any observables."
},
{
"code": null,
"e": 63956,
"s": 63877,
"text": "simpleExpression − It is a numeric value. It does not involve any observables."
},
{
"code": null,
"e": 64125,
"s": 63956,
"text": "simpleObservable − It is an instance that is defined on parent viewModel. The parent viewModel will automatically get the changes on observable done by child viewModel."
},
{
"code": null,
"e": 64294,
"s": 64125,
"text": "simpleObservable − It is an instance that is defined on parent viewModel. The parent viewModel will automatically get the changes on observable done by child viewModel."
},
{
"code": null,
"e": 64485,
"s": 64294,
"text": "observableExpression − Expression reads the observable when the expression is evaluated by itself. When the observable value changes, then the result of expression can also changs over time."
},
{
"code": null,
"e": 64676,
"s": 64485,
"text": "observableExpression − Expression reads the observable when the expression is evaluated by itself. When the observable value changes, then the result of expression can also changs over time."
},
{
"code": null,
"e": 64716,
"s": 64676,
"text": "We can pass the parameters as follows −"
},
{
"code": null,
"e": 64875,
"s": 64716,
"text": "<some-component\n params = 'simpleExpression: 1 + 1,\n simpleObservable: myObservable,\n observableExpression: myObservable() + 1'>\n</some-component>"
},
{
"code": null,
"e": 64928,
"s": 64875,
"text": "We can pass the parameters in viewModel as follows −"
},
{
"code": null,
"e": 65142,
"s": 64928,
"text": "<some-component\n params = 'objectValue:{a: 3, b: 2},\n dateValue: new date(),\n stringValue: \"Hi\",\n numericValue:123,\n boolValue: true/false,\n ModelProperty: ModelValue'>\n</some-component>"
},
{
"code": null,
"e": 65309,
"s": 65142,
"text": "The received markup is used to create a component and is selected as a part of the output. Following nodes are passed as part of the output in the component template."
},
{
"code": null,
"e": 65354,
"s": 65309,
"text": "template: { nodes: $componentTemplateNodes }"
},
{
"code": null,
"e": 65592,
"s": 65354,
"text": "The names which you register in the components using ko.components.register, the same name corresponds to the custom element tag names. We can change the custom element tag names by overriding it to control using getComponentNameForNode."
},
{
"code": null,
"e": 65690,
"s": 65592,
"text": "ko.components.getComponentNameForNode = function(node) {\n ...\n ... //function code\n ...\n}"
},
{
"code": null,
"e": 66162,
"s": 65690,
"text": "The custom elements can be made available immediately, if the default component loader is used and hence the component is registered using ko.components.register. If we are not using the ko.components.register and implementing the custom component loader, then the custom element can be used by defining any element name of choice. There is no need to specify configuration when you are using ko.components.register as the custom component loader does not use it anymore."
},
{
"code": null,
"e": 66220,
"s": 66162,
"text": "ko.components.register('custom-element', { ......... });\n"
},
{
"code": null,
"e": 66228,
"s": 66220,
"text": "Example"
},
{
"code": null,
"e": 67813,
"s": 66228,
"text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS Components</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"></script>\n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js\"></script>\n </head>\n \n <body>\n <!--params attribute is used to pass the parameter to component viewModel.-->\n <click params = \"a: a, b: b\"></click>\n\n <!--template is used for a component by specifying its ID -->\n <template id = \"click-l\">\n <div data-bind = \"text: a\"></div>\n\n <!--Use data-bind attribute to bind click:function() to ViewModel. -->\n <button data-bind = \"click:function(){callback(1)}\">Increase</button>\n <button data-bind = \"click:function(){callback(-1)}\">Decrease</button>\n </template>\n\n <script>\n //Here components are registered\n ko.components.register('click', {\n \n viewModel: function(params) {\n self = this;\n this.a = params.a;\n this.b = params.b;\n\n this.callback = function(num) {\n self.b(parseInt(num));\n self.a( self.a() + parseInt(num) );\n };\n },\n template: { element: 'click-l' }\n });\n\n //keeps an eye on variable for any modification in data\n function viewModel() {\n this.a = ko.observable(2);\n this.b = ko.observable(0);\n }\n\n ko.applyBindings(new viewModel() );\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 67820,
"s": 67813,
"text": "Output"
},
{
"code": null,
"e": 67890,
"s": 67820,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 67942,
"s": 67890,
"text": "Save the above code in component_register.htm file."
},
{
"code": null,
"e": 67994,
"s": 67942,
"text": "Save the above code in component_register.htm file."
},
{
"code": null,
"e": 68028,
"s": 67994,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 68062,
"s": 68028,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 68170,
"s": 68062,
"text": "Component loaders are used to pass the template/viewModel pair asynchronously for the given component name."
},
{
"code": null,
"e": 68308,
"s": 68170,
"text": "The default component loader depends on the explicitly registered configuration. Each component is registered before using the component."
},
{
"code": null,
"e": 68336,
"s": 68308,
"text": "ko.components.defaultLoader"
},
{
"code": null,
"e": 68415,
"s": 68336,
"text": "The default component loader can read and write using the following functions."
},
{
"code": null,
"e": 68459,
"s": 68415,
"text": "ko.components.register(name, configuration)"
},
{
"code": null,
"e": 68484,
"s": 68459,
"text": "Component is registered."
},
{
"code": null,
"e": 68517,
"s": 68484,
"text": "ko.components.isRegistered(name)"
},
{
"code": null,
"e": 68609,
"s": 68517,
"text": "If the particular component name is already registered, then it returns as true else false."
},
{
"code": null,
"e": 68640,
"s": 68609,
"text": "ko.components.unregister(name)"
},
{
"code": null,
"e": 68689,
"s": 68640,
"text": "The component name is removed from the registry."
},
{
"code": null,
"e": 68723,
"s": 68689,
"text": "ko.components.get(name, callback)"
},
{
"code": null,
"e": 69038,
"s": 68723,
"text": "This function goes turn by turn to each registered loader to find who has passed the viewModel/template definition for component name as first. Then it returns viewModel/template declaration by invoking callback. If the registered loader could not find anything about the component, then it invokes callback(null)."
},
{
"code": null,
"e": 69080,
"s": 69038,
"text": "ko.components.clearCachedDefinition(name)"
},
{
"code": null,
"e": 69238,
"s": 69080,
"text": "This function can be called when we want to clear the given component cache entry. If the component is needed next time, again the loaders will be consulted."
},
{
"code": null,
"e": 69309,
"s": 69238,
"text": "The custom component loader can be implemented in the following ways −"
},
{
"code": null,
"e": 69558,
"s": 69309,
"text": "getConfig(name, callback) − Depending on the names, we can pass configurations programatically. We can call callback(componentConfig) to pass the configurations, where the object componentConfig can be used by the loadComponent or any other loader."
},
{
"code": null,
"e": 69807,
"s": 69558,
"text": "getConfig(name, callback) − Depending on the names, we can pass configurations programatically. We can call callback(componentConfig) to pass the configurations, where the object componentConfig can be used by the loadComponent or any other loader."
},
{
"code": null,
"e": 70286,
"s": 69807,
"text": "loadComponent(name, componentConfig, callback) − This function resolves the viewModel and the template portion of config depending upon the way it is configured. We can call callback(result) to pass the viewmodel/template pair, where the object result is defined by the following properties.\n\ntemplate − Required. Return array of DOM nodes.\ncreateViewModel(params, componentInfo) − Optional. Returns the viewModel Object depending on how the viewModel property was configured.\n\n"
},
{
"code": null,
"e": 70578,
"s": 70286,
"text": "loadComponent(name, componentConfig, callback) − This function resolves the viewModel and the template portion of config depending upon the way it is configured. We can call callback(result) to pass the viewmodel/template pair, where the object result is defined by the following properties."
},
{
"code": null,
"e": 70626,
"s": 70578,
"text": "template − Required. Return array of DOM nodes."
},
{
"code": null,
"e": 70674,
"s": 70626,
"text": "template − Required. Return array of DOM nodes."
},
{
"code": null,
"e": 70810,
"s": 70674,
"text": "createViewModel(params, componentInfo) − Optional. Returns the viewModel Object depending on how the viewModel property was configured."
},
{
"code": null,
"e": 70946,
"s": 70810,
"text": "createViewModel(params, componentInfo) − Optional. Returns the viewModel Object depending on how the viewModel property was configured."
},
{
"code": null,
"e": 71199,
"s": 70946,
"text": "loadTemplate(name, templateConfig, callback) − DOM nodes is passed in a template using custom logic. The object templateConfig is a property of the template from an object componentConfig. callback(domNodeArray) is called to pass an array of DOM nodes."
},
{
"code": null,
"e": 71452,
"s": 71199,
"text": "loadTemplate(name, templateConfig, callback) − DOM nodes is passed in a template using custom logic. The object templateConfig is a property of the template from an object componentConfig. callback(domNodeArray) is called to pass an array of DOM nodes."
},
{
"code": null,
"e": 71577,
"s": 71452,
"text": "loadViewModel(name, templateConfig, callback) − viewModel factory is passed in a viewModel configuration using custom logic."
}
] |
Implementing Agglomerative Clustering using Sklearn
|
21 Jun, 2022
Prerequisites: Agglomerative Clustering Agglomerative Clustering is one of the most common hierarchical clustering techniques. Dataset – Credit Card Dataset. Assumption: The clustering technique assumes that each data point is similar enough to the other data points that the data at the starting can be assumed to be clustered in 1 cluster. Step 1: Importing the required libraries
Python3
import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.decomposition import PCAfrom sklearn.cluster import AgglomerativeClusteringfrom sklearn.preprocessing import StandardScaler, normalizefrom sklearn.metrics import silhouette_scoreimport scipy.cluster.hierarchy as shc
Step 2: Loading and Cleaning the data
Python3
# Changing the working location to the location of the filecd C:\Users\Dev\Desktop\Kaggle\Credit_Card X = pd.read_csv('CC_GENERAL.csv') # Dropping the CUST_ID column from the dataX = X.drop('CUST_ID', axis = 1) # Handling the missing valuesX.fillna(method ='ffill', inplace = True)
Step 3: Preprocessing the data
Python3
# Scaling the data so that all the features become comparablescaler = StandardScaler()X_scaled = scaler.fit_transform(X) # Normalizing the data so that the data approximately# follows a Gaussian distributionX_normalized = normalize(X_scaled) # Converting the numpy array into a pandas DataFrameX_normalized = pd.DataFrame(X_normalized)
Step 4: Reducing the dimensionality of the Data
Python3
pca = PCA(n_components = 2)X_principal = pca.fit_transform(X_normalized)X_principal = pd.DataFrame(X_principal)X_principal.columns = ['P1', 'P2']
Dendrograms are used to divide a given cluster into many different clusters. Step 5: Visualizing the working of the Dendrograms
Python3
plt.figure(figsize =(8, 8))plt.title('Visualising the data')Dendrogram = shc.dendrogram((shc.linkage(X_principal, method ='ward')))
To determine the optimal number of clusters by visualizing the data, imagine all the horizontal lines as being completely horizontal and then after calculating the maximum distance between any two horizontal lines, draw a horizontal line in the maximum distance calculated. The above image shows that the optimal number of clusters should be 2 for the given data. Step 6: Building and Visualizing the different clustering models for different values of k a) k = 2
Python3
ac2 = AgglomerativeClustering(n_clusters = 2) # Visualizing the clusteringplt.figure(figsize =(6, 6))plt.scatter(X_principal['P1'], X_principal['P2'], c = ac2.fit_predict(X_principal), cmap ='rainbow')plt.show()
b) k = 3
Python3
ac3 = AgglomerativeClustering(n_clusters = 3) plt.figure(figsize =(6, 6))plt.scatter(X_principal['P1'], X_principal['P2'], c = ac3.fit_predict(X_principal), cmap ='rainbow')plt.show()
c) k = 4
Python3
ac4 = AgglomerativeClustering(n_clusters = 4) plt.figure(figsize =(6, 6))plt.scatter(X_principal['P1'], X_principal['P2'], c = ac4.fit_predict(X_principal), cmap ='rainbow')plt.show()
d) k = 5
Python3
ac5 = AgglomerativeClustering(n_clusters = 5) plt.figure(figsize =(6, 6))plt.scatter(X_principal['P1'], X_principal['P2'], c = ac5.fit_predict(X_principal), cmap ='rainbow')plt.show()
e) k = 6
Python3
ac6 = AgglomerativeClustering(n_clusters = 6) plt.figure(figsize =(6, 6))plt.scatter(X_principal['P1'], X_principal['P2'], c = ac6.fit_predict(X_principal), cmap ='rainbow')plt.show()
We now determine the optimal number of clusters using a mathematical technique. Here, We will use the Silhouette Scores for the purpose. Step 7: Evaluating the different models and Visualizing the results.
Python3
k = [2, 3, 4, 5, 6] # Appending the silhouette scores of the different models to the listsilhouette_scores = []silhouette_scores.append( silhouette_score(X_principal, ac2.fit_predict(X_principal)))silhouette_scores.append( silhouette_score(X_principal, ac3.fit_predict(X_principal)))silhouette_scores.append( silhouette_score(X_principal, ac4.fit_predict(X_principal)))silhouette_scores.append( silhouette_score(X_principal, ac5.fit_predict(X_principal)))silhouette_scores.append( silhouette_score(X_principal, ac6.fit_predict(X_principal))) # Plotting a bar graph to compare the resultsplt.bar(k, silhouette_scores)plt.xlabel('Number of clusters', fontsize = 20)plt.ylabel('S(i)', fontsize = 20)plt.show()
Thus, with the help of the silhouette scores, it is concluded that the optimal number of clusters for the given data and clustering technique is 2.
rkbhola5
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Search Algorithms in AI
Decision Tree Introduction with example
ML | Monte Carlo Tree Search (MCTS)
Introduction to Recurrent Neural Network
Getting started with Machine Learning
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": 54,
"s": 26,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 438,
"s": 54,
"text": "Prerequisites: Agglomerative Clustering Agglomerative Clustering is one of the most common hierarchical clustering techniques. Dataset – Credit Card Dataset. Assumption: The clustering technique assumes that each data point is similar enough to the other data points that the data at the starting can be assumed to be clustered in 1 cluster. Step 1: Importing the required libraries "
},
{
"code": null,
"e": 446,
"s": 438,
"text": "Python3"
},
{
"code": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.decomposition import PCAfrom sklearn.cluster import AgglomerativeClusteringfrom sklearn.preprocessing import StandardScaler, normalizefrom sklearn.metrics import silhouette_scoreimport scipy.cluster.hierarchy as shc",
"e": 743,
"s": 446,
"text": null
},
{
"code": null,
"e": 782,
"s": 743,
"text": "Step 2: Loading and Cleaning the data "
},
{
"code": null,
"e": 790,
"s": 782,
"text": "Python3"
},
{
"code": "# Changing the working location to the location of the filecd C:\\Users\\Dev\\Desktop\\Kaggle\\Credit_Card X = pd.read_csv('CC_GENERAL.csv') # Dropping the CUST_ID column from the dataX = X.drop('CUST_ID', axis = 1) # Handling the missing valuesX.fillna(method ='ffill', inplace = True)",
"e": 1072,
"s": 790,
"text": null
},
{
"code": null,
"e": 1104,
"s": 1072,
"text": "Step 3: Preprocessing the data "
},
{
"code": null,
"e": 1112,
"s": 1104,
"text": "Python3"
},
{
"code": "# Scaling the data so that all the features become comparablescaler = StandardScaler()X_scaled = scaler.fit_transform(X) # Normalizing the data so that the data approximately# follows a Gaussian distributionX_normalized = normalize(X_scaled) # Converting the numpy array into a pandas DataFrameX_normalized = pd.DataFrame(X_normalized)",
"e": 1448,
"s": 1112,
"text": null
},
{
"code": null,
"e": 1497,
"s": 1448,
"text": "Step 4: Reducing the dimensionality of the Data "
},
{
"code": null,
"e": 1505,
"s": 1497,
"text": "Python3"
},
{
"code": "pca = PCA(n_components = 2)X_principal = pca.fit_transform(X_normalized)X_principal = pd.DataFrame(X_principal)X_principal.columns = ['P1', 'P2']",
"e": 1651,
"s": 1505,
"text": null
},
{
"code": null,
"e": 1780,
"s": 1651,
"text": "Dendrograms are used to divide a given cluster into many different clusters. Step 5: Visualizing the working of the Dendrograms "
},
{
"code": null,
"e": 1788,
"s": 1780,
"text": "Python3"
},
{
"code": "plt.figure(figsize =(8, 8))plt.title('Visualising the data')Dendrogram = shc.dendrogram((shc.linkage(X_principal, method ='ward')))",
"e": 1920,
"s": 1788,
"text": null
},
{
"code": null,
"e": 2387,
"s": 1920,
"text": " To determine the optimal number of clusters by visualizing the data, imagine all the horizontal lines as being completely horizontal and then after calculating the maximum distance between any two horizontal lines, draw a horizontal line in the maximum distance calculated. The above image shows that the optimal number of clusters should be 2 for the given data. Step 6: Building and Visualizing the different clustering models for different values of k a) k = 2 "
},
{
"code": null,
"e": 2395,
"s": 2387,
"text": "Python3"
},
{
"code": "ac2 = AgglomerativeClustering(n_clusters = 2) # Visualizing the clusteringplt.figure(figsize =(6, 6))plt.scatter(X_principal['P1'], X_principal['P2'], c = ac2.fit_predict(X_principal), cmap ='rainbow')plt.show()",
"e": 2617,
"s": 2395,
"text": null
},
{
"code": null,
"e": 2628,
"s": 2617,
"text": " b) k = 3 "
},
{
"code": null,
"e": 2636,
"s": 2628,
"text": "Python3"
},
{
"code": "ac3 = AgglomerativeClustering(n_clusters = 3) plt.figure(figsize =(6, 6))plt.scatter(X_principal['P1'], X_principal['P2'], c = ac3.fit_predict(X_principal), cmap ='rainbow')plt.show()",
"e": 2830,
"s": 2636,
"text": null
},
{
"code": null,
"e": 2841,
"s": 2830,
"text": " c) k = 4 "
},
{
"code": null,
"e": 2849,
"s": 2841,
"text": "Python3"
},
{
"code": "ac4 = AgglomerativeClustering(n_clusters = 4) plt.figure(figsize =(6, 6))plt.scatter(X_principal['P1'], X_principal['P2'], c = ac4.fit_predict(X_principal), cmap ='rainbow')plt.show()",
"e": 3044,
"s": 2849,
"text": null
},
{
"code": null,
"e": 3055,
"s": 3044,
"text": " d) k = 5 "
},
{
"code": null,
"e": 3063,
"s": 3055,
"text": "Python3"
},
{
"code": "ac5 = AgglomerativeClustering(n_clusters = 5) plt.figure(figsize =(6, 6))plt.scatter(X_principal['P1'], X_principal['P2'], c = ac5.fit_predict(X_principal), cmap ='rainbow')plt.show()",
"e": 3258,
"s": 3063,
"text": null
},
{
"code": null,
"e": 3269,
"s": 3258,
"text": " e) k = 6 "
},
{
"code": null,
"e": 3277,
"s": 3269,
"text": "Python3"
},
{
"code": "ac6 = AgglomerativeClustering(n_clusters = 6) plt.figure(figsize =(6, 6))plt.scatter(X_principal['P1'], X_principal['P2'], c = ac6.fit_predict(X_principal), cmap ='rainbow')plt.show()",
"e": 3472,
"s": 3277,
"text": null
},
{
"code": null,
"e": 3680,
"s": 3472,
"text": " We now determine the optimal number of clusters using a mathematical technique. Here, We will use the Silhouette Scores for the purpose. Step 7: Evaluating the different models and Visualizing the results. "
},
{
"code": null,
"e": 3688,
"s": 3680,
"text": "Python3"
},
{
"code": "k = [2, 3, 4, 5, 6] # Appending the silhouette scores of the different models to the listsilhouette_scores = []silhouette_scores.append( silhouette_score(X_principal, ac2.fit_predict(X_principal)))silhouette_scores.append( silhouette_score(X_principal, ac3.fit_predict(X_principal)))silhouette_scores.append( silhouette_score(X_principal, ac4.fit_predict(X_principal)))silhouette_scores.append( silhouette_score(X_principal, ac5.fit_predict(X_principal)))silhouette_scores.append( silhouette_score(X_principal, ac6.fit_predict(X_principal))) # Plotting a bar graph to compare the resultsplt.bar(k, silhouette_scores)plt.xlabel('Number of clusters', fontsize = 20)plt.ylabel('S(i)', fontsize = 20)plt.show()",
"e": 4430,
"s": 3688,
"text": null
},
{
"code": null,
"e": 4579,
"s": 4430,
"text": " Thus, with the help of the silhouette scores, it is concluded that the optimal number of clusters for the given data and clustering technique is 2."
},
{
"code": null,
"e": 4588,
"s": 4579,
"text": "rkbhola5"
},
{
"code": null,
"e": 4605,
"s": 4588,
"text": "Machine Learning"
},
{
"code": null,
"e": 4612,
"s": 4605,
"text": "Python"
},
{
"code": null,
"e": 4629,
"s": 4612,
"text": "Machine Learning"
},
{
"code": null,
"e": 4727,
"s": 4629,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4751,
"s": 4727,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 4791,
"s": 4751,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 4827,
"s": 4791,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 4868,
"s": 4827,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 4906,
"s": 4868,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 4934,
"s": 4906,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 4984,
"s": 4934,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 5006,
"s": 4984,
"text": "Python map() function"
}
] |
Create Sequence of Repeated Values in R
|
17 May, 2021
A repeated sequence of numbers is an incremental list of numbers arranged in such a way that the difference in the successive numbers is 1, and each of these numbers is repeated for the specified number of times. R provides us with a variety of methods to generate repeated sequences both using vectors or integers. In this article, we are going to see how to create a sequence of Repeated Values in R programming.
Method 1: Using rep() method
The rep() method of base R is used to generate a replicated sequence from a specified vector, where each element of the vector can be repeated at any number of specified times. This method can take a character, floats, or integers-type input vectors.
Syntax: rep(seq, each)
Arguments:
seq – The vector to generate a sequence of
each – The number of times to repeat each element of the sequence
Example 1: Creating a character sequence of repeated value.
R
# declaring vectorvec <- LETTERS[1 : 4] # replicate each letter in vec 3 timesprint ("Replicated Sequence")rep(vec, each = 3)
Output:
[1] "Replicated Sequence"
[1] "A" "A" "A" "B" "B" "B" "C" "C" "C" "D" "D" "D"
Example 2: Creating an integer sequence of repeated value.
R
# declaring vectorvec <- c(60 : 62) # replicate each integer in vec 3 timesprint ("Replicated Sequence")rep(vec, each = 2)
Output
[1] "Replicated Sequence"
[1] 60 60 61 61 62 62
Method 2: Using gl() method.
The gl() method in base R is used to generate factors in form of pattern specification. The output depends on the number of levels, with each of them being replicated k times until the length is achieved. In case, the length is not specified, the length is taken to be a number of levels * number of replications of each level. The drawback in this approach is that it always generates a sequence ranged between 1 to n. But, in case we need to overrule this default labelling, a customized label vector can be assigned to the output.
Syntax: gl(n, k, length, labels)
Arguments :
n – the total number of levels.
k – number of replications of each level.
length (By default : n * k ) – length of the output
labels – labels used for the factor levels.
Code:
R
# generate a sequence of 1:6 each# repeated 4 timesgl(6 , 4 )
Output:
[1] 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 6 6 6 6
Levels: 1 2 3 4 5 6
If the length is greater than n×k, then the same sequence is appended again at the end, till the total length of the vector is achieved.
R
# generate a sequence of 1:6 each# repeated 3 times until length=20gl(6 , 3 , length = 20)
Output:
[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 1 1
Levels: 1 2 3 4 5 6
Explanation: Since, 6×3 = 18, therefore, the same sequence starting from the beginning is appended until length=20 is achieved. Therefore, 1 1 is added at the end.
Also, customized labels can be assigned to the sequence, as a result of which the actual sequence numerals can be replaced by the label vector’s corresponding letters. To ensure proper mapping, the length of the labels’ vector should be same as the number of factor levels.
‘
R
# generate a sequence of 1:5# each repeated 2 times assigned# labels from 100seq1 <- gl(5, 2, labels = c(100 : 104))print("Sequence 1")print (seq1) # generate a sequence of 1:5# each repeated 2 times assigned# labels as letters from aseq2 <- gl(5, 2, labels = letters[ 1 : 5 ])print("Sequence 2")print (seq2)
Output:
[1] "Sequence 1"
[1] 100 100 101 101 102 102 103 103 104 104
Levels: 100 101 102 103 104
[1] "Sequence 2"
[1] a a b b c c d d e e
Levels: a b c d e
Explanation: In sequence 1, each instance of 1 in the original sequence is replaced by 101, 2 is replaced by 102, and so on. Similarly, in sequence 2, each instance of 1 is replaced by ‘a’, 2 by ‘b’, and so on.
clintra
Picked
R-Factors
R-Vectors
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 May, 2021"
},
{
"code": null,
"e": 443,
"s": 28,
"text": "A repeated sequence of numbers is an incremental list of numbers arranged in such a way that the difference in the successive numbers is 1, and each of these numbers is repeated for the specified number of times. R provides us with a variety of methods to generate repeated sequences both using vectors or integers. In this article, we are going to see how to create a sequence of Repeated Values in R programming."
},
{
"code": null,
"e": 472,
"s": 443,
"text": "Method 1: Using rep() method"
},
{
"code": null,
"e": 725,
"s": 472,
"text": "The rep() method of base R is used to generate a replicated sequence from a specified vector, where each element of the vector can be repeated at any number of specified times. This method can take a character, floats, or integers-type input vectors. "
},
{
"code": null,
"e": 748,
"s": 725,
"text": "Syntax: rep(seq, each)"
},
{
"code": null,
"e": 760,
"s": 748,
"text": "Arguments: "
},
{
"code": null,
"e": 803,
"s": 760,
"text": "seq – The vector to generate a sequence of"
},
{
"code": null,
"e": 869,
"s": 803,
"text": "each – The number of times to repeat each element of the sequence"
},
{
"code": null,
"e": 929,
"s": 869,
"text": "Example 1: Creating a character sequence of repeated value."
},
{
"code": null,
"e": 931,
"s": 929,
"text": "R"
},
{
"code": "# declaring vectorvec <- LETTERS[1 : 4] # replicate each letter in vec 3 timesprint (\"Replicated Sequence\")rep(vec, each = 3)",
"e": 1057,
"s": 931,
"text": null
},
{
"code": null,
"e": 1065,
"s": 1057,
"text": "Output:"
},
{
"code": null,
"e": 1143,
"s": 1065,
"text": "[1] \"Replicated Sequence\"\n[1] \"A\" \"A\" \"A\" \"B\" \"B\" \"B\" \"C\" \"C\" \"C\" \"D\" \"D\" \"D\""
},
{
"code": null,
"e": 1202,
"s": 1143,
"text": "Example 2: Creating an integer sequence of repeated value."
},
{
"code": null,
"e": 1204,
"s": 1202,
"text": "R"
},
{
"code": "# declaring vectorvec <- c(60 : 62) # replicate each integer in vec 3 timesprint (\"Replicated Sequence\")rep(vec, each = 2)",
"e": 1327,
"s": 1204,
"text": null
},
{
"code": null,
"e": 1334,
"s": 1327,
"text": "Output"
},
{
"code": null,
"e": 1382,
"s": 1334,
"text": "[1] \"Replicated Sequence\"\n[1] 60 60 61 61 62 62"
},
{
"code": null,
"e": 1411,
"s": 1382,
"text": "Method 2: Using gl() method."
},
{
"code": null,
"e": 1946,
"s": 1411,
"text": "The gl() method in base R is used to generate factors in form of pattern specification. The output depends on the number of levels, with each of them being replicated k times until the length is achieved. In case, the length is not specified, the length is taken to be a number of levels * number of replications of each level. The drawback in this approach is that it always generates a sequence ranged between 1 to n. But, in case we need to overrule this default labelling, a customized label vector can be assigned to the output. "
},
{
"code": null,
"e": 1979,
"s": 1946,
"text": "Syntax: gl(n, k, length, labels)"
},
{
"code": null,
"e": 1992,
"s": 1979,
"text": "Arguments : "
},
{
"code": null,
"e": 2024,
"s": 1992,
"text": "n – the total number of levels."
},
{
"code": null,
"e": 2066,
"s": 2024,
"text": "k – number of replications of each level."
},
{
"code": null,
"e": 2118,
"s": 2066,
"text": "length (By default : n * k ) – length of the output"
},
{
"code": null,
"e": 2162,
"s": 2118,
"text": "labels – labels used for the factor levels."
},
{
"code": null,
"e": 2168,
"s": 2162,
"text": "Code:"
},
{
"code": null,
"e": 2170,
"s": 2168,
"text": "R"
},
{
"code": "# generate a sequence of 1:6 each# repeated 4 timesgl(6 , 4 )",
"e": 2232,
"s": 2170,
"text": null
},
{
"code": null,
"e": 2240,
"s": 2232,
"text": "Output:"
},
{
"code": null,
"e": 2313,
"s": 2240,
"text": " [1] 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 6 6 6 6\nLevels: 1 2 3 4 5 6"
},
{
"code": null,
"e": 2451,
"s": 2313,
"text": "If the length is greater than n×k, then the same sequence is appended again at the end, till the total length of the vector is achieved. "
},
{
"code": null,
"e": 2453,
"s": 2451,
"text": "R"
},
{
"code": "# generate a sequence of 1:6 each# repeated 3 times until length=20gl(6 , 3 , length = 20)",
"e": 2544,
"s": 2453,
"text": null
},
{
"code": null,
"e": 2552,
"s": 2544,
"text": "Output:"
},
{
"code": null,
"e": 2616,
"s": 2552,
"text": "[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 1 1\nLevels: 1 2 3 4 5 6"
},
{
"code": null,
"e": 2781,
"s": 2616,
"text": "Explanation: Since, 6×3 = 18, therefore, the same sequence starting from the beginning is appended until length=20 is achieved. Therefore, 1 1 is added at the end. "
},
{
"code": null,
"e": 3056,
"s": 2781,
"text": "Also, customized labels can be assigned to the sequence, as a result of which the actual sequence numerals can be replaced by the label vector’s corresponding letters. To ensure proper mapping, the length of the labels’ vector should be same as the number of factor levels. "
},
{
"code": null,
"e": 3058,
"s": 3056,
"text": "‘"
},
{
"code": null,
"e": 3060,
"s": 3058,
"text": "R"
},
{
"code": "# generate a sequence of 1:5# each repeated 2 times assigned# labels from 100seq1 <- gl(5, 2, labels = c(100 : 104))print(\"Sequence 1\")print (seq1) # generate a sequence of 1:5# each repeated 2 times assigned# labels as letters from aseq2 <- gl(5, 2, labels = letters[ 1 : 5 ])print(\"Sequence 2\")print (seq2)",
"e": 3369,
"s": 3060,
"text": null
},
{
"code": null,
"e": 3377,
"s": 3369,
"text": "Output:"
},
{
"code": null,
"e": 3525,
"s": 3377,
"text": "[1] \"Sequence 1\"\n[1] 100 100 101 101 102 102 103 103 104 104\nLevels: 100 101 102 103 104\n[1] \"Sequence 2\"\n[1] a a b b c c d d e e\nLevels: a b c d e"
},
{
"code": null,
"e": 3737,
"s": 3525,
"text": "Explanation: In sequence 1, each instance of 1 in the original sequence is replaced by 101, 2 is replaced by 102, and so on. Similarly, in sequence 2, each instance of 1 is replaced by ‘a’, 2 by ‘b’, and so on. "
},
{
"code": null,
"e": 3745,
"s": 3737,
"text": "clintra"
},
{
"code": null,
"e": 3752,
"s": 3745,
"text": "Picked"
},
{
"code": null,
"e": 3762,
"s": 3752,
"text": "R-Factors"
},
{
"code": null,
"e": 3772,
"s": 3762,
"text": "R-Vectors"
},
{
"code": null,
"e": 3783,
"s": 3772,
"text": "R Language"
},
{
"code": null,
"e": 3881,
"s": 3783,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3933,
"s": 3881,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 3991,
"s": 3933,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 4026,
"s": 3991,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 4064,
"s": 4026,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 4113,
"s": 4064,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 4130,
"s": 4113,
"text": "R - if statement"
},
{
"code": null,
"e": 4167,
"s": 4130,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 4210,
"s": 4167,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 4247,
"s": 4210,
"text": "How to import an Excel File into R ?"
}
] |
How to set border for wedges in Matplotlib pie chart?
|
17 Dec, 2020
Pie charts can be used for relative comparison of data. Python offers several data visualization libraries to work with. The Matplotlib library offers different types of graphs and inbuild methods and properties to manipulate the graph. The wedges in the pie chart can be given a border using the wedgeprops attribute of the pie() method of matplotlib.pyplot. Given below are two such examples to set a border to the wedges of the pie chart.
Syntax: wedgeprops : [dict | None]
Parameters:
dict: It is the property and its value. Example: {‘linewidth’:2} or {‘edgecolor’:’black’}
Default value: None
Example 1:
At first, the pyplot module of matplotlib package is imported. The years and profit arrays are initialized. Next, the graph is plotted with the given data. The autopct attribute is used to specify the distance of the text within the wedge from the Centre of the circle. The startangle attribute is used to decide the direction in which the chart will be plotted. By default, startangle is 0 which means the chart starts at positive X axis. Here the startangle is set to 90 which means the chart is rotated by 90 degrees and the chart starts at the positive Y axis. The wedgeprops attribute is used to set the properties of each wedge. The edgecolor is set to black and the linewidth is set to 2. Antialiasing is set to True to prevent the aliasing effect on the image.
Below is the Implementation:
Python3
import matplotlib.pyplot as plt years = [2016, 2017, 2018, 2019, 2020]profit = [15, 19, 35, 14, 17] # Plotting the pie chartplt.pie(profit, labels = years, autopct = '%1.1f%%', startangle = 90, wedgeprops = {"edgecolor" : "black", 'linewidth': 2, 'antialiased': True}) # Equal aspect ratio ensures# that pie is drawn as a circle.plt.axis('equal') # Display the graph onto the screenplt.show()
Output:
Example 2:
At first, the pyplot module of matplotlib package is imported. The product and stock arrays are initialized. The explode is an optional array-like structure used to separate certain parts of the pie. Next, the graph is plotted with the given data. The autopct attribute is used to specify the distance of the text within the wedge from the Centre of the circle. The shadow attribute is generated shadows for the split portions. The startangle attribute is used to decide the direction in which the chart will be plotted. By default, startangle is 0 which means the chart starts at the positive X axis. Here the startangle is set to 90 which means the chart is rotated by 90 degrees and the chart starts at the positive Y axis. The wedgeprops attribute is used to set the properties of each wedge. The edgecolor is set to black and the linewidth is set to 3. Antialiasing is set to true to prevent the aliasing effect on the image.
Below is the Implementation:
Python3
import matplotlib.pyplot as plt # the slices are ordered and# plotted counter-clockwise:product = 'Product A', 'Product B', 'Product C', 'Product D' stock = [15, 30, 35, 20]explode = (0.1, 0, 0.1, 0) plt.pie(stock, explode = explode, labels = product, autopct = '%1.1f%%', shadow = True, startangle = 90, wedgeprops= {"edgecolor":"black", 'linewidth': 3, 'antialiased': True}) # Equal aspect ratio ensures that# pie is drawn as a circle.plt.axis('equal') plt.show()
Output:
Picked
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Dec, 2020"
},
{
"code": null,
"e": 470,
"s": 28,
"text": "Pie charts can be used for relative comparison of data. Python offers several data visualization libraries to work with. The Matplotlib library offers different types of graphs and inbuild methods and properties to manipulate the graph. The wedges in the pie chart can be given a border using the wedgeprops attribute of the pie() method of matplotlib.pyplot. Given below are two such examples to set a border to the wedges of the pie chart."
},
{
"code": null,
"e": 505,
"s": 470,
"text": "Syntax: wedgeprops : [dict | None]"
},
{
"code": null,
"e": 517,
"s": 505,
"text": "Parameters:"
},
{
"code": null,
"e": 607,
"s": 517,
"text": "dict: It is the property and its value. Example: {‘linewidth’:2} or {‘edgecolor’:’black’}"
},
{
"code": null,
"e": 627,
"s": 607,
"text": "Default value: None"
},
{
"code": null,
"e": 638,
"s": 627,
"text": "Example 1:"
},
{
"code": null,
"e": 1407,
"s": 638,
"text": "At first, the pyplot module of matplotlib package is imported. The years and profit arrays are initialized. Next, the graph is plotted with the given data. The autopct attribute is used to specify the distance of the text within the wedge from the Centre of the circle. The startangle attribute is used to decide the direction in which the chart will be plotted. By default, startangle is 0 which means the chart starts at positive X axis. Here the startangle is set to 90 which means the chart is rotated by 90 degrees and the chart starts at the positive Y axis. The wedgeprops attribute is used to set the properties of each wedge. The edgecolor is set to black and the linewidth is set to 2. Antialiasing is set to True to prevent the aliasing effect on the image."
},
{
"code": null,
"e": 1436,
"s": 1407,
"text": "Below is the Implementation:"
},
{
"code": null,
"e": 1444,
"s": 1436,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt years = [2016, 2017, 2018, 2019, 2020]profit = [15, 19, 35, 14, 17] # Plotting the pie chartplt.pie(profit, labels = years, autopct = '%1.1f%%', startangle = 90, wedgeprops = {\"edgecolor\" : \"black\", 'linewidth': 2, 'antialiased': True}) # Equal aspect ratio ensures# that pie is drawn as a circle.plt.axis('equal') # Display the graph onto the screenplt.show()",
"e": 1898,
"s": 1444,
"text": null
},
{
"code": null,
"e": 1906,
"s": 1898,
"text": "Output:"
},
{
"code": null,
"e": 1917,
"s": 1906,
"text": "Example 2:"
},
{
"code": null,
"e": 2848,
"s": 1917,
"text": "At first, the pyplot module of matplotlib package is imported. The product and stock arrays are initialized. The explode is an optional array-like structure used to separate certain parts of the pie. Next, the graph is plotted with the given data. The autopct attribute is used to specify the distance of the text within the wedge from the Centre of the circle. The shadow attribute is generated shadows for the split portions. The startangle attribute is used to decide the direction in which the chart will be plotted. By default, startangle is 0 which means the chart starts at the positive X axis. Here the startangle is set to 90 which means the chart is rotated by 90 degrees and the chart starts at the positive Y axis. The wedgeprops attribute is used to set the properties of each wedge. The edgecolor is set to black and the linewidth is set to 3. Antialiasing is set to true to prevent the aliasing effect on the image."
},
{
"code": null,
"e": 2877,
"s": 2848,
"text": "Below is the Implementation:"
},
{
"code": null,
"e": 2885,
"s": 2877,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt # the slices are ordered and# plotted counter-clockwise:product = 'Product A', 'Product B', 'Product C', 'Product D' stock = [15, 30, 35, 20]explode = (0.1, 0, 0.1, 0) plt.pie(stock, explode = explode, labels = product, autopct = '%1.1f%%', shadow = True, startangle = 90, wedgeprops= {\"edgecolor\":\"black\", 'linewidth': 3, 'antialiased': True}) # Equal aspect ratio ensures that# pie is drawn as a circle.plt.axis('equal') plt.show()",
"e": 3433,
"s": 2885,
"text": null
},
{
"code": null,
"e": 3441,
"s": 3433,
"text": "Output:"
},
{
"code": null,
"e": 3448,
"s": 3441,
"text": "Picked"
},
{
"code": null,
"e": 3466,
"s": 3448,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 3490,
"s": 3466,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3497,
"s": 3490,
"text": "Python"
},
{
"code": null,
"e": 3516,
"s": 3497,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3614,
"s": 3516,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3642,
"s": 3614,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3664,
"s": 3642,
"text": "Python map() function"
},
{
"code": null,
"e": 3714,
"s": 3664,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3732,
"s": 3714,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3776,
"s": 3732,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 3818,
"s": 3776,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3841,
"s": 3818,
"text": "Taking input in Python"
},
{
"code": null,
"e": 3863,
"s": 3841,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3898,
"s": 3863,
"text": "Read a file line by line in Python"
}
] |
MongoDB Cursor
|
17 Feb, 2021
In MongoDB, when the find() method is used to find the documents present in the given collection, then this method returned a pointer which will points to the documents of the collection, now this pointer is known as cursor. Or in other words we can say that a cursor is a pointer, and using this pointer we can access the document. By default, cursor iterate automatically, but you can iterate a cursor manually which we will discuss later.
Example: In this example, we are working with:
Database: gfg
Collection: student
Documents: Three documents contain the details of the students
Here, we use the following query to display all the documents present in the student collection
db.student.find().pretty()
This find() method return a cursor with contain all documents present in the student collection.
In MongoDB, the find() method return the cursor, now to access the document we need to iterate the cursor. In the mongo shell, if the cursor is not assigned to a var keyword then the mongo shell automatically iterates the cursor up to 20 documents. MongoDB also allows you to iterate cursor manually. So, to iterate a cursor manually simply assign the cursor return by the find() method to the var keyword Or JavaScript variable.
Note: If a cursor inactive for 10 min then MongoDB server will automatically close that cursor.
Syntax:
var name = db.collection_name.find()
name
Example :
var mycursor = db.student.find({studentId:3}).pretty()
mycursor
Here, we iterate the cursor manually to find the document whose studentId is 3. So, we assigned the cursor returned by the find() method to the JavaScript variable(i.e. mycursor).
Using next() method:
We can also use next() cursor method to access the next document. Let us discuss with the help of an example:
Example:
var mycursor = db.student.find({studentId:{$gt:1}});
> while(mycursor.hasNext()){
... print(tojson(mycursor.next()));
... }
In this example, studentId 2 and 3 documents displays because in the first line we exclusively took the cursor to start with the studentId > 1. So it skipped 1st document and retrieve the remaining documents. Here, print(tojson()) method is used to display the result. You can also use printjson() method to display the result.
Using forEach() method:
We can also use forEach() method to iterate the cursor. This function applies a JavaScript function to each document from the cursor.
Syntax:
db.collection.find().forEach(<function>)
Example:
var mycursor = db.student.find({studentId:3}).pretty()
mycursor.forEach(printjson)
Here, first we store the cursor returned by the find() method(i.e., studentId:3) in the mycursor variable. Now, we use forEach() method to iterate the cursor and display the resultant document using printjson.
Iterator Index :
In mongo shell, you are allowed to iterate the cursor and display the resultant document in the array using toArray() method.
Syntax:
cursor.toArray()
Example:
var mycursor = db.student.find().pretty()
var docs = mycursor.toArray()
var resultdoc = docs[0]
resultdoc
Here, first we assign the returned cursor to the var keyword(i.e. mycursor), in the next we create a array from the resultant cursor using toArray() method and assign the result to the var keyword(i.e. docs). Now we access the documents according to their index e.g. var resultdoc = docs[0], here we display a document whose index is 0.
Alternate Method:
You can also this method to access a document using index on the cursor.
var mycursor = db.student.find().pretty()
var resultdoc = mycursor[0]
resultdoc
Below are the commonly used cursor methods:
Count cursor:
In order to get the correct documents, we need to know how many documents are present for that collection. To get that we can use the count() method which returns the total number of documents are present in the given collection.
Syntax:
db.collection_name.find().count()
or
db.collection_name.count()
Example:
db.student.find().count()
Here, we find the total number of documents present in the student collection using count() method.
Cursor Limit:
The limit() method helps to fetch limited records from a collection. Suppose we have multiple documents, but we want to have topmost or only 2 documents, then by using the limit() method, we can achieve that.
Syntax:
db.collection_name.find().limit(<number>)
Example:
db.student.find().limit(2).pretty()
Here, we only display the first two documents from the student collection.
Cursor size:
The cursor.size() method will be helpful to return a count of the number of documents which got as the output from db.collection.find() query after applying any cursor.skip() and cursor.limit() methods. Basically, it will filter for the given condition and find the size of the cursor. Hence, it is mentioned as it has applied cursor.skip() and cursor.limit() methods.
Syntax:
db.collection_name.find().size()
Example:
db.student.find({studentId:1}).size()
Cursor sort:
Usually while verifying documents, if the output is in sorted order, either in ascending or descending order, it will be easier. So we use sort() method to sort the documents. It you want to sort the documents in ascending, then set the value of the field to 1 and in descending, then set -1.
Syntax:
db.collection_name.find().sort(<sort>)
Example:
db.student.find().sort({studentId:-1}).pretty()
Here, we sort all the documents present in the student collection in descending order.
Cursor.toArray():
In order to have as an array that contains all documents returned by the cursor, we can use toArray() method.
Syntax:
db.collection_name.find().toArray()
Example:
db.student.find().toArray()
Cursor.next:
The next() method is used to return the next document in a cursor. Usually, it will return the first document as that will be the result of the first document in the cursor.
Syntax:
db.student.find().next()
Example:
db.student.find().next()
Here, the next() method return the first document from the collection.
Cursor Methods modify the way that the underlying query is executed.
MongoDB
Picked
Technical Scripter 2020
MongoDB
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Feb, 2021"
},
{
"code": null,
"e": 471,
"s": 28,
"text": "In MongoDB, when the find() method is used to find the documents present in the given collection, then this method returned a pointer which will points to the documents of the collection, now this pointer is known as cursor. Or in other words we can say that a cursor is a pointer, and using this pointer we can access the document. By default, cursor iterate automatically, but you can iterate a cursor manually which we will discuss later. "
},
{
"code": null,
"e": 518,
"s": 471,
"text": "Example: In this example, we are working with:"
},
{
"code": null,
"e": 532,
"s": 518,
"text": "Database: gfg"
},
{
"code": null,
"e": 552,
"s": 532,
"text": "Collection: student"
},
{
"code": null,
"e": 615,
"s": 552,
"text": "Documents: Three documents contain the details of the students"
},
{
"code": null,
"e": 711,
"s": 615,
"text": "Here, we use the following query to display all the documents present in the student collection"
},
{
"code": null,
"e": 738,
"s": 711,
"text": "db.student.find().pretty()"
},
{
"code": null,
"e": 835,
"s": 738,
"text": "This find() method return a cursor with contain all documents present in the student collection."
},
{
"code": null,
"e": 1266,
"s": 835,
"text": "In MongoDB, the find() method return the cursor, now to access the document we need to iterate the cursor. In the mongo shell, if the cursor is not assigned to a var keyword then the mongo shell automatically iterates the cursor up to 20 documents. MongoDB also allows you to iterate cursor manually. So, to iterate a cursor manually simply assign the cursor return by the find() method to the var keyword Or JavaScript variable. "
},
{
"code": null,
"e": 1362,
"s": 1266,
"text": "Note: If a cursor inactive for 10 min then MongoDB server will automatically close that cursor."
},
{
"code": null,
"e": 1370,
"s": 1362,
"text": "Syntax:"
},
{
"code": null,
"e": 1407,
"s": 1370,
"text": "var name = db.collection_name.find()"
},
{
"code": null,
"e": 1412,
"s": 1407,
"text": "name"
},
{
"code": null,
"e": 1422,
"s": 1412,
"text": "Example :"
},
{
"code": null,
"e": 1486,
"s": 1422,
"text": "var mycursor = db.student.find({studentId:3}).pretty()\nmycursor"
},
{
"code": null,
"e": 1666,
"s": 1486,
"text": "Here, we iterate the cursor manually to find the document whose studentId is 3. So, we assigned the cursor returned by the find() method to the JavaScript variable(i.e. mycursor)."
},
{
"code": null,
"e": 1687,
"s": 1666,
"text": "Using next() method:"
},
{
"code": null,
"e": 1797,
"s": 1687,
"text": "We can also use next() cursor method to access the next document. Let us discuss with the help of an example:"
},
{
"code": null,
"e": 1806,
"s": 1797,
"text": "Example:"
},
{
"code": null,
"e": 1930,
"s": 1806,
"text": "var mycursor = db.student.find({studentId:{$gt:1}});\n> while(mycursor.hasNext()){\n... print(tojson(mycursor.next()));\n... }"
},
{
"code": null,
"e": 2258,
"s": 1930,
"text": "In this example, studentId 2 and 3 documents displays because in the first line we exclusively took the cursor to start with the studentId > 1. So it skipped 1st document and retrieve the remaining documents. Here, print(tojson()) method is used to display the result. You can also use printjson() method to display the result."
},
{
"code": null,
"e": 2282,
"s": 2258,
"text": "Using forEach() method:"
},
{
"code": null,
"e": 2416,
"s": 2282,
"text": "We can also use forEach() method to iterate the cursor. This function applies a JavaScript function to each document from the cursor."
},
{
"code": null,
"e": 2424,
"s": 2416,
"text": "Syntax:"
},
{
"code": null,
"e": 2465,
"s": 2424,
"text": "db.collection.find().forEach(<function>)"
},
{
"code": null,
"e": 2474,
"s": 2465,
"text": "Example:"
},
{
"code": null,
"e": 2557,
"s": 2474,
"text": "var mycursor = db.student.find({studentId:3}).pretty()\nmycursor.forEach(printjson)"
},
{
"code": null,
"e": 2767,
"s": 2557,
"text": "Here, first we store the cursor returned by the find() method(i.e., studentId:3) in the mycursor variable. Now, we use forEach() method to iterate the cursor and display the resultant document using printjson."
},
{
"code": null,
"e": 2784,
"s": 2767,
"text": "Iterator Index :"
},
{
"code": null,
"e": 2910,
"s": 2784,
"text": "In mongo shell, you are allowed to iterate the cursor and display the resultant document in the array using toArray() method."
},
{
"code": null,
"e": 2918,
"s": 2910,
"text": "Syntax:"
},
{
"code": null,
"e": 2935,
"s": 2918,
"text": "cursor.toArray()"
},
{
"code": null,
"e": 2944,
"s": 2935,
"text": "Example:"
},
{
"code": null,
"e": 3050,
"s": 2944,
"text": "var mycursor = db.student.find().pretty()\nvar docs = mycursor.toArray()\nvar resultdoc = docs[0]\nresultdoc"
},
{
"code": null,
"e": 3387,
"s": 3050,
"text": "Here, first we assign the returned cursor to the var keyword(i.e. mycursor), in the next we create a array from the resultant cursor using toArray() method and assign the result to the var keyword(i.e. docs). Now we access the documents according to their index e.g. var resultdoc = docs[0], here we display a document whose index is 0."
},
{
"code": null,
"e": 3405,
"s": 3387,
"text": "Alternate Method:"
},
{
"code": null,
"e": 3480,
"s": 3405,
"text": "You can also this method to access a document using index on the cursor. "
},
{
"code": null,
"e": 3560,
"s": 3480,
"text": "var mycursor = db.student.find().pretty()\nvar resultdoc = mycursor[0]\nresultdoc"
},
{
"code": null,
"e": 3604,
"s": 3560,
"text": "Below are the commonly used cursor methods:"
},
{
"code": null,
"e": 3618,
"s": 3604,
"text": "Count cursor:"
},
{
"code": null,
"e": 3848,
"s": 3618,
"text": "In order to get the correct documents, we need to know how many documents are present for that collection. To get that we can use the count() method which returns the total number of documents are present in the given collection."
},
{
"code": null,
"e": 3856,
"s": 3848,
"text": "Syntax:"
},
{
"code": null,
"e": 3890,
"s": 3856,
"text": "db.collection_name.find().count()"
},
{
"code": null,
"e": 3894,
"s": 3890,
"text": "or "
},
{
"code": null,
"e": 3921,
"s": 3894,
"text": "db.collection_name.count()"
},
{
"code": null,
"e": 3931,
"s": 3921,
"text": "Example: "
},
{
"code": null,
"e": 3957,
"s": 3931,
"text": "db.student.find().count()"
},
{
"code": null,
"e": 4057,
"s": 3957,
"text": "Here, we find the total number of documents present in the student collection using count() method."
},
{
"code": null,
"e": 4071,
"s": 4057,
"text": "Cursor Limit:"
},
{
"code": null,
"e": 4280,
"s": 4071,
"text": "The limit() method helps to fetch limited records from a collection. Suppose we have multiple documents, but we want to have topmost or only 2 documents, then by using the limit() method, we can achieve that."
},
{
"code": null,
"e": 4288,
"s": 4280,
"text": "Syntax:"
},
{
"code": null,
"e": 4330,
"s": 4288,
"text": "db.collection_name.find().limit(<number>)"
},
{
"code": null,
"e": 4339,
"s": 4330,
"text": "Example:"
},
{
"code": null,
"e": 4375,
"s": 4339,
"text": "db.student.find().limit(2).pretty()"
},
{
"code": null,
"e": 4450,
"s": 4375,
"text": "Here, we only display the first two documents from the student collection."
},
{
"code": null,
"e": 4463,
"s": 4450,
"text": "Cursor size:"
},
{
"code": null,
"e": 4832,
"s": 4463,
"text": "The cursor.size() method will be helpful to return a count of the number of documents which got as the output from db.collection.find() query after applying any cursor.skip() and cursor.limit() methods. Basically, it will filter for the given condition and find the size of the cursor. Hence, it is mentioned as it has applied cursor.skip() and cursor.limit() methods."
},
{
"code": null,
"e": 4840,
"s": 4832,
"text": "Syntax:"
},
{
"code": null,
"e": 4873,
"s": 4840,
"text": "db.collection_name.find().size()"
},
{
"code": null,
"e": 4882,
"s": 4873,
"text": "Example:"
},
{
"code": null,
"e": 4920,
"s": 4882,
"text": "db.student.find({studentId:1}).size()"
},
{
"code": null,
"e": 4933,
"s": 4920,
"text": "Cursor sort:"
},
{
"code": null,
"e": 5226,
"s": 4933,
"text": "Usually while verifying documents, if the output is in sorted order, either in ascending or descending order, it will be easier. So we use sort() method to sort the documents. It you want to sort the documents in ascending, then set the value of the field to 1 and in descending, then set -1."
},
{
"code": null,
"e": 5234,
"s": 5226,
"text": "Syntax:"
},
{
"code": null,
"e": 5273,
"s": 5234,
"text": "db.collection_name.find().sort(<sort>)"
},
{
"code": null,
"e": 5282,
"s": 5273,
"text": "Example:"
},
{
"code": null,
"e": 5330,
"s": 5282,
"text": "db.student.find().sort({studentId:-1}).pretty()"
},
{
"code": null,
"e": 5417,
"s": 5330,
"text": "Here, we sort all the documents present in the student collection in descending order."
},
{
"code": null,
"e": 5435,
"s": 5417,
"text": "Cursor.toArray():"
},
{
"code": null,
"e": 5545,
"s": 5435,
"text": "In order to have as an array that contains all documents returned by the cursor, we can use toArray() method."
},
{
"code": null,
"e": 5553,
"s": 5545,
"text": "Syntax:"
},
{
"code": null,
"e": 5589,
"s": 5553,
"text": "db.collection_name.find().toArray()"
},
{
"code": null,
"e": 5598,
"s": 5589,
"text": "Example:"
},
{
"code": null,
"e": 5626,
"s": 5598,
"text": "db.student.find().toArray()"
},
{
"code": null,
"e": 5639,
"s": 5626,
"text": "Cursor.next:"
},
{
"code": null,
"e": 5813,
"s": 5639,
"text": "The next() method is used to return the next document in a cursor. Usually, it will return the first document as that will be the result of the first document in the cursor."
},
{
"code": null,
"e": 5821,
"s": 5813,
"text": "Syntax:"
},
{
"code": null,
"e": 5846,
"s": 5821,
"text": "db.student.find().next()"
},
{
"code": null,
"e": 5855,
"s": 5846,
"text": "Example:"
},
{
"code": null,
"e": 5880,
"s": 5855,
"text": "db.student.find().next()"
},
{
"code": null,
"e": 5951,
"s": 5880,
"text": "Here, the next() method return the first document from the collection."
},
{
"code": null,
"e": 6020,
"s": 5951,
"text": "Cursor Methods modify the way that the underlying query is executed."
},
{
"code": null,
"e": 6028,
"s": 6020,
"text": "MongoDB"
},
{
"code": null,
"e": 6035,
"s": 6028,
"text": "Picked"
},
{
"code": null,
"e": 6059,
"s": 6035,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 6067,
"s": 6059,
"text": "MongoDB"
},
{
"code": null,
"e": 6086,
"s": 6067,
"text": "Technical Scripter"
}
] |
First and last occurrences of x | Practice | GeeksforGeeks
|
Given a sorted array arr containing n elements with possibly duplicate elements, the task is to find indexes of first and last occurrences of an element x in the given array.
Example 1:
Input:
n=9, x=5
arr[] = { 1, 3, 5, 5, 5, 5, 67, 123, 125 }
Output: 2 5
Explanation: First occurrence of 5 is at index 2 and last
occurrence of 5 is at index 5.
Example 2:
Input:
n=9, x=7
arr[] = { 1, 3, 5, 5, 5, 5, 7, 123, 125 }
Output: 6 6
Your Task:
Since, this is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function find() that takes array arr, integer n and integer x as parameters and returns the required answer.
Note: If the number x is not found in the array just return both index as -1.
Expected Time Complexity: O(logN)
Expected Auxiliary Space: O(1).
Constraints:
1 ≤ N ≤ 107
+1
nikhil_deore1 hour ago
C++ Fast AF 0.29
vector<int> find(int arr[], int n , int x )
{ long count=0;
vector<long long>ans;
for(long long i=0;i<n;i++){
if(arr[i]==x){
ans.push_back(i);
count++;
}
}
if(ans.size()==0){
return {-1,-1};
}
return {ans[0],ans[count-1]};
}
0
yashdalal452 hours ago
Binary Search Solution
Time Complexity : O(log n)
Space Complexity: O(1)
ArrayList<Long> find(long arr[], int n, int x)
{
// code here
ArrayList<Long> a = new ArrayList<>();
a.add((long)-1); // store min index
a.add((long)-1); // store max index
binary_s(arr,x,0,n-1,a);
return a;
}
public void binary_s(long[] arr,int x,int s,int e,ArrayList<Long> a){
if(s>e){
return;
}
int mid = s+(e-s)/2;
if(x<=arr[mid]){
if(x==arr[mid]) {
if(a.get(0)>mid || a.get(0)==-1) a.set(0,(long)mid);
if(a.get(1)<mid) a.set(1,(long)mid);
}
binary_s(arr,x,s,mid-1,a);
}
//use if block again because in case when x==arr[mid] we have to search in both left and right part of array.
if(x>=arr[mid]){
binary_s(arr,x,mid+1,e,a);
}
}
0
surabhichoubey5520 hours ago
ALGO TO SOLVE THIS QUESTION
based on binary search
// for left occurrences
lets take example of given array
0 1 2 3 4 5 6 7 8 index
1, 3, 5, 5, 5, 5, 7, 123, 125 arr
LETS UNDERSTAND IN OUR NATIVE LANGUAGE
1 first find mid if equal to key to answer mai store karalo
maybe left mai iski or bhi occurrences mil jaye
fir ham apne end ko left mai lane ke liye
end = mid-1 //left wala part
kr dete hain
2 further steps are same as binary search
2.1 if the key, you are searching for is less than mid that means hamko left wale part pr aana hai iske liye end = mid-1 kr dete hain
2.2 if the key you are searching for is greater than arr[mid]
that means hamko right wale part pr search karna hai
s = mid+1;
3 and yeah don't forget to update your mid
//for right occurrences
1 same as left occurence but the key point is
if arr[mid] == key than store it in ans and go for right side
maybe we are able to find its right most occurrences
for that start = mid + 1//right wala part
and furhter steps are same
store both the answer in vector ans return happy!
// { Driver Code Starts#include<bits/stdc++.h>using namespace std;
// } Driver Code Endsvector<int> find(int arr[], int n , int key ){ // code here vector<int>ans; int s = 0; int e = n-1; int mid = s+(e-s)/2; int ans1 = -1; //left occurance while(s<=e) { if(arr[mid] == key) { ans1 = mid; e = mid-1; } else if(key>arr[mid]) { s = mid+1; } else if(key<arr[mid]) { e = mid-1; } mid = (s+e)/2; } ans.push_back(ans1); //right int s1 = 0; int e1 = n-1; int mid1 = s+(e-s)/2; int ans2 = -1; while(s1<=e1) { if(arr[mid1] == key) { ans2 = mid1; s1 = mid1+1; } else if(key>arr[mid1]) { s1 = mid1+1; } else if(key<arr[mid1]) { e1 = mid1-1; } mid1 = (s1+e1)/2; } ans.push_back(ans2); return ans; }
0
vijeayaetv02 days ago
Python solution.
All test cases passed.
def find(arr,n,x): # code here l1=[-1,-1] c=arr.count(x) if c>0: a=arr.index(x) if c==1: return [a,a] if c>1: return [a,a+c-1] return l1
0
subhambhttachariya032 days ago
JAVA CODE :
ArrayList<Long> find(long arr[], int n, int x) { // code here HashMap<Integer, Long> ans = new HashMap<>(); ArrayList<Long> al = new ArrayList<>(); ArrayList<Long> res = new ArrayList<>(); for(int i = 0; i < n; i++) { if(arr[i] == x) { ans.put(i, arr[i]); // Store index as an Key } } if(ans.size() >= 1) { for(java.util.Map.Entry<Integer, Long> map : ans.entrySet()) { al.add((long)map.getKey()); // Add all the key in arrayList } Collections.sort(al); // Sort the index values res.add(al.get(0)); // Store the first value res.add(al.get(al.size()-1)); // Store the last value // System.out.println(ans); ans.clear(); al.clear(); } else { // If the search value is not present then add -1 res.add((long)-1); res.add((long)-1); } return res;
}
+1
ramesh76909507023 days ago
vector<int> find(int arr[], int n , int x )
{
// code here
vector<int> ans;
int s=0;
int e=n-1;
int first=-1;
int last=-1;
while(s<=e)
{
int mid=s+(e-s)/2;
if(arr[mid]==x)
{
first=mid;
e=mid-1;
}
else if(arr[mid]>x)
{
e=mid-1;
}
else
{
s=mid+1;
}
}
s=0;
e=n-1;
while(s<=e)
{
int mid=s+(e-s)/2;
if(arr[mid]==x)
{
last=mid;
s=mid+1;
}
else if(arr[mid]>x)
{
e=mid-1;
}
else
{
s=mid+1;
}
}
ans={first,last};
return ans;
}
0
mandeepjain004 days ago
Approach
Find an element X by using Binary Search
When you find x element save index in element and move end to m-1
This will help you to search first occurrence (agar uske phle koi element ho skta hai)
This way we can find last occurrence change is that instead of moving end to m-1 move start to m+1
OR you can find last occurrence iterative too complexity will be almost same (in coments)
Code
//first occurrence
int start = 0;
int end = n-1;
int StartPos = -1;
while(start <= end){
int mid = start + (end-start)/2;
if(arr[mid] == x){
StartPos = mid;
//jha element mila h uske phle bhi ho skta hai tou check kro
end = mid-1;
}
else if(arr[mid] < x) start = mid+1;
else end = mid-1;
}
if(StartPos < 0) return {-1,-1};
//last occurance
// int i = StartPos;
//while(arr[i] == x) i++;
int EndPos = -1;
start = 0;
end = n-1;
while(start <= end){
int mid = start + (end-start)/2;
if(arr[mid] == x){
EndPos = mid;
//jha element mila h uske phle bhi ho skta hai tou check kro
start = mid+1;
}
else if(arr[mid] < x) start = mid+1;
else end = mid-1;
}
return {StartPos, EndPos};
-1
himv1135 days ago
//C++ EASIEST SOLUTION
vector<int> find(int arr[], int n , int x )
{
// code here
vector<int>v;
int count=0;
for(int i=0;i<n;i++){
if(arr[i]==x){
v.push_back(i);
while(arr[i]==x){
count++;
i++;
}
break;
}
}
if(v.size()==0){
v.push_back(-1);
v.push_back(-1);
}
else{
v.push_back(v[0]+count-1);}
return v;
}
+2
lekoloritse5 days ago
SIMPLE JAVA CODE USING BINARY SEARCH
class GFG
{
ArrayList<Long> find(long arr[], int n, int x)
{
ArrayList<Long> list = new ArrayList<>();
list.add(first(arr,n,x));
list.add(last(arr,n,x));
return list;
}
public static long first(long[] arr, int n, int x){
int start=0;
int end= n-1;
long res=-1;
while(start<=end){
int mid = start + (end -start)/2;
if(x==arr[mid]){
res=mid;
end=mid-1;
}
else if(x<arr[mid]){
end=mid-1;
}
else{
start=mid+1;
}
}
return res;
}
public static long last(long[] arr, int n ,int x){
int start=0;
int end= n-1;
long res=-1;
while(start<=end){
int mid = start + (end -start)/2;
if(x==arr[mid]){
res=mid;
start=mid+1;
}
else if(x<arr[mid]){
end=mid-1;
}
else{
start=mid+1;
}
}
return res;
}
}
0
nitesh800
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
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": 401,
"s": 226,
"text": "Given a sorted array arr containing n elements with possibly duplicate elements, the task is to find indexes of first and last occurrences of an element x in the given array."
},
{
"code": null,
"e": 412,
"s": 401,
"text": "Example 1:"
},
{
"code": null,
"e": 588,
"s": 412,
"text": "Input:\nn=9, x=5\narr[] = { 1, 3, 5, 5, 5, 5, 67, 123, 125 }\nOutput: 2 5\nExplanation: First occurrence of 5 is at index 2 and last\n occurrence of 5 is at index 5. \n"
},
{
"code": null,
"e": 601,
"s": 590,
"text": "Example 2:"
},
{
"code": null,
"e": 675,
"s": 601,
"text": "Input:\nn=9, x=7\narr[] = { 1, 3, 5, 5, 5, 5, 7, 123, 125 }\nOutput: 6 6 \n\n"
},
{
"code": null,
"e": 1022,
"s": 675,
"text": "Your Task:\nSince, this is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function find() that takes array arr, integer n and integer x as parameters and returns the required answer.\nNote: If the number x is not found in the array just return both index as -1."
},
{
"code": null,
"e": 1090,
"s": 1024,
"text": "Expected Time Complexity: O(logN)\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 1117,
"s": 1092,
"text": "Constraints:\n1 ≤ N ≤ 107"
},
{
"code": null,
"e": 1122,
"s": 1119,
"text": "+1"
},
{
"code": null,
"e": 1145,
"s": 1122,
"text": "nikhil_deore1 hour ago"
},
{
"code": null,
"e": 1164,
"s": 1145,
"text": "C++ Fast AF 0.29"
},
{
"code": null,
"e": 1450,
"s": 1166,
"text": "vector<int> find(int arr[], int n , int x )\n{ long count=0;\n vector<long long>ans;\n for(long long i=0;i<n;i++){\n if(arr[i]==x){\n ans.push_back(i);\n count++;\n }\n }\n if(ans.size()==0){\n return {-1,-1};\n }\n return {ans[0],ans[count-1]};\n \n}"
},
{
"code": null,
"e": 1452,
"s": 1450,
"text": "0"
},
{
"code": null,
"e": 1475,
"s": 1452,
"text": "yashdalal452 hours ago"
},
{
"code": null,
"e": 1498,
"s": 1475,
"text": "Binary Search Solution"
},
{
"code": null,
"e": 1525,
"s": 1498,
"text": "Time Complexity : O(log n)"
},
{
"code": null,
"e": 1548,
"s": 1525,
"text": "Space Complexity: O(1)"
},
{
"code": null,
"e": 2412,
"s": 1548,
"text": "ArrayList<Long> find(long arr[], int n, int x)\n {\n // code here\n ArrayList<Long> a = new ArrayList<>();\n a.add((long)-1); // store min index\n a.add((long)-1); // store max index\n binary_s(arr,x,0,n-1,a);\n return a;\n \n }\n public void binary_s(long[] arr,int x,int s,int e,ArrayList<Long> a){\n if(s>e){\n return;\n }\n int mid = s+(e-s)/2;\n if(x<=arr[mid]){\n if(x==arr[mid]) {\n if(a.get(0)>mid || a.get(0)==-1) a.set(0,(long)mid);\n if(a.get(1)<mid) a.set(1,(long)mid);\n \n }\n binary_s(arr,x,s,mid-1,a);\n }\n //use if block again because in case when x==arr[mid] we have to search in both left and right part of array.\n if(x>=arr[mid]){ \n binary_s(arr,x,mid+1,e,a);\n }\n }"
},
{
"code": null,
"e": 2414,
"s": 2412,
"text": "0"
},
{
"code": null,
"e": 2443,
"s": 2414,
"text": "surabhichoubey5520 hours ago"
},
{
"code": null,
"e": 2473,
"s": 2443,
"text": " ALGO TO SOLVE THIS QUESTION "
},
{
"code": null,
"e": 2499,
"s": 2475,
"text": "based on binary search "
},
{
"code": null,
"e": 2525,
"s": 2501,
"text": "// for left occurrences"
},
{
"code": null,
"e": 2560,
"s": 2527,
"text": "lets take example of given array"
},
{
"code": null,
"e": 2597,
"s": 2560,
"text": "0 1 2 3 4 5 6 7 8 index"
},
{
"code": null,
"e": 2631,
"s": 2597,
"text": "1, 3, 5, 5, 5, 5, 7, 123, 125 arr"
},
{
"code": null,
"e": 2672,
"s": 2633,
"text": "LETS UNDERSTAND IN OUR NATIVE LANGUAGE"
},
{
"code": null,
"e": 2735,
"s": 2674,
"text": "1 first find mid if equal to key to answer mai store karalo "
},
{
"code": null,
"e": 2784,
"s": 2735,
"text": "maybe left mai iski or bhi occurrences mil jaye "
},
{
"code": null,
"e": 2826,
"s": 2784,
"text": "fir ham apne end ko left mai lane ke liye"
},
{
"code": null,
"e": 2856,
"s": 2826,
"text": " end = mid-1 //left wala part"
},
{
"code": null,
"e": 2869,
"s": 2856,
"text": "kr dete hain"
},
{
"code": null,
"e": 2914,
"s": 2871,
"text": "2 further steps are same as binary search "
},
{
"code": null,
"e": 3048,
"s": 2914,
"text": "2.1 if the key, you are searching for is less than mid that means hamko left wale part pr aana hai iske liye end = mid-1 kr dete hain"
},
{
"code": null,
"e": 3112,
"s": 3050,
"text": "2.2 if the key you are searching for is greater than arr[mid]"
},
{
"code": null,
"e": 3166,
"s": 3112,
"text": "that means hamko right wale part pr search karna hai "
},
{
"code": null,
"e": 3177,
"s": 3166,
"text": "s = mid+1;"
},
{
"code": null,
"e": 3222,
"s": 3179,
"text": "3 and yeah don't forget to update your mid"
},
{
"code": null,
"e": 3252,
"s": 3228,
"text": "//for right occurrences"
},
{
"code": null,
"e": 3301,
"s": 3254,
"text": "1 same as left occurence but the key point is "
},
{
"code": null,
"e": 3363,
"s": 3301,
"text": "if arr[mid] == key than store it in ans and go for right side"
},
{
"code": null,
"e": 3417,
"s": 3363,
"text": "maybe we are able to find its right most occurrences "
},
{
"code": null,
"e": 3459,
"s": 3417,
"text": "for that start = mid + 1//right wala part"
},
{
"code": null,
"e": 3489,
"s": 3461,
"text": "and furhter steps are same "
},
{
"code": null,
"e": 3539,
"s": 3489,
"text": "store both the answer in vector ans return happy!"
},
{
"code": null,
"e": 3606,
"s": 3539,
"text": "// { Driver Code Starts#include<bits/stdc++.h>using namespace std;"
},
{
"code": null,
"e": 4488,
"s": 3606,
"text": "// } Driver Code Endsvector<int> find(int arr[], int n , int key ){ // code here vector<int>ans; int s = 0; int e = n-1; int mid = s+(e-s)/2; int ans1 = -1; //left occurance while(s<=e) { if(arr[mid] == key) { ans1 = mid; e = mid-1; } else if(key>arr[mid]) { s = mid+1; } else if(key<arr[mid]) { e = mid-1; } mid = (s+e)/2; } ans.push_back(ans1); //right int s1 = 0; int e1 = n-1; int mid1 = s+(e-s)/2; int ans2 = -1; while(s1<=e1) { if(arr[mid1] == key) { ans2 = mid1; s1 = mid1+1; } else if(key>arr[mid1]) { s1 = mid1+1; } else if(key<arr[mid1]) { e1 = mid1-1; } mid1 = (s1+e1)/2; } ans.push_back(ans2); return ans; }"
},
{
"code": null,
"e": 4502,
"s": 4500,
"text": "0"
},
{
"code": null,
"e": 4524,
"s": 4502,
"text": "vijeayaetv02 days ago"
},
{
"code": null,
"e": 4541,
"s": 4524,
"text": "Python solution."
},
{
"code": null,
"e": 4564,
"s": 4541,
"text": "All test cases passed."
},
{
"code": null,
"e": 4751,
"s": 4566,
"text": "def find(arr,n,x): # code here l1=[-1,-1] c=arr.count(x) if c>0: a=arr.index(x) if c==1: return [a,a] if c>1: return [a,a+c-1] return l1"
},
{
"code": null,
"e": 4755,
"s": 4753,
"text": "0"
},
{
"code": null,
"e": 4786,
"s": 4755,
"text": "subhambhttachariya032 days ago"
},
{
"code": null,
"e": 4799,
"s": 4786,
"text": "JAVA CODE : "
},
{
"code": null,
"e": 5847,
"s": 4801,
"text": "ArrayList<Long> find(long arr[], int n, int x) { // code here HashMap<Integer, Long> ans = new HashMap<>(); ArrayList<Long> al = new ArrayList<>(); ArrayList<Long> res = new ArrayList<>(); for(int i = 0; i < n; i++) { if(arr[i] == x) { ans.put(i, arr[i]); // Store index as an Key } } if(ans.size() >= 1) { for(java.util.Map.Entry<Integer, Long> map : ans.entrySet()) { al.add((long)map.getKey()); // Add all the key in arrayList } Collections.sort(al); // Sort the index values res.add(al.get(0)); // Store the first value res.add(al.get(al.size()-1)); // Store the last value // System.out.println(ans); ans.clear(); al.clear(); } else { // If the search value is not present then add -1 res.add((long)-1); res.add((long)-1); } return res;"
},
{
"code": null,
"e": 5852,
"s": 5847,
"text": " }"
},
{
"code": null,
"e": 5855,
"s": 5852,
"text": "+1"
},
{
"code": null,
"e": 5882,
"s": 5855,
"text": "ramesh76909507023 days ago"
},
{
"code": null,
"e": 6584,
"s": 5882,
"text": "vector<int> find(int arr[], int n , int x )\n{\n // code here\n vector<int> ans;\n int s=0;\n int e=n-1;\n int first=-1;\n int last=-1;\n while(s<=e)\n {\n int mid=s+(e-s)/2;\n if(arr[mid]==x)\n {\n first=mid;\n e=mid-1;\n }\n else if(arr[mid]>x)\n {\n e=mid-1;\n }\n else\n {\n s=mid+1;\n }\n }\n \n s=0;\n e=n-1;\n \n while(s<=e)\n {\n int mid=s+(e-s)/2;\n if(arr[mid]==x)\n {\n last=mid;\n s=mid+1;\n }\n else if(arr[mid]>x)\n {\n e=mid-1;\n }\n else\n {\n s=mid+1;\n }\n }\n ans={first,last};\n return ans;\n}"
},
{
"code": null,
"e": 6586,
"s": 6584,
"text": "0"
},
{
"code": null,
"e": 6610,
"s": 6586,
"text": "mandeepjain004 days ago"
},
{
"code": null,
"e": 6619,
"s": 6610,
"text": "Approach"
},
{
"code": null,
"e": 6665,
"s": 6621,
"text": "Find an element X by using Binary Search "
},
{
"code": null,
"e": 6732,
"s": 6665,
"text": "When you find x element save index in element and move end to m-1 "
},
{
"code": null,
"e": 6819,
"s": 6732,
"text": "This will help you to search first occurrence (agar uske phle koi element ho skta hai)"
},
{
"code": null,
"e": 6921,
"s": 6821,
"text": "This way we can find last occurrence change is that instead of moving end to m-1 move start to m+1 "
},
{
"code": null,
"e": 7015,
"s": 6923,
"text": " OR you can find last occurrence iterative too complexity will be almost same (in coments)"
},
{
"code": null,
"e": 7023,
"s": 7017,
"text": "Code "
},
{
"code": null,
"e": 7918,
"s": 7023,
"text": "//first occurrence \n int start = 0;\n int end = n-1;\n int StartPos = -1;\n while(start <= end){\n \n int mid = start + (end-start)/2;\n if(arr[mid] == x){\n StartPos = mid;\n //jha element mila h uske phle bhi ho skta hai tou check kro\n end = mid-1;\n }\n else if(arr[mid] < x) start = mid+1;\n else end = mid-1;\n }\n \n if(StartPos < 0) return {-1,-1};\n //last occurance \n // int i = StartPos;\n //while(arr[i] == x) i++;\n int EndPos = -1;\n start = 0;\n end = n-1;\n while(start <= end){\n \n int mid = start + (end-start)/2;\n if(arr[mid] == x){\n EndPos = mid;\n //jha element mila h uske phle bhi ho skta hai tou check kro\n start = mid+1;\n }\n else if(arr[mid] < x) start = mid+1;\n else end = mid-1;\n }\n return {StartPos, EndPos};"
},
{
"code": null,
"e": 7921,
"s": 7918,
"text": "-1"
},
{
"code": null,
"e": 7939,
"s": 7921,
"text": "himv1135 days ago"
},
{
"code": null,
"e": 8377,
"s": 7939,
"text": "//C++ EASIEST SOLUTION\nvector<int> find(int arr[], int n , int x )\n{\n // code here\n vector<int>v;\n int count=0;\n for(int i=0;i<n;i++){\n if(arr[i]==x){\n v.push_back(i);\n while(arr[i]==x){\n count++;\n i++;\n }\n break;\n }\n }\n if(v.size()==0){\n v.push_back(-1);\n v.push_back(-1);\n }\n else{\n v.push_back(v[0]+count-1);}\n return v;\n}"
},
{
"code": null,
"e": 8380,
"s": 8377,
"text": "+2"
},
{
"code": null,
"e": 8402,
"s": 8380,
"text": "lekoloritse5 days ago"
},
{
"code": null,
"e": 8439,
"s": 8402,
"text": "SIMPLE JAVA CODE USING BINARY SEARCH"
},
{
"code": null,
"e": 9573,
"s": 8439,
"text": "class GFG\n{\n ArrayList<Long> find(long arr[], int n, int x)\n {\n ArrayList<Long> list = new ArrayList<>();\n list.add(first(arr,n,x));\n list.add(last(arr,n,x));\n return list;\n }\n public static long first(long[] arr, int n, int x){\n int start=0;\n int end= n-1;\n long res=-1;\n while(start<=end){\n int mid = start + (end -start)/2;\n if(x==arr[mid]){\n res=mid;\n end=mid-1;\n }\n else if(x<arr[mid]){\n end=mid-1;\n }\n else{\n start=mid+1;\n }\n }\n return res;\n }\n public static long last(long[] arr, int n ,int x){\n int start=0;\n int end= n-1;\n long res=-1;\n while(start<=end){\n int mid = start + (end -start)/2;\n if(x==arr[mid]){\n res=mid;\n start=mid+1;\n }\n else if(x<arr[mid]){\n end=mid-1;\n }\n else{\n start=mid+1;\n }\n }\n return res;\n }\n}"
},
{
"code": null,
"e": 9575,
"s": 9573,
"text": "0"
},
{
"code": null,
"e": 9585,
"s": 9575,
"text": "nitesh800"
},
{
"code": null,
"e": 9611,
"s": 9585,
"text": "This comment was deleted."
},
{
"code": null,
"e": 9757,
"s": 9611,
"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": 9793,
"s": 9757,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 9803,
"s": 9793,
"text": "\nProblem\n"
},
{
"code": null,
"e": 9813,
"s": 9803,
"text": "\nContest\n"
},
{
"code": null,
"e": 9876,
"s": 9813,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 10061,
"s": 9876,
"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": 10345,
"s": 10061,
"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": 10491,
"s": 10345,
"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": 10568,
"s": 10491,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 10609,
"s": 10568,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 10637,
"s": 10609,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 10708,
"s": 10637,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 10895,
"s": 10708,
"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."
}
] |
ComboBox in C# - GeeksforGeeks
|
30 Jun, 2019
In Windows Forms, ComboBox provides two different features in a single control, it means ComboBox works as both TextBox and ListBox. In ComboBox, only one item is displayed at a time and the rest of the items are present in the drop-down menu. The ComboBox is a class in C# and defined under System.Windows.Forms Namespace. You can create ComboBox using the two different ways:
1. Design-Time: It is the easiest method to create a ComboBox control using the following steps:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the ComboBox control from the ToolBox and drop it on the windows form. You are allowed to place a ComboBox control anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the ComboBox control to set the properties of the ComboBox according to your need.Output:
Output:
Run-Time: It is a little bit trickier than the above method. In this method, you can set create your own ComboBox control using the ComboBox class. Steps to create a dynamic ComboBox:
Step 1: Create a combobox using the ComboBox() constructor is provided by the ComboBox class.// Creating combobox using ComboBox class
ComboBox mybox = new ComboBox();
// Creating combobox using ComboBox class
ComboBox mybox = new ComboBox();
Step 2: After creating ComboBox, set the properties of the ComboBox provided by the ComboBox class.// Set the location of the ComboBox
mybox.Location = new Point(327, 77);
// Set the size of the ComboBox
mybox.Size = new Size(216, 26);
// Add items in the ComboBox
mybox.Items.Add("C#");
mybox.Items.Add("Java");
mybox.Items.Add("Scala");
mybox.Items.Add("C");
mybox.Items.Add("C++");
// Set the location of the ComboBox
mybox.Location = new Point(327, 77);
// Set the size of the ComboBox
mybox.Size = new Size(216, 26);
// Add items in the ComboBox
mybox.Items.Add("C#");
mybox.Items.Add("Java");
mybox.Items.Add("Scala");
mybox.Items.Add("C");
mybox.Items.Add("C++");
Step 3: And last add this ComboBox control to form using Add() method.// Add this ComboBox to the form
this.Controls.Add(mybox);
Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp18 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(122, 80); l.AutoSize = true; l.Text = "Select Programming Language"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.Items.Add("C#"); mybox.Items.Add("Java"); mybox.Items.Add("Scala"); mybox.Items.Add("C"); mybox.Items.Add("C++"); // Adding this ComboBox to the form this.Controls.Add(mybox); }}}Output:
// Add this ComboBox to the form
this.Controls.Add(mybox);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp18 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(122, 80); l.AutoSize = true; l.Text = "Select Programming Language"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.Items.Add("C#"); mybox.Items.Add("Java"); mybox.Items.Add("Scala"); mybox.Items.Add("C"); mybox.Items.Add("C++"); // Adding this ComboBox to the form this.Controls.Add(mybox); }}}
Output:
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Method Overriding
Difference between Ref and Out keywords in C#
C# | Delegates
Top 50 C# Interview Questions & Answers
Introduction to .NET Framework
C# | Constructors
Extension Method in C#
C# | Class and Object
C# | Abstract Classes
C# | String.IndexOf( ) Method | Set - 1
|
[
{
"code": null,
"e": 23585,
"s": 23557,
"text": "\n30 Jun, 2019"
},
{
"code": null,
"e": 23963,
"s": 23585,
"text": "In Windows Forms, ComboBox provides two different features in a single control, it means ComboBox works as both TextBox and ListBox. In ComboBox, only one item is displayed at a time and the rest of the items are present in the drop-down menu. The ComboBox is a class in C# and defined under System.Windows.Forms Namespace. You can create ComboBox using the two different ways:"
},
{
"code": null,
"e": 24060,
"s": 23963,
"text": "1. Design-Time: It is the easiest method to create a ComboBox control using the following steps:"
},
{
"code": null,
"e": 24176,
"s": 24060,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 24357,
"s": 24176,
"text": "Step 2: Drag the ComboBox control from the ToolBox and drop it on the windows form. You are allowed to place a ComboBox control anywhere on the windows form according to your need."
},
{
"code": null,
"e": 24508,
"s": 24357,
"text": "Step 3: After drag and drop you will go to the properties of the ComboBox control to set the properties of the ComboBox according to your need.Output:"
},
{
"code": null,
"e": 24516,
"s": 24508,
"text": "Output:"
},
{
"code": null,
"e": 24700,
"s": 24516,
"text": "Run-Time: It is a little bit trickier than the above method. In this method, you can set create your own ComboBox control using the ComboBox class. Steps to create a dynamic ComboBox:"
},
{
"code": null,
"e": 24869,
"s": 24700,
"text": "Step 1: Create a combobox using the ComboBox() constructor is provided by the ComboBox class.// Creating combobox using ComboBox class\nComboBox mybox = new ComboBox();\n"
},
{
"code": null,
"e": 24945,
"s": 24869,
"text": "// Creating combobox using ComboBox class\nComboBox mybox = new ComboBox();\n"
},
{
"code": null,
"e": 25334,
"s": 24945,
"text": "Step 2: After creating ComboBox, set the properties of the ComboBox provided by the ComboBox class.// Set the location of the ComboBox \nmybox.Location = new Point(327, 77);\n\n// Set the size of the ComboBox\nmybox.Size = new Size(216, 26);\n\n// Add items in the ComboBox\nmybox.Items.Add(\"C#\");\nmybox.Items.Add(\"Java\");\nmybox.Items.Add(\"Scala\");\nmybox.Items.Add(\"C\");\nmybox.Items.Add(\"C++\");\n"
},
{
"code": null,
"e": 25624,
"s": 25334,
"text": "// Set the location of the ComboBox \nmybox.Location = new Point(327, 77);\n\n// Set the size of the ComboBox\nmybox.Size = new Size(216, 26);\n\n// Add items in the ComboBox\nmybox.Items.Add(\"C#\");\nmybox.Items.Add(\"Java\");\nmybox.Items.Add(\"Scala\");\nmybox.Items.Add(\"C\");\nmybox.Items.Add(\"C++\");\n"
},
{
"code": null,
"e": 26856,
"s": 25624,
"text": "Step 3: And last add this ComboBox control to form using Add() method.// Add this ComboBox to the form\nthis.Controls.Add(mybox);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp18 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(122, 80); l.AutoSize = true; l.Text = \"Select Programming Language\"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.Items.Add(\"C#\"); mybox.Items.Add(\"Java\"); mybox.Items.Add(\"Scala\"); mybox.Items.Add(\"C\"); mybox.Items.Add(\"C++\"); // Adding this ComboBox to the form this.Controls.Add(mybox); }}}Output:"
},
{
"code": null,
"e": 26916,
"s": 26856,
"text": "// Add this ComboBox to the form\nthis.Controls.Add(mybox);\n"
},
{
"code": null,
"e": 26925,
"s": 26916,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp18 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Location = new Point(122, 80); l.AutoSize = true; l.Text = \"Select Programming Language\"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the properties of comboBox ComboBox mybox = new ComboBox(); mybox.Location = new Point(327, 77); mybox.Size = new Size(216, 26); mybox.Items.Add(\"C#\"); mybox.Items.Add(\"Java\"); mybox.Items.Add(\"Scala\"); mybox.Items.Add(\"C\"); mybox.Items.Add(\"C++\"); // Adding this ComboBox to the form this.Controls.Add(mybox); }}}",
"e": 28013,
"s": 26925,
"text": null
},
{
"code": null,
"e": 28021,
"s": 28013,
"text": "Output:"
},
{
"code": null,
"e": 28024,
"s": 28021,
"text": "C#"
},
{
"code": null,
"e": 28122,
"s": 28024,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28131,
"s": 28122,
"text": "Comments"
},
{
"code": null,
"e": 28144,
"s": 28131,
"text": "Old Comments"
},
{
"code": null,
"e": 28167,
"s": 28144,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 28213,
"s": 28167,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 28228,
"s": 28213,
"text": "C# | Delegates"
},
{
"code": null,
"e": 28268,
"s": 28228,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28299,
"s": 28268,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 28317,
"s": 28299,
"text": "C# | Constructors"
},
{
"code": null,
"e": 28340,
"s": 28317,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28362,
"s": 28340,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 28384,
"s": 28362,
"text": "C# | Abstract Classes"
}
] |
Python Seaborn Plots in R using reticulate | by AbdulMajedRaja RS | Towards Data Science
|
I think there is no argument about how ggplot2 amazing is. But there are a couple of plots that I admire in Python’s modern Data Visualisation library Seaborn. It’s not just it produces high-quality visualization but also how easy and simple it is building that one. Those two plots are heatmap and pairplot. I’ve always missed them but I guess not anymore.
What If I tell you that you can now build that Seaborn heatmap and pairplot in R using your RStudio? In this post, We will see how to make such Seaborn visualizations like Pairplot and Heatmap and for that matter, any Python code in R.
The Holy Grail here is the recently made available R package reticulate, developed by RStudio.
The reticulate package provides a comprehensive set of tools for interoperability between Python and R. The package includes facilities for:
Calling Python from R in a variety of ways including R Markdown, sourcing Python scripts, importing Python modules, and using Python interactively within an R session.
Translation between R and Python objects (for example, between R and Pandas data frames, or between R matrices and NumPy arrays).
Flexible binding to different versions of Python including virtual environments and Conda environments.
Reticulate embeds a Python session within your R session, enabling seamless, high-performance interoperability.
reticulate is available on CRAN and can be installed with the below code:
install.packages('reticulate')
Let us load the R package (just like we load other R packages) into our current R session:
#loading required R libraries library(reticulate) #the superpower bridges python and R
Remember, You need to have Python in your machine for this package to access. So make sure you have got you Python installed along with the required packages and are available on the PATH and by default, reticulate uses the Python version that’s on the PATH. If you have got multiple Python versions on your machine, you can instruct which version of Python for reticulate to use with the following code:
#specifying which version of python to useuse_python('C:\\PROGRA~1\\Python35\\python.exe')
import() function helps in importing the specified Python library into the current R session. Remember, the specified Python library must have been already installed on the machine.
#importing required Python libraries/modulessns <- import('seaborn')plt <- import('matplotlib.pyplot')pd <- import('pandas')
This code does two things:
#using R's inbuilt AirPassengers datasetdf <- datasets::AirPassengers#converting Time-Series object into an R Dataframe #Thx: https://stackoverflow.com/questions/5331901/transforming-a-time-series-into-a-data-frame-and-backdf1 <- data.frame(tapply(df, list(year = floor(time(df)), month = month.abb[cycle(df)]), c))df1 <- df1[month.abb]#building a heatmap using seaborn #please note the function r_to_py() that converts R object into a python sns$heatmap(r_to_py(df1), fmt="g", cmap ='viridis')#display the plotplt$show()
Gives this plot:
That’s really a beautiful heatmap. To understand what’s going on there, We have taken AirPassengers dataset which is an R Object in Time Series format. That is converted to a dataframe which is then inputted to seaborn’s heatmap function to plot the heatmap. A few things to note down here:
The function of a python package is accessed using $ symbol after the object into which the Python library is loaded. This is very similar to how a column of a dataframe is accessed usin $.
r_to_py() is a function used to convert R objects into Python objects. In this case, an R dataframe is converted into a Python Pandas Dataframe which is ideally the object type that the heatmap function would take in to plot the heatmap.
#building a seaborn pairplot using pairplot()sns$pairplot(r_to_py(iris), hue = 'Species')#display the plotplt$show()
Gives this plot:
And this is a good plot to understand pairwise relationships in the given dataset.
Thus with very little coding and configurations, we managed to beautifully visualize the given dataset using Python Seaborn in R and plotted Heatmap and Pairplot. While this post might have been very specific about making those two plots, the larger idea to be inferred from this post is to understand how simpler and easier it is to integrate Python codes into your R codes with reticulate package. The complete code used here is available on my github. R is an amazing tool for Data Visualization of any form and to learn more check out this.
|
[
{
"code": null,
"e": 529,
"s": 171,
"text": "I think there is no argument about how ggplot2 amazing is. But there are a couple of plots that I admire in Python’s modern Data Visualisation library Seaborn. It’s not just it produces high-quality visualization but also how easy and simple it is building that one. Those two plots are heatmap and pairplot. I’ve always missed them but I guess not anymore."
},
{
"code": null,
"e": 765,
"s": 529,
"text": "What If I tell you that you can now build that Seaborn heatmap and pairplot in R using your RStudio? In this post, We will see how to make such Seaborn visualizations like Pairplot and Heatmap and for that matter, any Python code in R."
},
{
"code": null,
"e": 860,
"s": 765,
"text": "The Holy Grail here is the recently made available R package reticulate, developed by RStudio."
},
{
"code": null,
"e": 1001,
"s": 860,
"text": "The reticulate package provides a comprehensive set of tools for interoperability between Python and R. The package includes facilities for:"
},
{
"code": null,
"e": 1169,
"s": 1001,
"text": "Calling Python from R in a variety of ways including R Markdown, sourcing Python scripts, importing Python modules, and using Python interactively within an R session."
},
{
"code": null,
"e": 1299,
"s": 1169,
"text": "Translation between R and Python objects (for example, between R and Pandas data frames, or between R matrices and NumPy arrays)."
},
{
"code": null,
"e": 1403,
"s": 1299,
"text": "Flexible binding to different versions of Python including virtual environments and Conda environments."
},
{
"code": null,
"e": 1515,
"s": 1403,
"text": "Reticulate embeds a Python session within your R session, enabling seamless, high-performance interoperability."
},
{
"code": null,
"e": 1589,
"s": 1515,
"text": "reticulate is available on CRAN and can be installed with the below code:"
},
{
"code": null,
"e": 1620,
"s": 1589,
"text": "install.packages('reticulate')"
},
{
"code": null,
"e": 1711,
"s": 1620,
"text": "Let us load the R package (just like we load other R packages) into our current R session:"
},
{
"code": null,
"e": 1798,
"s": 1711,
"text": "#loading required R libraries library(reticulate) #the superpower bridges python and R"
},
{
"code": null,
"e": 2203,
"s": 1798,
"text": "Remember, You need to have Python in your machine for this package to access. So make sure you have got you Python installed along with the required packages and are available on the PATH and by default, reticulate uses the Python version that’s on the PATH. If you have got multiple Python versions on your machine, you can instruct which version of Python for reticulate to use with the following code:"
},
{
"code": null,
"e": 2294,
"s": 2203,
"text": "#specifying which version of python to useuse_python('C:\\\\PROGRA~1\\\\Python35\\\\python.exe')"
},
{
"code": null,
"e": 2476,
"s": 2294,
"text": "import() function helps in importing the specified Python library into the current R session. Remember, the specified Python library must have been already installed on the machine."
},
{
"code": null,
"e": 2601,
"s": 2476,
"text": "#importing required Python libraries/modulessns <- import('seaborn')plt <- import('matplotlib.pyplot')pd <- import('pandas')"
},
{
"code": null,
"e": 2628,
"s": 2601,
"text": "This code does two things:"
},
{
"code": null,
"e": 3150,
"s": 2628,
"text": "#using R's inbuilt AirPassengers datasetdf <- datasets::AirPassengers#converting Time-Series object into an R Dataframe #Thx: https://stackoverflow.com/questions/5331901/transforming-a-time-series-into-a-data-frame-and-backdf1 <- data.frame(tapply(df, list(year = floor(time(df)), month = month.abb[cycle(df)]), c))df1 <- df1[month.abb]#building a heatmap using seaborn #please note the function r_to_py() that converts R object into a python sns$heatmap(r_to_py(df1), fmt=\"g\", cmap ='viridis')#display the plotplt$show()"
},
{
"code": null,
"e": 3167,
"s": 3150,
"text": "Gives this plot:"
},
{
"code": null,
"e": 3458,
"s": 3167,
"text": "That’s really a beautiful heatmap. To understand what’s going on there, We have taken AirPassengers dataset which is an R Object in Time Series format. That is converted to a dataframe which is then inputted to seaborn’s heatmap function to plot the heatmap. A few things to note down here:"
},
{
"code": null,
"e": 3648,
"s": 3458,
"text": "The function of a python package is accessed using $ symbol after the object into which the Python library is loaded. This is very similar to how a column of a dataframe is accessed usin $."
},
{
"code": null,
"e": 3886,
"s": 3648,
"text": "r_to_py() is a function used to convert R objects into Python objects. In this case, an R dataframe is converted into a Python Pandas Dataframe which is ideally the object type that the heatmap function would take in to plot the heatmap."
},
{
"code": null,
"e": 4003,
"s": 3886,
"text": "#building a seaborn pairplot using pairplot()sns$pairplot(r_to_py(iris), hue = 'Species')#display the plotplt$show()"
},
{
"code": null,
"e": 4020,
"s": 4003,
"text": "Gives this plot:"
},
{
"code": null,
"e": 4103,
"s": 4020,
"text": "And this is a good plot to understand pairwise relationships in the given dataset."
}
] |
HTML5 | Semantics - GeeksforGeeks
|
13 Aug, 2021
HTML tags are classified in two types.
Semantic
Non-Semantic
Semantic Elements: Semantic elements have meaningful names which tells about type of content. For example header, footer, table, ... etc. HTML5 introduces many semantic elements as mentioned below which make the code easier to write and understand for the developer as well as instructs the browser on how to treat them.
article
aside
details
figcaption
figure
footer
header
main
mark
nav
section
Article: It contains independent content which doesnt require any other context. Example: Blog Post, Newspaper Article etc.
html
<!DOCTYPE html><html> <head> <title>Article Tag</title> <style> h1 { Color:#006400; font-size:50px; Text-align:left; } p { font-size:25px; text-align:left; margin-top:-40px; } </style> </head> <body> <article> <h1>GeeksforGeeks</h1> <p>A Computer Science Portal for Geeks</p> </article> </body></html>
Output:
Aside: It is used to place content in a sidebar i.e. aside the existing content. It is related to surrounding content.
html
<!DOCTYPE html><html> <head> <title>Aside Tag</title> <style> h4 { Color:#006400; font-size:50px; Text-align:none; margin-bottom:0px; } p { font-size:25px; text-align:none; margin-top:0px; } </style> </head> <body> <p>GeeksforGeeks is a Computer Science Portal</p> <aside> <h4>GeeksForGeeks</h4> <p>GeeksforGeeks is a computer Science platform where you can learn good programming. </p> </aside> </body></html>
Output:
Details and Summary: “details” defines additional details that the user can hide or view. “summary” defines a visible heading for a “details” element.
html
<!DOCTYPE html><html> <head> <title>Detail and summary Tag</title> <style> .GFG { Color:#006400; font-size:50px; Text-align:none; margin-bottom:0px; } p { font-size:25px; text-align:none; margin-top:0px; } </style> </head> <body> <details> <summary class="GFG">GeeksforGeeks</summary> <p>GeeksforGeeks is a Computer Science portal where you can learn good programming. </p> </details> </body></html>
Output:
Figure and Figcaption: These are used to add an image in a web page with small description.
html
<!DOCTYPE html><html> <head> <title>Figcaption Tag</title> <style> h2 { Color:#006400; font-size:50px; Text-align:none; margin-bottom:0px; } p { font-size:25px; text-align:none; margin-top:0px; } </style> </head> <body> <h2>GeeksforGeeks</h2> <figure> <img src="4.jpg" alt="gfg" style="width:20%"> <figcaption>GeeksforGeeks Logo</figcaption> </figure> </body></html>
Output:
Header: As the name suggests, it is for the header of a section introductory of a page. There can be multiple headers on a page.
html
<!DOCTYPE html><html> <head> <title>Header Tag</title> <style> h1, h3 { Color:#006400; Text-align:left; margin-bottom:0px; } p { font-size:25px; text-align:left; margin-top:0px; } </style> </head> <body> <article> <header> <h1>GeeksforGeeks</h1> <h3>GeeksforGeeks</h3> <p>A computer Science portal</p> </header> </article> </body></html>
Output:
Footer: Footer located at the bottom of any article or document, they can contain contact details, copyright information etc. There can be multiple footers on a page.
html
<!DOCTYPE html><html> <head> <title>footer Tag</title> <style> p { font-size:25px; text-align:left; margin-top:0px; } </style> </head> <body> <footer> <p>Posted by: GeeksforGeeks</p> <p>Contact: <a href="https://www.geeksforgeeks.org"> geeksforgeeks.org</a>. </p> </footer> </body></html>
Output:
Main: It defines the main content of the document. The content inside main tag should be unique.
html
<!DOCTYPE html><html> <head> <title>main Tag</title> <style> h1 { color:#006400; } p { font-size:25px; text-align:none; margin-top:0px; } </style> </head> <body> <main> <h1>Important Residences</h1> <p>A few of them are Rashtrapati Bhavan, White House etc</p> <article> <h1>Rashtrapati Bhavan</h1> <p>It is the home of the President of India.</p> </article> <article> <h1>The White House</h1> <p>It is the home of the President of United States of America. </p> </article> </main> </body></html>
Output:
Section: A page can be split into sections like Introduction, Contact Information, Details etc and each of these sections can be in a different section tag.
html
<!DOCTYPE html><html> <head> <title>section Tag</title> <style> h1 { color:#006400; } p { font-size:25px; text-align:none; margin-top:0px; } </style> </head> <body> <section> <h1>Data Structure</h1> <p>Data Structure is a data organization and storage format that enables efficient access and modification. </p> </section> <section> <h1>Algorithm</h1> <p>A process or set of rules to be followed in calculations or other problem-solving operations, especially by a computer. </p> </section> </body></html>
Output:
nav: It is used to define a set of navigation links in the form of navigation bar or nav menu.
html
<!DOCTYPE html><html> <head> <title>nav Tag</title> <style> h1 { color:#006400; } </style> </head> <body> <h1>Navigation Bar</h1> <nav> <a href="/home/">Home</a> | <a href="/about-us/">About Us</a> | <a href="/data-structure/">Data Structure</a> | <a href="/operating-system/">Operating System</a> </nav> </body></html>
Output:
Mark: It is used to highlight the text.
html
<!DOCTYPE html><html> <head> <title>mark Tag</title> <style> h1 { color:#006400; } </style> </head> <body> <h1>mark tag</h1> <p>GeeksforGeeks is a <mark>Computer Science</mark> portal</p> </body></html>
Output:
Non-Semantic Elements: Tags like div, span fall under the Non- Semantic categories as their names don’t tell anything about what kind of content is present inside them.div It is a block level element or division of a section. It is used as a container.
html
<!DOCTYPE html><html> <head> <title>div Tag</title> <style> .GFG { color:#006400; } </style> </head> <body> <h1>div Tag</h1> <div class="GFG"> <h1>GeeksforGeeks</h1> <p>GeeksforGeeks is a Computer Science portal</p> </div> </body></html>
Output:
span: It is an inline element which doesn’t start on a new line and takes up only the necessary width. For more details use https://www.geeksforgeeks.org/span-tag-html/.
Supported Browsers:
Google Chrome 6.0 and above
Internet Explorer 9.0 and above
Mozilla 4.0 and above
Opera 11.1 and above
Safari 5.0 and above
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
ysachin2314
HTML5
Web technologies
CSS
HTML
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
|
[
{
"code": null,
"e": 22985,
"s": 22957,
"text": "\n13 Aug, 2021"
},
{
"code": null,
"e": 23026,
"s": 22985,
"text": "HTML tags are classified in two types. "
},
{
"code": null,
"e": 23035,
"s": 23026,
"text": "Semantic"
},
{
"code": null,
"e": 23048,
"s": 23035,
"text": "Non-Semantic"
},
{
"code": null,
"e": 23371,
"s": 23048,
"text": "Semantic Elements: Semantic elements have meaningful names which tells about type of content. For example header, footer, table, ... etc. HTML5 introduces many semantic elements as mentioned below which make the code easier to write and understand for the developer as well as instructs the browser on how to treat them. "
},
{
"code": null,
"e": 23379,
"s": 23371,
"text": "article"
},
{
"code": null,
"e": 23385,
"s": 23379,
"text": "aside"
},
{
"code": null,
"e": 23393,
"s": 23385,
"text": "details"
},
{
"code": null,
"e": 23404,
"s": 23393,
"text": "figcaption"
},
{
"code": null,
"e": 23411,
"s": 23404,
"text": "figure"
},
{
"code": null,
"e": 23418,
"s": 23411,
"text": "footer"
},
{
"code": null,
"e": 23425,
"s": 23418,
"text": "header"
},
{
"code": null,
"e": 23430,
"s": 23425,
"text": "main"
},
{
"code": null,
"e": 23435,
"s": 23430,
"text": "mark"
},
{
"code": null,
"e": 23439,
"s": 23435,
"text": "nav"
},
{
"code": null,
"e": 23447,
"s": 23439,
"text": "section"
},
{
"code": null,
"e": 23572,
"s": 23447,
"text": "Article: It contains independent content which doesnt require any other context. Example: Blog Post, Newspaper Article etc. "
},
{
"code": null,
"e": 23577,
"s": 23572,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Article Tag</title> <style> h1 { Color:#006400; font-size:50px; Text-align:left; } p { font-size:25px; text-align:left; margin-top:-40px; } </style> </head> <body> <article> <h1>GeeksforGeeks</h1> <p>A Computer Science Portal for Geeks</p> </article> </body></html>",
"e": 24010,
"s": 23577,
"text": null
},
{
"code": null,
"e": 24020,
"s": 24010,
"text": "Output: "
},
{
"code": null,
"e": 24140,
"s": 24020,
"text": "Aside: It is used to place content in a sidebar i.e. aside the existing content. It is related to surrounding content. "
},
{
"code": null,
"e": 24145,
"s": 24140,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Aside Tag</title> <style> h4 { Color:#006400; font-size:50px; Text-align:none; margin-bottom:0px; } p { font-size:25px; text-align:none; margin-top:0px; } </style> </head> <body> <p>GeeksforGeeks is a Computer Science Portal</p> <aside> <h4>GeeksForGeeks</h4> <p>GeeksforGeeks is a computer Science platform where you can learn good programming. </p> </aside> </body></html>",
"e": 24721,
"s": 24145,
"text": null
},
{
"code": null,
"e": 24730,
"s": 24721,
"text": "Output: "
},
{
"code": null,
"e": 24882,
"s": 24730,
"text": "Details and Summary: “details” defines additional details that the user can hide or view. “summary” defines a visible heading for a “details” element. "
},
{
"code": null,
"e": 24887,
"s": 24882,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Detail and summary Tag</title> <style> .GFG { Color:#006400; font-size:50px; Text-align:none; margin-bottom:0px; } p { font-size:25px; text-align:none; margin-top:0px; } </style> </head> <body> <details> <summary class=\"GFG\">GeeksforGeeks</summary> <p>GeeksforGeeks is a Computer Science portal where you can learn good programming. </p> </details> </body></html>",
"e": 25445,
"s": 24887,
"text": null
},
{
"code": null,
"e": 25454,
"s": 25445,
"text": "Output: "
},
{
"code": null,
"e": 25547,
"s": 25454,
"text": "Figure and Figcaption: These are used to add an image in a web page with small description. "
},
{
"code": null,
"e": 25552,
"s": 25547,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Figcaption Tag</title> <style> h2 { Color:#006400; font-size:50px; Text-align:none; margin-bottom:0px; } p { font-size:25px; text-align:none; margin-top:0px; } </style> </head> <body> <h2>GeeksforGeeks</h2> <figure> <img src=\"4.jpg\" alt=\"gfg\" style=\"width:20%\"> <figcaption>GeeksforGeeks Logo</figcaption> </figure> </body></html>",
"e": 26061,
"s": 25552,
"text": null
},
{
"code": null,
"e": 26070,
"s": 26061,
"text": "Output: "
},
{
"code": null,
"e": 26201,
"s": 26070,
"text": "Header: As the name suggests, it is for the header of a section introductory of a page. There can be multiple headers on a page. "
},
{
"code": null,
"e": 26206,
"s": 26201,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Header Tag</title> <style> h1, h3 { Color:#006400; Text-align:left; margin-bottom:0px; } p { font-size:25px; text-align:left; margin-top:0px; } </style> </head> <body> <article> <header> <h1>GeeksforGeeks</h1> <h3>GeeksforGeeks</h3> <p>A computer Science portal</p> </header> </article> </body></html>",
"e": 26708,
"s": 26206,
"text": null
},
{
"code": null,
"e": 26717,
"s": 26708,
"text": "Output: "
},
{
"code": null,
"e": 26885,
"s": 26717,
"text": "Footer: Footer located at the bottom of any article or document, they can contain contact details, copyright information etc. There can be multiple footers on a page. "
},
{
"code": null,
"e": 26890,
"s": 26885,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>footer Tag</title> <style> p { font-size:25px; text-align:left; margin-top:0px; } </style> </head> <body> <footer> <p>Posted by: GeeksforGeeks</p> <p>Contact: <a href=\"https://www.geeksforgeeks.org\"> geeksforgeeks.org</a>. </p> </footer> </body></html>",
"e": 27291,
"s": 26890,
"text": null
},
{
"code": null,
"e": 27300,
"s": 27291,
"text": "Output: "
},
{
"code": null,
"e": 27398,
"s": 27300,
"text": "Main: It defines the main content of the document. The content inside main tag should be unique. "
},
{
"code": null,
"e": 27403,
"s": 27398,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>main Tag</title> <style> h1 { color:#006400; } p { font-size:25px; text-align:none; margin-top:0px; } </style> </head> <body> <main> <h1>Important Residences</h1> <p>A few of them are Rashtrapati Bhavan, White House etc</p> <article> <h1>Rashtrapati Bhavan</h1> <p>It is the home of the President of India.</p> </article> <article> <h1>The White House</h1> <p>It is the home of the President of United States of America. </p> </article> </main> </body></html>",
"e": 28119,
"s": 27403,
"text": null
},
{
"code": null,
"e": 28128,
"s": 28119,
"text": "Output: "
},
{
"code": null,
"e": 28286,
"s": 28128,
"text": "Section: A page can be split into sections like Introduction, Contact Information, Details etc and each of these sections can be in a different section tag. "
},
{
"code": null,
"e": 28291,
"s": 28286,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>section Tag</title> <style> h1 { color:#006400; } p { font-size:25px; text-align:none; margin-top:0px; } </style> </head> <body> <section> <h1>Data Structure</h1> <p>Data Structure is a data organization and storage format that enables efficient access and modification. </p> </section> <section> <h1>Algorithm</h1> <p>A process or set of rules to be followed in calculations or other problem-solving operations, especially by a computer. </p> </section> </body></html>",
"e": 29000,
"s": 28291,
"text": null
},
{
"code": null,
"e": 29009,
"s": 29000,
"text": "Output: "
},
{
"code": null,
"e": 29105,
"s": 29009,
"text": "nav: It is used to define a set of navigation links in the form of navigation bar or nav menu. "
},
{
"code": null,
"e": 29110,
"s": 29105,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>nav Tag</title> <style> h1 { color:#006400; } </style> </head> <body> <h1>Navigation Bar</h1> <nav> <a href=\"/home/\">Home</a> | <a href=\"/about-us/\">About Us</a> | <a href=\"/data-structure/\">Data Structure</a> | <a href=\"/operating-system/\">Operating System</a> </nav> </body></html>",
"e": 29524,
"s": 29110,
"text": null
},
{
"code": null,
"e": 29533,
"s": 29524,
"text": "Output: "
},
{
"code": null,
"e": 29574,
"s": 29533,
"text": "Mark: It is used to highlight the text. "
},
{
"code": null,
"e": 29579,
"s": 29574,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>mark Tag</title> <style> h1 { color:#006400; } </style> </head> <body> <h1>mark tag</h1> <p>GeeksforGeeks is a <mark>Computer Science</mark> portal</p> </body></html>",
"e": 29841,
"s": 29579,
"text": null
},
{
"code": null,
"e": 29850,
"s": 29841,
"text": "Output: "
},
{
"code": null,
"e": 30104,
"s": 29850,
"text": "Non-Semantic Elements: Tags like div, span fall under the Non- Semantic categories as their names don’t tell anything about what kind of content is present inside them.div It is a block level element or division of a section. It is used as a container. "
},
{
"code": null,
"e": 30109,
"s": 30104,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>div Tag</title> <style> .GFG { color:#006400; } </style> </head> <body> <h1>div Tag</h1> <div class=\"GFG\"> <h1>GeeksforGeeks</h1> <p>GeeksforGeeks is a Computer Science portal</p> </div> </body></html>",
"e": 30427,
"s": 30109,
"text": null
},
{
"code": null,
"e": 30436,
"s": 30427,
"text": "Output: "
},
{
"code": null,
"e": 30607,
"s": 30436,
"text": "span: It is an inline element which doesn’t start on a new line and takes up only the necessary width. For more details use https://www.geeksforgeeks.org/span-tag-html/. "
},
{
"code": null,
"e": 30629,
"s": 30607,
"text": "Supported Browsers: "
},
{
"code": null,
"e": 30657,
"s": 30629,
"text": "Google Chrome 6.0 and above"
},
{
"code": null,
"e": 30689,
"s": 30657,
"text": "Internet Explorer 9.0 and above"
},
{
"code": null,
"e": 30711,
"s": 30689,
"text": "Mozilla 4.0 and above"
},
{
"code": null,
"e": 30732,
"s": 30711,
"text": "Opera 11.1 and above"
},
{
"code": null,
"e": 30753,
"s": 30732,
"text": "Safari 5.0 and above"
},
{
"code": null,
"e": 30890,
"s": 30753,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 30902,
"s": 30890,
"text": "ysachin2314"
},
{
"code": null,
"e": 30908,
"s": 30902,
"text": "HTML5"
},
{
"code": null,
"e": 30925,
"s": 30908,
"text": "Web technologies"
},
{
"code": null,
"e": 30929,
"s": 30925,
"text": "CSS"
},
{
"code": null,
"e": 30934,
"s": 30929,
"text": "HTML"
},
{
"code": null,
"e": 30961,
"s": 30934,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 30966,
"s": 30961,
"text": "HTML"
},
{
"code": null,
"e": 31064,
"s": 30966,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31073,
"s": 31064,
"text": "Comments"
},
{
"code": null,
"e": 31086,
"s": 31073,
"text": "Old Comments"
},
{
"code": null,
"e": 31148,
"s": 31086,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 31198,
"s": 31148,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 31256,
"s": 31198,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 31304,
"s": 31256,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 31341,
"s": 31304,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 31403,
"s": 31341,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 31453,
"s": 31403,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 31513,
"s": 31453,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 31561,
"s": 31513,
"text": "How to update Node.js and NPM to next version ?"
}
] |
Solidity - Assembly
|
Solidity provides an option to use assembly language to write inline assembly within Solidity source code. We can also write a standalone assembly code which then be converted to bytecode. Standalone Assembly is an intermediate language for a Solidity compiler and it converts the Solidity code into a Standalone Assembly and then to byte code. We can used the same language used in Inline Assembly to write code in a Standalone assembly.
Inline assembly code can be interleaved within Solidity code base to have more fine-grain control over EVM and is used especially while writing the library functions.
An assembly code is written under assembly { ... } block.
Try the following code to understand how a Library works in Solidity.
pragma solidity ^0.5.0;
library Sum {
function sumUsingInlineAssembly(uint[] memory _data) public pure returns (uint o_sum) {
for (uint i = 0; i < _data.length; ++i) {
assembly {
o_sum := add(o_sum, mload(add(add(_data, 0x20), mul(i, 0x20))))
}
}
}
}
contract Test {
uint[] data;
constructor() public {
data.push(1);
data.push(2);
data.push(3);
data.push(4);
data.push(5);
}
function sum() external view returns(uint){
return Sum.sumUsingInlineAssembly(data);
}
}
Run the above program using steps provided in Solidity First Application chapter.
Note − Select Test from dropdown before clicking the deploy button.
0: uint256: 15
38 Lectures
4.5 hours
Abhilash Nelson
62 Lectures
8.5 hours
Frahaan Hussain
31 Lectures
3.5 hours
Swapnil Kole
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2994,
"s": 2555,
"text": "Solidity provides an option to use assembly language to write inline assembly within Solidity source code. We can also write a standalone assembly code which then be converted to bytecode. Standalone Assembly is an intermediate language for a Solidity compiler and it converts the Solidity code into a Standalone Assembly and then to byte code. We can used the same language used in Inline Assembly to write code in a Standalone assembly."
},
{
"code": null,
"e": 3161,
"s": 2994,
"text": "Inline assembly code can be interleaved within Solidity code base to have more fine-grain control over EVM and is used especially while writing the library functions."
},
{
"code": null,
"e": 3221,
"s": 3161,
"text": "An assembly code is written under assembly { ... } block. "
},
{
"code": null,
"e": 3291,
"s": 3221,
"text": "Try the following code to understand how a Library works in Solidity."
},
{
"code": null,
"e": 3868,
"s": 3291,
"text": "pragma solidity ^0.5.0;\n\nlibrary Sum { \n function sumUsingInlineAssembly(uint[] memory _data) public pure returns (uint o_sum) {\n for (uint i = 0; i < _data.length; ++i) {\n assembly {\n o_sum := add(o_sum, mload(add(add(_data, 0x20), mul(i, 0x20))))\n }\n }\n }\n}\ncontract Test {\n uint[] data;\n \n constructor() public {\n data.push(1);\n data.push(2);\n data.push(3);\n data.push(4);\n data.push(5);\n }\n function sum() external view returns(uint){ \n return Sum.sumUsingInlineAssembly(data);\n }\n}"
},
{
"code": null,
"e": 3950,
"s": 3868,
"text": "Run the above program using steps provided in Solidity First Application chapter."
},
{
"code": null,
"e": 4018,
"s": 3950,
"text": "Note − Select Test from dropdown before clicking the deploy button."
},
{
"code": null,
"e": 4034,
"s": 4018,
"text": "0: uint256: 15\n"
},
{
"code": null,
"e": 4069,
"s": 4034,
"text": "\n 38 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4086,
"s": 4069,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4121,
"s": 4086,
"text": "\n 62 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4138,
"s": 4121,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4173,
"s": 4138,
"text": "\n 31 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4187,
"s": 4173,
"text": " Swapnil Kole"
},
{
"code": null,
"e": 4194,
"s": 4187,
"text": " Print"
},
{
"code": null,
"e": 4205,
"s": 4194,
"text": " Add Notes"
}
] |
Combinations in Python without using itertools - GeeksforGeeks
|
22 Oct, 2021
Itertools in Python is a module that produces complex iterators with the help of methods that work on iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.
Using Itertools we can display all the possible combinations of the string in a quite optimized way. To display the combination, it requires 2 parameters. First is the string and second is the length of substrings needed. The following example makes all combinations for the string ‘abc’ using itertools. Example:
Python3
# Import combinations from itertoolsfrom itertools import combinations def n_length_combo(arr, n): # using set to deal # with duplicates return list(combinations(arr, n)) # Driver Functionif __name__ == "__main__": arr = 'abc' n = 2 print (n_length_combo([x for x in arr], n) )
Output
[('a', 'b'), ('a', 'c'), ('b', 'c')]
By using recursion.To create combinations without using itertools, iterate the list one by one and fix the first element of the list and make combinations with the remaining list. Similarly, iterate with all the list elements one by one by recursion of the remaining list.
Python3
# Function to create combinations# without itertoolsdef n_length_combo(lst, n): if n == 0: return [[]] l =[] for i in range(0, len(lst)): m = lst[i] remLst = lst[i + 1:] for p in n_length_combo(remLst, n-1): l.append([m]+p) return l # Driver codeif __name__=="__main__": arr ="abc" print(n_length_combo([x for x in arr], 2))
Output
[('a', 'b'), ('a', 'c'), ('b', 'c')]
By using iterationsIn this, return the first combination of n elements from the string as it is, then other combinations are made by considering each element by its position. Each element is treated as unique based on its position, not on its value. So if the input elements are unique, there will be no repeat values in each combination.
Python3
import numpy def n_length_combo(iterable, r): char = tuple(iterable) n = len(char) if r > n: return index = numpy.arange(r) # returns the first sequence yield tuple(char[i] for i in index) while True: for i in reversed(range(r)): if index[i] != i + n - r: break else: return index[i] += 1 for j in range(i + 1, r): index[j] = index[j-1] + 1 yield tuple(char[i] for i in index) # Driver codeprint([x for x in n_length_combo("abc", 2)])
Output
[('a', 'b'), ('a', 'c'), ('b', 'c')]
adnanirshad158
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
|
[
{
"code": null,
"e": 23927,
"s": 23899,
"text": "\n22 Oct, 2021"
},
{
"code": null,
"e": 24170,
"s": 23927,
"text": "Itertools in Python is a module that produces complex iterators with the help of methods that work on iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. "
},
{
"code": null,
"e": 24485,
"s": 24170,
"text": "Using Itertools we can display all the possible combinations of the string in a quite optimized way. To display the combination, it requires 2 parameters. First is the string and second is the length of substrings needed. The following example makes all combinations for the string ‘abc’ using itertools. Example: "
},
{
"code": null,
"e": 24493,
"s": 24485,
"text": "Python3"
},
{
"code": "# Import combinations from itertoolsfrom itertools import combinations def n_length_combo(arr, n): # using set to deal # with duplicates return list(combinations(arr, n)) # Driver Functionif __name__ == \"__main__\": arr = 'abc' n = 2 print (n_length_combo([x for x in arr], n) )",
"e": 24804,
"s": 24493,
"text": null
},
{
"code": null,
"e": 24811,
"s": 24804,
"text": "Output"
},
{
"code": null,
"e": 24848,
"s": 24811,
"text": "[('a', 'b'), ('a', 'c'), ('b', 'c')]"
},
{
"code": null,
"e": 25121,
"s": 24848,
"text": "By using recursion.To create combinations without using itertools, iterate the list one by one and fix the first element of the list and make combinations with the remaining list. Similarly, iterate with all the list elements one by one by recursion of the remaining list."
},
{
"code": null,
"e": 25129,
"s": 25121,
"text": "Python3"
},
{
"code": "# Function to create combinations# without itertoolsdef n_length_combo(lst, n): if n == 0: return [[]] l =[] for i in range(0, len(lst)): m = lst[i] remLst = lst[i + 1:] for p in n_length_combo(remLst, n-1): l.append([m]+p) return l # Driver codeif __name__==\"__main__\": arr =\"abc\" print(n_length_combo([x for x in arr], 2))",
"e": 25552,
"s": 25129,
"text": null
},
{
"code": null,
"e": 25560,
"s": 25552,
"text": "Output "
},
{
"code": null,
"e": 25597,
"s": 25560,
"text": "[('a', 'b'), ('a', 'c'), ('b', 'c')]"
},
{
"code": null,
"e": 25937,
"s": 25597,
"text": "By using iterationsIn this, return the first combination of n elements from the string as it is, then other combinations are made by considering each element by its position. Each element is treated as unique based on its position, not on its value. So if the input elements are unique, there will be no repeat values in each combination. "
},
{
"code": null,
"e": 25945,
"s": 25937,
"text": "Python3"
},
{
"code": "import numpy def n_length_combo(iterable, r): char = tuple(iterable) n = len(char) if r > n: return index = numpy.arange(r) # returns the first sequence yield tuple(char[i] for i in index) while True: for i in reversed(range(r)): if index[i] != i + n - r: break else: return index[i] += 1 for j in range(i + 1, r): index[j] = index[j-1] + 1 yield tuple(char[i] for i in index) # Driver codeprint([x for x in n_length_combo(\"abc\", 2)])",
"e": 26578,
"s": 25945,
"text": null
},
{
"code": null,
"e": 26586,
"s": 26578,
"text": "Output "
},
{
"code": null,
"e": 26623,
"s": 26586,
"text": "[('a', 'b'), ('a', 'c'), ('b', 'c')]"
},
{
"code": null,
"e": 26638,
"s": 26623,
"text": "adnanirshad158"
},
{
"code": null,
"e": 26653,
"s": 26638,
"text": "python-utility"
},
{
"code": null,
"e": 26660,
"s": 26653,
"text": "Python"
},
{
"code": null,
"e": 26758,
"s": 26660,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26767,
"s": 26758,
"text": "Comments"
},
{
"code": null,
"e": 26780,
"s": 26767,
"text": "Old Comments"
},
{
"code": null,
"e": 26812,
"s": 26780,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26868,
"s": 26812,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26910,
"s": 26868,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26952,
"s": 26910,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26988,
"s": 26952,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 27010,
"s": 26988,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27049,
"s": 27010,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27076,
"s": 27049,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27107,
"s": 27076,
"text": "Python | os.path.join() method"
}
] |
Clojure - If/do Expression
|
The ‘if-do’ expression in Clojure is used to allow multiple expressions to be executed for each branch of the ‘if’ statement. We have seen in the classic ‘if’ statement in Clojure that you can just have two statements, one which is executed for the true part and the other which is for the false part. But the ‘if-do’ expression allows you to use multiple expressions. Following is the general form of the ‘if-do’ expression.
if(condition) (
statement #1
statement #1.1
)
(
statement #2
statement #2.1
)
Following is an example of a ‘for if-do’ statement.
(ns clojure.examples.hello
(:gen-class))
;; This program displays Hello World
(defn Example [] (
if (= 2 2)
(do(println "Both the values are equal")
(println "true"))
(do(println "Both the values are not equal")
(println "false"))))
(Example)
In the above example, the ‘if’ condition is used to evaluate whether the values of 2 and 2 are equal. If they are, then it will print the value of “Values are equal” and in addition we are printing the value of “true”, else it will print the value of “Values are not equal” and the value of “false”.
The above code produces the following output.
Both the values are equal
true
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2800,
"s": 2374,
"text": "The ‘if-do’ expression in Clojure is used to allow multiple expressions to be executed for each branch of the ‘if’ statement. We have seen in the classic ‘if’ statement in Clojure that you can just have two statements, one which is executed for the true part and the other which is for the false part. But the ‘if-do’ expression allows you to use multiple expressions. Following is the general form of the ‘if-do’ expression."
},
{
"code": null,
"e": 2892,
"s": 2800,
"text": "if(condition) (\n statement #1\n statement #1.1\n)\n\n(\n statement #2\n statement #2.1\n)\n"
},
{
"code": null,
"e": 2944,
"s": 2892,
"text": "Following is an example of a ‘for if-do’ statement."
},
{
"code": null,
"e": 3224,
"s": 2944,
"text": "(ns clojure.examples.hello\n (:gen-class))\n\n;; This program displays Hello World\n(defn Example [] (\n if (= 2 2)\n (do(println \"Both the values are equal\")\n (println \"true\"))\n (do(println \"Both the values are not equal\")\n (println \"false\"))))\n(Example)"
},
{
"code": null,
"e": 3524,
"s": 3224,
"text": "In the above example, the ‘if’ condition is used to evaluate whether the values of 2 and 2 are equal. If they are, then it will print the value of “Values are equal” and in addition we are printing the value of “true”, else it will print the value of “Values are not equal” and the value of “false”."
},
{
"code": null,
"e": 3570,
"s": 3524,
"text": "The above code produces the following output."
},
{
"code": null,
"e": 3602,
"s": 3570,
"text": "Both the values are equal\ntrue\n"
},
{
"code": null,
"e": 3609,
"s": 3602,
"text": " Print"
},
{
"code": null,
"e": 3620,
"s": 3609,
"text": " Add Notes"
}
] |
Can Machine Learn the Concept of Sine | by Ying Xie | Towards Data Science
|
It is well known that artificial neural networks are good at modeling any function. I wonder whether they can go one step further, and learn the generalized model of a function. For simplicity let’s try to learn a sine function with just one parameter A, which controls the frequency:
y = sin(A*x)
For us humans, once we understand the sine function, we know how it behaves under any parameter A. If we are presented with a partial sine wave, we can figure out what A should be, and we can extrapolate the wave out to infinity.
Can ML predict a sine wave for a parameter A it hasn’t seen?
Let’s do an experiment to find out. We frame the problem as a time-series prediction problem. Given some data points that match a function sin(A*x), try to predict the future values. Of course the challenge is that we want to learn the general concept of sine. We want to be able to predict the future values, even for a parameter (A) that was never seen by our models during training.
We will use Keras, and try several different models — fully connected network that is used often to model functions, CNN that is used often in pattern recognition, and LSTM that is used often in sequence modeling like NLP.
For each model, we will train under parameter A in the range of (0.06, 0.12). For test we will try to predict under A values of 0.033, 0.06, 0.083, and 0.163. This way we can see the performance with 2 parameters inside the training range, and 2 outside on each end.
During tests we will start with a history of real sin(A*x) value under the correct A. This is the equivalent of giving a human a partial sine wave. When we do prediction, the future prediction of value y will be using the earlier predicted values of y. To given an example, suppose we start with 40 real data samples — y[0] ... y[39], with y[i] = sin(A*i). We use our model to predict y[40]. Then we will use y[1] ... y[40], where y[40] is the predicted value, to predict y[41].
The reason we do the above, instead of using sin(A*i) to predict y[i+1], is to make the errors in our models easier to see by making the errors cumulative.
In Keras a fully connected layer is called a Dense layer. We use 3 Dense layers in our FC network.
model = models.Sequential()model.add(Dense(100, input_shape=(INPUT_COUNT,)))model.add(LeakyReLU(alpha=0.03))model.add(Dense(100))model.add(LeakyReLU(alpha=0.03))model.add(Dense(1))
The input shape is INPUT_COUNT (defined to be 40) prior data points. The last Dense layer has one unit, because we are predicting the next value given the prior 40 values.
Below are the results. The green dotted line is the prediction. Again during training parameter A is in the range of 0.06 to 0.12.
As we can see, our model managed A value of 0.06 and 0.083 pretty well, but did poorly for 0.033 and 0.163. Basically once parameter A is outside of the training range, our model can’t handle it.
Note that on the chart our function doesn’t start at 0, because we used 40 data points as historical data to feed into the model. All charts are offset by that 40 data points.
We used Conv1D layers, since our data is one dimensional.
model = models.Sequential()model.add(Conv1D(100, 3, strides=1, input_shape=(INPUT_COUNT, 1)))model.add(LeakyReLU(alpha=0.03))model.add(Conv1D(100, 3, strides=1))model.add(LeakyReLU(alpha=0.03))model.add(Flatten())model.add(Dense(100))model.add(LeakyReLU(alpha=0.03))model.add(Dense(1))
For convolution we used size 3 filters and stride of 1. We didn’t do max-pooling because the position matters in regression problems.
Similar to FC network, the inputs are 40 prior data points, and the output is the next point on the curve.
The result is similar to the fully connected network. It wasn’t able to learn the general formula of sine given any parameter A.
LSTM network retains memory of the data it has seen in the past. Therefore the data we feed into it is in a different form. We just need to feed one data point at a time, instead of a history of past 40 data points for FC and CNN models. As we can see below, the input_batch_size is (1,1,1).
model = models.Sequential()model.add(LSTM(100, batch_input_shape=(1, 1, 1), return_sequences=True, stateful=True))model.add(LSTM(100, return_sequences=False, stateful=True))model.add(Dense(1))
Because we can only feed in one data point at a time, as later data points depend on the LSTM internal state built up by earlier data points, we can’t leverage the parallelism in the hardware. As a result the training is really slow. I didn’t experiment much with the LSTM parameters because of it. Here is the result.
The result is worse than FC and CNN. Again this may be because I didn’t work with it enough. On the other hand, I don’t expect it to behave better, because the other models have enough historical data, and the data is repeating.
I find this problem interesting, because in life we often need to use historical data to predict future in a time-series. If NN models can generalize the concept of repeating patterns, and predict patterns even when the frequency change, they will be much more powerful in our applications.
In our experiments we see that the models all learned the general shape of sine function, but failed to generate future data points at a frequency outside of the training range.
Is the conclusion here that NN models have a hard time generalize the concept of sine, or simply that I suck and failed to build a model that can solve this problem? My code is on github:
github.com
Please play with it, send me your comments, and do let me know if a better model can solve the problem. Thank you.
|
[
{
"code": null,
"e": 457,
"s": 172,
"text": "It is well known that artificial neural networks are good at modeling any function. I wonder whether they can go one step further, and learn the generalized model of a function. For simplicity let’s try to learn a sine function with just one parameter A, which controls the frequency:"
},
{
"code": null,
"e": 470,
"s": 457,
"text": "y = sin(A*x)"
},
{
"code": null,
"e": 700,
"s": 470,
"text": "For us humans, once we understand the sine function, we know how it behaves under any parameter A. If we are presented with a partial sine wave, we can figure out what A should be, and we can extrapolate the wave out to infinity."
},
{
"code": null,
"e": 761,
"s": 700,
"text": "Can ML predict a sine wave for a parameter A it hasn’t seen?"
},
{
"code": null,
"e": 1147,
"s": 761,
"text": "Let’s do an experiment to find out. We frame the problem as a time-series prediction problem. Given some data points that match a function sin(A*x), try to predict the future values. Of course the challenge is that we want to learn the general concept of sine. We want to be able to predict the future values, even for a parameter (A) that was never seen by our models during training."
},
{
"code": null,
"e": 1370,
"s": 1147,
"text": "We will use Keras, and try several different models — fully connected network that is used often to model functions, CNN that is used often in pattern recognition, and LSTM that is used often in sequence modeling like NLP."
},
{
"code": null,
"e": 1637,
"s": 1370,
"text": "For each model, we will train under parameter A in the range of (0.06, 0.12). For test we will try to predict under A values of 0.033, 0.06, 0.083, and 0.163. This way we can see the performance with 2 parameters inside the training range, and 2 outside on each end."
},
{
"code": null,
"e": 2116,
"s": 1637,
"text": "During tests we will start with a history of real sin(A*x) value under the correct A. This is the equivalent of giving a human a partial sine wave. When we do prediction, the future prediction of value y will be using the earlier predicted values of y. To given an example, suppose we start with 40 real data samples — y[0] ... y[39], with y[i] = sin(A*i). We use our model to predict y[40]. Then we will use y[1] ... y[40], where y[40] is the predicted value, to predict y[41]."
},
{
"code": null,
"e": 2272,
"s": 2116,
"text": "The reason we do the above, instead of using sin(A*i) to predict y[i+1], is to make the errors in our models easier to see by making the errors cumulative."
},
{
"code": null,
"e": 2371,
"s": 2272,
"text": "In Keras a fully connected layer is called a Dense layer. We use 3 Dense layers in our FC network."
},
{
"code": null,
"e": 2552,
"s": 2371,
"text": "model = models.Sequential()model.add(Dense(100, input_shape=(INPUT_COUNT,)))model.add(LeakyReLU(alpha=0.03))model.add(Dense(100))model.add(LeakyReLU(alpha=0.03))model.add(Dense(1))"
},
{
"code": null,
"e": 2724,
"s": 2552,
"text": "The input shape is INPUT_COUNT (defined to be 40) prior data points. The last Dense layer has one unit, because we are predicting the next value given the prior 40 values."
},
{
"code": null,
"e": 2855,
"s": 2724,
"text": "Below are the results. The green dotted line is the prediction. Again during training parameter A is in the range of 0.06 to 0.12."
},
{
"code": null,
"e": 3051,
"s": 2855,
"text": "As we can see, our model managed A value of 0.06 and 0.083 pretty well, but did poorly for 0.033 and 0.163. Basically once parameter A is outside of the training range, our model can’t handle it."
},
{
"code": null,
"e": 3227,
"s": 3051,
"text": "Note that on the chart our function doesn’t start at 0, because we used 40 data points as historical data to feed into the model. All charts are offset by that 40 data points."
},
{
"code": null,
"e": 3285,
"s": 3227,
"text": "We used Conv1D layers, since our data is one dimensional."
},
{
"code": null,
"e": 3571,
"s": 3285,
"text": "model = models.Sequential()model.add(Conv1D(100, 3, strides=1, input_shape=(INPUT_COUNT, 1)))model.add(LeakyReLU(alpha=0.03))model.add(Conv1D(100, 3, strides=1))model.add(LeakyReLU(alpha=0.03))model.add(Flatten())model.add(Dense(100))model.add(LeakyReLU(alpha=0.03))model.add(Dense(1))"
},
{
"code": null,
"e": 3705,
"s": 3571,
"text": "For convolution we used size 3 filters and stride of 1. We didn’t do max-pooling because the position matters in regression problems."
},
{
"code": null,
"e": 3812,
"s": 3705,
"text": "Similar to FC network, the inputs are 40 prior data points, and the output is the next point on the curve."
},
{
"code": null,
"e": 3941,
"s": 3812,
"text": "The result is similar to the fully connected network. It wasn’t able to learn the general formula of sine given any parameter A."
},
{
"code": null,
"e": 4233,
"s": 3941,
"text": "LSTM network retains memory of the data it has seen in the past. Therefore the data we feed into it is in a different form. We just need to feed one data point at a time, instead of a history of past 40 data points for FC and CNN models. As we can see below, the input_batch_size is (1,1,1)."
},
{
"code": null,
"e": 4426,
"s": 4233,
"text": "model = models.Sequential()model.add(LSTM(100, batch_input_shape=(1, 1, 1), return_sequences=True, stateful=True))model.add(LSTM(100, return_sequences=False, stateful=True))model.add(Dense(1))"
},
{
"code": null,
"e": 4745,
"s": 4426,
"text": "Because we can only feed in one data point at a time, as later data points depend on the LSTM internal state built up by earlier data points, we can’t leverage the parallelism in the hardware. As a result the training is really slow. I didn’t experiment much with the LSTM parameters because of it. Here is the result."
},
{
"code": null,
"e": 4974,
"s": 4745,
"text": "The result is worse than FC and CNN. Again this may be because I didn’t work with it enough. On the other hand, I don’t expect it to behave better, because the other models have enough historical data, and the data is repeating."
},
{
"code": null,
"e": 5265,
"s": 4974,
"text": "I find this problem interesting, because in life we often need to use historical data to predict future in a time-series. If NN models can generalize the concept of repeating patterns, and predict patterns even when the frequency change, they will be much more powerful in our applications."
},
{
"code": null,
"e": 5443,
"s": 5265,
"text": "In our experiments we see that the models all learned the general shape of sine function, but failed to generate future data points at a frequency outside of the training range."
},
{
"code": null,
"e": 5631,
"s": 5443,
"text": "Is the conclusion here that NN models have a hard time generalize the concept of sine, or simply that I suck and failed to build a model that can solve this problem? My code is on github:"
},
{
"code": null,
"e": 5642,
"s": 5631,
"text": "github.com"
}
] |
Python | Convert an array to an ordinary list with the same items
|
21 Nov, 2018
Prerequisite : Array in Python
Python program to convert an array to an ordinary list with the same items.
Examples:
Input : array('i', [1, 3, 5, 3, 7, 1, 9, 3])
Output :[1, 3, 5, 3, 7, 1, 9, 3]
Explanation: the array with elements [1, 3, 5, 3,
7, 1, 9, 3] are converted into list with the
same elements.
Input :array('k', [45, 23, 56, 12])
Output :[45, 23, 56, 12]
Explanation: the array with elements [45, 23, 56,
12] are converted into list with the same elements.
Approach to the problem:We want to convert an array into an ordinary list with the same items. For doing so we need to use a function
// This function tolist() converts the array into a list.
arrayname.tolist()
from array import *def array_list(array_num): num_list = array_num.tolist() # list print(num_list) # driver codearray_num = array('i', [45,34,67]) # arrayarray_list(array_num)
Output:
[45, 34, 67]
Python list-programs
python-list
Python
python-list
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": 54,
"s": 26,
"text": "\n21 Nov, 2018"
},
{
"code": null,
"e": 85,
"s": 54,
"text": "Prerequisite : Array in Python"
},
{
"code": null,
"e": 161,
"s": 85,
"text": "Python program to convert an array to an ordinary list with the same items."
},
{
"code": null,
"e": 171,
"s": 161,
"text": "Examples:"
},
{
"code": null,
"e": 527,
"s": 171,
"text": "Input : array('i', [1, 3, 5, 3, 7, 1, 9, 3])\nOutput :[1, 3, 5, 3, 7, 1, 9, 3]\nExplanation: the array with elements [1, 3, 5, 3, \n7, 1, 9, 3] are converted into list with the \nsame elements.\n\nInput :array('k', [45, 23, 56, 12])\nOutput :[45, 23, 56, 12]\nExplanation: the array with elements [45, 23, 56, \n12] are converted into list with the same elements.\n"
},
{
"code": null,
"e": 661,
"s": 527,
"text": "Approach to the problem:We want to convert an array into an ordinary list with the same items. For doing so we need to use a function"
},
{
"code": null,
"e": 738,
"s": 661,
"text": "// This function tolist() converts the array into a list.\narrayname.tolist()"
},
{
"code": "from array import *def array_list(array_num): num_list = array_num.tolist() # list print(num_list) # driver codearray_num = array('i', [45,34,67]) # arrayarray_list(array_num)",
"e": 921,
"s": 738,
"text": null
},
{
"code": null,
"e": 929,
"s": 921,
"text": "Output:"
},
{
"code": null,
"e": 943,
"s": 929,
"text": "[45, 34, 67]\n"
},
{
"code": null,
"e": 964,
"s": 943,
"text": "Python list-programs"
},
{
"code": null,
"e": 976,
"s": 964,
"text": "python-list"
},
{
"code": null,
"e": 983,
"s": 976,
"text": "Python"
},
{
"code": null,
"e": 995,
"s": 983,
"text": "python-list"
},
{
"code": null,
"e": 1093,
"s": 995,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1111,
"s": 1093,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1153,
"s": 1111,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1175,
"s": 1153,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1210,
"s": 1175,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1236,
"s": 1210,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1268,
"s": 1236,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1297,
"s": 1268,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1324,
"s": 1297,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1354,
"s": 1324,
"text": "Iterate over a list in Python"
}
] |
Data Mining Process - GeeksforGeeks
|
18 Apr, 2022
Data Mining refers to extracting or mining knowledge from large amounts of data. The term is actually a misnomer. Thus, data mining should have been more appropriately named as knowledge mining which emphasis on mining from large amounts of data. It is computational process of discovering patterns in large data sets involving methods at intersection of artificial intelligence, machine learning, statistics, and database systems. The overall goal of data mining process is to extract information from a data set and transform it into an understandable structure for further use. It is also defined as extraction of interesting (non-trivial, implicit, previously unknown and potentially useful) patterns or knowledge from a huge amount of data. Data mining is a rapidly growing field that is concerned with developing techniques to assist managers and decision-makers to make intelligent use of a huge amount of repositories. Alternative names for Data Mining :
1. Knowledge discovery (mining) in databases (KDD)
2. Knowledge extraction
3. Data/pattern analysis
4. Data archaeology
5. Data dredging
6. Information harvesting
7. Business intelligence
Data Mining and Business Intelligence : Key properties of Data Mining :
1. Automatic discovery of patterns
2. Prediction of likely outcomes
3. Creation of actionable information
4. Focus on large datasets and databases
Data Mining : Confluence of Multiple Disciplines – Data Mining Process : Data Mining is a process of discovering various models, summaries, and derived values from a given collection of data. The general experimental procedure adapted to data-mining problem involves following steps :
State problem and formulate hypothesis – In this step, a modeler usually specifies a group of variables for unknown dependency and, if possible, a general sort of this dependency as an initial hypothesis. There could also be several hypotheses formulated for one problem at this stage. The primary step requires combined expertise of an application domain and a data-mining model. In practice, it always means an in-depth interaction between data-mining expert and application expert. In successful data-mining applications, this cooperation does not stop within initial phase. It continues during whole data-mining process.Collect data – This step cares about how information is generated and picked up. Generally, there are two distinct possibilities. The primary is when data-generation process is under control of an expert (modeler). This approach is understood as a designed experiment. The second possibility is when expert cannot influence data generation process. This is often referred to as observational approach. An observational setting, namely, random data generation, is assumed in most data-mining applications. Typically, sampling distribution is totally unknown after data are collected, or it is partially and implicitly given within data-collection procedure. It is vital, however, to know how data collection affects its theoretical distribution since such a piece of prior knowledge is often useful for modeling and, later, for ultimate interpretation of results. Also, it is important to form sure that information used for estimating a model and therefore data used later for testing and applying a model come from an equivalent, unknown, sampling distribution. If this is often not case, estimated model cannot be successfully utilized in a final application of results.Data Preprocessing – In the observational setting, data is usually “collected” from prevailing databases, data warehouses, and data marts. Data preprocessing usually includes a minimum of two common tasks :(i) Outlier Detection (and removal) : Outliers are unusual data values that are not according to most observations. Commonly, outliers result from measurement errors, coding, and recording errors, and, sometimes, are natural, abnormal values. Such non-representative samples can seriously affect model produced later. There are two strategies for handling outliers : Detect and eventually remove outliers as a neighborhood of preprocessing phase. And Develop robust modeling methods that are insensitive to outliers.(ii) Scaling, encoding, and selecting features : Data preprocessing includes several steps like variable scaling and differing types of encoding. For instance, one feature with range [0, 1] and other with range [100, 1000] will not have an equivalent weight within applied technique. They are going to also influence ultimate data-mining results differently. Therefore, it is recommended to scale them and convey both features to an equivalent weight for further analysis. Also, application-specific encoding methods usually achieve dimensionality reduction by providing a smaller number of informative features for subsequent data modeling.Estimate model – The selection and implementation of acceptable data-mining technique is that main task during this phase. This process is not straightforward. Usually, in practice, implementation is predicated on several models, and selecting simplest one is a further task.Interpret model and draw conclusions – In most cases, data-mining models should help in deciding. Hence, such models got to be interpretable so as to be useful because humans are not likely to base their decisions on complex “black-box” models. Note that goals of accuracy of model and accuracy of its interpretation are somewhat contradictory. Usually, simple models are more interpretable, but they are also less accurate. Modern data-mining methods are expected to yield highly accurate results using high dimensional models. The matter of interpreting these models, also vital, is taken into account a separate task, with specific techniques to validate results. Classification of Data Mining Systems :
State problem and formulate hypothesis – In this step, a modeler usually specifies a group of variables for unknown dependency and, if possible, a general sort of this dependency as an initial hypothesis. There could also be several hypotheses formulated for one problem at this stage. The primary step requires combined expertise of an application domain and a data-mining model. In practice, it always means an in-depth interaction between data-mining expert and application expert. In successful data-mining applications, this cooperation does not stop within initial phase. It continues during whole data-mining process.
Collect data – This step cares about how information is generated and picked up. Generally, there are two distinct possibilities. The primary is when data-generation process is under control of an expert (modeler). This approach is understood as a designed experiment. The second possibility is when expert cannot influence data generation process. This is often referred to as observational approach. An observational setting, namely, random data generation, is assumed in most data-mining applications. Typically, sampling distribution is totally unknown after data are collected, or it is partially and implicitly given within data-collection procedure. It is vital, however, to know how data collection affects its theoretical distribution since such a piece of prior knowledge is often useful for modeling and, later, for ultimate interpretation of results. Also, it is important to form sure that information used for estimating a model and therefore data used later for testing and applying a model come from an equivalent, unknown, sampling distribution. If this is often not case, estimated model cannot be successfully utilized in a final application of results.
Data Preprocessing – In the observational setting, data is usually “collected” from prevailing databases, data warehouses, and data marts. Data preprocessing usually includes a minimum of two common tasks :(i) Outlier Detection (and removal) : Outliers are unusual data values that are not according to most observations. Commonly, outliers result from measurement errors, coding, and recording errors, and, sometimes, are natural, abnormal values. Such non-representative samples can seriously affect model produced later. There are two strategies for handling outliers : Detect and eventually remove outliers as a neighborhood of preprocessing phase. And Develop robust modeling methods that are insensitive to outliers.(ii) Scaling, encoding, and selecting features : Data preprocessing includes several steps like variable scaling and differing types of encoding. For instance, one feature with range [0, 1] and other with range [100, 1000] will not have an equivalent weight within applied technique. They are going to also influence ultimate data-mining results differently. Therefore, it is recommended to scale them and convey both features to an equivalent weight for further analysis. Also, application-specific encoding methods usually achieve dimensionality reduction by providing a smaller number of informative features for subsequent data modeling.
(i) Outlier Detection (and removal) : Outliers are unusual data values that are not according to most observations. Commonly, outliers result from measurement errors, coding, and recording errors, and, sometimes, are natural, abnormal values. Such non-representative samples can seriously affect model produced later. There are two strategies for handling outliers : Detect and eventually remove outliers as a neighborhood of preprocessing phase. And Develop robust modeling methods that are insensitive to outliers.
(ii) Scaling, encoding, and selecting features : Data preprocessing includes several steps like variable scaling and differing types of encoding. For instance, one feature with range [0, 1] and other with range [100, 1000] will not have an equivalent weight within applied technique. They are going to also influence ultimate data-mining results differently. Therefore, it is recommended to scale them and convey both features to an equivalent weight for further analysis. Also, application-specific encoding methods usually achieve dimensionality reduction by providing a smaller number of informative features for subsequent data modeling.
Estimate model – The selection and implementation of acceptable data-mining technique is that main task during this phase. This process is not straightforward. Usually, in practice, implementation is predicated on several models, and selecting simplest one is a further task.
Interpret model and draw conclusions – In most cases, data-mining models should help in deciding. Hence, such models got to be interpretable so as to be useful because humans are not likely to base their decisions on complex “black-box” models. Note that goals of accuracy of model and accuracy of its interpretation are somewhat contradictory. Usually, simple models are more interpretable, but they are also less accurate. Modern data-mining methods are expected to yield highly accurate results using high dimensional models. The matter of interpreting these models, also vital, is taken into account a separate task, with specific techniques to validate results. Classification of Data Mining Systems :
1. Database Technology
2. Statistics
3. Machine Learning
4. Information Science
5. Visualization
Major issues in Data Mining :Mining different kinds of knowledge in databases – The need for different users is not same. Different users may be interested in different kinds of knowledge. Therefore it is necessary for data mining to cover a broad range of knowledge discovery tasks.Interactive mining of knowledge at multiple levels of abstraction – The data mining process needs to be interactive because it allows users to focus on search for patterns, providing and refining data mining requests based on returned results.Incorporation of background knowledge – To guide discovery process and to express discovered patterns, background knowledge can be used to express discovered patterns not only in concise terms but at multiple levels of abstraction.Data mining query languages and ad-hoc data mining – Data Mining Query language that allows user to describe ad-hoc mining tasks should be integrated with a data warehouse query language and optimized for efficient and flexible data mining.Presentation and visualization of data mining results – Once patterns are discovered it needs to be expressed in high-level languages, visual representations. These representations should be easily understandable by users.Handling noisy or incomplete data – The data cleaning methods are required that can handle noise, incomplete objects while mining data regularities. If data cleaning methods are not there then accuracy of discovered patterns will be poor.Pattern evaluation – It refers to interestingness of problem. The patterns discovered should be interesting because either they represent common knowledge or lack of novelty.Efficiency and scalability of data mining algorithms – In order to effectively extract information from huge amount of data in databases, data mining algorithm must be efficient and scalable.Parallel, distributed, and incremental mining algorithms – The factors such as huge size of databases, wide distribution of data, and complexity of data mining methods motivate development of parallel and distributed data mining algorithms. These algorithms divide data into partitions that are further processed parallel. Then results from partitions are merged. The incremental algorithms update databases without having mined data again from scratch.
Major issues in Data Mining :Mining different kinds of knowledge in databases – The need for different users is not same. Different users may be interested in different kinds of knowledge. Therefore it is necessary for data mining to cover a broad range of knowledge discovery tasks.Interactive mining of knowledge at multiple levels of abstraction – The data mining process needs to be interactive because it allows users to focus on search for patterns, providing and refining data mining requests based on returned results.Incorporation of background knowledge – To guide discovery process and to express discovered patterns, background knowledge can be used to express discovered patterns not only in concise terms but at multiple levels of abstraction.Data mining query languages and ad-hoc data mining – Data Mining Query language that allows user to describe ad-hoc mining tasks should be integrated with a data warehouse query language and optimized for efficient and flexible data mining.Presentation and visualization of data mining results – Once patterns are discovered it needs to be expressed in high-level languages, visual representations. These representations should be easily understandable by users.Handling noisy or incomplete data – The data cleaning methods are required that can handle noise, incomplete objects while mining data regularities. If data cleaning methods are not there then accuracy of discovered patterns will be poor.Pattern evaluation – It refers to interestingness of problem. The patterns discovered should be interesting because either they represent common knowledge or lack of novelty.Efficiency and scalability of data mining algorithms – In order to effectively extract information from huge amount of data in databases, data mining algorithm must be efficient and scalable.Parallel, distributed, and incremental mining algorithms – The factors such as huge size of databases, wide distribution of data, and complexity of data mining methods motivate development of parallel and distributed data mining algorithms. These algorithms divide data into partitions that are further processed parallel. Then results from partitions are merged. The incremental algorithms update databases without having mined data again from scratch.
Mining different kinds of knowledge in databases – The need for different users is not same. Different users may be interested in different kinds of knowledge. Therefore it is necessary for data mining to cover a broad range of knowledge discovery tasks.Interactive mining of knowledge at multiple levels of abstraction – The data mining process needs to be interactive because it allows users to focus on search for patterns, providing and refining data mining requests based on returned results.Incorporation of background knowledge – To guide discovery process and to express discovered patterns, background knowledge can be used to express discovered patterns not only in concise terms but at multiple levels of abstraction.Data mining query languages and ad-hoc data mining – Data Mining Query language that allows user to describe ad-hoc mining tasks should be integrated with a data warehouse query language and optimized for efficient and flexible data mining.Presentation and visualization of data mining results – Once patterns are discovered it needs to be expressed in high-level languages, visual representations. These representations should be easily understandable by users.Handling noisy or incomplete data – The data cleaning methods are required that can handle noise, incomplete objects while mining data regularities. If data cleaning methods are not there then accuracy of discovered patterns will be poor.Pattern evaluation – It refers to interestingness of problem. The patterns discovered should be interesting because either they represent common knowledge or lack of novelty.Efficiency and scalability of data mining algorithms – In order to effectively extract information from huge amount of data in databases, data mining algorithm must be efficient and scalable.Parallel, distributed, and incremental mining algorithms – The factors such as huge size of databases, wide distribution of data, and complexity of data mining methods motivate development of parallel and distributed data mining algorithms. These algorithms divide data into partitions that are further processed parallel. Then results from partitions are merged. The incremental algorithms update databases without having mined data again from scratch.
Mining different kinds of knowledge in databases – The need for different users is not same. Different users may be interested in different kinds of knowledge. Therefore it is necessary for data mining to cover a broad range of knowledge discovery tasks.
Interactive mining of knowledge at multiple levels of abstraction – The data mining process needs to be interactive because it allows users to focus on search for patterns, providing and refining data mining requests based on returned results.
Incorporation of background knowledge – To guide discovery process and to express discovered patterns, background knowledge can be used to express discovered patterns not only in concise terms but at multiple levels of abstraction.
Data mining query languages and ad-hoc data mining – Data Mining Query language that allows user to describe ad-hoc mining tasks should be integrated with a data warehouse query language and optimized for efficient and flexible data mining.
Presentation and visualization of data mining results – Once patterns are discovered it needs to be expressed in high-level languages, visual representations. These representations should be easily understandable by users.
Handling noisy or incomplete data – The data cleaning methods are required that can handle noise, incomplete objects while mining data regularities. If data cleaning methods are not there then accuracy of discovered patterns will be poor.
Pattern evaluation – It refers to interestingness of problem. The patterns discovered should be interesting because either they represent common knowledge or lack of novelty.
Efficiency and scalability of data mining algorithms – In order to effectively extract information from huge amount of data in databases, data mining algorithm must be efficient and scalable.
Parallel, distributed, and incremental mining algorithms – The factors such as huge size of databases, wide distribution of data, and complexity of data mining methods motivate development of parallel and distributed data mining algorithms. These algorithms divide data into partitions that are further processed parallel. Then results from partitions are merged. The incremental algorithms update databases without having mined data again from scratch.
kashishsoda
data mining
DBMS
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
Conflict Serializability in DBMS
Difference between Star Schema and Snowflake Schema
MySQL | Regular expressions (Regexp)
Nested Queries in SQL
First Normal Form (1NF)
|
[
{
"code": null,
"e": 24304,
"s": 24276,
"text": "\n18 Apr, 2022"
},
{
"code": null,
"e": 25267,
"s": 24304,
"text": "Data Mining refers to extracting or mining knowledge from large amounts of data. The term is actually a misnomer. Thus, data mining should have been more appropriately named as knowledge mining which emphasis on mining from large amounts of data. It is computational process of discovering patterns in large data sets involving methods at intersection of artificial intelligence, machine learning, statistics, and database systems. The overall goal of data mining process is to extract information from a data set and transform it into an understandable structure for further use. It is also defined as extraction of interesting (non-trivial, implicit, previously unknown and potentially useful) patterns or knowledge from a huge amount of data. Data mining is a rapidly growing field that is concerned with developing techniques to assist managers and decision-makers to make intelligent use of a huge amount of repositories. Alternative names for Data Mining :"
},
{
"code": null,
"e": 25456,
"s": 25267,
"text": "1. Knowledge discovery (mining) in databases (KDD)\n2. Knowledge extraction\n3. Data/pattern analysis\n4. Data archaeology\n5. Data dredging\n6. Information harvesting\n7. Business intelligence "
},
{
"code": null,
"e": 25529,
"s": 25456,
"text": "Data Mining and Business Intelligence : Key properties of Data Mining :"
},
{
"code": null,
"e": 25677,
"s": 25529,
"text": "1. Automatic discovery of patterns\n2. Prediction of likely outcomes\n3. Creation of actionable information\n4. Focus on large datasets and databases "
},
{
"code": null,
"e": 25963,
"s": 25677,
"text": "Data Mining : Confluence of Multiple Disciplines – Data Mining Process : Data Mining is a process of discovering various models, summaries, and derived values from a given collection of data. The general experimental procedure adapted to data-mining problem involves following steps :"
},
{
"code": null,
"e": 30105,
"s": 25963,
"text": "State problem and formulate hypothesis – In this step, a modeler usually specifies a group of variables for unknown dependency and, if possible, a general sort of this dependency as an initial hypothesis. There could also be several hypotheses formulated for one problem at this stage. The primary step requires combined expertise of an application domain and a data-mining model. In practice, it always means an in-depth interaction between data-mining expert and application expert. In successful data-mining applications, this cooperation does not stop within initial phase. It continues during whole data-mining process.Collect data – This step cares about how information is generated and picked up. Generally, there are two distinct possibilities. The primary is when data-generation process is under control of an expert (modeler). This approach is understood as a designed experiment. The second possibility is when expert cannot influence data generation process. This is often referred to as observational approach. An observational setting, namely, random data generation, is assumed in most data-mining applications. Typically, sampling distribution is totally unknown after data are collected, or it is partially and implicitly given within data-collection procedure. It is vital, however, to know how data collection affects its theoretical distribution since such a piece of prior knowledge is often useful for modeling and, later, for ultimate interpretation of results. Also, it is important to form sure that information used for estimating a model and therefore data used later for testing and applying a model come from an equivalent, unknown, sampling distribution. If this is often not case, estimated model cannot be successfully utilized in a final application of results.Data Preprocessing – In the observational setting, data is usually “collected” from prevailing databases, data warehouses, and data marts. Data preprocessing usually includes a minimum of two common tasks :(i) Outlier Detection (and removal) : Outliers are unusual data values that are not according to most observations. Commonly, outliers result from measurement errors, coding, and recording errors, and, sometimes, are natural, abnormal values. Such non-representative samples can seriously affect model produced later. There are two strategies for handling outliers : Detect and eventually remove outliers as a neighborhood of preprocessing phase. And Develop robust modeling methods that are insensitive to outliers.(ii) Scaling, encoding, and selecting features : Data preprocessing includes several steps like variable scaling and differing types of encoding. For instance, one feature with range [0, 1] and other with range [100, 1000] will not have an equivalent weight within applied technique. They are going to also influence ultimate data-mining results differently. Therefore, it is recommended to scale them and convey both features to an equivalent weight for further analysis. Also, application-specific encoding methods usually achieve dimensionality reduction by providing a smaller number of informative features for subsequent data modeling.Estimate model – The selection and implementation of acceptable data-mining technique is that main task during this phase. This process is not straightforward. Usually, in practice, implementation is predicated on several models, and selecting simplest one is a further task.Interpret model and draw conclusions – In most cases, data-mining models should help in deciding. Hence, such models got to be interpretable so as to be useful because humans are not likely to base their decisions on complex “black-box” models. Note that goals of accuracy of model and accuracy of its interpretation are somewhat contradictory. Usually, simple models are more interpretable, but they are also less accurate. Modern data-mining methods are expected to yield highly accurate results using high dimensional models. The matter of interpreting these models, also vital, is taken into account a separate task, with specific techniques to validate results. Classification of Data Mining Systems :"
},
{
"code": null,
"e": 30730,
"s": 30105,
"text": "State problem and formulate hypothesis – In this step, a modeler usually specifies a group of variables for unknown dependency and, if possible, a general sort of this dependency as an initial hypothesis. There could also be several hypotheses formulated for one problem at this stage. The primary step requires combined expertise of an application domain and a data-mining model. In practice, it always means an in-depth interaction between data-mining expert and application expert. In successful data-mining applications, this cooperation does not stop within initial phase. It continues during whole data-mining process."
},
{
"code": null,
"e": 31903,
"s": 30730,
"text": "Collect data – This step cares about how information is generated and picked up. Generally, there are two distinct possibilities. The primary is when data-generation process is under control of an expert (modeler). This approach is understood as a designed experiment. The second possibility is when expert cannot influence data generation process. This is often referred to as observational approach. An observational setting, namely, random data generation, is assumed in most data-mining applications. Typically, sampling distribution is totally unknown after data are collected, or it is partially and implicitly given within data-collection procedure. It is vital, however, to know how data collection affects its theoretical distribution since such a piece of prior knowledge is often useful for modeling and, later, for ultimate interpretation of results. Also, it is important to form sure that information used for estimating a model and therefore data used later for testing and applying a model come from an equivalent, unknown, sampling distribution. If this is often not case, estimated model cannot be successfully utilized in a final application of results."
},
{
"code": null,
"e": 33267,
"s": 31903,
"text": "Data Preprocessing – In the observational setting, data is usually “collected” from prevailing databases, data warehouses, and data marts. Data preprocessing usually includes a minimum of two common tasks :(i) Outlier Detection (and removal) : Outliers are unusual data values that are not according to most observations. Commonly, outliers result from measurement errors, coding, and recording errors, and, sometimes, are natural, abnormal values. Such non-representative samples can seriously affect model produced later. There are two strategies for handling outliers : Detect and eventually remove outliers as a neighborhood of preprocessing phase. And Develop robust modeling methods that are insensitive to outliers.(ii) Scaling, encoding, and selecting features : Data preprocessing includes several steps like variable scaling and differing types of encoding. For instance, one feature with range [0, 1] and other with range [100, 1000] will not have an equivalent weight within applied technique. They are going to also influence ultimate data-mining results differently. Therefore, it is recommended to scale them and convey both features to an equivalent weight for further analysis. Also, application-specific encoding methods usually achieve dimensionality reduction by providing a smaller number of informative features for subsequent data modeling."
},
{
"code": null,
"e": 33784,
"s": 33267,
"text": "(i) Outlier Detection (and removal) : Outliers are unusual data values that are not according to most observations. Commonly, outliers result from measurement errors, coding, and recording errors, and, sometimes, are natural, abnormal values. Such non-representative samples can seriously affect model produced later. There are two strategies for handling outliers : Detect and eventually remove outliers as a neighborhood of preprocessing phase. And Develop robust modeling methods that are insensitive to outliers."
},
{
"code": null,
"e": 34426,
"s": 33784,
"text": "(ii) Scaling, encoding, and selecting features : Data preprocessing includes several steps like variable scaling and differing types of encoding. For instance, one feature with range [0, 1] and other with range [100, 1000] will not have an equivalent weight within applied technique. They are going to also influence ultimate data-mining results differently. Therefore, it is recommended to scale them and convey both features to an equivalent weight for further analysis. Also, application-specific encoding methods usually achieve dimensionality reduction by providing a smaller number of informative features for subsequent data modeling."
},
{
"code": null,
"e": 34702,
"s": 34426,
"text": "Estimate model – The selection and implementation of acceptable data-mining technique is that main task during this phase. This process is not straightforward. Usually, in practice, implementation is predicated on several models, and selecting simplest one is a further task."
},
{
"code": null,
"e": 35410,
"s": 34702,
"text": "Interpret model and draw conclusions – In most cases, data-mining models should help in deciding. Hence, such models got to be interpretable so as to be useful because humans are not likely to base their decisions on complex “black-box” models. Note that goals of accuracy of model and accuracy of its interpretation are somewhat contradictory. Usually, simple models are more interpretable, but they are also less accurate. Modern data-mining methods are expected to yield highly accurate results using high dimensional models. The matter of interpreting these models, also vital, is taken into account a separate task, with specific techniques to validate results. Classification of Data Mining Systems :"
},
{
"code": null,
"e": 35508,
"s": 35410,
"text": "1. Database Technology\n2. Statistics\n3. Machine Learning\n4. Information Science\n5. Visualization "
},
{
"code": null,
"e": 37784,
"s": 35508,
"text": "Major issues in Data Mining :Mining different kinds of knowledge in databases – The need for different users is not same. Different users may be interested in different kinds of knowledge. Therefore it is necessary for data mining to cover a broad range of knowledge discovery tasks.Interactive mining of knowledge at multiple levels of abstraction – The data mining process needs to be interactive because it allows users to focus on search for patterns, providing and refining data mining requests based on returned results.Incorporation of background knowledge – To guide discovery process and to express discovered patterns, background knowledge can be used to express discovered patterns not only in concise terms but at multiple levels of abstraction.Data mining query languages and ad-hoc data mining – Data Mining Query language that allows user to describe ad-hoc mining tasks should be integrated with a data warehouse query language and optimized for efficient and flexible data mining.Presentation and visualization of data mining results – Once patterns are discovered it needs to be expressed in high-level languages, visual representations. These representations should be easily understandable by users.Handling noisy or incomplete data – The data cleaning methods are required that can handle noise, incomplete objects while mining data regularities. If data cleaning methods are not there then accuracy of discovered patterns will be poor.Pattern evaluation – It refers to interestingness of problem. The patterns discovered should be interesting because either they represent common knowledge or lack of novelty.Efficiency and scalability of data mining algorithms – In order to effectively extract information from huge amount of data in databases, data mining algorithm must be efficient and scalable.Parallel, distributed, and incremental mining algorithms – The factors such as huge size of databases, wide distribution of data, and complexity of data mining methods motivate development of parallel and distributed data mining algorithms. These algorithms divide data into partitions that are further processed parallel. Then results from partitions are merged. The incremental algorithms update databases without having mined data again from scratch."
},
{
"code": null,
"e": 40060,
"s": 37784,
"text": "Major issues in Data Mining :Mining different kinds of knowledge in databases – The need for different users is not same. Different users may be interested in different kinds of knowledge. Therefore it is necessary for data mining to cover a broad range of knowledge discovery tasks.Interactive mining of knowledge at multiple levels of abstraction – The data mining process needs to be interactive because it allows users to focus on search for patterns, providing and refining data mining requests based on returned results.Incorporation of background knowledge – To guide discovery process and to express discovered patterns, background knowledge can be used to express discovered patterns not only in concise terms but at multiple levels of abstraction.Data mining query languages and ad-hoc data mining – Data Mining Query language that allows user to describe ad-hoc mining tasks should be integrated with a data warehouse query language and optimized for efficient and flexible data mining.Presentation and visualization of data mining results – Once patterns are discovered it needs to be expressed in high-level languages, visual representations. These representations should be easily understandable by users.Handling noisy or incomplete data – The data cleaning methods are required that can handle noise, incomplete objects while mining data regularities. If data cleaning methods are not there then accuracy of discovered patterns will be poor.Pattern evaluation – It refers to interestingness of problem. The patterns discovered should be interesting because either they represent common knowledge or lack of novelty.Efficiency and scalability of data mining algorithms – In order to effectively extract information from huge amount of data in databases, data mining algorithm must be efficient and scalable.Parallel, distributed, and incremental mining algorithms – The factors such as huge size of databases, wide distribution of data, and complexity of data mining methods motivate development of parallel and distributed data mining algorithms. These algorithms divide data into partitions that are further processed parallel. Then results from partitions are merged. The incremental algorithms update databases without having mined data again from scratch."
},
{
"code": null,
"e": 42307,
"s": 40060,
"text": "Mining different kinds of knowledge in databases – The need for different users is not same. Different users may be interested in different kinds of knowledge. Therefore it is necessary for data mining to cover a broad range of knowledge discovery tasks.Interactive mining of knowledge at multiple levels of abstraction – The data mining process needs to be interactive because it allows users to focus on search for patterns, providing and refining data mining requests based on returned results.Incorporation of background knowledge – To guide discovery process and to express discovered patterns, background knowledge can be used to express discovered patterns not only in concise terms but at multiple levels of abstraction.Data mining query languages and ad-hoc data mining – Data Mining Query language that allows user to describe ad-hoc mining tasks should be integrated with a data warehouse query language and optimized for efficient and flexible data mining.Presentation and visualization of data mining results – Once patterns are discovered it needs to be expressed in high-level languages, visual representations. These representations should be easily understandable by users.Handling noisy or incomplete data – The data cleaning methods are required that can handle noise, incomplete objects while mining data regularities. If data cleaning methods are not there then accuracy of discovered patterns will be poor.Pattern evaluation – It refers to interestingness of problem. The patterns discovered should be interesting because either they represent common knowledge or lack of novelty.Efficiency and scalability of data mining algorithms – In order to effectively extract information from huge amount of data in databases, data mining algorithm must be efficient and scalable.Parallel, distributed, and incremental mining algorithms – The factors such as huge size of databases, wide distribution of data, and complexity of data mining methods motivate development of parallel and distributed data mining algorithms. These algorithms divide data into partitions that are further processed parallel. Then results from partitions are merged. The incremental algorithms update databases without having mined data again from scratch."
},
{
"code": null,
"e": 42562,
"s": 42307,
"text": "Mining different kinds of knowledge in databases – The need for different users is not same. Different users may be interested in different kinds of knowledge. Therefore it is necessary for data mining to cover a broad range of knowledge discovery tasks."
},
{
"code": null,
"e": 42806,
"s": 42562,
"text": "Interactive mining of knowledge at multiple levels of abstraction – The data mining process needs to be interactive because it allows users to focus on search for patterns, providing and refining data mining requests based on returned results."
},
{
"code": null,
"e": 43038,
"s": 42806,
"text": "Incorporation of background knowledge – To guide discovery process and to express discovered patterns, background knowledge can be used to express discovered patterns not only in concise terms but at multiple levels of abstraction."
},
{
"code": null,
"e": 43279,
"s": 43038,
"text": "Data mining query languages and ad-hoc data mining – Data Mining Query language that allows user to describe ad-hoc mining tasks should be integrated with a data warehouse query language and optimized for efficient and flexible data mining."
},
{
"code": null,
"e": 43502,
"s": 43279,
"text": "Presentation and visualization of data mining results – Once patterns are discovered it needs to be expressed in high-level languages, visual representations. These representations should be easily understandable by users."
},
{
"code": null,
"e": 43741,
"s": 43502,
"text": "Handling noisy or incomplete data – The data cleaning methods are required that can handle noise, incomplete objects while mining data regularities. If data cleaning methods are not there then accuracy of discovered patterns will be poor."
},
{
"code": null,
"e": 43916,
"s": 43741,
"text": "Pattern evaluation – It refers to interestingness of problem. The patterns discovered should be interesting because either they represent common knowledge or lack of novelty."
},
{
"code": null,
"e": 44108,
"s": 43916,
"text": "Efficiency and scalability of data mining algorithms – In order to effectively extract information from huge amount of data in databases, data mining algorithm must be efficient and scalable."
},
{
"code": null,
"e": 44562,
"s": 44108,
"text": "Parallel, distributed, and incremental mining algorithms – The factors such as huge size of databases, wide distribution of data, and complexity of data mining methods motivate development of parallel and distributed data mining algorithms. These algorithms divide data into partitions that are further processed parallel. Then results from partitions are merged. The incremental algorithms update databases without having mined data again from scratch."
},
{
"code": null,
"e": 44574,
"s": 44562,
"text": "kashishsoda"
},
{
"code": null,
"e": 44586,
"s": 44574,
"text": "data mining"
},
{
"code": null,
"e": 44591,
"s": 44586,
"text": "DBMS"
},
{
"code": null,
"e": 44596,
"s": 44591,
"text": "DBMS"
},
{
"code": null,
"e": 44694,
"s": 44596,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44735,
"s": 44694,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 44778,
"s": 44735,
"text": "Introduction of Relational Algebra in DBMS"
},
{
"code": null,
"e": 44810,
"s": 44778,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 44837,
"s": 44810,
"text": "Two Phase Locking Protocol"
},
{
"code": null,
"e": 44864,
"s": 44837,
"text": "KDD Process in Data Mining"
},
{
"code": null,
"e": 44897,
"s": 44864,
"text": "Conflict Serializability in DBMS"
},
{
"code": null,
"e": 44949,
"s": 44897,
"text": "Difference between Star Schema and Snowflake Schema"
},
{
"code": null,
"e": 44986,
"s": 44949,
"text": "MySQL | Regular expressions (Regexp)"
},
{
"code": null,
"e": 45008,
"s": 44986,
"text": "Nested Queries in SQL"
}
] |
C++ Program to Implement Set_Union in STL
|
The union of two sets is created by the elements that are present in either one of the sets, or in both. Elements from the second set that has the same element in the first set are not copied to the resulting set.
Common set operations are −
Set Union
Set Intersection
Symmetric Set Difference or Exclusive-OR
Set Difference or Subtraction
Begin
Declare set vector v and iterator st.
Initialize st= set_union (set1, set1 + n, set2, set2 +n, v.begin()))
Print the elements.
End.
Live Demo
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main () {
int set1[] = {5,6,7,8,9,10};
int set2[] = {1,2,3,4,6,7};
vector<int> v(10);
vector<int>::iterator st;
sort (set1, set1 + 6);
sort (set2, set2 + 6);
st = set_union(set1, set1 + 6, set2, set2 + 6, v.begin());
v.resize(st - v.begin());
cout<<"The union between the sets has "<< (v.size())<< " elements: "<<endl;
for (st = v.begin(); st != v.end(); ++st)
cout<< *st<<" ";
cout <<endl;
return 0;
}
The union between the sets has 10 elements:
1 2 3 4 5 6 7 8 9 10
|
[
{
"code": null,
"e": 1276,
"s": 1062,
"text": "The union of two sets is created by the elements that are present in either one of the sets, or in both. Elements from the second set that has the same element in the first set are not copied to the resulting set."
},
{
"code": null,
"e": 1304,
"s": 1276,
"text": "Common set operations are −"
},
{
"code": null,
"e": 1314,
"s": 1304,
"text": "Set Union"
},
{
"code": null,
"e": 1331,
"s": 1314,
"text": "Set Intersection"
},
{
"code": null,
"e": 1372,
"s": 1331,
"text": "Symmetric Set Difference or Exclusive-OR"
},
{
"code": null,
"e": 1402,
"s": 1372,
"text": "Set Difference or Subtraction"
},
{
"code": null,
"e": 1549,
"s": 1402,
"text": "Begin\n Declare set vector v and iterator st.\n Initialize st= set_union (set1, set1 + n, set2, set2 +n, v.begin()))\n Print the elements.\nEnd."
},
{
"code": null,
"e": 1560,
"s": 1549,
"text": " Live Demo"
},
{
"code": null,
"e": 2089,
"s": 1560,
"text": "#include <iostream>\n#include <algorithm>\n#include <vector>\nusing namespace std;\nint main () {\n int set1[] = {5,6,7,8,9,10};\n int set2[] = {1,2,3,4,6,7};\n vector<int> v(10);\n vector<int>::iterator st;\n sort (set1, set1 + 6);\n sort (set2, set2 + 6);\n st = set_union(set1, set1 + 6, set2, set2 + 6, v.begin());\n v.resize(st - v.begin());\n cout<<\"The union between the sets has \"<< (v.size())<< \" elements: \"<<endl;\n for (st = v.begin(); st != v.end(); ++st)\n cout<< *st<<\" \";\n cout <<endl;\n return 0;\n}"
},
{
"code": null,
"e": 2154,
"s": 2089,
"text": "The union between the sets has 10 elements:\n1 2 3 4 5 6 7 8 9 10"
}
] |
PDF is not a probability.. The probability density at x can be... | by Aerin Kim | Towards Data Science
|
It’s a well-known fact that the largest value a probability can take is 1.
However, for some PDFs (e.g. the PDF of the exponential distribution, the graph below), when λ= 1.5 and x = 0, the probability density is 1.5, which is obviously greater than 1!
Even if the PDF f(x) takes on values greater than 1, if the domain that it integrates over is less than 1, it can add up to only 1. Let’s take an example of the easiest PDF — the uniform distribution defined on the domain [0, 0.5]. The PDF of the uniform distribution is 1/(b-a), which is constantly 2 throughout.
The total probability is the total area under the graph f(x), which is 2 * 0.5 = 1.
As you can see, even if a PDF is greater than 1, because it integrates over the domain that is less than 1, it can add up to 1.
Isn’t the PDF f(x) a probability?
No. Because f(x) can be greater than 1. (“PD” in PDF stands for “Probability Density,” not Probability.)
f(x) is just a height of the PDF graph at X = x. (Are you confused with X vs x notation? Check it out here.)
The whole “PDF = probability” misconception comes about because we are used to the notion of “PMF = probability”, which is, in fact, correct. However, a PDF is not the same thing as a PMF, and it shouldn’t be interpreted in the same way as a PMF, because discrete random variables and continuous random variables are not defined the same way.
For discrete random variables, we look up the value of a PMF at a single point to find its probability P(X=x) (e.g. Remember how we plugged x into the Poisson PMF?)For continuous random variables, we take an integral of a PDF over a certain interval to find its probability that X will fall in that interval.
f(x) ≠ P(X = x)* f(x): PDF for a continuous r.v.* P(X = x) : PMF for a discrete r.v.
Sure, all good. However, you might wonder...
Why do we have to *integrate* a PDF?
Can we just sum up PDF values, just like we do with PMF values?
No. Because, for continuous random variables, the probability that X takes on any particular value x is 0.
Let's look at the previous example — the Uniform Distribution in [0, 0.5].
The probability density at x=1 is two.But why is the probability at x=1 zero?
To answer the above question, we need to answer the following question first: How many total real numbers do we have in [0, 0.5]?
Infinite ∞. (To be mathematically thorough, uncountably infinite.)0.1, 0.01, 0.001, 0.0001,... You can keep inserting 0 in front of the smallest decimal.
Therefore, a continuous random variable has an infinite # of possible values that it can take, even if the domain is small and fixed. And let's say, the probability density for each value in [0, 0.5] takes an extremely small value, e.g. 000000001. Still, the sum of infinitely (uncountably) many values will reach infinity, no matter how small their values are.
Then, in order to make the sum of probabilities 1, the probability at a single point should be 1/∞, which is 0.
Well, this doesn’t really make sense, either. If you add the infinite number of zeros, you will still get zero. The total probability should add up to one, not to zero.
The thing is, we can’t use the notion of discrete PMF (one value has one matching probability) for continuous variables. We can’t define the probability of continuous variables as we did for discrete variables.
If the probability of X being exactly at point x is zero, how about an extremely small interval around the point x? Say, [x, x+dx]? Let’s say dx is 0.00000000001.
Then the probability that X will fall in [x, x+dx] is the area under the curve f(x) sandwiched by [x, x+dx].
If dx is infinitesimally small, this approximation will be good enough for P(X=x).
f(x)dx : The probability of X in [x, x+dx].f(x): Probability density.dx : Interval length.
A few things to note:
1. If you take a look at the definition of both a PDF and a PMF, it’s actually simply changing the summations in the discrete case (PMF) to integrals in the continuous case (PDF).
2. Why do we use the terms “Density” and “Mass”?
This is analogous to mass density in physics — integrating the density to get the mass. If you think of a mass as a probability, we are integrating a probability density to get a probability (mass).
3. What does a probability density at point x mean?
It means how much probability is concentrated per unit length (dx) near x, or how dense the probability is near x.
4. We need to fix the Wikipedia graph of the exponential distribution. The level of Y-axis P(X) sounds like a probability. We need to change it to f(x) or “Probability Density”.
|
[
{
"code": null,
"e": 122,
"s": 47,
"text": "It’s a well-known fact that the largest value a probability can take is 1."
},
{
"code": null,
"e": 300,
"s": 122,
"text": "However, for some PDFs (e.g. the PDF of the exponential distribution, the graph below), when λ= 1.5 and x = 0, the probability density is 1.5, which is obviously greater than 1!"
},
{
"code": null,
"e": 614,
"s": 300,
"text": "Even if the PDF f(x) takes on values greater than 1, if the domain that it integrates over is less than 1, it can add up to only 1. Let’s take an example of the easiest PDF — the uniform distribution defined on the domain [0, 0.5]. The PDF of the uniform distribution is 1/(b-a), which is constantly 2 throughout."
},
{
"code": null,
"e": 698,
"s": 614,
"text": "The total probability is the total area under the graph f(x), which is 2 * 0.5 = 1."
},
{
"code": null,
"e": 826,
"s": 698,
"text": "As you can see, even if a PDF is greater than 1, because it integrates over the domain that is less than 1, it can add up to 1."
},
{
"code": null,
"e": 860,
"s": 826,
"text": "Isn’t the PDF f(x) a probability?"
},
{
"code": null,
"e": 965,
"s": 860,
"text": "No. Because f(x) can be greater than 1. (“PD” in PDF stands for “Probability Density,” not Probability.)"
},
{
"code": null,
"e": 1074,
"s": 965,
"text": "f(x) is just a height of the PDF graph at X = x. (Are you confused with X vs x notation? Check it out here.)"
},
{
"code": null,
"e": 1417,
"s": 1074,
"text": "The whole “PDF = probability” misconception comes about because we are used to the notion of “PMF = probability”, which is, in fact, correct. However, a PDF is not the same thing as a PMF, and it shouldn’t be interpreted in the same way as a PMF, because discrete random variables and continuous random variables are not defined the same way."
},
{
"code": null,
"e": 1726,
"s": 1417,
"text": "For discrete random variables, we look up the value of a PMF at a single point to find its probability P(X=x) (e.g. Remember how we plugged x into the Poisson PMF?)For continuous random variables, we take an integral of a PDF over a certain interval to find its probability that X will fall in that interval."
},
{
"code": null,
"e": 1812,
"s": 1726,
"text": "f(x) ≠ P(X = x)* f(x): PDF for a continuous r.v.* P(X = x) : PMF for a discrete r.v."
},
{
"code": null,
"e": 1857,
"s": 1812,
"text": "Sure, all good. However, you might wonder..."
},
{
"code": null,
"e": 1894,
"s": 1857,
"text": "Why do we have to *integrate* a PDF?"
},
{
"code": null,
"e": 1958,
"s": 1894,
"text": "Can we just sum up PDF values, just like we do with PMF values?"
},
{
"code": null,
"e": 2065,
"s": 1958,
"text": "No. Because, for continuous random variables, the probability that X takes on any particular value x is 0."
},
{
"code": null,
"e": 2140,
"s": 2065,
"text": "Let's look at the previous example — the Uniform Distribution in [0, 0.5]."
},
{
"code": null,
"e": 2218,
"s": 2140,
"text": "The probability density at x=1 is two.But why is the probability at x=1 zero?"
},
{
"code": null,
"e": 2348,
"s": 2218,
"text": "To answer the above question, we need to answer the following question first: How many total real numbers do we have in [0, 0.5]?"
},
{
"code": null,
"e": 2502,
"s": 2348,
"text": "Infinite ∞. (To be mathematically thorough, uncountably infinite.)0.1, 0.01, 0.001, 0.0001,... You can keep inserting 0 in front of the smallest decimal."
},
{
"code": null,
"e": 2864,
"s": 2502,
"text": "Therefore, a continuous random variable has an infinite # of possible values that it can take, even if the domain is small and fixed. And let's say, the probability density for each value in [0, 0.5] takes an extremely small value, e.g. 000000001. Still, the sum of infinitely (uncountably) many values will reach infinity, no matter how small their values are."
},
{
"code": null,
"e": 2976,
"s": 2864,
"text": "Then, in order to make the sum of probabilities 1, the probability at a single point should be 1/∞, which is 0."
},
{
"code": null,
"e": 3145,
"s": 2976,
"text": "Well, this doesn’t really make sense, either. If you add the infinite number of zeros, you will still get zero. The total probability should add up to one, not to zero."
},
{
"code": null,
"e": 3356,
"s": 3145,
"text": "The thing is, we can’t use the notion of discrete PMF (one value has one matching probability) for continuous variables. We can’t define the probability of continuous variables as we did for discrete variables."
},
{
"code": null,
"e": 3519,
"s": 3356,
"text": "If the probability of X being exactly at point x is zero, how about an extremely small interval around the point x? Say, [x, x+dx]? Let’s say dx is 0.00000000001."
},
{
"code": null,
"e": 3628,
"s": 3519,
"text": "Then the probability that X will fall in [x, x+dx] is the area under the curve f(x) sandwiched by [x, x+dx]."
},
{
"code": null,
"e": 3711,
"s": 3628,
"text": "If dx is infinitesimally small, this approximation will be good enough for P(X=x)."
},
{
"code": null,
"e": 3802,
"s": 3711,
"text": "f(x)dx : The probability of X in [x, x+dx].f(x): Probability density.dx : Interval length."
},
{
"code": null,
"e": 3824,
"s": 3802,
"text": "A few things to note:"
},
{
"code": null,
"e": 4004,
"s": 3824,
"text": "1. If you take a look at the definition of both a PDF and a PMF, it’s actually simply changing the summations in the discrete case (PMF) to integrals in the continuous case (PDF)."
},
{
"code": null,
"e": 4053,
"s": 4004,
"text": "2. Why do we use the terms “Density” and “Mass”?"
},
{
"code": null,
"e": 4252,
"s": 4053,
"text": "This is analogous to mass density in physics — integrating the density to get the mass. If you think of a mass as a probability, we are integrating a probability density to get a probability (mass)."
},
{
"code": null,
"e": 4304,
"s": 4252,
"text": "3. What does a probability density at point x mean?"
},
{
"code": null,
"e": 4419,
"s": 4304,
"text": "It means how much probability is concentrated per unit length (dx) near x, or how dense the probability is near x."
}
] |
Adding Ones | Practice | GeeksforGeeks
|
You start with an array A of size N. Also, A[i] = 0 for i = 1 to N. You will be given K positive integers. Let j be one of these integers, you have to add 1 to all A[i], for i ≥ j. Your task is to print array A after all these K updates are done.
Example 1:
Input:
3 4
1 1 2 3
Output:
2 3 4
Explanation:
Initially the array is {0, 0, 0}. After the
first 1, it becomes {1, 1, 1}. After the
second 1 it becomes {2, 2, 2}. After 2, it
becomes {2, 3, 3}. After 3 it becomes, {2, 3, 4}.
Example 2:
Input:
2 3
1 1 1
Output:
3 3
Explanation:
Initially the array is {0, 0}. After the
first 1, it becomes {1, 1}. After the
second 1 it becomes {2, 2}. After the
third 1, it becomes {3, 3}.
Your Task:
You don't need to read input or print anything. Your task is to complete the function update() which takes the array A[] and its size N as inputs and make the updates and fill the array A[].
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N, K ≤ 105
0
19003001002372 days ago
class Solution{ public: void update(int a[], int n, int updates[], int k) { // Your code goes here for(int i=0;i<k;i++) { a[updates[i] - 1]++; } for(int i=1;i<n;i++) { a[i] = a[i] + a[i-1]; } }};
0
arvind16yadav2 weeks ago
/*JAVA CODE (TIME : 1.1 / 2.7)*/
public static void update(int a[], int n, int updates[], int k) { // Your code goes here for(int x : updates){ ++a[x-1]; } int sum = a[0]; for(int i=1; i<n; i++){ a[i] += sum; sum = a[i]; } }
0
anirbanhaldar6003 weeks ago
Very simple TWO lines solution C++
void update(int a[], int n, int u[], int k){
for(int i = 0; i < k; i++) a[u[i]-1]++;
for(int i = 1; i < n; i++) a[i] += a[i-1];
}
0
dangrio2 months ago
//Simple two liner solution
for(int j=0;j<k;j++) a[updates[j]-1]++;for(int i=1;i<n;i++) a[i]+=a[i-1];
0
kumardiv20012 months ago
// can anyone explain me why is this solution showing me run time //error(segmentaiton fault)
class Solution{ public: void update(int a[], int n, int updates[], int k) { // Your code goes here while(updates[k] != '/0'){ for(int i = 0; i < n; i++){ a[i] += updates[k]; } updates++; } }};
0
mohituniyal462 months ago
here is a simple implementation
class Solution{
public:
void update(int a[], int n, int updates[], int k)
{
// Your code goes here
for(int i=0;i<k;i++){
a[updates[i]-1]++;
}
int prevSum=0;
for(int i=0;i<n;i++){
a[i]+=prevSum;
prevSum=a[i];
}
}
};
+1
9986610789csr4 months ago
for(int j=0;j<k;j++) for(int i=updates[j]-1;i<n;i++)a[i]+=1;
what can i modifie to optimize my code
0
c1phani1simha6 months ago
class Solution{ public: void update(int a[], int n, int updates[], int k) {for(int i=0;i<k;i++) { int num=updates[i]; for(;num-1<n;(num)++) { a[num-1]=a[num-1]+1; } } }};
+1
vivekpatel87700328877 months ago
//easy problem using hashing
void update(int a[],int n,int updates[],int k)
{
for(int i=0;i<k;i++)
a[updates[i]-1]++;
for(int i=1;i<n;i++)
a[i]=a[i]+a[i-1];
}
0
aniketsingh27220017 months ago
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": 485,
"s": 238,
"text": "You start with an array A of size N. Also, A[i] = 0 for i = 1 to N. You will be given K positive integers. Let j be one of these integers, you have to add 1 to all A[i], for i ≥ j. Your task is to print array A after all these K updates are done."
},
{
"code": null,
"e": 498,
"s": 485,
"text": "\nExample 1: "
},
{
"code": null,
"e": 724,
"s": 498,
"text": "Input:\n3 4\n1 1 2 3\nOutput:\n2 3 4\nExplanation:\nInitially the array is {0, 0, 0}. After the\nfirst 1, it becomes {1, 1, 1}. After the\nsecond 1 it becomes {2, 2, 2}. After 2, it \nbecomes {2, 3, 3}. After 3 it becomes, {2, 3, 4}. "
},
{
"code": null,
"e": 738,
"s": 726,
"text": "Example 2: "
},
{
"code": null,
"e": 926,
"s": 738,
"text": "Input:\n2 3\n1 1 1\nOutput:\n3 3 \nExplanation:\nInitially the array is {0, 0}. After the\nfirst 1, it becomes {1, 1}. After the\nsecond 1 it becomes {2, 2}. After the\nthird 1, it becomes {3, 3}."
},
{
"code": null,
"e": 1132,
"s": 928,
"text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function update() which takes the array A[] and its size N as inputs and make the updates and fill the array A[]."
},
{
"code": null,
"e": 1196,
"s": 1134,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1226,
"s": 1198,
"text": "Constraints:\n1 ≤ N, K ≤ 105"
},
{
"code": null,
"e": 1228,
"s": 1226,
"text": "0"
},
{
"code": null,
"e": 1252,
"s": 1228,
"text": "19003001002372 days ago"
},
{
"code": null,
"e": 1519,
"s": 1252,
"text": "class Solution{ public: void update(int a[], int n, int updates[], int k) { // Your code goes here for(int i=0;i<k;i++) { a[updates[i] - 1]++; } for(int i=1;i<n;i++) { a[i] = a[i] + a[i-1]; } }}; "
},
{
"code": null,
"e": 1521,
"s": 1519,
"text": "0"
},
{
"code": null,
"e": 1546,
"s": 1521,
"text": "arvind16yadav2 weeks ago"
},
{
"code": null,
"e": 1579,
"s": 1546,
"text": "/*JAVA CODE (TIME : 1.1 / 2.7)*/"
},
{
"code": null,
"e": 1849,
"s": 1579,
"text": "public static void update(int a[], int n, int updates[], int k) { // Your code goes here for(int x : updates){ ++a[x-1]; } int sum = a[0]; for(int i=1; i<n; i++){ a[i] += sum; sum = a[i]; } }"
},
{
"code": null,
"e": 1851,
"s": 1849,
"text": "0"
},
{
"code": null,
"e": 1879,
"s": 1851,
"text": "anirbanhaldar6003 weeks ago"
},
{
"code": null,
"e": 1914,
"s": 1879,
"text": "Very simple TWO lines solution C++"
},
{
"code": null,
"e": 2054,
"s": 1916,
"text": "void update(int a[], int n, int u[], int k){\n for(int i = 0; i < k; i++) a[u[i]-1]++;\n for(int i = 1; i < n; i++) a[i] += a[i-1];\n}"
},
{
"code": null,
"e": 2056,
"s": 2054,
"text": "0"
},
{
"code": null,
"e": 2076,
"s": 2056,
"text": "dangrio2 months ago"
},
{
"code": null,
"e": 2104,
"s": 2076,
"text": "//Simple two liner solution"
},
{
"code": null,
"e": 2178,
"s": 2104,
"text": "for(int j=0;j<k;j++) a[updates[j]-1]++;for(int i=1;i<n;i++) a[i]+=a[i-1];"
},
{
"code": null,
"e": 2180,
"s": 2178,
"text": "0"
},
{
"code": null,
"e": 2205,
"s": 2180,
"text": "kumardiv20012 months ago"
},
{
"code": null,
"e": 2299,
"s": 2205,
"text": "// can anyone explain me why is this solution showing me run time //error(segmentaiton fault)"
},
{
"code": null,
"e": 2522,
"s": 2299,
"text": "class Solution{ public: void update(int a[], int n, int updates[], int k) { // Your code goes here while(updates[k] != '/0'){ for(int i = 0; i < n; i++){ a[i] += updates[k]; } updates++; } }};"
},
{
"code": null,
"e": 2524,
"s": 2522,
"text": "0"
},
{
"code": null,
"e": 2550,
"s": 2524,
"text": "mohituniyal462 months ago"
},
{
"code": null,
"e": 2582,
"s": 2550,
"text": "here is a simple implementation"
},
{
"code": null,
"e": 2899,
"s": 2584,
"text": "class Solution{\n public:\n void update(int a[], int n, int updates[], int k)\n {\n // Your code goes here\n for(int i=0;i<k;i++){\n a[updates[i]-1]++;\n }\n int prevSum=0;\n for(int i=0;i<n;i++){\n a[i]+=prevSum;\n prevSum=a[i];\n }\n }\n};"
},
{
"code": null,
"e": 2902,
"s": 2899,
"text": "+1"
},
{
"code": null,
"e": 2928,
"s": 2902,
"text": "9986610789csr4 months ago"
},
{
"code": null,
"e": 2999,
"s": 2928,
"text": "for(int j=0;j<k;j++) for(int i=updates[j]-1;i<n;i++)a[i]+=1;"
},
{
"code": null,
"e": 3040,
"s": 3001,
"text": "what can i modifie to optimize my code"
},
{
"code": null,
"e": 3042,
"s": 3040,
"text": "0"
},
{
"code": null,
"e": 3068,
"s": 3042,
"text": "c1phani1simha6 months ago"
},
{
"code": null,
"e": 3299,
"s": 3068,
"text": "class Solution{ public: void update(int a[], int n, int updates[], int k) {for(int i=0;i<k;i++) { int num=updates[i]; for(;num-1<n;(num)++) { a[num-1]=a[num-1]+1; } } }};"
},
{
"code": null,
"e": 3302,
"s": 3299,
"text": "+1"
},
{
"code": null,
"e": 3335,
"s": 3302,
"text": "vivekpatel87700328877 months ago"
},
{
"code": null,
"e": 3364,
"s": 3335,
"text": "//easy problem using hashing"
},
{
"code": null,
"e": 3411,
"s": 3364,
"text": "void update(int a[],int n,int updates[],int k)"
},
{
"code": null,
"e": 3413,
"s": 3411,
"text": "{"
},
{
"code": null,
"e": 3442,
"s": 3417,
"text": " for(int i=0;i<k;i++)"
},
{
"code": null,
"e": 3469,
"s": 3442,
"text": " a[updates[i]-1]++;"
},
{
"code": null,
"e": 3493,
"s": 3469,
"text": " for(int i=1;i<n;i++)"
},
{
"code": null,
"e": 3518,
"s": 3493,
"text": " a[i]=a[i]+a[i-1];"
},
{
"code": null,
"e": 3526,
"s": 3524,
"text": "}"
},
{
"code": null,
"e": 3528,
"s": 3526,
"text": "0"
},
{
"code": null,
"e": 3559,
"s": 3528,
"text": "aniketsingh27220017 months ago"
},
{
"code": null,
"e": 3705,
"s": 3559,
"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": 3741,
"s": 3705,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3751,
"s": 3741,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3761,
"s": 3751,
"text": "\nContest\n"
},
{
"code": null,
"e": 3824,
"s": 3761,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3972,
"s": 3824,
"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": 4180,
"s": 3972,
"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": 4286,
"s": 4180,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Difference between Int16 and UInt16 in C# - GeeksforGeeks
|
26 May, 2020
Int16: This Struct is used to represents 16-bit signed integer. The Int16 can store both types of values including negative and positive between the ranges of -32768 to +32767.
Example :
C#
// C# program to show the// difference between Int16// and UInt16 using System;using System.Text; publicclass GFG { // Main Method static void Main(string[] args) { // printing minimum & maximum values Console.WriteLine("Minimum value of Int16: " + Int16.MinValue); Console.WriteLine("Maximum value of Int16: " + Int16.MaxValue); Console.WriteLine(); // Int16 array Int16[] arr1 = {-3, 0, 1, 3, 7}; foreach (Int16 i in arr1) { Console.WriteLine(i); } }}
Output:
Minimum value of Int16: -32768
Maximum value of Int16: 32767
-3
0
1
3
7
UInt16: This Struct is used to represents 16-bit unsigned integer. The UInt16 can store only positive value only which ranges from 0 to 65535.
Example :
C#
// C# program to show the // difference between Int16 // and UInt16 using System;using System.Text; public class GFG{ // Main Method static void Main(string[] args) { // printing minimum & maximum values Console.WriteLine("Minimum value of UInt16: " + UInt16.MinValue); Console.WriteLine("Maximum value of UInt16: " + UInt16.MaxValue); Console.WriteLine(); // Int16 array UInt16[] arr1 = { 13, 0, 1, 3, 7}; foreach (UInt16 i in arr1) { Console.WriteLine(i); } }}
Output:
Minimum value of UInt16: 0
Maximum value of UInt16: 65535
13
0
1
3
7
Differences between Int16 and UInt16in C#
Sr.No
INT16
UINT16
1.
2.
3.
4.
5.
6.
Syntax to declare the Int16 :
Int16 variable_name;
Syntax to declare the UInt16 :
UInt16 variable_name;
CSharp-Int16-Struct
CSharp-UInt16-Struct
C#
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Difference between Ref and Out keywords in C#
C# | Delegates
C# | Constructors
Extension Method in C#
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": 24282,
"s": 24254,
"text": "\n26 May, 2020"
},
{
"code": null,
"e": 24459,
"s": 24282,
"text": "Int16: This Struct is used to represents 16-bit signed integer. The Int16 can store both types of values including negative and positive between the ranges of -32768 to +32767."
},
{
"code": null,
"e": 24469,
"s": 24459,
"text": "Example :"
},
{
"code": null,
"e": 24472,
"s": 24469,
"text": "C#"
},
{
"code": "// C# program to show the// difference between Int16// and UInt16 using System;using System.Text; publicclass GFG { // Main Method static void Main(string[] args) { // printing minimum & maximum values Console.WriteLine(\"Minimum value of Int16: \" + Int16.MinValue); Console.WriteLine(\"Maximum value of Int16: \" + Int16.MaxValue); Console.WriteLine(); // Int16 array Int16[] arr1 = {-3, 0, 1, 3, 7}; foreach (Int16 i in arr1) { Console.WriteLine(i); } }}",
"e": 25016,
"s": 24472,
"text": null
},
{
"code": null,
"e": 25024,
"s": 25016,
"text": "Output:"
},
{
"code": null,
"e": 25098,
"s": 25024,
"text": "Minimum value of Int16: -32768\nMaximum value of Int16: 32767\n\n-3\n0\n1\n3\n7\n"
},
{
"code": null,
"e": 25241,
"s": 25098,
"text": "UInt16: This Struct is used to represents 16-bit unsigned integer. The UInt16 can store only positive value only which ranges from 0 to 65535."
},
{
"code": null,
"e": 25251,
"s": 25241,
"text": "Example :"
},
{
"code": null,
"e": 25254,
"s": 25251,
"text": "C#"
},
{
"code": "// C# program to show the // difference between Int16 // and UInt16 using System;using System.Text; public class GFG{ // Main Method static void Main(string[] args) { // printing minimum & maximum values Console.WriteLine(\"Minimum value of UInt16: \" + UInt16.MinValue); Console.WriteLine(\"Maximum value of UInt16: \" + UInt16.MaxValue); Console.WriteLine(); // Int16 array UInt16[] arr1 = { 13, 0, 1, 3, 7}; foreach (UInt16 i in arr1) { Console.WriteLine(i); } }}",
"e": 25883,
"s": 25254,
"text": null
},
{
"code": null,
"e": 25891,
"s": 25883,
"text": "Output:"
},
{
"code": null,
"e": 25962,
"s": 25891,
"text": "Minimum value of UInt16: 0\nMaximum value of UInt16: 65535\n\n13\n0\n1\n3\n7\n"
},
{
"code": null,
"e": 26004,
"s": 25962,
"text": "Differences between Int16 and UInt16in C#"
},
{
"code": null,
"e": 26010,
"s": 26004,
"text": "Sr.No"
},
{
"code": null,
"e": 26016,
"s": 26010,
"text": "INT16"
},
{
"code": null,
"e": 26023,
"s": 26016,
"text": "UINT16"
},
{
"code": null,
"e": 26026,
"s": 26023,
"text": "1."
},
{
"code": null,
"e": 26029,
"s": 26026,
"text": "2."
},
{
"code": null,
"e": 26032,
"s": 26029,
"text": "3."
},
{
"code": null,
"e": 26035,
"s": 26032,
"text": "4."
},
{
"code": null,
"e": 26038,
"s": 26035,
"text": "5."
},
{
"code": null,
"e": 26042,
"s": 26038,
"text": " 6."
},
{
"code": null,
"e": 26073,
"s": 26042,
"text": " Syntax to declare the Int16 :"
},
{
"code": null,
"e": 26095,
"s": 26073,
"text": "Int16 variable_name;\n"
},
{
"code": null,
"e": 26128,
"s": 26095,
"text": " Syntax to declare the UInt16 :"
},
{
"code": null,
"e": 26151,
"s": 26128,
"text": "UInt16 variable_name;\n"
},
{
"code": null,
"e": 26171,
"s": 26151,
"text": "CSharp-Int16-Struct"
},
{
"code": null,
"e": 26192,
"s": 26171,
"text": "CSharp-UInt16-Struct"
},
{
"code": null,
"e": 26195,
"s": 26192,
"text": "C#"
},
{
"code": null,
"e": 26214,
"s": 26195,
"text": "Difference Between"
},
{
"code": null,
"e": 26312,
"s": 26214,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26330,
"s": 26312,
"text": "Destructors in C#"
},
{
"code": null,
"e": 26376,
"s": 26330,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 26391,
"s": 26376,
"text": "C# | Delegates"
},
{
"code": null,
"e": 26409,
"s": 26391,
"text": "C# | Constructors"
},
{
"code": null,
"e": 26432,
"s": 26409,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 26463,
"s": 26432,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 26503,
"s": 26463,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 26535,
"s": 26503,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 26596,
"s": 26535,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
cut - Unix, Linux Command
|
cut - To divide a file into several parts (columns)
cut [OPTION]... [FILE]...
cur writes to standard output selected parts of each line of each input file, or standard input if no files are given or for a file name of '-'.
Let's have a sample file sample.txt
$ cat sample.txt
1;2;3;4;5;6;7;8;9
To Parse out column 2 from a semicolon (;) delimited file:
$ cat sample.txt | cut -d \; -f 2 > output.txt
$ cat output.txt
2
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 10629,
"s": 10577,
"text": "cut - To divide a file into several parts (columns)"
},
{
"code": null,
"e": 10655,
"s": 10629,
"text": "cut [OPTION]... [FILE]..."
},
{
"code": null,
"e": 10800,
"s": 10655,
"text": "cur writes to standard output selected parts of each line of each input file, or standard input if no files are given or for a file name of '-'."
},
{
"code": null,
"e": 10836,
"s": 10800,
"text": "Let's have a sample file sample.txt"
},
{
"code": null,
"e": 10872,
"s": 10836,
"text": "$ cat sample.txt\n1;2;3;4;5;6;7;8;9\n"
},
{
"code": null,
"e": 10931,
"s": 10872,
"text": "To Parse out column 2 from a semicolon (;) delimited file:"
},
{
"code": null,
"e": 10998,
"s": 10931,
"text": "$ cat sample.txt | cut -d \\; -f 2 > output.txt\n$ cat output.txt\n2\n"
},
{
"code": null,
"e": 11033,
"s": 10998,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 11061,
"s": 11033,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 11095,
"s": 11061,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 11112,
"s": 11095,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 11145,
"s": 11112,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 11156,
"s": 11145,
"text": " Pradeep D"
},
{
"code": null,
"e": 11191,
"s": 11156,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 11207,
"s": 11191,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 11240,
"s": 11207,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 11252,
"s": 11240,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 11284,
"s": 11252,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 11292,
"s": 11284,
"text": " Uplatz"
},
{
"code": null,
"e": 11299,
"s": 11292,
"text": " Print"
},
{
"code": null,
"e": 11310,
"s": 11299,
"text": " Add Notes"
}
] |
Kaplan-Meier curve explained | by Zolzaya Luvsandorj | Towards Data Science
|
Kaplan-Meier curve, a popular survival analysis tool, is useful in understanding survival probability over time in the presence of incomplete data. In this post, we will learn how to build a Kaplan-Meier curve from scratch to gain a better understanding, then look at two ways to build it using survival analysis libraries in Python.
Let’s imagine we have data collected from September 2020 to June 2021 for a clinical study to understand the survival-time among cancer patients. Here’s a timeline for the people who participated in this hypothetical study:
We kept the dataset for our imaginary study small so that it’s easier to closely monitor the process. Black solid circles signifies the last data entry for a record. A cross inside the circle means the record had the event (i.e. death) whereas a question mark means the record haven’t had the event. To be more specific, there are three possible scenarios.
Had event: Had event during the study (e.g. record a and c)No event: Didn’t have event by the end of study (e.g. record b and d).No event: Dropped out of study before the endpoint and didn’t have event while enrolled in the study (e.g. record f and h).
Had event: Had event during the study (e.g. record a and c)
No event: Didn’t have event by the end of study (e.g. record b and d).
No event: Dropped out of study before the endpoint and didn’t have event while enrolled in the study (e.g. record f and h).
The second and third types of records are called censored, more specifically right-censored, records as we have incomplete information regarding the event.
In the chart above, we see a calendar time in the horizontal axis. Now, we need to convert a calendar time to a survival time, a time duration measured relative to the study enrolment date. Survival time is commonly referred to as duration in the Python libraries we are going to later familiarise; hence, we will be using these terms interchangeably here onwards.
Using the following script, let’s import the libraries that we need and create a small DataFrame containing duration and event for the 9 records:
# Data manipulationimport numpy as npimport pandas as pdfrom string import ascii_lowercase# Visualisationimport matplotlib.pyplot as pltimport seaborn as snssns.set(style='dark', context='talk')# Kaplan-Meier curvefrom lifelines import KaplanMeierFitter from sksurv.nonparametric import kaplan_meier_estimator# Create a toy dataframedf = pd.DataFrame(data={'duration': [3,9,5,8,7,2,1,3,4], 'event': [1,0,1,0,1,0,1,0,0]}, index=list(ascii_lowercase[:9]))df
Now let’s familiarise ourselves with the conceptual knowledge. The Kaplan-Meier curve is the visual representation of the Kaplan-Meier estimator which makes the following assumptions:
Censorship: Censored observations have the same survival prospects as uncensored observations.Study entry time: Survival probabilities are the same for observations recruited early and later in the study.Event time: Event happened at the defined time
Censorship: Censored observations have the same survival prospects as uncensored observations.
Study entry time: Survival probabilities are the same for observations recruited early and later in the study.
Event time: Event happened at the defined time
The Kaplan-Meier estimator is defined by the following formula:
With this formula, we can find the survival probability at a given time. Whether i starts from 1 or 0 doesn’t make a difference as survival probability at time 0 is 1. If we look at this formula closely, we will notice that what’s inside bracket is capturing the proportion survived (i.e. 1- proportion died).
Let’s find the survival probability for the first three durations with this formula:
At one month into the study, we had 9 participants at risk and one participant had died. Hence, d1 = 1 and n1 = 9.
At two months into the study, we had 8 participants at risk and no one had died. Hence, d2 = 0 and n = 8. As you can see, when duration has no event, the survival probability remains the same as the previous duration. Therefore, if a duration has no event, we can skip the calculation and use survival probability from the previous survival time.
At three months into the study, we had 7 records at risk and 1 death, the survival probability drops to 0.76. The equation is getting longer and more tedious now. We can rewrite the formula to the following simpler form:
Using this formula, calculations are more succinct:
These three examples have illustrated how the probabilities are estimated. Instead of repetitively calculating the rest, let’s translate the logic into Python scripts and calculate the survival probability for all durations:
# Prepare unique durations in ascending orderdurations = df.sort_values('duration')['duration'].unique()# Initialise the tablecolumns = ['duration', 'n_at_risk', 'n_events', 'survival_probability']km = pd.DataFrame(columns=columns, dtype=np.number)km = km.append(pd.DataFrame([[0, df.shape[0], 0, 1]], columns=columns))# Calculate survival probability for each durationfor i, t in enumerate(durations): n = np.sum(df['duration']>=t) d = np.sum((df['duration']==t) & (df['event']==1)) s = (1 - d / n) * km.loc[i, 'survival_probability'] km = km.append(pd.DataFrame([[t, n, d, s]], index=[i+1], columns=columns))km
The Kaplan-Meier curve needs the survival probability and duration columns. Let’s plot the curve now since we have the inputs ready.
plt.figure(figsize=(8,4))sns.lineplot(data=km, x='duration', y='survival_probability', drawstyle='steps-post')plt.ylim(0,1.1) plt.title("Kaplan-Meier curve");
Voila, we just plotted the curve ourselves. Constructing the curve from scratch hopefully helped you to understand the underlying logic. Having learned how to construct the curve ourselves, let’s learn more practical ways to plot the Kaplan-Meier curve. We will familiarise with two libraries that provide the solution out-of-the-box.
Lifeline is an easy-to-use survival analysis library in Python. Kaplan-Meier curve can be plotted using the KaplanMeierFitter object in a handful of lines:
kmf = KaplanMeierFitter() kmf.fit(df['duration'], df['event'])plt.figure(figsize=(8,4))kmf.plot()plt.title("Kaplan-Meier curve");
From the fitted object, we can also see the survival probabilities by accessing the survival_function_ attribute:
kmf.survival_function_
We can also extract the event table, which is similar to a table we built in Section 1.
kmf.event_table
With lifelines, plotting the curve and inspecting details regarding the estimator becomes easy.
Another useful survival analysis library is scikit-survival. As the name suggests, it works harmoniously with scikit-learn. We can get the duration and survival probability by utilising kaplan_meier_estimator(). Once we have the required inputs for the curve, we can plot it using any visualisation library. Since we used seaborn in Section 1, we will look at an alternative way to plot using matplotlib:
duration, survival_probability = kaplan_meier_estimator(df['event']==1, df['duration'])plt.figure(figsize=(8,4))plt.step(x=duration, y=survival_probability, where="post")plt.ylim(0,1.1)plt.xlabel("Survival time (months)")plt.ylabel("Survival probability")plt.title("Kaplan-Meier curve");
That was it, you have learned underlying logic for preparing the inputs for the Kaplan-Meier curve and familiarised with a few different ways to plot the curve!
Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me.
Thank you for reading this article. If you are interested, here are links to some of my other posts:◼️ ROC curve explained◼️ Useful IPython magic commands◼️ 5 tips to learn Python from zero◼️ Organise your Jupyter Notebook with these tips◼️️ Writing 5 common SQL queries in pandas
Bye for now 🏃💨
|
[
{
"code": null,
"e": 505,
"s": 171,
"text": "Kaplan-Meier curve, a popular survival analysis tool, is useful in understanding survival probability over time in the presence of incomplete data. In this post, we will learn how to build a Kaplan-Meier curve from scratch to gain a better understanding, then look at two ways to build it using survival analysis libraries in Python."
},
{
"code": null,
"e": 729,
"s": 505,
"text": "Let’s imagine we have data collected from September 2020 to June 2021 for a clinical study to understand the survival-time among cancer patients. Here’s a timeline for the people who participated in this hypothetical study:"
},
{
"code": null,
"e": 1086,
"s": 729,
"text": "We kept the dataset for our imaginary study small so that it’s easier to closely monitor the process. Black solid circles signifies the last data entry for a record. A cross inside the circle means the record had the event (i.e. death) whereas a question mark means the record haven’t had the event. To be more specific, there are three possible scenarios."
},
{
"code": null,
"e": 1339,
"s": 1086,
"text": "Had event: Had event during the study (e.g. record a and c)No event: Didn’t have event by the end of study (e.g. record b and d).No event: Dropped out of study before the endpoint and didn’t have event while enrolled in the study (e.g. record f and h)."
},
{
"code": null,
"e": 1399,
"s": 1339,
"text": "Had event: Had event during the study (e.g. record a and c)"
},
{
"code": null,
"e": 1470,
"s": 1399,
"text": "No event: Didn’t have event by the end of study (e.g. record b and d)."
},
{
"code": null,
"e": 1594,
"s": 1470,
"text": "No event: Dropped out of study before the endpoint and didn’t have event while enrolled in the study (e.g. record f and h)."
},
{
"code": null,
"e": 1750,
"s": 1594,
"text": "The second and third types of records are called censored, more specifically right-censored, records as we have incomplete information regarding the event."
},
{
"code": null,
"e": 2115,
"s": 1750,
"text": "In the chart above, we see a calendar time in the horizontal axis. Now, we need to convert a calendar time to a survival time, a time duration measured relative to the study enrolment date. Survival time is commonly referred to as duration in the Python libraries we are going to later familiarise; hence, we will be using these terms interchangeably here onwards."
},
{
"code": null,
"e": 2261,
"s": 2115,
"text": "Using the following script, let’s import the libraries that we need and create a small DataFrame containing duration and event for the 9 records:"
},
{
"code": null,
"e": 2758,
"s": 2261,
"text": "# Data manipulationimport numpy as npimport pandas as pdfrom string import ascii_lowercase# Visualisationimport matplotlib.pyplot as pltimport seaborn as snssns.set(style='dark', context='talk')# Kaplan-Meier curvefrom lifelines import KaplanMeierFitter from sksurv.nonparametric import kaplan_meier_estimator# Create a toy dataframedf = pd.DataFrame(data={'duration': [3,9,5,8,7,2,1,3,4], 'event': [1,0,1,0,1,0,1,0,0]}, index=list(ascii_lowercase[:9]))df"
},
{
"code": null,
"e": 2942,
"s": 2758,
"text": "Now let’s familiarise ourselves with the conceptual knowledge. The Kaplan-Meier curve is the visual representation of the Kaplan-Meier estimator which makes the following assumptions:"
},
{
"code": null,
"e": 3193,
"s": 2942,
"text": "Censorship: Censored observations have the same survival prospects as uncensored observations.Study entry time: Survival probabilities are the same for observations recruited early and later in the study.Event time: Event happened at the defined time"
},
{
"code": null,
"e": 3288,
"s": 3193,
"text": "Censorship: Censored observations have the same survival prospects as uncensored observations."
},
{
"code": null,
"e": 3399,
"s": 3288,
"text": "Study entry time: Survival probabilities are the same for observations recruited early and later in the study."
},
{
"code": null,
"e": 3446,
"s": 3399,
"text": "Event time: Event happened at the defined time"
},
{
"code": null,
"e": 3510,
"s": 3446,
"text": "The Kaplan-Meier estimator is defined by the following formula:"
},
{
"code": null,
"e": 3820,
"s": 3510,
"text": "With this formula, we can find the survival probability at a given time. Whether i starts from 1 or 0 doesn’t make a difference as survival probability at time 0 is 1. If we look at this formula closely, we will notice that what’s inside bracket is capturing the proportion survived (i.e. 1- proportion died)."
},
{
"code": null,
"e": 3905,
"s": 3820,
"text": "Let’s find the survival probability for the first three durations with this formula:"
},
{
"code": null,
"e": 4020,
"s": 3905,
"text": "At one month into the study, we had 9 participants at risk and one participant had died. Hence, d1 = 1 and n1 = 9."
},
{
"code": null,
"e": 4367,
"s": 4020,
"text": "At two months into the study, we had 8 participants at risk and no one had died. Hence, d2 = 0 and n = 8. As you can see, when duration has no event, the survival probability remains the same as the previous duration. Therefore, if a duration has no event, we can skip the calculation and use survival probability from the previous survival time."
},
{
"code": null,
"e": 4588,
"s": 4367,
"text": "At three months into the study, we had 7 records at risk and 1 death, the survival probability drops to 0.76. The equation is getting longer and more tedious now. We can rewrite the formula to the following simpler form:"
},
{
"code": null,
"e": 4640,
"s": 4588,
"text": "Using this formula, calculations are more succinct:"
},
{
"code": null,
"e": 4865,
"s": 4640,
"text": "These three examples have illustrated how the probabilities are estimated. Instead of repetitively calculating the rest, let’s translate the logic into Python scripts and calculate the survival probability for all durations:"
},
{
"code": null,
"e": 5592,
"s": 4865,
"text": "# Prepare unique durations in ascending orderdurations = df.sort_values('duration')['duration'].unique()# Initialise the tablecolumns = ['duration', 'n_at_risk', 'n_events', 'survival_probability']km = pd.DataFrame(columns=columns, dtype=np.number)km = km.append(pd.DataFrame([[0, df.shape[0], 0, 1]], columns=columns))# Calculate survival probability for each durationfor i, t in enumerate(durations): n = np.sum(df['duration']>=t) d = np.sum((df['duration']==t) & (df['event']==1)) s = (1 - d / n) * km.loc[i, 'survival_probability'] km = km.append(pd.DataFrame([[t, n, d, s]], index=[i+1], columns=columns))km"
},
{
"code": null,
"e": 5725,
"s": 5592,
"text": "The Kaplan-Meier curve needs the survival probability and duration columns. Let’s plot the curve now since we have the inputs ready."
},
{
"code": null,
"e": 5897,
"s": 5725,
"text": "plt.figure(figsize=(8,4))sns.lineplot(data=km, x='duration', y='survival_probability', drawstyle='steps-post')plt.ylim(0,1.1) plt.title(\"Kaplan-Meier curve\");"
},
{
"code": null,
"e": 6232,
"s": 5897,
"text": "Voila, we just plotted the curve ourselves. Constructing the curve from scratch hopefully helped you to understand the underlying logic. Having learned how to construct the curve ourselves, let’s learn more practical ways to plot the Kaplan-Meier curve. We will familiarise with two libraries that provide the solution out-of-the-box."
},
{
"code": null,
"e": 6388,
"s": 6232,
"text": "Lifeline is an easy-to-use survival analysis library in Python. Kaplan-Meier curve can be plotted using the KaplanMeierFitter object in a handful of lines:"
},
{
"code": null,
"e": 6518,
"s": 6388,
"text": "kmf = KaplanMeierFitter() kmf.fit(df['duration'], df['event'])plt.figure(figsize=(8,4))kmf.plot()plt.title(\"Kaplan-Meier curve\");"
},
{
"code": null,
"e": 6632,
"s": 6518,
"text": "From the fitted object, we can also see the survival probabilities by accessing the survival_function_ attribute:"
},
{
"code": null,
"e": 6655,
"s": 6632,
"text": "kmf.survival_function_"
},
{
"code": null,
"e": 6743,
"s": 6655,
"text": "We can also extract the event table, which is similar to a table we built in Section 1."
},
{
"code": null,
"e": 6759,
"s": 6743,
"text": "kmf.event_table"
},
{
"code": null,
"e": 6855,
"s": 6759,
"text": "With lifelines, plotting the curve and inspecting details regarding the estimator becomes easy."
},
{
"code": null,
"e": 7260,
"s": 6855,
"text": "Another useful survival analysis library is scikit-survival. As the name suggests, it works harmoniously with scikit-learn. We can get the duration and survival probability by utilising kaplan_meier_estimator(). Once we have the required inputs for the curve, we can plot it using any visualisation library. Since we used seaborn in Section 1, we will look at an alternative way to plot using matplotlib:"
},
{
"code": null,
"e": 7548,
"s": 7260,
"text": "duration, survival_probability = kaplan_meier_estimator(df['event']==1, df['duration'])plt.figure(figsize=(8,4))plt.step(x=duration, y=survival_probability, where=\"post\")plt.ylim(0,1.1)plt.xlabel(\"Survival time (months)\")plt.ylabel(\"Survival probability\")plt.title(\"Kaplan-Meier curve\");"
},
{
"code": null,
"e": 7709,
"s": 7548,
"text": "That was it, you have learned underlying logic for preparing the inputs for the Kaplan-Meier curve and familiarised with a few different ways to plot the curve!"
},
{
"code": null,
"e": 7933,
"s": 7709,
"text": "Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me."
},
{
"code": null,
"e": 8214,
"s": 7933,
"text": "Thank you for reading this article. If you are interested, here are links to some of my other posts:◼️ ROC curve explained◼️ Useful IPython magic commands◼️ 5 tips to learn Python from zero◼️ Organise your Jupyter Notebook with these tips◼️️ Writing 5 common SQL queries in pandas"
}
] |
Deep learning unbalanced training data?Solve it like this. | by Shubrashankh Chatterjee | Towards Data Science
|
One of the biggest problems that we face when we tackle any machine learning problem is the problem of unbalanced training data.The problem of unbalanced data is such that the academia is split with respect to the definition, implication & possible solutions for the same.We will here try to unravel the mystery of unbalanced classes in the training data using an image classification problem.
In a classification problem when out of all the classes which you want to predict if for one or more classes there are extremely low number of samples you may be facing a problem of unbalanced classes in your data.
Examples
Fraud prediction(Number of frauds will be much lower that genuine transactions)Natural disaster predictions(Bad events will be much lower than good)Identifying malignant tumor in an image classification(images with a tumor will be much less than that of no tumor within a training sample)
Fraud prediction(Number of frauds will be much lower that genuine transactions)
Natural disaster predictions(Bad events will be much lower than good)
Identifying malignant tumor in an image classification(images with a tumor will be much less than that of no tumor within a training sample)
Why is this a problem?
The unbalanced classes create a problem due to two main reasons:
We don’t get optimized results for the class which is unbalanced in real time as the model/algorithm never gets sufficient look at the underlying classIt creates a problem of making a validation or test sample as its difficult to have representation across classes in case number of observation for few classes is extremely less
We don’t get optimized results for the class which is unbalanced in real time as the model/algorithm never gets sufficient look at the underlying class
It creates a problem of making a validation or test sample as its difficult to have representation across classes in case number of observation for few classes is extremely less
What are the different approaches followed to solve this?
There are three main approaches which are suggested each having its pros and cons:
Undersampling- Randomly delete the class which has sufficient observations so that the comparative ratio of two classes is significant in our data.Although this approach is really simple to follow but there is a high possibility that the data that we are deleting may contain important information about the predictive class.Oversampling-For the unbalanced class randomly increase the number of observations which are just copies of existing samples.This ideally gives us sufficient number of samples to play with.The oversampling may lead to overfitting to the training dataSynthetic sampling(SMOTE)-The technique asks to synthetically manufacture observations of unbalanced classes which are similar to the existing using nearest neighbors classification.The problem is what to do when the number of observations of is an extremely rare class .For example-we may have only one picture of a rare species which we want to identify using image classification algorithm
Undersampling- Randomly delete the class which has sufficient observations so that the comparative ratio of two classes is significant in our data.Although this approach is really simple to follow but there is a high possibility that the data that we are deleting may contain important information about the predictive class.
Oversampling-For the unbalanced class randomly increase the number of observations which are just copies of existing samples.This ideally gives us sufficient number of samples to play with.The oversampling may lead to overfitting to the training data
Synthetic sampling(SMOTE)-The technique asks to synthetically manufacture observations of unbalanced classes which are similar to the existing using nearest neighbors classification.The problem is what to do when the number of observations of is an extremely rare class .For example-we may have only one picture of a rare species which we want to identify using image classification algorithm
Although each of the approaches have their own benefits there is no particular heuristic of which technique to use when.We will now look into this problem in detail using a deep learning specific image classification problem.
In this section we will pick up a problem of image classification which has an issue of unbalanced classes and then we will solve it using a simple and effective technique.
The problem-We picked up “Humpback Whale Identification Challenge” on kaggle which we expected to have a challenge of solving for unbalanced classes(as ideally the number of whales classified will be less than non-classified also there will be few rare whale species for which we will have less number of images)
From kaggle:“In this competition, you’re challenged to build an algorithm to identifying whale species in images. You’ll analyze Happy Whale’s database of over 25,000 images, gathered from research institutions and public contributors. By contributing, you’ll help to open rich fields of understanding for marine mammal population dynamics around the globe.”
As this is a multi-label image classification problem I first wanted to check how is the data distributed across the classes.
The above chart dictates that out of 4251 training images more than 2000 have only one image per class.There are also classes with ~2–5 images .Now, this is a serious problem of unbalanced classes.We can’t expect a DL model to train using just one image per class(Although there are algorithms that may just do that for example one shot classification but we are as of now ignoring that).This also creates a problem how to create a split between training and validation sample.You will ideally want each of the classes to be represented in both training and validation sample.
There are two options in particular that we considered:
option1-Rigorous data augmentation on the training sample(We could have done that but as we need data augmentation only for specific classes this may not solve our purpose completely).Hence I went for option-2 which looked simple enough to try .
option2-Similar to the oversampling option that I mentioned above.I just copied the images of unbalanced classes back into the training data 15 times using different image augmented techniques.This is inspired from Jeremy Howard who I guess mentioned this in one of the deep learning lectures of part-1 fast.ai course.
Before we start with option-2 lets view few images from the training sample.
The images are specific to the fluke of the whales .Hence, identification will be probably quite specific to the way images will be oriented.
I also noticed there are lots of images in the data which are specific B&W or only of R/B/G channel.
Based on these observations I decided to write the below code to do small changes in images which are from unbalanced classes in training sample ans save them:
import osfrom PIL import Imagefrom PIL import ImageFilterfilelist = train['Image'].loc[(train['cnt_freq']<10)].tolist()for count in range(0,2): for imagefile in filelist: os.chdir('/home/paperspace/fastai/courses/dl1/data/humpback/train') im=Image.open(imagefile) im=im.convert("RGB") r,g,b=im.split() r=r.convert("RGB") g=g.convert("RGB") b=b.convert("RGB") im_blur=im.filter(ImageFilter.GaussianBlur) im_unsharp=im.filter(ImageFilter.UnsharpMask) os.chdir('/home/paperspace/fastai/courses/dl1/data/humpback/copy') r.save(str(count)+'r_'+imagefile) g.save(str(count)+'g_'+imagefile) b.save(str(count)+'b_'+imagefile) im_blur.save(str(count)+'bl_'+imagefile) im_unsharp.save(str(count)+'un_'+imagefile)
The above code block does the following to each of the images in unbalanced class(which have frequency less than 10):
Save augmented copy of each of the images each as R/B& GSave augmented copy of each image which is blurySave augmented copy of each image which in unsharp
Save augmented copy of each of the images each as R/B& G
Save augmented copy of each image which is blury
Save augmented copy of each image which in unsharp
We used pillow (a python image library)rigorously for this exercise as can be seen in the above code
Now we have for all of the unbalanced classes at-least 10 samples.We proceeded with the training .
Image augmentation-We kept this simple.We only wanted to make sure that our model is able to get a detailed view of the fluke of the whale.For this we incorporated zoom into image augmentation.
Learning rate finder-We decided upon a learning rate of 0.01 as identified as lr find.
We ran few iteration using Resnet50 (first frozen and unfrozen).Turns out the frozen model is also quite good for this problem statement as there are images of whale flukes in imagenet.
epoch trn_loss val_loss accuracy 0 1.827677 0.492113 0.895976 1 0.93804 0.188566 0.964128 2 0.844708 0.175866 0.967555 3 0.571255 0.126632 0.977614 4 0.458565 0.116253 0.979991 5 0.410907 0.113607 0.980544 6 0.42319 0.109893 0.981097
How does this look on test data?
Finally our moment of truth on kaggle leader board.The solution proposed ranks 34 in this competition with a Mean Average Precision @ 5 of 0.41928 :)
Conclusion
Sometimes the simple approaches which are most logical (If you don’t have more data just copy existing data again with slight variation pretend most of the class observations will be on same line for the model) are the ones most effective and can get the work done more easily and intuitively.
|
[
{
"code": null,
"e": 566,
"s": 172,
"text": "One of the biggest problems that we face when we tackle any machine learning problem is the problem of unbalanced training data.The problem of unbalanced data is such that the academia is split with respect to the definition, implication & possible solutions for the same.We will here try to unravel the mystery of unbalanced classes in the training data using an image classification problem."
},
{
"code": null,
"e": 781,
"s": 566,
"text": "In a classification problem when out of all the classes which you want to predict if for one or more classes there are extremely low number of samples you may be facing a problem of unbalanced classes in your data."
},
{
"code": null,
"e": 790,
"s": 781,
"text": "Examples"
},
{
"code": null,
"e": 1079,
"s": 790,
"text": "Fraud prediction(Number of frauds will be much lower that genuine transactions)Natural disaster predictions(Bad events will be much lower than good)Identifying malignant tumor in an image classification(images with a tumor will be much less than that of no tumor within a training sample)"
},
{
"code": null,
"e": 1159,
"s": 1079,
"text": "Fraud prediction(Number of frauds will be much lower that genuine transactions)"
},
{
"code": null,
"e": 1229,
"s": 1159,
"text": "Natural disaster predictions(Bad events will be much lower than good)"
},
{
"code": null,
"e": 1370,
"s": 1229,
"text": "Identifying malignant tumor in an image classification(images with a tumor will be much less than that of no tumor within a training sample)"
},
{
"code": null,
"e": 1393,
"s": 1370,
"text": "Why is this a problem?"
},
{
"code": null,
"e": 1458,
"s": 1393,
"text": "The unbalanced classes create a problem due to two main reasons:"
},
{
"code": null,
"e": 1787,
"s": 1458,
"text": "We don’t get optimized results for the class which is unbalanced in real time as the model/algorithm never gets sufficient look at the underlying classIt creates a problem of making a validation or test sample as its difficult to have representation across classes in case number of observation for few classes is extremely less"
},
{
"code": null,
"e": 1939,
"s": 1787,
"text": "We don’t get optimized results for the class which is unbalanced in real time as the model/algorithm never gets sufficient look at the underlying class"
},
{
"code": null,
"e": 2117,
"s": 1939,
"text": "It creates a problem of making a validation or test sample as its difficult to have representation across classes in case number of observation for few classes is extremely less"
},
{
"code": null,
"e": 2175,
"s": 2117,
"text": "What are the different approaches followed to solve this?"
},
{
"code": null,
"e": 2258,
"s": 2175,
"text": "There are three main approaches which are suggested each having its pros and cons:"
},
{
"code": null,
"e": 3226,
"s": 2258,
"text": "Undersampling- Randomly delete the class which has sufficient observations so that the comparative ratio of two classes is significant in our data.Although this approach is really simple to follow but there is a high possibility that the data that we are deleting may contain important information about the predictive class.Oversampling-For the unbalanced class randomly increase the number of observations which are just copies of existing samples.This ideally gives us sufficient number of samples to play with.The oversampling may lead to overfitting to the training dataSynthetic sampling(SMOTE)-The technique asks to synthetically manufacture observations of unbalanced classes which are similar to the existing using nearest neighbors classification.The problem is what to do when the number of observations of is an extremely rare class .For example-we may have only one picture of a rare species which we want to identify using image classification algorithm"
},
{
"code": null,
"e": 3552,
"s": 3226,
"text": "Undersampling- Randomly delete the class which has sufficient observations so that the comparative ratio of two classes is significant in our data.Although this approach is really simple to follow but there is a high possibility that the data that we are deleting may contain important information about the predictive class."
},
{
"code": null,
"e": 3803,
"s": 3552,
"text": "Oversampling-For the unbalanced class randomly increase the number of observations which are just copies of existing samples.This ideally gives us sufficient number of samples to play with.The oversampling may lead to overfitting to the training data"
},
{
"code": null,
"e": 4196,
"s": 3803,
"text": "Synthetic sampling(SMOTE)-The technique asks to synthetically manufacture observations of unbalanced classes which are similar to the existing using nearest neighbors classification.The problem is what to do when the number of observations of is an extremely rare class .For example-we may have only one picture of a rare species which we want to identify using image classification algorithm"
},
{
"code": null,
"e": 4422,
"s": 4196,
"text": "Although each of the approaches have their own benefits there is no particular heuristic of which technique to use when.We will now look into this problem in detail using a deep learning specific image classification problem."
},
{
"code": null,
"e": 4595,
"s": 4422,
"text": "In this section we will pick up a problem of image classification which has an issue of unbalanced classes and then we will solve it using a simple and effective technique."
},
{
"code": null,
"e": 4908,
"s": 4595,
"text": "The problem-We picked up “Humpback Whale Identification Challenge” on kaggle which we expected to have a challenge of solving for unbalanced classes(as ideally the number of whales classified will be less than non-classified also there will be few rare whale species for which we will have less number of images)"
},
{
"code": null,
"e": 5267,
"s": 4908,
"text": "From kaggle:“In this competition, you’re challenged to build an algorithm to identifying whale species in images. You’ll analyze Happy Whale’s database of over 25,000 images, gathered from research institutions and public contributors. By contributing, you’ll help to open rich fields of understanding for marine mammal population dynamics around the globe.”"
},
{
"code": null,
"e": 5393,
"s": 5267,
"text": "As this is a multi-label image classification problem I first wanted to check how is the data distributed across the classes."
},
{
"code": null,
"e": 5970,
"s": 5393,
"text": "The above chart dictates that out of 4251 training images more than 2000 have only one image per class.There are also classes with ~2–5 images .Now, this is a serious problem of unbalanced classes.We can’t expect a DL model to train using just one image per class(Although there are algorithms that may just do that for example one shot classification but we are as of now ignoring that).This also creates a problem how to create a split between training and validation sample.You will ideally want each of the classes to be represented in both training and validation sample."
},
{
"code": null,
"e": 6026,
"s": 5970,
"text": "There are two options in particular that we considered:"
},
{
"code": null,
"e": 6272,
"s": 6026,
"text": "option1-Rigorous data augmentation on the training sample(We could have done that but as we need data augmentation only for specific classes this may not solve our purpose completely).Hence I went for option-2 which looked simple enough to try ."
},
{
"code": null,
"e": 6591,
"s": 6272,
"text": "option2-Similar to the oversampling option that I mentioned above.I just copied the images of unbalanced classes back into the training data 15 times using different image augmented techniques.This is inspired from Jeremy Howard who I guess mentioned this in one of the deep learning lectures of part-1 fast.ai course."
},
{
"code": null,
"e": 6668,
"s": 6591,
"text": "Before we start with option-2 lets view few images from the training sample."
},
{
"code": null,
"e": 6810,
"s": 6668,
"text": "The images are specific to the fluke of the whales .Hence, identification will be probably quite specific to the way images will be oriented."
},
{
"code": null,
"e": 6911,
"s": 6810,
"text": "I also noticed there are lots of images in the data which are specific B&W or only of R/B/G channel."
},
{
"code": null,
"e": 7071,
"s": 6911,
"text": "Based on these observations I decided to write the below code to do small changes in images which are from unbalanced classes in training sample ans save them:"
},
{
"code": null,
"e": 7826,
"s": 7071,
"text": "import osfrom PIL import Imagefrom PIL import ImageFilterfilelist = train['Image'].loc[(train['cnt_freq']<10)].tolist()for count in range(0,2): for imagefile in filelist: os.chdir('/home/paperspace/fastai/courses/dl1/data/humpback/train') im=Image.open(imagefile) im=im.convert(\"RGB\") r,g,b=im.split() r=r.convert(\"RGB\") g=g.convert(\"RGB\") b=b.convert(\"RGB\") im_blur=im.filter(ImageFilter.GaussianBlur) im_unsharp=im.filter(ImageFilter.UnsharpMask) os.chdir('/home/paperspace/fastai/courses/dl1/data/humpback/copy') r.save(str(count)+'r_'+imagefile) g.save(str(count)+'g_'+imagefile) b.save(str(count)+'b_'+imagefile) im_blur.save(str(count)+'bl_'+imagefile) im_unsharp.save(str(count)+'un_'+imagefile)"
},
{
"code": null,
"e": 7944,
"s": 7826,
"text": "The above code block does the following to each of the images in unbalanced class(which have frequency less than 10):"
},
{
"code": null,
"e": 8099,
"s": 7944,
"text": "Save augmented copy of each of the images each as R/B& GSave augmented copy of each image which is blurySave augmented copy of each image which in unsharp"
},
{
"code": null,
"e": 8156,
"s": 8099,
"text": "Save augmented copy of each of the images each as R/B& G"
},
{
"code": null,
"e": 8205,
"s": 8156,
"text": "Save augmented copy of each image which is blury"
},
{
"code": null,
"e": 8256,
"s": 8205,
"text": "Save augmented copy of each image which in unsharp"
},
{
"code": null,
"e": 8357,
"s": 8256,
"text": "We used pillow (a python image library)rigorously for this exercise as can be seen in the above code"
},
{
"code": null,
"e": 8456,
"s": 8357,
"text": "Now we have for all of the unbalanced classes at-least 10 samples.We proceeded with the training ."
},
{
"code": null,
"e": 8650,
"s": 8456,
"text": "Image augmentation-We kept this simple.We only wanted to make sure that our model is able to get a detailed view of the fluke of the whale.For this we incorporated zoom into image augmentation."
},
{
"code": null,
"e": 8737,
"s": 8650,
"text": "Learning rate finder-We decided upon a learning rate of 0.01 as identified as lr find."
},
{
"code": null,
"e": 8923,
"s": 8737,
"text": "We ran few iteration using Resnet50 (first frozen and unfrozen).Turns out the frozen model is also quite good for this problem statement as there are images of whale flukes in imagenet."
},
{
"code": null,
"e": 9385,
"s": 8923,
"text": "epoch trn_loss val_loss accuracy 0 1.827677 0.492113 0.895976 1 0.93804 0.188566 0.964128 2 0.844708 0.175866 0.967555 3 0.571255 0.126632 0.977614 4 0.458565 0.116253 0.979991 5 0.410907 0.113607 0.980544 6 0.42319 0.109893 0.981097"
},
{
"code": null,
"e": 9418,
"s": 9385,
"text": "How does this look on test data?"
},
{
"code": null,
"e": 9568,
"s": 9418,
"text": "Finally our moment of truth on kaggle leader board.The solution proposed ranks 34 in this competition with a Mean Average Precision @ 5 of 0.41928 :)"
},
{
"code": null,
"e": 9579,
"s": 9568,
"text": "Conclusion"
}
] |
Check if a directed graph is connected or not - GeeksforGeeks
|
13 Mar, 2022
Given a directed graph. The task is to check if the given graph is connected or not.Examples:
Input:
Output: YesInput:
Output: No
Approach:
Take two bool arrays vis1 and vis2 of size N (number of nodes of a graph) and keep false in all indexes.Start at a random vertex v of the graph G, and run a DFS(G, v).Make all visited vertices v as vis1[v] = true.Now reverse the direction of all the edges.Start DFS at the vertex which was chosen at step 2.Make all visited vertices v as vis2[v] = true.If any vertex v has vis1[v] = false and vis2[v] = false then the graph is not connected.
Take two bool arrays vis1 and vis2 of size N (number of nodes of a graph) and keep false in all indexes.
Start at a random vertex v of the graph G, and run a DFS(G, v).
Make all visited vertices v as vis1[v] = true.
Now reverse the direction of all the edges.
Start DFS at the vertex which was chosen at step 2.
Make all visited vertices v as vis2[v] = true.
If any vertex v has vis1[v] = false and vis2[v] = false then the graph is not connected.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define N 100000 // To keep correct and reverse directionvector<int> gr1[N], gr2[N]; bool vis1[N], vis2[N]; // Function to add edgesvoid Add_edge(int u, int v){ gr1[u].push_back(v); gr2[v].push_back(u);} // DFS functionvoid dfs1(int x){ vis1[x] = true; for (auto i : gr1[x]) if (!vis1[i]) dfs1(i);} // DFS functionvoid dfs2(int x){ vis2[x] = true; for (auto i : gr2[x]) if (!vis2[i]) dfs2(i);} bool Is_Connected(int n){ // Call for correct direction memset(vis1, false, sizeof vis1); dfs1(1); // Call for reverse direction memset(vis2, false, sizeof vis2); dfs2(1); for (int i = 1; i <= n; i++) { // If any vertex it not visited in any direction // Then graph is not connected if (!vis1[i] and !vis2[i]) return false; } // If graph is connected return true;} // Driver codeint main(){ int n = 4; // Add edges Add_edge(1, 2); Add_edge(1, 3); Add_edge(2, 3); Add_edge(3, 4); // Function call if (Is_Connected(n)) cout << "Yes"; else cout << "No"; return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ static int N = 100000; // To keep correct and reverse direction @SuppressWarnings("unchecked") static Vector<Integer>[] gr1 = new Vector[N]; @SuppressWarnings("unchecked") static Vector<Integer>[] gr2 = new Vector[N]; static boolean[] vis1 = new boolean[N]; static boolean[] vis2 = new boolean[N]; static { for (int i = 0; i < N; i++) { gr1[i] = new Vector<>(); gr2[i] = new Vector<>(); } } // Function to add edges static void Add_edge(int u, int v) { gr1[u].add(v); gr2[v].add(u); } // DFS function static void dfs1(int x) { vis1[x] = true; for (int i : gr1[x]) if (!vis1[i]) dfs1(i); } // DFS function static void dfs2(int x) { vis2[x] = true; for (int i : gr2[x]) if (!vis2[i]) dfs2(i); } static boolean Is_connected(int n) { // Call for correct direction Arrays.fill(vis1, false); dfs1(1); // Call for reverse direction Arrays.fill(vis2, false); dfs2(1); for (int i = 1; i <= n; i++) { // If any vertex it not visited in any direction // Then graph is not connected if (!vis1[i] && !vis2[i]) return false; } // If graph is connected return true; } // Driver Code public static void main(String[] args) { int n = 4; // Add edges Add_edge(1, 2); Add_edge(1, 3); Add_edge(2, 3); Add_edge(3, 4); // Function call if (Is_connected(n)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by// sanjeev2552
# Python3 implementation of the approachN = 100000 # To keep correct and reverse directiongr1 = {}; gr2 = {}; vis1 = [0] * N; vis2 = [0] * N; # Function to add edgesdef Add_edge(u, v) : if u not in gr1 : gr1[u] = []; if v not in gr2 : gr2[v] = []; gr1[u].append(v); gr2[v].append(u); # DFS functiondef dfs1(x) : vis1[x] = True; if x not in gr1 : gr1[x] = {}; for i in gr1[x] : if (not vis1[i]) : dfs1(i) # DFS functiondef dfs2(x) : vis2[x] = True; if x not in gr2 : gr2[x] = {}; for i in gr2[x] : if (not vis2[i]) : dfs2(i); def Is_Connected(n) : global vis1; global vis2; # Call for correct direction vis1 = [False] * len(vis1); dfs1(1); # Call for reverse direction vis2 = [False] * len(vis2); dfs2(1); for i in range(1, n + 1) : # If any vertex it not visited in any direction # Then graph is not connected if (not vis1[i] and not vis2[i]) : return False; # If graph is connected return True; # Driver codeif __name__ == "__main__" : n = 4; # Add edges Add_edge(1, 2); Add_edge(1, 3); Add_edge(2, 3); Add_edge(3, 4); # Function call if (Is_Connected(n)) : print("Yes"); else : print("No"); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static int N = 100000; // To keep correct and reverse direction static List<int>[] gr1 = new List<int>[N]; static List<int>[] gr2 = new List<int>[N]; static bool[] vis1 = new bool[N]; static bool[] vis2 = new bool[N]; // Function to add edges static void Add_edge(int u, int v) { gr1[u].Add(v); gr2[v].Add(u); } // DFS function static void dfs1(int x) { vis1[x] = true; foreach (int i in gr1[x]) if (!vis1[i]) dfs1(i); } // DFS function static void dfs2(int x) { vis2[x] = true; foreach (int i in gr2[x]) if (!vis2[i]) dfs2(i); } static bool Is_connected(int n) { // Call for correct direction for (int i = 0; i < n; i++) vis1[i] = false; dfs1(1); // Call for reverse direction for (int i = 0; i < n; i++) vis2[i] = false; dfs2(1); for (int i = 1; i <= n; i++) { // If any vertex it not visited in any direction // Then graph is not connected if (!vis1[i] && !vis2[i]) return false; } // If graph is connected return true; } // Driver Code public static void Main(String[] args) { int n = 4; for (int i = 0; i < N; i++) { gr1[i] = new List<int>(); gr2[i] = new List<int>(); } // Add edges Add_edge(1, 2); Add_edge(1, 3); Add_edge(2, 3); Add_edge(3, 4); // Function call if (Is_connected(n)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by PrinciRaj1992
<script> // Javascript implementation of the approach let N = 100000; // To keep correct and reverse direction let gr1 = []; let gr2 = []; for(let i = 0; i < N; i++) { gr1.push([]); gr2.push([]); } let vis1 = new Array(N); let vis2 = new Array(N); vis1.fill(false); vis2.fill(false); // Function to add edges function Add_edge(u, v) { gr1[u].push(v); gr2[v].push(u); } // DFS function function dfs1(x) { vis1[x] = true; for(let i = 0; i < gr1[x].length; i++) { if (!vis1[gr1[x][i]]) { dfs1(gr1[x][i]); } } } // DFS function function dfs2(x) { vis2[x] = true; for(let i = 0; i < gr2[x].length; i++) { if (!vis2[gr2[x][i]]) { dfs2(gr2[x][i]); } } } function Is_connected(n) { // Call for correct direction for (let i = 0; i < n; i++) vis1[i] = false; dfs1(1); // Call for reverse direction for (let i = 0; i < n; i++) vis2[i] = false; dfs2(1); for (let i = 1; i <= n; i++) { // If any vertex it not visited in any direction // Then graph is not connected if (!vis1[i] && !vis2[i]) return false; } // If graph is connected return true; } let n = 4; for (let i = 0; i < N; i++) { gr1[i] = []; gr2[i] = []; } // Add edges Add_edge(1, 2); Add_edge(1, 3); Add_edge(2, 3); Add_edge(3, 4); // Function call if (Is_connected(n)) document.write("Yes"); else document.write("No"); // This code is contributed by divyesh072019.</script>
Yes
Time Complexity: O(V+E) where V is the number of vertices and E is the number of edges.
Auxiliary Space: O(B^M), where B is the maximum branching factor of the search tree and M is the maximum depth of the state space.
sanjeev2552
ankthon
princiraj1992
divyesh072019
prophet1999
Algorithms-Graph Traversals
DFS
Graph
DFS
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Best First Search (Informed Search)
Longest Path in a Directed Acyclic Graph
Graph Coloring | Set 2 (Greedy Algorithm)
Find if there is a path between two vertices in a directed graph
Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)
Snake and Ladder Problem
Check if a given graph is tree or not
Tree, Back, Edge and Cross Edges in DFS of Graph
Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
Real-time application of Data Structures
|
[
{
"code": null,
"e": 24699,
"s": 24671,
"text": "\n13 Mar, 2022"
},
{
"code": null,
"e": 24795,
"s": 24699,
"text": "Given a directed graph. The task is to check if the given graph is connected or not.Examples: "
},
{
"code": null,
"e": 24804,
"s": 24795,
"text": "Input: "
},
{
"code": null,
"e": 24824,
"s": 24804,
"text": "Output: YesInput: "
},
{
"code": null,
"e": 24837,
"s": 24824,
"text": "Output: No "
},
{
"code": null,
"e": 24851,
"s": 24839,
"text": "Approach: "
},
{
"code": null,
"e": 25293,
"s": 24851,
"text": "Take two bool arrays vis1 and vis2 of size N (number of nodes of a graph) and keep false in all indexes.Start at a random vertex v of the graph G, and run a DFS(G, v).Make all visited vertices v as vis1[v] = true.Now reverse the direction of all the edges.Start DFS at the vertex which was chosen at step 2.Make all visited vertices v as vis2[v] = true.If any vertex v has vis1[v] = false and vis2[v] = false then the graph is not connected."
},
{
"code": null,
"e": 25398,
"s": 25293,
"text": "Take two bool arrays vis1 and vis2 of size N (number of nodes of a graph) and keep false in all indexes."
},
{
"code": null,
"e": 25462,
"s": 25398,
"text": "Start at a random vertex v of the graph G, and run a DFS(G, v)."
},
{
"code": null,
"e": 25509,
"s": 25462,
"text": "Make all visited vertices v as vis1[v] = true."
},
{
"code": null,
"e": 25553,
"s": 25509,
"text": "Now reverse the direction of all the edges."
},
{
"code": null,
"e": 25605,
"s": 25553,
"text": "Start DFS at the vertex which was chosen at step 2."
},
{
"code": null,
"e": 25652,
"s": 25605,
"text": "Make all visited vertices v as vis2[v] = true."
},
{
"code": null,
"e": 25741,
"s": 25652,
"text": "If any vertex v has vis1[v] = false and vis2[v] = false then the graph is not connected."
},
{
"code": null,
"e": 25794,
"s": 25741,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25798,
"s": 25794,
"text": "C++"
},
{
"code": null,
"e": 25803,
"s": 25798,
"text": "Java"
},
{
"code": null,
"e": 25811,
"s": 25803,
"text": "Python3"
},
{
"code": null,
"e": 25814,
"s": 25811,
"text": "C#"
},
{
"code": null,
"e": 25825,
"s": 25814,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define N 100000 // To keep correct and reverse directionvector<int> gr1[N], gr2[N]; bool vis1[N], vis2[N]; // Function to add edgesvoid Add_edge(int u, int v){ gr1[u].push_back(v); gr2[v].push_back(u);} // DFS functionvoid dfs1(int x){ vis1[x] = true; for (auto i : gr1[x]) if (!vis1[i]) dfs1(i);} // DFS functionvoid dfs2(int x){ vis2[x] = true; for (auto i : gr2[x]) if (!vis2[i]) dfs2(i);} bool Is_Connected(int n){ // Call for correct direction memset(vis1, false, sizeof vis1); dfs1(1); // Call for reverse direction memset(vis2, false, sizeof vis2); dfs2(1); for (int i = 1; i <= n; i++) { // If any vertex it not visited in any direction // Then graph is not connected if (!vis1[i] and !vis2[i]) return false; } // If graph is connected return true;} // Driver codeint main(){ int n = 4; // Add edges Add_edge(1, 2); Add_edge(1, 3); Add_edge(2, 3); Add_edge(3, 4); // Function call if (Is_Connected(n)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 27031,
"s": 25825,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ static int N = 100000; // To keep correct and reverse direction @SuppressWarnings(\"unchecked\") static Vector<Integer>[] gr1 = new Vector[N]; @SuppressWarnings(\"unchecked\") static Vector<Integer>[] gr2 = new Vector[N]; static boolean[] vis1 = new boolean[N]; static boolean[] vis2 = new boolean[N]; static { for (int i = 0; i < N; i++) { gr1[i] = new Vector<>(); gr2[i] = new Vector<>(); } } // Function to add edges static void Add_edge(int u, int v) { gr1[u].add(v); gr2[v].add(u); } // DFS function static void dfs1(int x) { vis1[x] = true; for (int i : gr1[x]) if (!vis1[i]) dfs1(i); } // DFS function static void dfs2(int x) { vis2[x] = true; for (int i : gr2[x]) if (!vis2[i]) dfs2(i); } static boolean Is_connected(int n) { // Call for correct direction Arrays.fill(vis1, false); dfs1(1); // Call for reverse direction Arrays.fill(vis2, false); dfs2(1); for (int i = 1; i <= n; i++) { // If any vertex it not visited in any direction // Then graph is not connected if (!vis1[i] && !vis2[i]) return false; } // If graph is connected return true; } // Driver Code public static void main(String[] args) { int n = 4; // Add edges Add_edge(1, 2); Add_edge(1, 3); Add_edge(2, 3); Add_edge(3, 4); // Function call if (Is_connected(n)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by// sanjeev2552",
"e": 28890,
"s": 27031,
"text": null
},
{
"code": "# Python3 implementation of the approachN = 100000 # To keep correct and reverse directiongr1 = {}; gr2 = {}; vis1 = [0] * N; vis2 = [0] * N; # Function to add edgesdef Add_edge(u, v) : if u not in gr1 : gr1[u] = []; if v not in gr2 : gr2[v] = []; gr1[u].append(v); gr2[v].append(u); # DFS functiondef dfs1(x) : vis1[x] = True; if x not in gr1 : gr1[x] = {}; for i in gr1[x] : if (not vis1[i]) : dfs1(i) # DFS functiondef dfs2(x) : vis2[x] = True; if x not in gr2 : gr2[x] = {}; for i in gr2[x] : if (not vis2[i]) : dfs2(i); def Is_Connected(n) : global vis1; global vis2; # Call for correct direction vis1 = [False] * len(vis1); dfs1(1); # Call for reverse direction vis2 = [False] * len(vis2); dfs2(1); for i in range(1, n + 1) : # If any vertex it not visited in any direction # Then graph is not connected if (not vis1[i] and not vis2[i]) : return False; # If graph is connected return True; # Driver codeif __name__ == \"__main__\" : n = 4; # Add edges Add_edge(1, 2); Add_edge(1, 3); Add_edge(2, 3); Add_edge(3, 4); # Function call if (Is_Connected(n)) : print(\"Yes\"); else : print(\"No\"); # This code is contributed by AnkitRai01",
"e": 30304,
"s": 28890,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static int N = 100000; // To keep correct and reverse direction static List<int>[] gr1 = new List<int>[N]; static List<int>[] gr2 = new List<int>[N]; static bool[] vis1 = new bool[N]; static bool[] vis2 = new bool[N]; // Function to add edges static void Add_edge(int u, int v) { gr1[u].Add(v); gr2[v].Add(u); } // DFS function static void dfs1(int x) { vis1[x] = true; foreach (int i in gr1[x]) if (!vis1[i]) dfs1(i); } // DFS function static void dfs2(int x) { vis2[x] = true; foreach (int i in gr2[x]) if (!vis2[i]) dfs2(i); } static bool Is_connected(int n) { // Call for correct direction for (int i = 0; i < n; i++) vis1[i] = false; dfs1(1); // Call for reverse direction for (int i = 0; i < n; i++) vis2[i] = false; dfs2(1); for (int i = 1; i <= n; i++) { // If any vertex it not visited in any direction // Then graph is not connected if (!vis1[i] && !vis2[i]) return false; } // If graph is connected return true; } // Driver Code public static void Main(String[] args) { int n = 4; for (int i = 0; i < N; i++) { gr1[i] = new List<int>(); gr2[i] = new List<int>(); } // Add edges Add_edge(1, 2); Add_edge(1, 3); Add_edge(2, 3); Add_edge(3, 4); // Function call if (Is_connected(n)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by PrinciRaj1992",
"e": 32160,
"s": 30304,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach let N = 100000; // To keep correct and reverse direction let gr1 = []; let gr2 = []; for(let i = 0; i < N; i++) { gr1.push([]); gr2.push([]); } let vis1 = new Array(N); let vis2 = new Array(N); vis1.fill(false); vis2.fill(false); // Function to add edges function Add_edge(u, v) { gr1[u].push(v); gr2[v].push(u); } // DFS function function dfs1(x) { vis1[x] = true; for(let i = 0; i < gr1[x].length; i++) { if (!vis1[gr1[x][i]]) { dfs1(gr1[x][i]); } } } // DFS function function dfs2(x) { vis2[x] = true; for(let i = 0; i < gr2[x].length; i++) { if (!vis2[gr2[x][i]]) { dfs2(gr2[x][i]); } } } function Is_connected(n) { // Call for correct direction for (let i = 0; i < n; i++) vis1[i] = false; dfs1(1); // Call for reverse direction for (let i = 0; i < n; i++) vis2[i] = false; dfs2(1); for (let i = 1; i <= n; i++) { // If any vertex it not visited in any direction // Then graph is not connected if (!vis1[i] && !vis2[i]) return false; } // If graph is connected return true; } let n = 4; for (let i = 0; i < N; i++) { gr1[i] = []; gr2[i] = []; } // Add edges Add_edge(1, 2); Add_edge(1, 3); Add_edge(2, 3); Add_edge(3, 4); // Function call if (Is_connected(n)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by divyesh072019.</script>",
"e": 34001,
"s": 32160,
"text": null
},
{
"code": null,
"e": 34005,
"s": 34001,
"text": "Yes"
},
{
"code": null,
"e": 34095,
"s": 34007,
"text": "Time Complexity: O(V+E) where V is the number of vertices and E is the number of edges."
},
{
"code": null,
"e": 34227,
"s": 34095,
"text": "Auxiliary Space: O(B^M), where B is the maximum branching factor of the search tree and M is the maximum depth of the state space. "
},
{
"code": null,
"e": 34239,
"s": 34227,
"text": "sanjeev2552"
},
{
"code": null,
"e": 34247,
"s": 34239,
"text": "ankthon"
},
{
"code": null,
"e": 34261,
"s": 34247,
"text": "princiraj1992"
},
{
"code": null,
"e": 34275,
"s": 34261,
"text": "divyesh072019"
},
{
"code": null,
"e": 34287,
"s": 34275,
"text": "prophet1999"
},
{
"code": null,
"e": 34315,
"s": 34287,
"text": "Algorithms-Graph Traversals"
},
{
"code": null,
"e": 34319,
"s": 34315,
"text": "DFS"
},
{
"code": null,
"e": 34325,
"s": 34319,
"text": "Graph"
},
{
"code": null,
"e": 34329,
"s": 34325,
"text": "DFS"
},
{
"code": null,
"e": 34335,
"s": 34329,
"text": "Graph"
},
{
"code": null,
"e": 34433,
"s": 34335,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34442,
"s": 34433,
"text": "Comments"
},
{
"code": null,
"e": 34455,
"s": 34442,
"text": "Old Comments"
},
{
"code": null,
"e": 34491,
"s": 34455,
"text": "Best First Search (Informed Search)"
},
{
"code": null,
"e": 34532,
"s": 34491,
"text": "Longest Path in a Directed Acyclic Graph"
},
{
"code": null,
"e": 34574,
"s": 34532,
"text": "Graph Coloring | Set 2 (Greedy Algorithm)"
},
{
"code": null,
"e": 34639,
"s": 34574,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 34709,
"s": 34639,
"text": "Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)"
},
{
"code": null,
"e": 34734,
"s": 34709,
"text": "Snake and Ladder Problem"
},
{
"code": null,
"e": 34772,
"s": 34734,
"text": "Check if a given graph is tree or not"
},
{
"code": null,
"e": 34821,
"s": 34772,
"text": "Tree, Back, Edge and Cross Edges in DFS of Graph"
},
{
"code": null,
"e": 34902,
"s": 34821,
"text": "Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)"
}
] |
Update array in MongoDB document by variable index?
|
To update array in MongoDB document by variable index, use the below syntax. Here, yourIndexValue in the index value, where yourIndexVariableName is the variable name for index −
var yourIndexVariableName= yourIndexValue,
anyVariableName= { "$set": {} };
yourVariableName["$set"]["yourFieldName."+yourIndexVariableName] = "yourValue";
db.yourCollectionName.update({ "_id": yourObjectId}, yourVariableName);
Let us first create a collection with documents −
> db.updateByVariableDemo.insertOne({"StudentSubjects":["MySQL","Java","SQL Server","PL/SQL"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd553c37924bb85b3f4893a")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.updateByVariableDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd553c37924bb85b3f4893a"),
"StudentSubjects" : [
"MySQL",
"Java",
"SQL Server",
"PL/SQL"
]
}
Following is the query to update array in MongoDB document by variable index −
> var indexValue = 1,
... valueToUpdate= { "$set": {} };
> valueToUpdate["$set"]["StudentSubjects."+indexValue] = "MongoDB";
MongoDB
> db.updateByVariableDemo.update({ "_id": ObjectId("5cd553c37924bb85b3f4893a") }, valueToUpdate)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us display the documents once again −
> db.updateByVariableDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd553c37924bb85b3f4893a"),
"StudentSubjects" : [
"MySQL",
"MongoDB",
"SQL Server",
"PL/SQL"
]
}
|
[
{
"code": null,
"e": 1241,
"s": 1062,
"text": "To update array in MongoDB document by variable index, use the below syntax. Here, yourIndexValue in the index value, where yourIndexVariableName is the variable name for index −"
},
{
"code": null,
"e": 1470,
"s": 1241,
"text": "var yourIndexVariableName= yourIndexValue,\nanyVariableName= { \"$set\": {} };\nyourVariableName[\"$set\"][\"yourFieldName.\"+yourIndexVariableName] = \"yourValue\";\ndb.yourCollectionName.update({ \"_id\": yourObjectId}, yourVariableName);"
},
{
"code": null,
"e": 1520,
"s": 1470,
"text": "Let us first create a collection with documents −"
},
{
"code": null,
"e": 1702,
"s": 1520,
"text": "> db.updateByVariableDemo.insertOne({\"StudentSubjects\":[\"MySQL\",\"Java\",\"SQL Server\",\"PL/SQL\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd553c37924bb85b3f4893a\")\n}"
},
{
"code": null,
"e": 1801,
"s": 1702,
"text": "Following is the query to display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1844,
"s": 1801,
"text": "> db.updateByVariableDemo.find().pretty();"
},
{
"code": null,
"e": 1885,
"s": 1844,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2032,
"s": 1885,
"text": "{\n \"_id\" : ObjectId(\"5cd553c37924bb85b3f4893a\"),\n \"StudentSubjects\" : [\n \"MySQL\",\n \"Java\",\n \"SQL Server\",\n \"PL/SQL\"\n ]\n}"
},
{
"code": null,
"e": 2111,
"s": 2032,
"text": "Following is the query to update array in MongoDB document by variable index −"
},
{
"code": null,
"e": 2408,
"s": 2111,
"text": "> var indexValue = 1,\n... valueToUpdate= { \"$set\": {} };\n> valueToUpdate[\"$set\"][\"StudentSubjects.\"+indexValue] = \"MongoDB\";\nMongoDB\n> db.updateByVariableDemo.update({ \"_id\": ObjectId(\"5cd553c37924bb85b3f4893a\") }, valueToUpdate)\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })"
},
{
"code": null,
"e": 2450,
"s": 2408,
"text": "Let us display the documents once again −"
},
{
"code": null,
"e": 2493,
"s": 2450,
"text": "> db.updateByVariableDemo.find().pretty();"
},
{
"code": null,
"e": 2534,
"s": 2493,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2684,
"s": 2534,
"text": "{\n \"_id\" : ObjectId(\"5cd553c37924bb85b3f4893a\"),\n \"StudentSubjects\" : [\n \"MySQL\",\n \"MongoDB\",\n \"SQL Server\",\n \"PL/SQL\"\n ]\n}"
}
] |
How are files extracted from a tar file using Python?
|
You can use the tarfile module to read and write tar files. To extract a tar file, you need to first open the file and then use the extract method of the tarfile module.
import tarfile
my_tar = tarfile.open('my_tar.tar.gz')
my_tar.extractall('./my_folder') # specify which folder to extract to
my_tar.close()
This will extract the my_tar.tar.gz file's contents to my_folder.
You can also extract individual files from the tar using extract(filename, path).
import tarfile
my_tar = tarfile.open('my_tar.tar.gz')
my_tar.extract('hello.txt','./my_folder')
my_tar.close()
|
[
{
"code": null,
"e": 1232,
"s": 1062,
"text": "You can use the tarfile module to read and write tar files. To extract a tar file, you need to first open the file and then use the extract method of the tarfile module."
},
{
"code": null,
"e": 1371,
"s": 1232,
"text": "import tarfile\nmy_tar = tarfile.open('my_tar.tar.gz')\nmy_tar.extractall('./my_folder') # specify which folder to extract to\nmy_tar.close()"
},
{
"code": null,
"e": 1437,
"s": 1371,
"text": "This will extract the my_tar.tar.gz file's contents to my_folder."
},
{
"code": null,
"e": 1519,
"s": 1437,
"text": "You can also extract individual files from the tar using extract(filename, path)."
},
{
"code": null,
"e": 1630,
"s": 1519,
"text": "import tarfile\nmy_tar = tarfile.open('my_tar.tar.gz')\nmy_tar.extract('hello.txt','./my_folder')\nmy_tar.close()"
}
] |
Hyperparameter Tuning with Keras Tuner | by Cedric Conol | Towards Data Science
|
Great data scientists do not settle with “okay”, they go beyond to achieve the extraordinary.
In this article, we’ll review techniques data scientists use to create models that work great and win competitions. Getting the most out of our models means choosing the optimal hyperparameters for our learning algorithm. This task is known as hyperparameter optimization or hyperparameter tuning. This is especially strenuous in deep learning as neural networks are full of hyperparameters. I’ll assume that you are already familiar with common data science concepts like regression and mean squared error (MSE) metric and have experience building model using tensorflow and keras.
To demonstrate hyperparameter tuning methods, we’ll use keras tuner library to tune a regression model on the Boston housing price dataset. This dataset contains 13 attributes with 404 and 102 training and testing samples respectively. We’ll use tensorflow as keras backend so make sure you have tensorflow installed on your machines. I’m using tensorflow version ‘2.1.0’ and kerastuner version ‘1.0.1’. Tensorflow 2.0.x comes up with keras so you don’t need to install keras separately if you have version 2.0.x. You can check the version you have using the code below:
import tensorflow as tfimport kerastuner as ktprint(tf.__version__)print(kt.__version__)
Boston housing price regression dataset can be downloaded directly using keras. Here’s a list of datasets that comes with keras. To load the dataset, run the following codes.
from tensorflow.keras.datasets import boston_housing(x_train, y_train), (x_test, y_test) = boston_housing.load_data()
Note that if this is the first time you are using this dataset within keras, it will download the dataset from an external source.
This is the regression model I’ll use in this demo. The code below shows how the model was built without any tuning.
from sklearn.preprocessing import StandardScalerfrom tensorflow.keras import models, layers# set random seedfrom numpy.random import seedseed(42)import tensorflowtensorflow.random.set_seed(42)# preprocessing - normalizationscaler = StandardScaler()scaler.fit(x_train)x_train_scaled = scaler.transform(x_train)x_test_scaled = scaler.transform(x_test)# model buildingmodel = models.Sequential()model.add(layers.Dense(8, activation='relu', input_shape=(x_train.shape[1],)))model.add(layers.Dense(16, activation='relu'))model.add(layers.Dropout(0.1))model.add(layers.Dense(1))# compile model using rmspropmodel.compile(optimizer='rmsprop',loss='mse',metrics=['mse'])# model traininghistory = model.fit(x_train_scaled, y_train, validation_split=0.2, epochs=10)# model evaluationmodel.evaluate(x_test_scaled, y_test)
This model has a MSE of around 434. I have set the random seed in numpy and tensorflow to 42 to get reproducible results. Despite doing so, I still get slightly different results every time I run the code. Let me know in the comments what else I missed make this reproducible.
To start tuning the model in keras tuner, let’s define a hypermodel first. Hypermodel is a keras tuner class that lets you define the model with a searchable space and build it.
Create a class that inherits from kerastuner.HyperModel, like so:
from kerastuner import HyperModelclass RegressionHyperModel(HyperModel): def __init__(self, input_shape): self.input_shape = input_shape def build(self, hp): model = Sequential() model.add( layers.Dense( units=hp.Int('units', 8, 64, 4, default=8), activation=hp.Choice( 'dense_activation', values=['relu', 'tanh', 'sigmoid'], default='relu'), input_shape=input_shape ) ) model.add( layers.Dense( units=hp.Int('units', 16, 64, 4, default=16), activation=hp.Choice( 'dense_activation', values=['relu', 'tanh', 'sigmoid'], default='relu') ) ) model.add( layers.Dropout( hp.Float( 'dropout', min_value=0.0, max_value=0.1, default=0.005, step=0.01) ) ) model.add(layers.Dense(1)) model.compile( optimizer='rmsprop',loss='mse',metrics=['mse'] ) return model
This is the same model we built earlier, except that for every hyperparameter, we defined a search space. You may have noticed hp.Int, hp.Float, and hp.Choice, these are used to define a search space for a hyperparameter that accepts an integer, float and a category respectively. A complete list of hyperparameter methods can be found here. ‘hp’ is an alias for Keras Tuner’s HyperParameters class.
Hyperparameter such as the number of units in a dense layer accepts an integer, hence, hp.Int is used to define a range of integers to try. Similarly, the dropout rate accepts a float value so hp.Float is used. Both hp.Int and hp.Float requires a name, minimum value and maximum value, while the step size and default value is optional.
The hp.Int search space below is named, “units”, and will have values from 8 to 64 in multiples of 4, and a default value of 8. hp. Float is used similarly as hp.Int but accepts float values.
hp.Int('units', 8, 64, 4, default=8)
hp.Choice is used to define a categorical hyperparameter such as the activation function. The search space below, named “dense_activation”, will choose between “relu”, “tanh”, and “sigmoid” functions, with a default value set to “relu”.
hp.Choice('dense_activation', values=['relu', 'tanh', 'sigmoid'], default='relu')
Let’s instantiate a hypermodel object. Input shape varies per dataset and the problem you are trying to solve.
input_shape = (x_train.shape[1],)hypermodel = RegressionHyperModel(input_shape)
Let’s start tuning!
As the name suggests, this hyperparameter tuning method randomly tries a combination of hyperparameters from a given search space. To use this method in keras tuner, let’s define a tuner using one of the available Tuners. Here’s a full list of Tuners.
tuner_rs = RandomSearch( hypermodel, objective='mse', seed=42, max_trials=10, executions_per_trial=2)
Run the random search tuner using the search method.
tuner_rs.search(x_train_scaled, y_train, epochs=10, validation_split=0.2, verbose=0)
Select the best combination of hyperparameters the tuner had tried and evaluate.
best_model = tuner_rs.get_best_models(num_models=1)[0]loss, mse = best_model.evaluate(x_test_scaled, y_test)
Random search’s MSE is 53.48, a very big improvement from not performing any tuning at all.
Hyperband is based on the algorithm by Li et. al. It optimizes random search method through adaptive resource allocation and early-stopping. Hyperband first runs random hyperparameter configurations for one iteration or two, then selects which configurations perform well, then continues tuning the best performers.
tuner_hb = Hyperband( hypermodel, max_epochs=5, objective='mse', seed=42, executions_per_trial=2 )tuner_hb.search(x_train_scaled, y_train, epochs=10, validation_split=0.2, verbose=0)best_model = tuner_hb.get_best_models(num_models=1)[0]best_model.evaluate(x_test_scaled, y_test)
The resulting MSE is 395.19 which is a lot worse when compared to random search but a little bit better than not tuning at all.
Bayesian optimization is a probabilistic model that maps the hyperparameters to a probability score on the objective function. Unlike Random Search and Hyperband models, Bayesian Optimization keeps track of its past evaluation results and uses it to build the probability model.
tuner_bo = BayesianOptimization( hypermodel, objective='mse', max_trials=10, seed=42, executions_per_trial=2 )tuner_bo.search(x_train_scaled, y_train, epochs=10, validation_split=0.2, verbose=0)best_model = tuner_bo.get_best_models(num_models=1)[0]best_model.evaluate(x_test_scaled, y_test)
Best model MSE tuned using Bayesian optimization is 46.47, better than the first two tuners we have tried.
We were able to show that indeed, tuning helps us get the most out of our models. Discussed here are just 3 of the many methods of hyperparameter tuning. When trying out the codes above, we may get slightly different results, for some reason, despite setting numpy, tensorflow, and keras tuner random seeds, results per iteration still differ slightly. The notebook is uploaded in my github repo.
Furthermore, tuners can also be tuned! Yes, you read that right, tuning the tuners. Tuners accept values such as max_trials and execution per trial and are can, therefore, be tuned as well. Try changing these parameters and see if you get further improvements.
[1] F. Chollet, Deep Learning with Python (2018), Manning Publications Inc.
[2] Keras Tuner Documentation, https://keras-team.github.io/keras-tuner/
[3] L. Li, K. Jamieson, G. DeSalvo, A. Rostamizadeh, A. Talwalkar, Hyperband: A Novel Bandit-Based Approach to Hyperparameter Optimization (2018), https://arxiv.org/abs/1603.06560
|
[
{
"code": null,
"e": 266,
"s": 172,
"text": "Great data scientists do not settle with “okay”, they go beyond to achieve the extraordinary."
},
{
"code": null,
"e": 849,
"s": 266,
"text": "In this article, we’ll review techniques data scientists use to create models that work great and win competitions. Getting the most out of our models means choosing the optimal hyperparameters for our learning algorithm. This task is known as hyperparameter optimization or hyperparameter tuning. This is especially strenuous in deep learning as neural networks are full of hyperparameters. I’ll assume that you are already familiar with common data science concepts like regression and mean squared error (MSE) metric and have experience building model using tensorflow and keras."
},
{
"code": null,
"e": 1420,
"s": 849,
"text": "To demonstrate hyperparameter tuning methods, we’ll use keras tuner library to tune a regression model on the Boston housing price dataset. This dataset contains 13 attributes with 404 and 102 training and testing samples respectively. We’ll use tensorflow as keras backend so make sure you have tensorflow installed on your machines. I’m using tensorflow version ‘2.1.0’ and kerastuner version ‘1.0.1’. Tensorflow 2.0.x comes up with keras so you don’t need to install keras separately if you have version 2.0.x. You can check the version you have using the code below:"
},
{
"code": null,
"e": 1509,
"s": 1420,
"text": "import tensorflow as tfimport kerastuner as ktprint(tf.__version__)print(kt.__version__)"
},
{
"code": null,
"e": 1684,
"s": 1509,
"text": "Boston housing price regression dataset can be downloaded directly using keras. Here’s a list of datasets that comes with keras. To load the dataset, run the following codes."
},
{
"code": null,
"e": 1802,
"s": 1684,
"text": "from tensorflow.keras.datasets import boston_housing(x_train, y_train), (x_test, y_test) = boston_housing.load_data()"
},
{
"code": null,
"e": 1933,
"s": 1802,
"text": "Note that if this is the first time you are using this dataset within keras, it will download the dataset from an external source."
},
{
"code": null,
"e": 2050,
"s": 1933,
"text": "This is the regression model I’ll use in this demo. The code below shows how the model was built without any tuning."
},
{
"code": null,
"e": 2861,
"s": 2050,
"text": "from sklearn.preprocessing import StandardScalerfrom tensorflow.keras import models, layers# set random seedfrom numpy.random import seedseed(42)import tensorflowtensorflow.random.set_seed(42)# preprocessing - normalizationscaler = StandardScaler()scaler.fit(x_train)x_train_scaled = scaler.transform(x_train)x_test_scaled = scaler.transform(x_test)# model buildingmodel = models.Sequential()model.add(layers.Dense(8, activation='relu', input_shape=(x_train.shape[1],)))model.add(layers.Dense(16, activation='relu'))model.add(layers.Dropout(0.1))model.add(layers.Dense(1))# compile model using rmspropmodel.compile(optimizer='rmsprop',loss='mse',metrics=['mse'])# model traininghistory = model.fit(x_train_scaled, y_train, validation_split=0.2, epochs=10)# model evaluationmodel.evaluate(x_test_scaled, y_test)"
},
{
"code": null,
"e": 3138,
"s": 2861,
"text": "This model has a MSE of around 434. I have set the random seed in numpy and tensorflow to 42 to get reproducible results. Despite doing so, I still get slightly different results every time I run the code. Let me know in the comments what else I missed make this reproducible."
},
{
"code": null,
"e": 3316,
"s": 3138,
"text": "To start tuning the model in keras tuner, let’s define a hypermodel first. Hypermodel is a keras tuner class that lets you define the model with a searchable space and build it."
},
{
"code": null,
"e": 3382,
"s": 3316,
"text": "Create a class that inherits from kerastuner.HyperModel, like so:"
},
{
"code": null,
"e": 4640,
"s": 3382,
"text": "from kerastuner import HyperModelclass RegressionHyperModel(HyperModel): def __init__(self, input_shape): self.input_shape = input_shape def build(self, hp): model = Sequential() model.add( layers.Dense( units=hp.Int('units', 8, 64, 4, default=8), activation=hp.Choice( 'dense_activation', values=['relu', 'tanh', 'sigmoid'], default='relu'), input_shape=input_shape ) ) model.add( layers.Dense( units=hp.Int('units', 16, 64, 4, default=16), activation=hp.Choice( 'dense_activation', values=['relu', 'tanh', 'sigmoid'], default='relu') ) ) model.add( layers.Dropout( hp.Float( 'dropout', min_value=0.0, max_value=0.1, default=0.005, step=0.01) ) ) model.add(layers.Dense(1)) model.compile( optimizer='rmsprop',loss='mse',metrics=['mse'] ) return model"
},
{
"code": null,
"e": 5040,
"s": 4640,
"text": "This is the same model we built earlier, except that for every hyperparameter, we defined a search space. You may have noticed hp.Int, hp.Float, and hp.Choice, these are used to define a search space for a hyperparameter that accepts an integer, float and a category respectively. A complete list of hyperparameter methods can be found here. ‘hp’ is an alias for Keras Tuner’s HyperParameters class."
},
{
"code": null,
"e": 5377,
"s": 5040,
"text": "Hyperparameter such as the number of units in a dense layer accepts an integer, hence, hp.Int is used to define a range of integers to try. Similarly, the dropout rate accepts a float value so hp.Float is used. Both hp.Int and hp.Float requires a name, minimum value and maximum value, while the step size and default value is optional."
},
{
"code": null,
"e": 5569,
"s": 5377,
"text": "The hp.Int search space below is named, “units”, and will have values from 8 to 64 in multiples of 4, and a default value of 8. hp. Float is used similarly as hp.Int but accepts float values."
},
{
"code": null,
"e": 5606,
"s": 5569,
"text": "hp.Int('units', 8, 64, 4, default=8)"
},
{
"code": null,
"e": 5843,
"s": 5606,
"text": "hp.Choice is used to define a categorical hyperparameter such as the activation function. The search space below, named “dense_activation”, will choose between “relu”, “tanh”, and “sigmoid” functions, with a default value set to “relu”."
},
{
"code": null,
"e": 5925,
"s": 5843,
"text": "hp.Choice('dense_activation', values=['relu', 'tanh', 'sigmoid'], default='relu')"
},
{
"code": null,
"e": 6036,
"s": 5925,
"text": "Let’s instantiate a hypermodel object. Input shape varies per dataset and the problem you are trying to solve."
},
{
"code": null,
"e": 6116,
"s": 6036,
"text": "input_shape = (x_train.shape[1],)hypermodel = RegressionHyperModel(input_shape)"
},
{
"code": null,
"e": 6136,
"s": 6116,
"text": "Let’s start tuning!"
},
{
"code": null,
"e": 6388,
"s": 6136,
"text": "As the name suggests, this hyperparameter tuning method randomly tries a combination of hyperparameters from a given search space. To use this method in keras tuner, let’s define a tuner using one of the available Tuners. Here’s a full list of Tuners."
},
{
"code": null,
"e": 6545,
"s": 6388,
"text": "tuner_rs = RandomSearch( hypermodel, objective='mse', seed=42, max_trials=10, executions_per_trial=2)"
},
{
"code": null,
"e": 6598,
"s": 6545,
"text": "Run the random search tuner using the search method."
},
{
"code": null,
"e": 6683,
"s": 6598,
"text": "tuner_rs.search(x_train_scaled, y_train, epochs=10, validation_split=0.2, verbose=0)"
},
{
"code": null,
"e": 6764,
"s": 6683,
"text": "Select the best combination of hyperparameters the tuner had tried and evaluate."
},
{
"code": null,
"e": 6873,
"s": 6764,
"text": "best_model = tuner_rs.get_best_models(num_models=1)[0]loss, mse = best_model.evaluate(x_test_scaled, y_test)"
},
{
"code": null,
"e": 6965,
"s": 6873,
"text": "Random search’s MSE is 53.48, a very big improvement from not performing any tuning at all."
},
{
"code": null,
"e": 7281,
"s": 6965,
"text": "Hyperband is based on the algorithm by Li et. al. It optimizes random search method through adaptive resource allocation and early-stopping. Hyperband first runs random hyperparameter configurations for one iteration or two, then selects which configurations perform well, then continues tuning the best performers."
},
{
"code": null,
"e": 7622,
"s": 7281,
"text": "tuner_hb = Hyperband( hypermodel, max_epochs=5, objective='mse', seed=42, executions_per_trial=2 )tuner_hb.search(x_train_scaled, y_train, epochs=10, validation_split=0.2, verbose=0)best_model = tuner_hb.get_best_models(num_models=1)[0]best_model.evaluate(x_test_scaled, y_test)"
},
{
"code": null,
"e": 7750,
"s": 7622,
"text": "The resulting MSE is 395.19 which is a lot worse when compared to random search but a little bit better than not tuning at all."
},
{
"code": null,
"e": 8029,
"s": 7750,
"text": "Bayesian optimization is a probabilistic model that maps the hyperparameters to a probability score on the objective function. Unlike Random Search and Hyperband models, Bayesian Optimization keeps track of its past evaluation results and uses it to build the probability model."
},
{
"code": null,
"e": 8382,
"s": 8029,
"text": "tuner_bo = BayesianOptimization( hypermodel, objective='mse', max_trials=10, seed=42, executions_per_trial=2 )tuner_bo.search(x_train_scaled, y_train, epochs=10, validation_split=0.2, verbose=0)best_model = tuner_bo.get_best_models(num_models=1)[0]best_model.evaluate(x_test_scaled, y_test)"
},
{
"code": null,
"e": 8489,
"s": 8382,
"text": "Best model MSE tuned using Bayesian optimization is 46.47, better than the first two tuners we have tried."
},
{
"code": null,
"e": 8886,
"s": 8489,
"text": "We were able to show that indeed, tuning helps us get the most out of our models. Discussed here are just 3 of the many methods of hyperparameter tuning. When trying out the codes above, we may get slightly different results, for some reason, despite setting numpy, tensorflow, and keras tuner random seeds, results per iteration still differ slightly. The notebook is uploaded in my github repo."
},
{
"code": null,
"e": 9147,
"s": 8886,
"text": "Furthermore, tuners can also be tuned! Yes, you read that right, tuning the tuners. Tuners accept values such as max_trials and execution per trial and are can, therefore, be tuned as well. Try changing these parameters and see if you get further improvements."
},
{
"code": null,
"e": 9223,
"s": 9147,
"text": "[1] F. Chollet, Deep Learning with Python (2018), Manning Publications Inc."
},
{
"code": null,
"e": 9296,
"s": 9223,
"text": "[2] Keras Tuner Documentation, https://keras-team.github.io/keras-tuner/"
}
] |
Bringing Customization to Pandas Profiling | by Ian Eaves | Towards Data Science
|
If you’ve previously used pandas-profiling, you might have observed that column summaries are unique to the data types of each feature in your data. However, until recently it wasn’t possible to customize those summaries, so, if you wanted to automatically compute the average surface area of a sequence of shapely geometries, or the set of domain names in a sequence of email addresses, you were out of luck — until now.
The recently completed migration of pandas-profiling to the visions type system brings fully customizable type detection logic, summary algorithms, and is the first step towards end-to-end report customization including customized renderings. Over the rest of blog post I’m going to show you how to get started with visions and easily customize your data summaries using pandas-profiling.
The default pandas-profiling type system consists of four basic data types:
Categories
DateTimes
Boolean
Numeric
Technically, there is a fifth catch-all type called Unsupported for anything that doesn’t fit in the other four (these are usually complex objects like lists). If you want to inspect it’s implementation check out the ProfilingTypeSet object found in pandas_profiling.model.typeset.
NOTE: You’ll need to install pydot and pygraphviz to reproduce these plots
These typesets can be as complicated or simple as your usecase calls for. Want to distinguish between Integers and Floats? URLs from Strings? Images from Files? Something else specific to your data? You can find most of these types now available in pandas-profiling with many more available in visions, and if not available, writing your own is usually just a few lines of code. A full walk-through of types and type systems can be found here.
To get started let’s download a copy of the Titanic dataset and convert the Survived field over to a boolean.
Now that we have some data we can use pandas-profiling to create a profile report.
No surprises here, just the standard pandas-profiling workflow. In addition to the normal html report we can directly inspect the summarization values computed by pandas-profiling through the description_set attribute on the report. Let's check out our summary of the Survived attribute.
{'n_distinct': 2, 'p_distinct': 0.002244668911335578, 'is_unique': False, 'n_unique': 0, 'p_unique': 0.0, 'type': Boolean, 'hashable': True, 'value_counts_without_nan': False 549 True 342 Name: Survived, dtype: int64, 'n_missing': 0, 'n': 891, 'p_missing': 0.0, 'count': 891, 'memory_size': 1019}
There’s a lot of useful information here: memory usage, whether series values are hashable, missing value counts, etc... By default, every Boolean sequence receives an identical summary — and now, thanks to summarizers, we can customize these results!
Under the hood, pandas-profiling uses a PandasProfilingSummarizer object to generate summaries for the profile report. These summarizers map data types, like Boolean, to a list of summary functions used to create the final summary.
You can reproduce the summary above directly from this summarizer like so:
{'n_distinct': 2, 'p_distinct': 0.002244668911335578, 'is_unique': False, 'n_unique': 0, 'p_unique': 0.0, 'type': Boolean, 'hashable': True, 'value_counts_without_nan': False 549 True 342 Name: Survived, dtype: int64, 'n_missing': 0, 'n': 891, 'p_missing': 0.0, 'count': 891, 'memory_size': 1019}
To make a customized summary we need to specify a sequence of function(s) to call for each data type in our typeset. Types support arithmetic in much the you would naturally expect such that adding two types together, like Boolean + Unsupported, yields a typeset containing Boolean and Unsupported.
Combining these together, let’s write a summarizer that computes length of each series for all data types and additionally, the probability of being True for boolean.
Although this may look complicated, at heart it’s just keeping track of a bunch of functions to call on series of different data types. Behind the scenes, the summarizer object took care of composing the summary functions together to produce a final result tacking on a “type” value to indicate which summarization was used.
{'type': Boolean, 'length': 891, 'probability_true': 0.3838383838383838}
{'type': Unsupported, 'length': 891}
Although summarizers are now fully customizable, the associated html renderings haven’t been updated to expose customized statistics so be on the lookout for additional updates in the future.
Although you can now customize summaries in pandas-profiling pretty much to your hearts content, in most cases you’ll be modifying or adding to the default summarizer rather than building one entirely from scratch. This is also pretty easy, just append any new functionality you want onto it’s associated type! Let’s update the default PandasProfilingSummarizier to include the new_boolean_summary function and run a report with the new functionality
{'n_distinct': 2, 'p_distinct': 0.002244668911335578, 'is_unique': False, 'n_unique': 0, 'p_unique': 0.0, 'type': Boolean, 'hashable': True, 'value_counts_without_nan': False 549 True 342 Name: Survived, dtype: int64, 'n_missing': 0, 'n': 891, 'p_missing': 0.0, 'count': 891, 'memory_size': 1019, 'probability_true': 0.3838383838383838}
Voila, just like that we were able to insert the probability_true calculation into our profile report.
So far we’ve been quite happy with the flexibility afforded by visions to define advanced data types and support user defined functionality. We’re excited to begin rolling out more of these capabilities soon, including support for customized renderings, and are eager to gather feedback. How have you been using customized types and summaries or do you have interesting use-cases worth adding into pandas-profiling? If so, please comment below and share!
|
[
{
"code": null,
"e": 593,
"s": 171,
"text": "If you’ve previously used pandas-profiling, you might have observed that column summaries are unique to the data types of each feature in your data. However, until recently it wasn’t possible to customize those summaries, so, if you wanted to automatically compute the average surface area of a sequence of shapely geometries, or the set of domain names in a sequence of email addresses, you were out of luck — until now."
},
{
"code": null,
"e": 982,
"s": 593,
"text": "The recently completed migration of pandas-profiling to the visions type system brings fully customizable type detection logic, summary algorithms, and is the first step towards end-to-end report customization including customized renderings. Over the rest of blog post I’m going to show you how to get started with visions and easily customize your data summaries using pandas-profiling."
},
{
"code": null,
"e": 1058,
"s": 982,
"text": "The default pandas-profiling type system consists of four basic data types:"
},
{
"code": null,
"e": 1069,
"s": 1058,
"text": "Categories"
},
{
"code": null,
"e": 1079,
"s": 1069,
"text": "DateTimes"
},
{
"code": null,
"e": 1087,
"s": 1079,
"text": "Boolean"
},
{
"code": null,
"e": 1095,
"s": 1087,
"text": "Numeric"
},
{
"code": null,
"e": 1377,
"s": 1095,
"text": "Technically, there is a fifth catch-all type called Unsupported for anything that doesn’t fit in the other four (these are usually complex objects like lists). If you want to inspect it’s implementation check out the ProfilingTypeSet object found in pandas_profiling.model.typeset."
},
{
"code": null,
"e": 1452,
"s": 1377,
"text": "NOTE: You’ll need to install pydot and pygraphviz to reproduce these plots"
},
{
"code": null,
"e": 1896,
"s": 1452,
"text": "These typesets can be as complicated or simple as your usecase calls for. Want to distinguish between Integers and Floats? URLs from Strings? Images from Files? Something else specific to your data? You can find most of these types now available in pandas-profiling with many more available in visions, and if not available, writing your own is usually just a few lines of code. A full walk-through of types and type systems can be found here."
},
{
"code": null,
"e": 2006,
"s": 1896,
"text": "To get started let’s download a copy of the Titanic dataset and convert the Survived field over to a boolean."
},
{
"code": null,
"e": 2089,
"s": 2006,
"text": "Now that we have some data we can use pandas-profiling to create a profile report."
},
{
"code": null,
"e": 2377,
"s": 2089,
"text": "No surprises here, just the standard pandas-profiling workflow. In addition to the normal html report we can directly inspect the summarization values computed by pandas-profiling through the description_set attribute on the report. Let's check out our summary of the Survived attribute."
},
{
"code": null,
"e": 2681,
"s": 2377,
"text": "{'n_distinct': 2, 'p_distinct': 0.002244668911335578, 'is_unique': False, 'n_unique': 0, 'p_unique': 0.0, 'type': Boolean, 'hashable': True, 'value_counts_without_nan': False 549 True 342 Name: Survived, dtype: int64, 'n_missing': 0, 'n': 891, 'p_missing': 0.0, 'count': 891, 'memory_size': 1019}"
},
{
"code": null,
"e": 2933,
"s": 2681,
"text": "There’s a lot of useful information here: memory usage, whether series values are hashable, missing value counts, etc... By default, every Boolean sequence receives an identical summary — and now, thanks to summarizers, we can customize these results!"
},
{
"code": null,
"e": 3165,
"s": 2933,
"text": "Under the hood, pandas-profiling uses a PandasProfilingSummarizer object to generate summaries for the profile report. These summarizers map data types, like Boolean, to a list of summary functions used to create the final summary."
},
{
"code": null,
"e": 3240,
"s": 3165,
"text": "You can reproduce the summary above directly from this summarizer like so:"
},
{
"code": null,
"e": 3544,
"s": 3240,
"text": "{'n_distinct': 2, 'p_distinct': 0.002244668911335578, 'is_unique': False, 'n_unique': 0, 'p_unique': 0.0, 'type': Boolean, 'hashable': True, 'value_counts_without_nan': False 549 True 342 Name: Survived, dtype: int64, 'n_missing': 0, 'n': 891, 'p_missing': 0.0, 'count': 891, 'memory_size': 1019}"
},
{
"code": null,
"e": 3843,
"s": 3544,
"text": "To make a customized summary we need to specify a sequence of function(s) to call for each data type in our typeset. Types support arithmetic in much the you would naturally expect such that adding two types together, like Boolean + Unsupported, yields a typeset containing Boolean and Unsupported."
},
{
"code": null,
"e": 4010,
"s": 3843,
"text": "Combining these together, let’s write a summarizer that computes length of each series for all data types and additionally, the probability of being True for boolean."
},
{
"code": null,
"e": 4335,
"s": 4010,
"text": "Although this may look complicated, at heart it’s just keeping track of a bunch of functions to call on series of different data types. Behind the scenes, the summarizer object took care of composing the summary functions together to produce a final result tacking on a “type” value to indicate which summarization was used."
},
{
"code": null,
"e": 4408,
"s": 4335,
"text": "{'type': Boolean, 'length': 891, 'probability_true': 0.3838383838383838}"
},
{
"code": null,
"e": 4445,
"s": 4408,
"text": "{'type': Unsupported, 'length': 891}"
},
{
"code": null,
"e": 4637,
"s": 4445,
"text": "Although summarizers are now fully customizable, the associated html renderings haven’t been updated to expose customized statistics so be on the lookout for additional updates in the future."
},
{
"code": null,
"e": 5088,
"s": 4637,
"text": "Although you can now customize summaries in pandas-profiling pretty much to your hearts content, in most cases you’ll be modifying or adding to the default summarizer rather than building one entirely from scratch. This is also pretty easy, just append any new functionality you want onto it’s associated type! Let’s update the default PandasProfilingSummarizier to include the new_boolean_summary function and run a report with the new functionality"
},
{
"code": null,
"e": 5432,
"s": 5088,
"text": "{'n_distinct': 2, 'p_distinct': 0.002244668911335578, 'is_unique': False, 'n_unique': 0, 'p_unique': 0.0, 'type': Boolean, 'hashable': True, 'value_counts_without_nan': False 549 True 342 Name: Survived, dtype: int64, 'n_missing': 0, 'n': 891, 'p_missing': 0.0, 'count': 891, 'memory_size': 1019, 'probability_true': 0.3838383838383838}"
},
{
"code": null,
"e": 5535,
"s": 5432,
"text": "Voila, just like that we were able to insert the probability_true calculation into our profile report."
}
] |
wxPython TreeCtrl - GeeksforGeeks
|
08 Jul, 2020
In this article we are going to learn about and TreeCtrl and how can we add TreeCtrl to our window. A tree control presents information as a hierarchy, with items that may be expanded to show further items. Items in a tree control are referenced by wx.TreeItemId handles, which may be tested for validity by calling wx.TreeItemId.IsOk .
We will use TreeCtrl() constructor to create TreeCtrl.
Syntax: wx.TreeCtrl.TreeCtrl(parent, id=ID_ANY, pos=DefaultPosition, size=DefaultSize, style=TR_DEFAULT_STYLE, validator=DefaultValidator, name=TreeCtrlNameStr)
Parameters
Code Example:
import wx class MainFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, parent = None, title ='TreeCtrl Demo') # tree control self.tree = wx.TreeCtrl(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize) # add root to tree self.root = self.tree.AddRoot('Root ') # add item to root self.tree.AppendItem(self.root, 'Child') # expand tree self.tree.Expand(self.root) # show frame self.Show() if __name__ == '__main__': app = wx.App(redirect = False) frame = MainFrame() app.MainLoop()
Output Window:
Python wxPython-TreeCtrl
Python-gui
Python-wxPython
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25337,
"s": 25309,
"text": "\n08 Jul, 2020"
},
{
"code": null,
"e": 25674,
"s": 25337,
"text": "In this article we are going to learn about and TreeCtrl and how can we add TreeCtrl to our window. A tree control presents information as a hierarchy, with items that may be expanded to show further items. Items in a tree control are referenced by wx.TreeItemId handles, which may be tested for validity by calling wx.TreeItemId.IsOk ."
},
{
"code": null,
"e": 25729,
"s": 25674,
"text": "We will use TreeCtrl() constructor to create TreeCtrl."
},
{
"code": null,
"e": 25890,
"s": 25729,
"text": "Syntax: wx.TreeCtrl.TreeCtrl(parent, id=ID_ANY, pos=DefaultPosition, size=DefaultSize, style=TR_DEFAULT_STYLE, validator=DefaultValidator, name=TreeCtrlNameStr)"
},
{
"code": null,
"e": 25901,
"s": 25890,
"text": "Parameters"
},
{
"code": null,
"e": 25915,
"s": 25901,
"text": "Code Example:"
},
{
"code": "import wx class MainFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, parent = None, title ='TreeCtrl Demo') # tree control self.tree = wx.TreeCtrl(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize) # add root to tree self.root = self.tree.AddRoot('Root ') # add item to root self.tree.AppendItem(self.root, 'Child') # expand tree self.tree.Expand(self.root) # show frame self.Show() if __name__ == '__main__': app = wx.App(redirect = False) frame = MainFrame() app.MainLoop()",
"e": 26506,
"s": 25915,
"text": null
},
{
"code": null,
"e": 26521,
"s": 26506,
"text": "Output Window:"
},
{
"code": null,
"e": 26546,
"s": 26521,
"text": "Python wxPython-TreeCtrl"
},
{
"code": null,
"e": 26557,
"s": 26546,
"text": "Python-gui"
},
{
"code": null,
"e": 26573,
"s": 26557,
"text": "Python-wxPython"
},
{
"code": null,
"e": 26580,
"s": 26573,
"text": "Python"
},
{
"code": null,
"e": 26678,
"s": 26580,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26696,
"s": 26678,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26731,
"s": 26696,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26763,
"s": 26731,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26785,
"s": 26763,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26827,
"s": 26785,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26857,
"s": 26827,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26883,
"s": 26857,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26912,
"s": 26883,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 26956,
"s": 26912,
"text": "Reading and Writing to text files in Python"
}
] |
What is the difference between declarations, providers, and import in NgModule? - GeeksforGeeks
|
24 Sep, 2020
Let us first discuss about these terms:
Declarations: Declarations are used to declare components, directives, pipes that belongs to the current module. Everything inside declarations knows each other.Declarations are used to make directives (including components and pipes) from the current module available to other directives in the current module.Selectors of directives, components or pipes are only matched against the HTML if they are declared or imported.
Declarations are used to declare components, directives, pipes that belongs to the current module.
Everything inside declarations knows each other.
Declarations are used to make directives (including components and pipes) from the current module available to other directives in the current module.
Selectors of directives, components or pipes are only matched against the HTML if they are declared or imported.
Providers: Providers are used to make services and values known to dependency injection.They are added to the root scope and they are injected to other services or directives that have them as dependency.
Providers are used to make services and values known to dependency injection.
They are added to the root scope and they are injected to other services or directives that have them as dependency.
Imports:Imports makes the exported declarations of other modules available in the current module.It is used to import supporting modules likes FormsModule, RouterModule, CommonModule etc.
Imports makes the exported declarations of other modules available in the current module.
It is used to import supporting modules likes FormsModule, RouterModule, CommonModule etc.
Differences:
Declarations
Providers
Imports
Defined in Declarations array in @NgModule
@NgModule({
declarations: [ ],
)}
Defined in Providers array in @NgModule.
@NgModule({
providers: [ ],
)}
Defined in imports array in @NgModule.
@NgModule({
imports: [],
)}
An example in which all three declarations, imports and providers are used:
The providers used in this project is custom service named UserService.
ng g s User
user.service.ts
javascript
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root'})export class UserService { constructor() { }}
This UserService is used as provider in app.module.ts.
app.module.ts
javascript
// imports for the applicationimport { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { HttpClientModule } from '@angular/common/http';import { FormsModule } from '@angular/forms';import { AppRoutingModule } from './app-routing.module';// declarations for the applicationimport { AppComponent } from './app.component';// providers for the applicationimport { UserService } from './user.service'; @NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, FormsModule ], providers: [UserService], bootstrap: [AppComponent]})export class AppModule { }
app.component.html
html
<h1>GeeksforGeeks</h1><ul> <li>imports in this app: BrowserModule, AppRoutingModule, HttpClientModule, FormsModule</li> <li>declarations in this app: AppComponent</li> <li>providers in this app: UserService</li></ul>
Output:
bunnyram19
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Auth Guards in Angular 9/10/11
Angular PrimeNG Calendar Component
What is AOT and JIT Compiler in Angular ?
How to bundle an Angular app for production?
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": 26156,
"s": 26128,
"text": "\n24 Sep, 2020"
},
{
"code": null,
"e": 26196,
"s": 26156,
"text": "Let us first discuss about these terms:"
},
{
"code": null,
"e": 26620,
"s": 26196,
"text": "Declarations: Declarations are used to declare components, directives, pipes that belongs to the current module. Everything inside declarations knows each other.Declarations are used to make directives (including components and pipes) from the current module available to other directives in the current module.Selectors of directives, components or pipes are only matched against the HTML if they are declared or imported."
},
{
"code": null,
"e": 26720,
"s": 26620,
"text": "Declarations are used to declare components, directives, pipes that belongs to the current module. "
},
{
"code": null,
"e": 26769,
"s": 26720,
"text": "Everything inside declarations knows each other."
},
{
"code": null,
"e": 26920,
"s": 26769,
"text": "Declarations are used to make directives (including components and pipes) from the current module available to other directives in the current module."
},
{
"code": null,
"e": 27033,
"s": 26920,
"text": "Selectors of directives, components or pipes are only matched against the HTML if they are declared or imported."
},
{
"code": null,
"e": 27238,
"s": 27033,
"text": "Providers: Providers are used to make services and values known to dependency injection.They are added to the root scope and they are injected to other services or directives that have them as dependency."
},
{
"code": null,
"e": 27316,
"s": 27238,
"text": "Providers are used to make services and values known to dependency injection."
},
{
"code": null,
"e": 27433,
"s": 27316,
"text": "They are added to the root scope and they are injected to other services or directives that have them as dependency."
},
{
"code": null,
"e": 27621,
"s": 27433,
"text": "Imports:Imports makes the exported declarations of other modules available in the current module.It is used to import supporting modules likes FormsModule, RouterModule, CommonModule etc."
},
{
"code": null,
"e": 27711,
"s": 27621,
"text": "Imports makes the exported declarations of other modules available in the current module."
},
{
"code": null,
"e": 27802,
"s": 27711,
"text": "It is used to import supporting modules likes FormsModule, RouterModule, CommonModule etc."
},
{
"code": null,
"e": 27815,
"s": 27802,
"text": "Differences:"
},
{
"code": null,
"e": 27828,
"s": 27815,
"text": "Declarations"
},
{
"code": null,
"e": 27838,
"s": 27828,
"text": "Providers"
},
{
"code": null,
"e": 27846,
"s": 27838,
"text": "Imports"
},
{
"code": null,
"e": 27889,
"s": 27846,
"text": "Defined in Declarations array in @NgModule"
},
{
"code": null,
"e": 27901,
"s": 27889,
"text": "@NgModule({"
},
{
"code": null,
"e": 27922,
"s": 27901,
"text": " declarations: [ ],"
},
{
"code": null,
"e": 27926,
"s": 27922,
"text": " )}"
},
{
"code": null,
"e": 27967,
"s": 27926,
"text": "Defined in Providers array in @NgModule."
},
{
"code": null,
"e": 27979,
"s": 27967,
"text": "@NgModule({"
},
{
"code": null,
"e": 27995,
"s": 27979,
"text": "providers: [ ],"
},
{
"code": null,
"e": 27998,
"s": 27995,
"text": ")}"
},
{
"code": null,
"e": 28037,
"s": 27998,
"text": "Defined in imports array in @NgModule."
},
{
"code": null,
"e": 28049,
"s": 28037,
"text": "@NgModule({"
},
{
"code": null,
"e": 28062,
"s": 28049,
"text": "imports: [],"
},
{
"code": null,
"e": 28065,
"s": 28062,
"text": ")}"
},
{
"code": null,
"e": 28141,
"s": 28065,
"text": "An example in which all three declarations, imports and providers are used:"
},
{
"code": null,
"e": 28213,
"s": 28141,
"text": "The providers used in this project is custom service named UserService."
},
{
"code": null,
"e": 28226,
"s": 28213,
"text": "ng g s User\n"
},
{
"code": null,
"e": 28242,
"s": 28226,
"text": "user.service.ts"
},
{
"code": null,
"e": 28253,
"s": 28242,
"text": "javascript"
},
{
"code": "import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root'})export class UserService { constructor() { }}",
"e": 28380,
"s": 28253,
"text": null
},
{
"code": null,
"e": 28435,
"s": 28380,
"text": "This UserService is used as provider in app.module.ts."
},
{
"code": null,
"e": 28449,
"s": 28435,
"text": "app.module.ts"
},
{
"code": null,
"e": 28460,
"s": 28449,
"text": "javascript"
},
{
"code": "// imports for the applicationimport { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { HttpClientModule } from '@angular/common/http';import { FormsModule } from '@angular/forms';import { AppRoutingModule } from './app-routing.module';// declarations for the applicationimport { AppComponent } from './app.component';// providers for the applicationimport { UserService } from './user.service'; @NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, FormsModule ], providers: [UserService], bootstrap: [AppComponent]})export class AppModule { }",
"e": 29129,
"s": 28460,
"text": null
},
{
"code": null,
"e": 29148,
"s": 29129,
"text": "app.component.html"
},
{
"code": null,
"e": 29153,
"s": 29148,
"text": "html"
},
{
"code": "<h1>GeeksforGeeks</h1><ul> <li>imports in this app: BrowserModule, AppRoutingModule, HttpClientModule, FormsModule</li> <li>declarations in this app: AppComponent</li> <li>providers in this app: UserService</li></ul>",
"e": 29384,
"s": 29153,
"text": null
},
{
"code": null,
"e": 29392,
"s": 29384,
"text": "Output:"
},
{
"code": null,
"e": 29403,
"s": 29392,
"text": "bunnyram19"
},
{
"code": null,
"e": 29418,
"s": 29403,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 29425,
"s": 29418,
"text": "Picked"
},
{
"code": null,
"e": 29435,
"s": 29425,
"text": "AngularJS"
},
{
"code": null,
"e": 29452,
"s": 29435,
"text": "Web Technologies"
},
{
"code": null,
"e": 29550,
"s": 29452,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29585,
"s": 29550,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 29616,
"s": 29585,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 29651,
"s": 29616,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 29693,
"s": 29651,
"text": "What is AOT and JIT Compiler in Angular ?"
},
{
"code": null,
"e": 29738,
"s": 29693,
"text": "How to bundle an Angular app for production?"
},
{
"code": null,
"e": 29778,
"s": 29738,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29811,
"s": 29778,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29856,
"s": 29811,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29899,
"s": 29856,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
ungetc() in C/C++ - GeeksforGeeks
|
25 Oct, 2018
The ungetc() function takes a single character and shoves it back onto an input stream. It is the opposite of the getc() function, which reads a single character from an input stream. Also, ungetc() is an input function, not an output function.Syntax:
int ungetc(int char, FILE *stream)
Parameters:
char: specifies the int promotion of the character to be put back. The value is internally converted to an unsigned char when put back.
stream: specifies the pointer to a FILE object that identifies an input stream.
Return Value: The function returns two kind of values.
On success, the ungetc() function returns the character ch.
On failure, EOF is returned without changing the stream.
Important points about the function:
The ungetc() function pushes the byte specified by char (converted to an unsigned char) back onto the input stream pointed to by stream.The pushed-back bytes is returned by subsequent reads on that stream in the reverse order of their pushing.A successful intervening call (with the stream pointed to by stream) to a file-positioning function ( fseek(), fsetpos(), or rewind()) discards any pushed-back bytes for the stream.The external storage corresponding to the stream shall be unchanged.A successful call to ungetc() clears the end-of-file indicator for the stream.The value of the file-position indicator for the stream after reading or discarding all pushed-back bytes shall be the same as it was before the bytes were pushed back.The file-position indicator is decremented by each successful call to ungetc(), if its value was 0 before a call, its value is unspecified after the call.
The ungetc() function pushes the byte specified by char (converted to an unsigned char) back onto the input stream pointed to by stream.
The pushed-back bytes is returned by subsequent reads on that stream in the reverse order of their pushing.
A successful intervening call (with the stream pointed to by stream) to a file-positioning function ( fseek(), fsetpos(), or rewind()) discards any pushed-back bytes for the stream.
The external storage corresponding to the stream shall be unchanged.
A successful call to ungetc() clears the end-of-file indicator for the stream.
The value of the file-position indicator for the stream after reading or discarding all pushed-back bytes shall be the same as it was before the bytes were pushed back.
The file-position indicator is decremented by each successful call to ungetc(), if its value was 0 before a call, its value is unspecified after the call.
Below programs illustrate the above function.
Program 1:
#include <stdio.h> int main(){ FILE* f; int char; char buffer[256]; // read a file f = fopen("use1.txt", "r"); // when no data if (f == NULL) { printf("Error in opening file"); return (-1); } // read lines till end while (!feof(f)) { // get line char = getc(f); // replace ! with + if (char == '!') { ungetc('+', f); } // if not else { ungetc(c, f); } fgets(buffer, 255, f); fputs(buffer, stdout); } return 0;}
Let us assume, we have a text file use1.txt, which contains the following data. This file will be used as an input for our example program, then the input and output are shown below:
Input: !c standard library
!library function stdio.h-ungetc()
Output: +c standard library
+library function stdio.h-ungetc()
Program 2:
// C program for taking input till we// get 1 at the input #include <stdio.h>int main(){ int ch; // reads characters from the stdin and show // them on stdout until encounters '1' while ((ch = getchar()) != '1') putchar(ch); // ungetc() returns '1' previously // read back to stdin ungetc(ch, stdin); // getchar() attempts to read // next character from stdin // and reads character '1' returned // back to the stdin by ungetc() ch = getchar(); // putchar() displays character putchar(ch); return 0;}
C-Library
CPP-Functions
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
|
[
{
"code": null,
"e": 25477,
"s": 25449,
"text": "\n25 Oct, 2018"
},
{
"code": null,
"e": 25729,
"s": 25477,
"text": "The ungetc() function takes a single character and shoves it back onto an input stream. It is the opposite of the getc() function, which reads a single character from an input stream. Also, ungetc() is an input function, not an output function.Syntax:"
},
{
"code": null,
"e": 25764,
"s": 25729,
"text": "int ungetc(int char, FILE *stream)"
},
{
"code": null,
"e": 25776,
"s": 25764,
"text": "Parameters:"
},
{
"code": null,
"e": 25912,
"s": 25776,
"text": "char: specifies the int promotion of the character to be put back. The value is internally converted to an unsigned char when put back."
},
{
"code": null,
"e": 25992,
"s": 25912,
"text": "stream: specifies the pointer to a FILE object that identifies an input stream."
},
{
"code": null,
"e": 26047,
"s": 25992,
"text": "Return Value: The function returns two kind of values."
},
{
"code": null,
"e": 26107,
"s": 26047,
"text": "On success, the ungetc() function returns the character ch."
},
{
"code": null,
"e": 26164,
"s": 26107,
"text": "On failure, EOF is returned without changing the stream."
},
{
"code": null,
"e": 26201,
"s": 26164,
"text": "Important points about the function:"
},
{
"code": null,
"e": 27094,
"s": 26201,
"text": "The ungetc() function pushes the byte specified by char (converted to an unsigned char) back onto the input stream pointed to by stream.The pushed-back bytes is returned by subsequent reads on that stream in the reverse order of their pushing.A successful intervening call (with the stream pointed to by stream) to a file-positioning function ( fseek(), fsetpos(), or rewind()) discards any pushed-back bytes for the stream.The external storage corresponding to the stream shall be unchanged.A successful call to ungetc() clears the end-of-file indicator for the stream.The value of the file-position indicator for the stream after reading or discarding all pushed-back bytes shall be the same as it was before the bytes were pushed back.The file-position indicator is decremented by each successful call to ungetc(), if its value was 0 before a call, its value is unspecified after the call."
},
{
"code": null,
"e": 27231,
"s": 27094,
"text": "The ungetc() function pushes the byte specified by char (converted to an unsigned char) back onto the input stream pointed to by stream."
},
{
"code": null,
"e": 27339,
"s": 27231,
"text": "The pushed-back bytes is returned by subsequent reads on that stream in the reverse order of their pushing."
},
{
"code": null,
"e": 27521,
"s": 27339,
"text": "A successful intervening call (with the stream pointed to by stream) to a file-positioning function ( fseek(), fsetpos(), or rewind()) discards any pushed-back bytes for the stream."
},
{
"code": null,
"e": 27590,
"s": 27521,
"text": "The external storage corresponding to the stream shall be unchanged."
},
{
"code": null,
"e": 27669,
"s": 27590,
"text": "A successful call to ungetc() clears the end-of-file indicator for the stream."
},
{
"code": null,
"e": 27838,
"s": 27669,
"text": "The value of the file-position indicator for the stream after reading or discarding all pushed-back bytes shall be the same as it was before the bytes were pushed back."
},
{
"code": null,
"e": 27993,
"s": 27838,
"text": "The file-position indicator is decremented by each successful call to ungetc(), if its value was 0 before a call, its value is unspecified after the call."
},
{
"code": null,
"e": 28039,
"s": 27993,
"text": "Below programs illustrate the above function."
},
{
"code": null,
"e": 28050,
"s": 28039,
"text": "Program 1:"
},
{
"code": "#include <stdio.h> int main(){ FILE* f; int char; char buffer[256]; // read a file f = fopen(\"use1.txt\", \"r\"); // when no data if (f == NULL) { printf(\"Error in opening file\"); return (-1); } // read lines till end while (!feof(f)) { // get line char = getc(f); // replace ! with + if (char == '!') { ungetc('+', f); } // if not else { ungetc(c, f); } fgets(buffer, 255, f); fputs(buffer, stdout); } return 0;}",
"e": 28612,
"s": 28050,
"text": null
},
{
"code": null,
"e": 28795,
"s": 28612,
"text": "Let us assume, we have a text file use1.txt, which contains the following data. This file will be used as an input for our example program, then the input and output are shown below:"
},
{
"code": null,
"e": 28936,
"s": 28795,
"text": "Input: !c standard library\n !library function stdio.h-ungetc()\nOutput: +c standard library\n +library function stdio.h-ungetc()\n"
},
{
"code": null,
"e": 28947,
"s": 28936,
"text": "Program 2:"
},
{
"code": "// C program for taking input till we// get 1 at the input #include <stdio.h>int main(){ int ch; // reads characters from the stdin and show // them on stdout until encounters '1' while ((ch = getchar()) != '1') putchar(ch); // ungetc() returns '1' previously // read back to stdin ungetc(ch, stdin); // getchar() attempts to read // next character from stdin // and reads character '1' returned // back to the stdin by ungetc() ch = getchar(); // putchar() displays character putchar(ch); return 0;}",
"e": 29508,
"s": 28947,
"text": null
},
{
"code": null,
"e": 29518,
"s": 29508,
"text": "C-Library"
},
{
"code": null,
"e": 29532,
"s": 29518,
"text": "CPP-Functions"
},
{
"code": null,
"e": 29543,
"s": 29532,
"text": "C Language"
},
{
"code": null,
"e": 29547,
"s": 29543,
"text": "C++"
},
{
"code": null,
"e": 29551,
"s": 29547,
"text": "CPP"
},
{
"code": null,
"e": 29649,
"s": 29551,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29687,
"s": 29649,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 29713,
"s": 29687,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 29733,
"s": 29713,
"text": "Multithreading in C"
},
{
"code": null,
"e": 29755,
"s": 29733,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 29796,
"s": 29755,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 29814,
"s": 29796,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 29860,
"s": 29814,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 29879,
"s": 29860,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 29922,
"s": 29879,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
How to Install iPython on MacOS? - GeeksforGeeks
|
21 Sep, 2021
In this article, we will learn how to install iPython in Python on MacOS.
IPython is a command shell for interactive computing in multiple programming languages, originally developed for the Python programming language, that offers introspection, rich media, shell syntax, tab completion, and history.
Follow the below steps to install the iPython package on macOS using pip:
Step 1: Install the latest Python3 in MacOS
Step 2: Check if pip3 and python3 are correctly installed.
python3 --version
pip3 --version
Step 3: Upgrade your pip to avoid errors during installation.
pip3 install --upgrade pip
Step 4: Enter the following command to install iPython using pip3.
pip3 install ipython
Follow the below steps to install iPython package on macOS using the setup.py file:
Step 1: Download the latest source package of iPython for python3 from here.
curl https://files.pythonhosted.org/packages/46/80/3942535e9c1025d4b379c447a0606bfbe140b25dc331d34910cf2f5e76c0/ipython-7.27.0.tar.gz > ipython.tar.gz
Step 2: Extract the downloaded package using the following command.
tar -xzvf ipython.tar.gz
Step 3: Go inside the folder and Enter the following command to install the package.
Note: You must have developer tools for XCode MacOS installed in your system
cd ipython-7.27.0
python3 setup.py install
Enter ipython in the terminal to verify if the installation has been done properly:
ipython
If there is any error then is not installed properly.
Blogathon-2021
how-to-install
Picked
Blogathon
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Table With Multiple Foreign Keys in SQL?
How to Import JSON Data into SQL Server?
Stratified Sampling in Pandas
How to Install Tkinter in Windows?
Python program to convert XML to Dictionary
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": 26097,
"s": 26069,
"text": "\n21 Sep, 2021"
},
{
"code": null,
"e": 26171,
"s": 26097,
"text": "In this article, we will learn how to install iPython in Python on MacOS."
},
{
"code": null,
"e": 26399,
"s": 26171,
"text": "IPython is a command shell for interactive computing in multiple programming languages, originally developed for the Python programming language, that offers introspection, rich media, shell syntax, tab completion, and history."
},
{
"code": null,
"e": 26473,
"s": 26399,
"text": "Follow the below steps to install the iPython package on macOS using pip:"
},
{
"code": null,
"e": 26517,
"s": 26473,
"text": "Step 1: Install the latest Python3 in MacOS"
},
{
"code": null,
"e": 26576,
"s": 26517,
"text": "Step 2: Check if pip3 and python3 are correctly installed."
},
{
"code": null,
"e": 26609,
"s": 26576,
"text": "python3 --version\npip3 --version"
},
{
"code": null,
"e": 26671,
"s": 26609,
"text": "Step 3: Upgrade your pip to avoid errors during installation."
},
{
"code": null,
"e": 26698,
"s": 26671,
"text": "pip3 install --upgrade pip"
},
{
"code": null,
"e": 26765,
"s": 26698,
"text": "Step 4: Enter the following command to install iPython using pip3."
},
{
"code": null,
"e": 26787,
"s": 26765,
"text": "pip3 install ipython "
},
{
"code": null,
"e": 26871,
"s": 26787,
"text": "Follow the below steps to install iPython package on macOS using the setup.py file:"
},
{
"code": null,
"e": 26948,
"s": 26871,
"text": "Step 1: Download the latest source package of iPython for python3 from here."
},
{
"code": null,
"e": 27099,
"s": 26948,
"text": "curl https://files.pythonhosted.org/packages/46/80/3942535e9c1025d4b379c447a0606bfbe140b25dc331d34910cf2f5e76c0/ipython-7.27.0.tar.gz > ipython.tar.gz"
},
{
"code": null,
"e": 27167,
"s": 27099,
"text": "Step 2: Extract the downloaded package using the following command."
},
{
"code": null,
"e": 27192,
"s": 27167,
"text": "tar -xzvf ipython.tar.gz"
},
{
"code": null,
"e": 27277,
"s": 27192,
"text": "Step 3: Go inside the folder and Enter the following command to install the package."
},
{
"code": null,
"e": 27354,
"s": 27277,
"text": "Note: You must have developer tools for XCode MacOS installed in your system"
},
{
"code": null,
"e": 27397,
"s": 27354,
"text": "cd ipython-7.27.0\npython3 setup.py install"
},
{
"code": null,
"e": 27481,
"s": 27397,
"text": "Enter ipython in the terminal to verify if the installation has been done properly:"
},
{
"code": null,
"e": 27489,
"s": 27481,
"text": "ipython"
},
{
"code": null,
"e": 27543,
"s": 27489,
"text": "If there is any error then is not installed properly."
},
{
"code": null,
"e": 27558,
"s": 27543,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 27573,
"s": 27558,
"text": "how-to-install"
},
{
"code": null,
"e": 27580,
"s": 27573,
"text": "Picked"
},
{
"code": null,
"e": 27590,
"s": 27580,
"text": "Blogathon"
},
{
"code": null,
"e": 27597,
"s": 27590,
"text": "How To"
},
{
"code": null,
"e": 27616,
"s": 27597,
"text": "Installation Guide"
},
{
"code": null,
"e": 27714,
"s": 27616,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27771,
"s": 27714,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 27812,
"s": 27771,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 27842,
"s": 27812,
"text": "Stratified Sampling in Pandas"
},
{
"code": null,
"e": 27877,
"s": 27842,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 27921,
"s": 27877,
"text": "Python program to convert XML to Dictionary"
},
{
"code": null,
"e": 27953,
"s": 27921,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28006,
"s": 27953,
"text": "How to Find the Wi-Fi Password Using CMD in Windows?"
},
{
"code": null,
"e": 28050,
"s": 28006,
"text": "How to install Jupyter Notebook on Windows?"
},
{
"code": null,
"e": 28077,
"s": 28050,
"text": "How to Align Text in HTML?"
}
] |
Ruby | Enumerable find() function - GeeksforGeeks
|
05 Dec, 2019
The find() of enumerable is an inbuilt method in Ruby returns the first element which satisfies the given condition in the block. If there is no block, then it returns the enumerator itself.
Syntax: block.find { |obj| block }
Parameters: The function takes the block according to which the first which satisfies is to be returned.
Return Value: It returns the first element which satisfies the block or the enumerator instead.
Example 1:
# Ruby program for find method in Enumerable # Initializeenu = (1..50) # returns first element enu.find { |el| el % 2 == 0 && el % 9 == 0}
Output:
18
Example 2:
# Ruby program for find method in Enumerable # Initializeenu = (1..50) # returns enumeratorenu.find
Output:
Enumerator: 1..50:find
Ruby Enumerable-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Array collect() operation
Ruby Integer odd? function with example
Ruby | Enumerator each_with_index function
Method Overloading In Ruby
Ruby on Rails Introduction
Ruby | Array class last() function
Ruby | Numeric abs() function
Ruby | Array zip() function
Ruby | Symbol Class
Ruby | reverse! function
|
[
{
"code": null,
"e": 24909,
"s": 24881,
"text": "\n05 Dec, 2019"
},
{
"code": null,
"e": 25100,
"s": 24909,
"text": "The find() of enumerable is an inbuilt method in Ruby returns the first element which satisfies the given condition in the block. If there is no block, then it returns the enumerator itself."
},
{
"code": null,
"e": 25135,
"s": 25100,
"text": "Syntax: block.find { |obj| block }"
},
{
"code": null,
"e": 25240,
"s": 25135,
"text": "Parameters: The function takes the block according to which the first which satisfies is to be returned."
},
{
"code": null,
"e": 25336,
"s": 25240,
"text": "Return Value: It returns the first element which satisfies the block or the enumerator instead."
},
{
"code": null,
"e": 25347,
"s": 25336,
"text": "Example 1:"
},
{
"code": "# Ruby program for find method in Enumerable # Initializeenu = (1..50) # returns first element enu.find { |el| el % 2 == 0 && el % 9 == 0}",
"e": 25489,
"s": 25347,
"text": null
},
{
"code": null,
"e": 25497,
"s": 25489,
"text": "Output:"
},
{
"code": null,
"e": 25501,
"s": 25497,
"text": "18\n"
},
{
"code": null,
"e": 25512,
"s": 25501,
"text": "Example 2:"
},
{
"code": "# Ruby program for find method in Enumerable # Initializeenu = (1..50) # returns enumeratorenu.find",
"e": 25614,
"s": 25512,
"text": null
},
{
"code": null,
"e": 25622,
"s": 25614,
"text": "Output:"
},
{
"code": null,
"e": 25646,
"s": 25622,
"text": "Enumerator: 1..50:find\n"
},
{
"code": null,
"e": 25668,
"s": 25646,
"text": "Ruby Enumerable-class"
},
{
"code": null,
"e": 25681,
"s": 25668,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 25686,
"s": 25681,
"text": "Ruby"
},
{
"code": null,
"e": 25784,
"s": 25686,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25817,
"s": 25784,
"text": "Ruby | Array collect() operation"
},
{
"code": null,
"e": 25857,
"s": 25817,
"text": "Ruby Integer odd? function with example"
},
{
"code": null,
"e": 25900,
"s": 25857,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 25927,
"s": 25900,
"text": "Method Overloading In Ruby"
},
{
"code": null,
"e": 25954,
"s": 25927,
"text": "Ruby on Rails Introduction"
},
{
"code": null,
"e": 25989,
"s": 25954,
"text": "Ruby | Array class last() function"
},
{
"code": null,
"e": 26019,
"s": 25989,
"text": "Ruby | Numeric abs() function"
},
{
"code": null,
"e": 26047,
"s": 26019,
"text": "Ruby | Array zip() function"
},
{
"code": null,
"e": 26067,
"s": 26047,
"text": "Ruby | Symbol Class"
}
] |
Ruby | Hash delete() function - GeeksforGeeks
|
07 Jan, 2020
delete() is an Hash class method which deletes the key-value pair and returns the value from hash whose key is equal to key.
Syntax: Hash.delete()
Parameter: Hash array
Return: value from hash whose key is equal to deleted key.
Example #1:
# Ruby code for delete() method # declaring Hash valuea = { "a" => 100, "b" => 200 } # declaring Hash valueb = {"a" => 100} puts "delete a : #{a.delete("a") }\n\n" puts "delete b : #{b.delete("a") }\n\n"
Output :
delete a : 100
delete b : 100
Example #2:
# Ruby code for delete () method # declaring Hash valuec = {"a" => 100, "c" => 300, "b" => 200} puts "delete c : #{c.delete("b") }\n\n" puts "delete c : #{c.delete("xy"){ |el| "#{el} not found" } }\n\n"
Output :
delete c : 200
delete c : xy not found
Ruby Hash-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | push() function
Ruby | Array count() operation
Ruby | Array slice() function
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Types of Variables
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | Array select() function
Ruby | Data Types
|
[
{
"code": null,
"e": 25217,
"s": 25189,
"text": "\n07 Jan, 2020"
},
{
"code": null,
"e": 25342,
"s": 25217,
"text": "delete() is an Hash class method which deletes the key-value pair and returns the value from hash whose key is equal to key."
},
{
"code": null,
"e": 25364,
"s": 25342,
"text": "Syntax: Hash.delete()"
},
{
"code": null,
"e": 25386,
"s": 25364,
"text": "Parameter: Hash array"
},
{
"code": null,
"e": 25445,
"s": 25386,
"text": "Return: value from hash whose key is equal to deleted key."
},
{
"code": null,
"e": 25457,
"s": 25445,
"text": "Example #1:"
},
{
"code": "# Ruby code for delete() method # declaring Hash valuea = { \"a\" => 100, \"b\" => 200 } # declaring Hash valueb = {\"a\" => 100} puts \"delete a : #{a.delete(\"a\") }\\n\\n\" puts \"delete b : #{b.delete(\"a\") }\\n\\n\"",
"e": 25671,
"s": 25457,
"text": null
},
{
"code": null,
"e": 25680,
"s": 25671,
"text": "Output :"
},
{
"code": null,
"e": 25717,
"s": 25680,
"text": "delete a : 100\n\ndelete b : 100\n\n"
},
{
"code": null,
"e": 25729,
"s": 25717,
"text": "Example #2:"
},
{
"code": "# Ruby code for delete () method # declaring Hash valuec = {\"a\" => 100, \"c\" => 300, \"b\" => 200} puts \"delete c : #{c.delete(\"b\") }\\n\\n\" puts \"delete c : #{c.delete(\"xy\"){ |el| \"#{el} not found\" } }\\n\\n\"",
"e": 25940,
"s": 25729,
"text": null
},
{
"code": null,
"e": 25949,
"s": 25940,
"text": "Output :"
},
{
"code": null,
"e": 25995,
"s": 25949,
"text": "delete c : 200\n\ndelete c : xy not found\n\n"
},
{
"code": null,
"e": 26011,
"s": 25995,
"text": "Ruby Hash-class"
},
{
"code": null,
"e": 26024,
"s": 26011,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 26029,
"s": 26024,
"text": "Ruby"
},
{
"code": null,
"e": 26127,
"s": 26029,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26150,
"s": 26127,
"text": "Ruby | push() function"
},
{
"code": null,
"e": 26181,
"s": 26150,
"text": "Ruby | Array count() operation"
},
{
"code": null,
"e": 26211,
"s": 26181,
"text": "Ruby | Array slice() function"
},
{
"code": null,
"e": 26238,
"s": 26211,
"text": "Include v/s Extend in Ruby"
},
{
"code": null,
"e": 26262,
"s": 26238,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 26288,
"s": 26262,
"text": "Ruby | Types of Variables"
},
{
"code": null,
"e": 26331,
"s": 26288,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 26353,
"s": 26331,
"text": "Ruby | Case Statement"
},
{
"code": null,
"e": 26384,
"s": 26353,
"text": "Ruby | Array select() function"
}
] |
Return maximum occurring character in an input string - GeeksforGeeks
|
24 Feb, 2022
Write an efficient function to return maximum occurring character in the input string e.g., if input string is “test” then function should return ‘t’.
Algorithm: One obvious approach to solve this problem would be to sort the input string and then traverse through the sorted string to find the character which is occurring maximum number of times. Let us see if we can improve on this. So we will use a technique called ‘Hashing’. In this, when we traverse through the string, we would hash each character into an array of ASCII characters.
Input string = “test”
1: Construct character count array from the input string.
count['e'] = 1
count['s'] = 1
count['t'] = 2
2: Return the index of maximum value in count array (returns ‘t’).
Typically, ASCII characters are 256, so we use our Hash array size as 256. But if we know that our input string will have characters with value from 0 to 127 only, we can limit Hash array size as 128. Similarly, based on extra info known about input string, the Hash array size can be limited to 26.Implementation:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to output the maximum occurring character// in a string#include<bits/stdc++.h>#define ASCII_SIZE 256using namespace std; char getMaxOccurringChar(char* str){ // Create array to keep the count of individual // characters and initialize the array as 0 int count[ASCII_SIZE] = {0}; // Construct character count array from the input // string. int len = strlen(str); int max = 0; // Initialize max count char result; // Initialize result // Traversing through the string and maintaining // the count of each character for (int i = 0; i < len; i++) { count[str[i]]++; if (max < count[str[i]]) { max = count[str[i]]; result = str[i]; } } return result;} // Driver program to test the above functionint main(){ char str[] = "sample string"; cout << "Max occurring character is " << getMaxOccuringChar(str);}
// Java program to output the maximum occurring character// in a string public class GFG{ static final int ASCII_SIZE = 256; static char getMaxOccurringChar(String str) { // Create array to keep the count of individual // characters and initialize the array as 0 int count[] = new int[ASCII_SIZE]; // Construct character count array from the input // string. int len = str.length(); for (int i=0; i<len; i++) count[str.charAt(i)]++; int max = -1; // Initialize max count char result = ' '; // Initialize result // Traversing through the string and maintaining // the count of each character for (int i = 0; i < len; i++) { if (max < count[str.charAt(i)]) { max = count[str.charAt(i)]; result = str.charAt(i); } } return result; } // Driver Method public static void main(String[] args) { String str = "sample string"; System.out.println("Max occurring character is " + getMaxOccuringChar(str)); }}
# Python program to return the maximum occurring character in the input stringASCII_SIZE = 256 def getMaxOccurringChar(str): # Create array to keep the count of individual characters # Initialize the count array to zero count = [0] * ASCII_SIZE # Utility variables max = -1 c = '' # Traversing through the string and maintaining the count of # each character for i in str: count[ord(i)]+=1; for i in str: if max < count[ord(i)]: max = count[ord(i)] c = i return c # Driver program to test the above functionstr = "sample string"print("Max occurring character is",getMaxOccuringChar(str)) # Although this program can be written in atmost 3 lines in Python# the above program has been written for a better understanding of# the reader # Shorter version of the program# import collections# str = "sample string"# print "Max occurring character is " +# collections.Counter(str).most_common(1)[0][0] # This code has been contributed by Bhavya Jain
// C# program to output the maximum// occurring character in a stringusing System; class GFG{ static int ASCII_SIZE = 256; static char getMaxOccurringChar(String str) { // Create array to keep the count of // individual characters and // initialize the array as 0 int []count = new int[ASCII_SIZE]; // Construct character count array // from the input string. int len = str.Length; for (int i = 0; i < len; i++) count[str[i]]++; int max = -1; // Initialize max count char result = ' '; // Initialize result // Traversing through the string and // maintaining the count of each character for (int i = 0; i < len; i++) { if (max < count[str[i]]) { max = count[str[i]]; result = str[i]; } } return result; } // Driver Method public static void Main() { String str = "sample string"; Console.Write("Max occurring character is " + getMaxOccuringChar(str)); }} // This code is contributed by Sam007
<?php// PHP program to output the maximum// occurring character in a string$ASCII_SIZE = 256; function getMaxOccurringChar($str){ global $ASCII_SIZE; // Create array to keep the count // of individual characters and // initialize the array as 0 $count = array_fill(0, $ASCII_SIZE, NULL); // Construct character count array // from the input string. $len = strlen($str); $max = 0; // Initialize max count // Traversing through the string // and maintaining the count of // each character for ($i = 0; $i < ($len); $i++) { $count[ord($str[$i])]++; if ($max < $count[ord($str[$i])]) { $max = $count[ord($str[$i])]; $result = $str[$i]; } } return $result;} // Driver Code$str = "sample string";echo "Max occurring character is " . getMaxOccuringChar($str); // This code is contributed by ita_c?>
<script>// Javascript program to output the maximum occurring character// in a string let ASCII_SIZE = 256; function getMaxOccurringChar(str) { // Create array to keep the count of individual // characters and initialize the array as 0 let count = new Array(ASCII_SIZE); for (let i = 0; i < ASCII_SIZE; i++) { count[i] = 0; } // Construct character count array from the input // string. let len = str.length; for (let i = 0; i < len; i++) { count[str[i].charCodeAt(0)] += 1; } let max = -1; // Initialize max count let result = ' '; // Initialize result // Traversing through the string and maintaining // the count of each character for (let i = 0; i < len; i++) { if (max < count[str[i].charCodeAt(0)]) { max = count[str[i].charCodeAt(0)]; result = str[i]; } } return result; } // Driver Method let str = "sample string"; document.write("Max occurring character is " , getMaxOccuringChar(str)); // This code is contributed by avanitrachhadiya2155</script>
Output:
Max occurring character is s
Time Complexity: O(n) Space Complexity: O(1) — Because we are using fixed space (Hash array) irrespective of input string size.Notes: If more than one characters have the same count and that count is maximum then the function returns the first character with maximum count in input string. For example if input string is “test sample” then there are three characters with same and maximum count two i.e. “t”, “e” and “s” but our program will result “t” because “t” comes first in input string. Similarly, the output for “cbbbbccc” would be “c”.As an variation to the above program, think about the change in code if you want to output “e” for input “test sample” i.e. the character of maximum count and that character should be of least ASCII value. For “cbbbbccc”, output should be “b”. Try it out !Also, can you think of improvement if we can avoid two loopings in the above? Basically, you need to figure out if we can solve the same problem with one loop itself instead of two loops.
YouTubeGeeksforGeeks507K subscribersReturn maximum occurring character in an input 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:08•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=uwbBxoCrbMg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Rajesh1978
ukasp
shubham_singh
avanitrachhadiya2155
amartyaghoshgfg
simmytarika5
Morgan Stanley
Hash
Strings
Morgan Stanley
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Most frequent element in an array
Sorting a Map by value in C++ STL
Double Hashing
Longest Consecutive Subsequence
C++ program for hashing with chaining
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Longest Common Subsequence | DP-4
|
[
{
"code": null,
"e": 26361,
"s": 26333,
"text": "\n24 Feb, 2022"
},
{
"code": null,
"e": 26513,
"s": 26361,
"text": "Write an efficient function to return maximum occurring character in the input string e.g., if input string is “test” then function should return ‘t’. "
},
{
"code": null,
"e": 26906,
"s": 26513,
"text": "Algorithm: One obvious approach to solve this problem would be to sort the input string and then traverse through the sorted string to find the character which is occurring maximum number of times. Let us see if we can improve on this. So we will use a technique called ‘Hashing’. In this, when we traverse through the string, we would hash each character into an array of ASCII characters. "
},
{
"code": null,
"e": 27105,
"s": 26906,
"text": "Input string = “test”\n1: Construct character count array from the input string.\n count['e'] = 1\n count['s'] = 1\n count['t'] = 2\n\n2: Return the index of maximum value in count array (returns ‘t’)."
},
{
"code": null,
"e": 27421,
"s": 27105,
"text": "Typically, ASCII characters are 256, so we use our Hash array size as 256. But if we know that our input string will have characters with value from 0 to 127 only, we can limit Hash array size as 128. Similarly, based on extra info known about input string, the Hash array size can be limited to 26.Implementation: "
},
{
"code": null,
"e": 27425,
"s": 27421,
"text": "C++"
},
{
"code": null,
"e": 27430,
"s": 27425,
"text": "Java"
},
{
"code": null,
"e": 27438,
"s": 27430,
"text": "Python3"
},
{
"code": null,
"e": 27441,
"s": 27438,
"text": "C#"
},
{
"code": null,
"e": 27445,
"s": 27441,
"text": "PHP"
},
{
"code": null,
"e": 27456,
"s": 27445,
"text": "Javascript"
},
{
"code": "// C++ program to output the maximum occurring character// in a string#include<bits/stdc++.h>#define ASCII_SIZE 256using namespace std; char getMaxOccurringChar(char* str){ // Create array to keep the count of individual // characters and initialize the array as 0 int count[ASCII_SIZE] = {0}; // Construct character count array from the input // string. int len = strlen(str); int max = 0; // Initialize max count char result; // Initialize result // Traversing through the string and maintaining // the count of each character for (int i = 0; i < len; i++) { count[str[i]]++; if (max < count[str[i]]) { max = count[str[i]]; result = str[i]; } } return result;} // Driver program to test the above functionint main(){ char str[] = \"sample string\"; cout << \"Max occurring character is \" << getMaxOccuringChar(str);}",
"e": 28374,
"s": 27456,
"text": null
},
{
"code": "// Java program to output the maximum occurring character// in a string public class GFG{ static final int ASCII_SIZE = 256; static char getMaxOccurringChar(String str) { // Create array to keep the count of individual // characters and initialize the array as 0 int count[] = new int[ASCII_SIZE]; // Construct character count array from the input // string. int len = str.length(); for (int i=0; i<len; i++) count[str.charAt(i)]++; int max = -1; // Initialize max count char result = ' '; // Initialize result // Traversing through the string and maintaining // the count of each character for (int i = 0; i < len; i++) { if (max < count[str.charAt(i)]) { max = count[str.charAt(i)]; result = str.charAt(i); } } return result; } // Driver Method public static void main(String[] args) { String str = \"sample string\"; System.out.println(\"Max occurring character is \" + getMaxOccuringChar(str)); }}",
"e": 29530,
"s": 28374,
"text": null
},
{
"code": "# Python program to return the maximum occurring character in the input stringASCII_SIZE = 256 def getMaxOccurringChar(str): # Create array to keep the count of individual characters # Initialize the count array to zero count = [0] * ASCII_SIZE # Utility variables max = -1 c = '' # Traversing through the string and maintaining the count of # each character for i in str: count[ord(i)]+=1; for i in str: if max < count[ord(i)]: max = count[ord(i)] c = i return c # Driver program to test the above functionstr = \"sample string\"print(\"Max occurring character is\",getMaxOccuringChar(str)) # Although this program can be written in atmost 3 lines in Python# the above program has been written for a better understanding of# the reader # Shorter version of the program# import collections# str = \"sample string\"# print \"Max occurring character is \" +# collections.Counter(str).most_common(1)[0][0] # This code has been contributed by Bhavya Jain",
"e": 30553,
"s": 29530,
"text": null
},
{
"code": "// C# program to output the maximum// occurring character in a stringusing System; class GFG{ static int ASCII_SIZE = 256; static char getMaxOccurringChar(String str) { // Create array to keep the count of // individual characters and // initialize the array as 0 int []count = new int[ASCII_SIZE]; // Construct character count array // from the input string. int len = str.Length; for (int i = 0; i < len; i++) count[str[i]]++; int max = -1; // Initialize max count char result = ' '; // Initialize result // Traversing through the string and // maintaining the count of each character for (int i = 0; i < len; i++) { if (max < count[str[i]]) { max = count[str[i]]; result = str[i]; } } return result; } // Driver Method public static void Main() { String str = \"sample string\"; Console.Write(\"Max occurring character is \" + getMaxOccuringChar(str)); }} // This code is contributed by Sam007",
"e": 31709,
"s": 30553,
"text": null
},
{
"code": "<?php// PHP program to output the maximum// occurring character in a string$ASCII_SIZE = 256; function getMaxOccurringChar($str){ global $ASCII_SIZE; // Create array to keep the count // of individual characters and // initialize the array as 0 $count = array_fill(0, $ASCII_SIZE, NULL); // Construct character count array // from the input string. $len = strlen($str); $max = 0; // Initialize max count // Traversing through the string // and maintaining the count of // each character for ($i = 0; $i < ($len); $i++) { $count[ord($str[$i])]++; if ($max < $count[ord($str[$i])]) { $max = $count[ord($str[$i])]; $result = $str[$i]; } } return $result;} // Driver Code$str = \"sample string\";echo \"Max occurring character is \" . getMaxOccuringChar($str); // This code is contributed by ita_c?>",
"e": 32629,
"s": 31709,
"text": null
},
{
"code": "<script>// Javascript program to output the maximum occurring character// in a string let ASCII_SIZE = 256; function getMaxOccurringChar(str) { // Create array to keep the count of individual // characters and initialize the array as 0 let count = new Array(ASCII_SIZE); for (let i = 0; i < ASCII_SIZE; i++) { count[i] = 0; } // Construct character count array from the input // string. let len = str.length; for (let i = 0; i < len; i++) { count[str[i].charCodeAt(0)] += 1; } let max = -1; // Initialize max count let result = ' '; // Initialize result // Traversing through the string and maintaining // the count of each character for (let i = 0; i < len; i++) { if (max < count[str[i].charCodeAt(0)]) { max = count[str[i].charCodeAt(0)]; result = str[i]; } } return result; } // Driver Method let str = \"sample string\"; document.write(\"Max occurring character is \" , getMaxOccuringChar(str)); // This code is contributed by avanitrachhadiya2155</script>",
"e": 33873,
"s": 32629,
"text": null
},
{
"code": null,
"e": 33883,
"s": 33873,
"text": "Output: "
},
{
"code": null,
"e": 33912,
"s": 33883,
"text": "Max occurring character is s"
},
{
"code": null,
"e": 34902,
"s": 33912,
"text": "Time Complexity: O(n) Space Complexity: O(1) — Because we are using fixed space (Hash array) irrespective of input string size.Notes: If more than one characters have the same count and that count is maximum then the function returns the first character with maximum count in input string. For example if input string is “test sample” then there are three characters with same and maximum count two i.e. “t”, “e” and “s” but our program will result “t” because “t” comes first in input string. Similarly, the output for “cbbbbccc” would be “c”.As an variation to the above program, think about the change in code if you want to output “e” for input “test sample” i.e. the character of maximum count and that character should be of least ASCII value. For “cbbbbccc”, output should be “b”. Try it out !Also, can you think of improvement if we can avoid two loopings in the above? Basically, you need to figure out if we can solve the same problem with one loop itself instead of two loops. "
},
{
"code": null,
"e": 35754,
"s": 34902,
"text": "YouTubeGeeksforGeeks507K subscribersReturn maximum occurring character in an input 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:08•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=uwbBxoCrbMg\" 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": 35879,
"s": 35754,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 35890,
"s": 35879,
"text": "Rajesh1978"
},
{
"code": null,
"e": 35896,
"s": 35890,
"text": "ukasp"
},
{
"code": null,
"e": 35910,
"s": 35896,
"text": "shubham_singh"
},
{
"code": null,
"e": 35931,
"s": 35910,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 35947,
"s": 35931,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 35960,
"s": 35947,
"text": "simmytarika5"
},
{
"code": null,
"e": 35975,
"s": 35960,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 35980,
"s": 35975,
"text": "Hash"
},
{
"code": null,
"e": 35988,
"s": 35980,
"text": "Strings"
},
{
"code": null,
"e": 36003,
"s": 35988,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 36008,
"s": 36003,
"text": "Hash"
},
{
"code": null,
"e": 36016,
"s": 36008,
"text": "Strings"
},
{
"code": null,
"e": 36114,
"s": 36016,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36148,
"s": 36114,
"text": "Most frequent element in an array"
},
{
"code": null,
"e": 36182,
"s": 36148,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 36197,
"s": 36182,
"text": "Double Hashing"
},
{
"code": null,
"e": 36229,
"s": 36197,
"text": "Longest Consecutive Subsequence"
},
{
"code": null,
"e": 36267,
"s": 36229,
"text": "C++ program for hashing with chaining"
},
{
"code": null,
"e": 36313,
"s": 36267,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 36338,
"s": 36313,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 36398,
"s": 36338,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 36413,
"s": 36398,
"text": "C++ Data Types"
}
] |
Program to check if an Array is Palindrome or not - GeeksforGeeks
|
22 Mar, 2021
Given an array, the task is to determine whether an array is a palindrome or not.Examples:
Input: arr[] = {3, 6, 0, 6, 3}
Output: Palindrome
Input: arr[] = {1, 2, 3, 4, 5}
Output: Not Palindrome
Approach:
Initialise flag to unset int flag = 0.
Loop the array till size n/2
In a loop check if arr[i]! = arr[n-i-1] then set the flag = 1 and break
After the loop has ended, If flag is set the print “Not Palindrome” else print “Palindrome”
Below is the implementation of above Approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to check whether the// Array is palindrome or not #include <iostream>using namespace std; void palindrome(int arr[], int n){ // Initialise flag to zero. int flag = 0; // Loop till array size n/2. for (int i = 0; i <= n / 2 && n != 0; i++) { // Check if first and last element are different // Then set flag to 1. if (arr[i] != arr[n - i - 1]) { flag = 1; break; } } // If flag is set then print Not Palindrome // else print Palindrome. if (flag == 1) cout << "Not Palindrome"; else cout << "Palindrome";} // Driver code.int main(){ int arr[] = { 1, 2, 3, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); palindrome(arr, n); return 0;}
// Java Program to check whether the// Array is palindromic or not class GfG { static void palindrome(int arr[], int n) { // Initialise flag to zero. int flag = 0; // Loop till array size n/2. for (int i = 0; i <= n / 2 && n != 0; i++) { // Check if first and last element are different // Then set flag to 1. if (arr[i] != arr[n - i - 1]) { flag = 1; break; } } // If flag is set then print Not Palindrome // else print Palindrome. if (flag == 1) System.out.println("Not Palindrome"); else System.out.println("Palindrome"); } // Driver code. public static void main(String[] args) { int arr[] = { 1, 2, 3, 2, 1 }; int n = arr.length; palindrome(arr, n); }}
# Python3 Program to check whether the# Array is palindromic or notdef palindrome(arr, n): # Initialise flag to zero. flag = 0; # Loop till array size n/2. i = 0; while (i <= n // 2 and n != 0): # Check if first and last element # are different. Then set flag to 1. if (arr[i] != arr[n - i - 1]): flag = 1; break; i += 1; # If flag is set then print Not Palindrome # else print Palindrome. if (flag == 1): print("Not Palindrome"); else: print("Palindrome"); # Driver code.arr = [ 1, 2, 3, 2, 1 ];n = len(arr); palindrome(arr, n); # This code is contributed# by chandan_jnu
// C# Program to check whether the// Array is palindromic or notclass GfG{ static void palindrome(int []arr, int n) { // Initialise flag to zero. int flag = 0; // Loop till array size n/2. for (int i = 0; i <= n / 2 && n != 0; i++) { // Check if first and last element are different // Then set flag to 1. if (arr[i] != arr[n - i - 1]) { flag = 1; break; } } // If flag is set then print Not Palindrome // else print Palindrome. if (flag == 1) System.Console.WriteLine("Not Palindrome"); else System.Console.WriteLine("Palindrome"); } // Driver code. static void Main() { int []arr = { 1, 2, 3, 2, 1 }; int n = arr.Length; palindrome(arr, n); }} // This code is contributed by chadan_jnu
<?php// PHP Program to check whether the// Array is palindrome or not function palindrome($arr, $n){ // Initialise flag to zero. $flag = 0; // Loop till array size n/2. for ($i = 0; $i <= $n / 2 && $n != 0; $i++) { // Check if first and last element are // different then set flag to 1. if ($arr[$i] != $arr[$n - $i - 1]) { $flag = 1; break; } } // If flag is set then print Not Palindrome // else print Palindrome. if ($flag == 1) echo "Not Palindrome"; else echo "Palindrome";} // Driver code.$arr = array( 1, 2, 3, 2, 1 );$n = count($arr); palindrome($arr, $n); // This code is contributed by chandan_jnu?>
<script> // Javascript Program to check whether the// Array is palindrome or not function palindrome(arr, n){ // Initialise flag to zero. let flag = 0; // Loop till array size n/2. for (let i = 0; i <= n / 2 && n != 0; i++) { // Check if first and last element are different // Then set flag to 1. if (arr[i] != arr[n - i - 1]) { flag = 1; break; } } // If flag is set then print Not Palindrome // else print Palindrome. if (flag == 1) document.write("Not Palindrome"); else document.write("Palindrome");} // Driver code. let arr = [ 1, 2, 3, 2, 1 ]; let n = arr.length; palindrome(arr, n); // This code is contributed by Mayank Tyagi </script>
Palindrome
Related Article: Program to check if an array is palindrome or not using Recursion
prerna saini
Chandan_Kumar
Akhilesh_Raturi
mayanktyagi1709
palindrome
Arrays
School Programming
Arrays
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Python Dictionary
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects
Interfaces in Java
|
[
{
"code": null,
"e": 26293,
"s": 26265,
"text": "\n22 Mar, 2021"
},
{
"code": null,
"e": 26386,
"s": 26293,
"text": "Given an array, the task is to determine whether an array is a palindrome or not.Examples: "
},
{
"code": null,
"e": 26491,
"s": 26386,
"text": "Input: arr[] = {3, 6, 0, 6, 3}\nOutput: Palindrome\n\nInput: arr[] = {1, 2, 3, 4, 5}\nOutput: Not Palindrome"
},
{
"code": null,
"e": 26505,
"s": 26493,
"text": "Approach: "
},
{
"code": null,
"e": 26544,
"s": 26505,
"text": "Initialise flag to unset int flag = 0."
},
{
"code": null,
"e": 26573,
"s": 26544,
"text": "Loop the array till size n/2"
},
{
"code": null,
"e": 26645,
"s": 26573,
"text": "In a loop check if arr[i]! = arr[n-i-1] then set the flag = 1 and break"
},
{
"code": null,
"e": 26737,
"s": 26645,
"text": "After the loop has ended, If flag is set the print “Not Palindrome” else print “Palindrome”"
},
{
"code": null,
"e": 26785,
"s": 26737,
"text": "Below is the implementation of above Approach: "
},
{
"code": null,
"e": 26789,
"s": 26785,
"text": "C++"
},
{
"code": null,
"e": 26794,
"s": 26789,
"text": "Java"
},
{
"code": null,
"e": 26802,
"s": 26794,
"text": "Python3"
},
{
"code": null,
"e": 26805,
"s": 26802,
"text": "C#"
},
{
"code": null,
"e": 26809,
"s": 26805,
"text": "PHP"
},
{
"code": null,
"e": 26820,
"s": 26809,
"text": "Javascript"
},
{
"code": "// C++ Program to check whether the// Array is palindrome or not #include <iostream>using namespace std; void palindrome(int arr[], int n){ // Initialise flag to zero. int flag = 0; // Loop till array size n/2. for (int i = 0; i <= n / 2 && n != 0; i++) { // Check if first and last element are different // Then set flag to 1. if (arr[i] != arr[n - i - 1]) { flag = 1; break; } } // If flag is set then print Not Palindrome // else print Palindrome. if (flag == 1) cout << \"Not Palindrome\"; else cout << \"Palindrome\";} // Driver code.int main(){ int arr[] = { 1, 2, 3, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); palindrome(arr, n); return 0;}",
"e": 27574,
"s": 26820,
"text": null
},
{
"code": "// Java Program to check whether the// Array is palindromic or not class GfG { static void palindrome(int arr[], int n) { // Initialise flag to zero. int flag = 0; // Loop till array size n/2. for (int i = 0; i <= n / 2 && n != 0; i++) { // Check if first and last element are different // Then set flag to 1. if (arr[i] != arr[n - i - 1]) { flag = 1; break; } } // If flag is set then print Not Palindrome // else print Palindrome. if (flag == 1) System.out.println(\"Not Palindrome\"); else System.out.println(\"Palindrome\"); } // Driver code. public static void main(String[] args) { int arr[] = { 1, 2, 3, 2, 1 }; int n = arr.length; palindrome(arr, n); }}",
"e": 28439,
"s": 27574,
"text": null
},
{
"code": "# Python3 Program to check whether the# Array is palindromic or notdef palindrome(arr, n): # Initialise flag to zero. flag = 0; # Loop till array size n/2. i = 0; while (i <= n // 2 and n != 0): # Check if first and last element # are different. Then set flag to 1. if (arr[i] != arr[n - i - 1]): flag = 1; break; i += 1; # If flag is set then print Not Palindrome # else print Palindrome. if (flag == 1): print(\"Not Palindrome\"); else: print(\"Palindrome\"); # Driver code.arr = [ 1, 2, 3, 2, 1 ];n = len(arr); palindrome(arr, n); # This code is contributed# by chandan_jnu",
"e": 29107,
"s": 28439,
"text": null
},
{
"code": "// C# Program to check whether the// Array is palindromic or notclass GfG{ static void palindrome(int []arr, int n) { // Initialise flag to zero. int flag = 0; // Loop till array size n/2. for (int i = 0; i <= n / 2 && n != 0; i++) { // Check if first and last element are different // Then set flag to 1. if (arr[i] != arr[n - i - 1]) { flag = 1; break; } } // If flag is set then print Not Palindrome // else print Palindrome. if (flag == 1) System.Console.WriteLine(\"Not Palindrome\"); else System.Console.WriteLine(\"Palindrome\"); } // Driver code. static void Main() { int []arr = { 1, 2, 3, 2, 1 }; int n = arr.Length; palindrome(arr, n); }} // This code is contributed by chadan_jnu",
"e": 30020,
"s": 29107,
"text": null
},
{
"code": "<?php// PHP Program to check whether the// Array is palindrome or not function palindrome($arr, $n){ // Initialise flag to zero. $flag = 0; // Loop till array size n/2. for ($i = 0; $i <= $n / 2 && $n != 0; $i++) { // Check if first and last element are // different then set flag to 1. if ($arr[$i] != $arr[$n - $i - 1]) { $flag = 1; break; } } // If flag is set then print Not Palindrome // else print Palindrome. if ($flag == 1) echo \"Not Palindrome\"; else echo \"Palindrome\";} // Driver code.$arr = array( 1, 2, 3, 2, 1 );$n = count($arr); palindrome($arr, $n); // This code is contributed by chandan_jnu?>",
"e": 30750,
"s": 30020,
"text": null
},
{
"code": "<script> // Javascript Program to check whether the// Array is palindrome or not function palindrome(arr, n){ // Initialise flag to zero. let flag = 0; // Loop till array size n/2. for (let i = 0; i <= n / 2 && n != 0; i++) { // Check if first and last element are different // Then set flag to 1. if (arr[i] != arr[n - i - 1]) { flag = 1; break; } } // If flag is set then print Not Palindrome // else print Palindrome. if (flag == 1) document.write(\"Not Palindrome\"); else document.write(\"Palindrome\");} // Driver code. let arr = [ 1, 2, 3, 2, 1 ]; let n = arr.length; palindrome(arr, n); // This code is contributed by Mayank Tyagi </script>",
"e": 31502,
"s": 30750,
"text": null
},
{
"code": null,
"e": 31513,
"s": 31502,
"text": "Palindrome"
},
{
"code": null,
"e": 31599,
"s": 31515,
"text": "Related Article: Program to check if an array is palindrome or not using Recursion "
},
{
"code": null,
"e": 31612,
"s": 31599,
"text": "prerna saini"
},
{
"code": null,
"e": 31626,
"s": 31612,
"text": "Chandan_Kumar"
},
{
"code": null,
"e": 31642,
"s": 31626,
"text": "Akhilesh_Raturi"
},
{
"code": null,
"e": 31658,
"s": 31642,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 31669,
"s": 31658,
"text": "palindrome"
},
{
"code": null,
"e": 31676,
"s": 31669,
"text": "Arrays"
},
{
"code": null,
"e": 31695,
"s": 31676,
"text": "School Programming"
},
{
"code": null,
"e": 31702,
"s": 31695,
"text": "Arrays"
},
{
"code": null,
"e": 31713,
"s": 31702,
"text": "palindrome"
},
{
"code": null,
"e": 31811,
"s": 31713,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31879,
"s": 31811,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 31923,
"s": 31879,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 31971,
"s": 31923,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 31994,
"s": 31971,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 32026,
"s": 31994,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 32044,
"s": 32026,
"text": "Python Dictionary"
},
{
"code": null,
"e": 32063,
"s": 32044,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 32088,
"s": 32063,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 32112,
"s": 32088,
"text": "C++ Classes and Objects"
}
] |
Image Analysis Tool using PyQtGraph - GeeksforGeeks
|
18 Nov, 2021
In this article we will see how we can perform common image analysis using PyQtGraph module in Python. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).
In order to install the PyQtGraph we use the command given below.
pip install pyqtgraph
Image analysis is the extraction of meaningful information from images; mainly from digital images by means of digital image processing techniques. Image analysis tasks can be as simple as reading bar coded tags or as sophisticated as identifying a person from their face.
In order to do this we have to do the following.
Import the required libraries like pyqtgraph, pyqt5 and numpy.Create a main window class using pyqt5.Create a graphic window to add the widgets required to show the image analysis.Create two plot area and add a image item to it with the roi object to first plot area.Create an isocurve object and add it to the image item.Create a data for image and add it to the image item.Connect a update method to the roi object when the region is changed, inside the update method get the region and set it to the second plot area.Create a mouse move event and set the position, pixel value to the title according to the mouse position.Add this graph window to the main window layout with any additional widgets.
Import the required libraries like pyqtgraph, pyqt5 and numpy.
Create a main window class using pyqt5.
Create a graphic window to add the widgets required to show the image analysis.
Create two plot area and add a image item to it with the roi object to first plot area.
Create an isocurve object and add it to the image item.
Create a data for image and add it to the image item.
Connect a update method to the roi object when the region is changed, inside the update method get the region and set it to the second plot area.
Create a mouse move event and set the position, pixel value to the title according to the mouse position.
Add this graph window to the main window layout with any additional widgets.
Below is the implementation
Python3
# importing Qt widgetsfrom PyQt5.QtWidgets import * # importing systemimport sys # importing numpy as npimport numpy as np # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import *from PyQt5.QtCore import * class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("PyQtGraph") # setting geometry self.setGeometry(100, 100, 900, 550) # icon icon = QIcon("skin.png") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # text text = "Image Analysis" # creating a label label = QLabel(text) # setting minimum width label.setMinimumWidth(130) # making label do word wrap label.setWordWrap(True) # creating a graphic layout widget win = pg.GraphicsLayoutWidget() # plot area (ViewBox + axes) for displaying the image p1 = win.addPlot(title="") # item for displaying image data img = pg.ImageItem() # adding image to the plot area p1.addItem(img) # Custom ROI for selecting an image region roi = pg.ROI([-10, 14], [5, 5]) roi.addScaleHandle([0.5, 1], [0.5, 0.5]) roi.addScaleHandle([0, 0.5], [0.5, 0.5]) # adding roi to the plot area p1.addItem(roi) # setting z value to roi # making sure ROI is drawn above image roi.setZValue(10) # creating a Isocurve drawing on the image iso = pg.IsocurveItem(level=1.2, pen='r') # setting parent as image iso.setParentItem(img) # setting z axis value of isocurve iso.setZValue(5) # Contrast/color control hist = pg.HistogramLUTItem() # setting image to the control hist.setImageItem(img) # adding control widget to the plot window win.addItem(hist) # creating draggable line for setting isocurve level isoLine = pg.InfiniteLine(angle=0, movable=True, pen='r') hist.vb.addItem(isoLine) # making user interaction a little easier hist.vb.setMouseEnabled(y=False) isoLine.setValue(0.8) # bring iso line above contrast controls isoLine.setZValue(1000) # going to next row of graphic window win.nextRow() # another plot area for displaying ROI data p2 = win.addPlot(colspan=2) # setting maximum height of plot area p2.setMaximumHeight(250) # generating image data data = np.random.normal(size=(200, 100)) data[20:80, 20:80] += 2. # setting gaussian filter to the data data = pg.gaussianFilter(data, (3, 3)) data += np.random.normal(size=(200, 100)) * 0.1 # setting data to the image img.setImage(data) # setting level hist.setLevels(data.min(), data.max()) # build isocurves from smoothed data iso.setData(pg.gaussianFilter(data, (2, 2))) # set position and scale of image img.scale(0.2, 0.2) img.translate(-50, 0) # zoom to fit image p1.autoRange() # method for updating the plot def updatePlot(): # getting the selected region by the roi selected = roi.getArrayRegion(data, img) # plot the selected region p2.plot(selected.mean(axis=0), clear=True) # connecting the update plot method # it get called when the region is changed roi.sigRegionChanged.connect(updatePlot) # call the update plot method updatePlot() # method for updating the isocurve def updateIsocurve(): # setting iso level iso.setLevel(isoLine.value()) isoLine.sigDragged.connect(updateIsocurve) # method for image hover event def imageHoverEvent(event): # showing the position, pixel, and value under the mouse cursor # if cursor is not on the plot area if event.isExit(): # set title as blank p1.setTitle("") return # getting cursor position pos = event.pos() i, j = pos.y(), pos.x() # pixel values i = int(np.clip(i, 0, data.shape[0] - 1)) j = int(np.clip(j, 0, data.shape[1] - 1)) # value of point val = data[i, j] ppos = img.mapToParent(pos) x, y = ppos.x(), ppos.y() # setting plot title data p1.setTitle( "pos: (%0.1f, %0.1f) pixel: (%d, %d) value: %g" % (x, y, i, j, val)) # Monkey-patch the image to use our custom hover function. img.hoverEvent = imageHoverEvent # Creating a grid layout layout = QGridLayout() # minimum width value of the label label.setMinimumWidth(130) # setting this layout to the widget widget.setLayout(layout) # adding label in the layout layout.addWidget(label, 1, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(win, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output:
ManasChhabra2
saurabh1990aror
sumitgumber28
anikakapoor
Python-gui
Python-PyQtGraph
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 26067,
"s": 26039,
"text": "\n18 Nov, 2021"
},
{
"code": null,
"e": 26548,
"s": 26067,
"text": "In this article we will see how we can perform common image analysis using PyQtGraph module in Python. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer)."
},
{
"code": null,
"e": 26614,
"s": 26548,
"text": "In order to install the PyQtGraph we use the command given below."
},
{
"code": null,
"e": 26636,
"s": 26614,
"text": "pip install pyqtgraph"
},
{
"code": null,
"e": 26909,
"s": 26636,
"text": "Image analysis is the extraction of meaningful information from images; mainly from digital images by means of digital image processing techniques. Image analysis tasks can be as simple as reading bar coded tags or as sophisticated as identifying a person from their face."
},
{
"code": null,
"e": 26958,
"s": 26909,
"text": "In order to do this we have to do the following."
},
{
"code": null,
"e": 27660,
"s": 26958,
"text": "Import the required libraries like pyqtgraph, pyqt5 and numpy.Create a main window class using pyqt5.Create a graphic window to add the widgets required to show the image analysis.Create two plot area and add a image item to it with the roi object to first plot area.Create an isocurve object and add it to the image item.Create a data for image and add it to the image item.Connect a update method to the roi object when the region is changed, inside the update method get the region and set it to the second plot area.Create a mouse move event and set the position, pixel value to the title according to the mouse position.Add this graph window to the main window layout with any additional widgets."
},
{
"code": null,
"e": 27723,
"s": 27660,
"text": "Import the required libraries like pyqtgraph, pyqt5 and numpy."
},
{
"code": null,
"e": 27763,
"s": 27723,
"text": "Create a main window class using pyqt5."
},
{
"code": null,
"e": 27843,
"s": 27763,
"text": "Create a graphic window to add the widgets required to show the image analysis."
},
{
"code": null,
"e": 27931,
"s": 27843,
"text": "Create two plot area and add a image item to it with the roi object to first plot area."
},
{
"code": null,
"e": 27987,
"s": 27931,
"text": "Create an isocurve object and add it to the image item."
},
{
"code": null,
"e": 28041,
"s": 27987,
"text": "Create a data for image and add it to the image item."
},
{
"code": null,
"e": 28187,
"s": 28041,
"text": "Connect a update method to the roi object when the region is changed, inside the update method get the region and set it to the second plot area."
},
{
"code": null,
"e": 28293,
"s": 28187,
"text": "Create a mouse move event and set the position, pixel value to the title according to the mouse position."
},
{
"code": null,
"e": 28370,
"s": 28293,
"text": "Add this graph window to the main window layout with any additional widgets."
},
{
"code": null,
"e": 28399,
"s": 28370,
"text": "Below is the implementation "
},
{
"code": null,
"e": 28407,
"s": 28399,
"text": "Python3"
},
{
"code": "# importing Qt widgetsfrom PyQt5.QtWidgets import * # importing systemimport sys # importing numpy as npimport numpy as np # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import *from PyQt5.QtCore import * class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"PyQtGraph\") # setting geometry self.setGeometry(100, 100, 900, 550) # icon icon = QIcon(\"skin.png\") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # text text = \"Image Analysis\" # creating a label label = QLabel(text) # setting minimum width label.setMinimumWidth(130) # making label do word wrap label.setWordWrap(True) # creating a graphic layout widget win = pg.GraphicsLayoutWidget() # plot area (ViewBox + axes) for displaying the image p1 = win.addPlot(title=\"\") # item for displaying image data img = pg.ImageItem() # adding image to the plot area p1.addItem(img) # Custom ROI for selecting an image region roi = pg.ROI([-10, 14], [5, 5]) roi.addScaleHandle([0.5, 1], [0.5, 0.5]) roi.addScaleHandle([0, 0.5], [0.5, 0.5]) # adding roi to the plot area p1.addItem(roi) # setting z value to roi # making sure ROI is drawn above image roi.setZValue(10) # creating a Isocurve drawing on the image iso = pg.IsocurveItem(level=1.2, pen='r') # setting parent as image iso.setParentItem(img) # setting z axis value of isocurve iso.setZValue(5) # Contrast/color control hist = pg.HistogramLUTItem() # setting image to the control hist.setImageItem(img) # adding control widget to the plot window win.addItem(hist) # creating draggable line for setting isocurve level isoLine = pg.InfiniteLine(angle=0, movable=True, pen='r') hist.vb.addItem(isoLine) # making user interaction a little easier hist.vb.setMouseEnabled(y=False) isoLine.setValue(0.8) # bring iso line above contrast controls isoLine.setZValue(1000) # going to next row of graphic window win.nextRow() # another plot area for displaying ROI data p2 = win.addPlot(colspan=2) # setting maximum height of plot area p2.setMaximumHeight(250) # generating image data data = np.random.normal(size=(200, 100)) data[20:80, 20:80] += 2. # setting gaussian filter to the data data = pg.gaussianFilter(data, (3, 3)) data += np.random.normal(size=(200, 100)) * 0.1 # setting data to the image img.setImage(data) # setting level hist.setLevels(data.min(), data.max()) # build isocurves from smoothed data iso.setData(pg.gaussianFilter(data, (2, 2))) # set position and scale of image img.scale(0.2, 0.2) img.translate(-50, 0) # zoom to fit image p1.autoRange() # method for updating the plot def updatePlot(): # getting the selected region by the roi selected = roi.getArrayRegion(data, img) # plot the selected region p2.plot(selected.mean(axis=0), clear=True) # connecting the update plot method # it get called when the region is changed roi.sigRegionChanged.connect(updatePlot) # call the update plot method updatePlot() # method for updating the isocurve def updateIsocurve(): # setting iso level iso.setLevel(isoLine.value()) isoLine.sigDragged.connect(updateIsocurve) # method for image hover event def imageHoverEvent(event): # showing the position, pixel, and value under the mouse cursor # if cursor is not on the plot area if event.isExit(): # set title as blank p1.setTitle(\"\") return # getting cursor position pos = event.pos() i, j = pos.y(), pos.x() # pixel values i = int(np.clip(i, 0, data.shape[0] - 1)) j = int(np.clip(j, 0, data.shape[1] - 1)) # value of point val = data[i, j] ppos = img.mapToParent(pos) x, y = ppos.x(), ppos.y() # setting plot title data p1.setTitle( \"pos: (%0.1f, %0.1f) pixel: (%d, %d) value: %g\" % (x, y, i, j, val)) # Monkey-patch the image to use our custom hover function. img.hoverEvent = imageHoverEvent # Creating a grid layout layout = QGridLayout() # minimum width value of the label label.setMinimumWidth(130) # setting this layout to the widget widget.setLayout(layout) # adding label in the layout layout.addWidget(label, 1, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(win, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 33971,
"s": 28407,
"text": null
},
{
"code": null,
"e": 33979,
"s": 33971,
"text": "Output:"
},
{
"code": null,
"e": 33993,
"s": 33979,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 34009,
"s": 33993,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 34023,
"s": 34009,
"text": "sumitgumber28"
},
{
"code": null,
"e": 34035,
"s": 34023,
"text": "anikakapoor"
},
{
"code": null,
"e": 34046,
"s": 34035,
"text": "Python-gui"
},
{
"code": null,
"e": 34063,
"s": 34046,
"text": "Python-PyQtGraph"
},
{
"code": null,
"e": 34070,
"s": 34063,
"text": "Python"
},
{
"code": null,
"e": 34168,
"s": 34070,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34186,
"s": 34168,
"text": "Python Dictionary"
},
{
"code": null,
"e": 34221,
"s": 34186,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 34253,
"s": 34221,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 34275,
"s": 34253,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 34317,
"s": 34275,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 34347,
"s": 34317,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 34373,
"s": 34347,
"text": "Python String | replace()"
},
{
"code": null,
"e": 34402,
"s": 34373,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 34446,
"s": 34402,
"text": "Reading and Writing to text files in Python"
}
] |
Python| AnchorLayout in Kivy - GeeksforGeeks
|
06 Feb, 2020
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.
Kivy Tutorial – Learn Kivy with Examples.
The AnchorLayout aligns its children to a border (top, bottom, left, right) or center. The class given below is used to implement the anchor layout.
kivy.uix.anchorlayout.AnchorLayout
AnchorLayout can be initialized with parameters:
anchor_x
Parameters can be passed: “left”, “right” and “center”.
anchor_y
Parameters can be passed:“top”, “bottom” and “center”.
to select the place where the widgets are placed in the parent container.
There are 9 different layout regions where the Anchorlayout can be placed for effect:
Top-left, top-center, top-right, center-left, center-center, center-right, bottom-left, bottom-center and bottom-right.
Note: Remember adding multiple widgets to an anchor layout, only positions the widgets at the same location.
Basic Approach:
1) import kivy
2) import kivyApp
4) import Anchorlayout
5) Set minimum version(optional)
6) create App class
7) return Layout/widget/Class(according to requirement)
8) Run an instance of the class
Implementation of the Approach (with some Styling):
1) anchor_x=’right’, anchor_y=’bottom’:
# Sample Python application demonstrating# the working of AnchorLayout in Kivy # Module imports # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # The AnchorLayout aligns its children to a border# (top, bottom, left, right) or centerfrom kivy.uix.anchorlayout import AnchorLayout # BoxLayout arranges children in a vertical or horizontal box.# or help to put the childrens at the desired location.from kivy.uix.boxlayout import BoxLayout # creates the button in kivy # if not imported shows the errorfrom kivy.uix.button import Button # A Kivy app demonstrating the working of anchor layoutclass AnchorLayoutApp(App): def build(self): # Anchor Layout1 layout = AnchorLayout( anchor_x ='right', anchor_y ='bottom') btn = Button(text ='Hello World', size_hint =(.3, .3), background_color =(1.0, 0.0, 0.0, 1.0)) layout.add_widget(btn) return layout # creating the object root for AnchorLayoutApp() class root = AnchorLayoutApp()# Run the Kivy approot.run()
Output:
If you want to change the positions of the AnchorLayouts then just replace the class code in the above code with below or you can change the anchor_x and anchor_y with any of the parameters to make any 9 combinations as described above.
2) anchor_x=’right’, anchor_y=’top’:
# A Kivy app demonstrating the working of anchor layoutclass AnchorLayoutApp(App): def build(self): # Anchor Layout1 layout = AnchorLayout( anchor_x ='right', anchor_y ='top') btn = Button(text ='Hello World', size_hint =(.3, .3), background_color =(1.0, 0.0, 1.0, 1.0)) layout.add_widget(btn) return layout
Output:
3) anchor_x=’center’, anchor_y=’top’:Output:
4) anchor_x=’left’, anchor_y=’top’:Output:
5) anchor_x=’left’, anchor_y=’bottom’:Output:
6) anchor_x=’left’, anchor_y=’center’:Output:
7) anchor_x=’center’, anchor_y=’center’:Output:
8) anchor_x=’center’, anchor_y=’bottom’:Output:
9) anchor_x=’right’, anchor_y=’center’:Output:
ManasChhabra2
Python-gui
Python-kivy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
|
[
{
"code": null,
"e": 42651,
"s": 42623,
"text": "\n06 Feb, 2020"
},
{
"code": null,
"e": 42887,
"s": 42651,
"text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications."
},
{
"code": null,
"e": 42930,
"s": 42887,
"text": " Kivy Tutorial – Learn Kivy with Examples."
},
{
"code": null,
"e": 43079,
"s": 42930,
"text": "The AnchorLayout aligns its children to a border (top, bottom, left, right) or center. The class given below is used to implement the anchor layout."
},
{
"code": null,
"e": 43114,
"s": 43079,
"text": "kivy.uix.anchorlayout.AnchorLayout"
},
{
"code": null,
"e": 43163,
"s": 43114,
"text": "AnchorLayout can be initialized with parameters:"
},
{
"code": null,
"e": 43295,
"s": 43163,
"text": "anchor_x\nParameters can be passed: “left”, “right” and “center”.\n\nanchor_y\nParameters can be passed:“top”, “bottom” and “center”.\n"
},
{
"code": null,
"e": 43369,
"s": 43295,
"text": "to select the place where the widgets are placed in the parent container."
},
{
"code": null,
"e": 43455,
"s": 43369,
"text": "There are 9 different layout regions where the Anchorlayout can be placed for effect:"
},
{
"code": null,
"e": 43575,
"s": 43455,
"text": "Top-left, top-center, top-right, center-left, center-center, center-right, bottom-left, bottom-center and bottom-right."
},
{
"code": null,
"e": 43684,
"s": 43575,
"text": "Note: Remember adding multiple widgets to an anchor layout, only positions the widgets at the same location."
},
{
"code": null,
"e": 43898,
"s": 43684,
"text": "Basic Approach:\n\n1) import kivy\n2) import kivyApp\n4) import Anchorlayout\n5) Set minimum version(optional)\n6) create App class\n7) return Layout/widget/Class(according to requirement)\n8) Run an instance of the class"
},
{
"code": null,
"e": 43951,
"s": 43898,
"text": " Implementation of the Approach (with some Styling):"
},
{
"code": null,
"e": 43991,
"s": 43951,
"text": "1) anchor_x=’right’, anchor_y=’bottom’:"
},
{
"code": "# Sample Python application demonstrating# the working of AnchorLayout in Kivy # Module imports # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # The AnchorLayout aligns its children to a border# (top, bottom, left, right) or centerfrom kivy.uix.anchorlayout import AnchorLayout # BoxLayout arranges children in a vertical or horizontal box.# or help to put the childrens at the desired location.from kivy.uix.boxlayout import BoxLayout # creates the button in kivy # if not imported shows the errorfrom kivy.uix.button import Button # A Kivy app demonstrating the working of anchor layoutclass AnchorLayoutApp(App): def build(self): # Anchor Layout1 layout = AnchorLayout( anchor_x ='right', anchor_y ='bottom') btn = Button(text ='Hello World', size_hint =(.3, .3), background_color =(1.0, 0.0, 0.0, 1.0)) layout.add_widget(btn) return layout # creating the object root for AnchorLayoutApp() class root = AnchorLayoutApp()# Run the Kivy approot.run()",
"e": 45151,
"s": 43991,
"text": null
},
{
"code": null,
"e": 45159,
"s": 45151,
"text": "Output:"
},
{
"code": null,
"e": 45396,
"s": 45159,
"text": "If you want to change the positions of the AnchorLayouts then just replace the class code in the above code with below or you can change the anchor_x and anchor_y with any of the parameters to make any 9 combinations as described above."
},
{
"code": null,
"e": 45433,
"s": 45396,
"text": "2) anchor_x=’right’, anchor_y=’top’:"
},
{
"code": "# A Kivy app demonstrating the working of anchor layoutclass AnchorLayoutApp(App): def build(self): # Anchor Layout1 layout = AnchorLayout( anchor_x ='right', anchor_y ='top') btn = Button(text ='Hello World', size_hint =(.3, .3), background_color =(1.0, 0.0, 1.0, 1.0)) layout.add_widget(btn) return layout ",
"e": 45849,
"s": 45433,
"text": null
},
{
"code": null,
"e": 45857,
"s": 45849,
"text": "Output:"
},
{
"code": null,
"e": 45902,
"s": 45857,
"text": "3) anchor_x=’center’, anchor_y=’top’:Output:"
},
{
"code": null,
"e": 45945,
"s": 45902,
"text": "4) anchor_x=’left’, anchor_y=’top’:Output:"
},
{
"code": null,
"e": 45991,
"s": 45945,
"text": "5) anchor_x=’left’, anchor_y=’bottom’:Output:"
},
{
"code": null,
"e": 46037,
"s": 45991,
"text": "6) anchor_x=’left’, anchor_y=’center’:Output:"
},
{
"code": null,
"e": 46085,
"s": 46037,
"text": "7) anchor_x=’center’, anchor_y=’center’:Output:"
},
{
"code": null,
"e": 46133,
"s": 46085,
"text": "8) anchor_x=’center’, anchor_y=’bottom’:Output:"
},
{
"code": null,
"e": 46180,
"s": 46133,
"text": "9) anchor_x=’right’, anchor_y=’center’:Output:"
},
{
"code": null,
"e": 46194,
"s": 46180,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 46205,
"s": 46194,
"text": "Python-gui"
},
{
"code": null,
"e": 46217,
"s": 46205,
"text": "Python-kivy"
},
{
"code": null,
"e": 46224,
"s": 46217,
"text": "Python"
},
{
"code": null,
"e": 46322,
"s": 46224,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 46350,
"s": 46322,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 46400,
"s": 46350,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 46422,
"s": 46400,
"text": "Python map() function"
},
{
"code": null,
"e": 46466,
"s": 46422,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 46501,
"s": 46466,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 46533,
"s": 46501,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 46555,
"s": 46533,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 46597,
"s": 46555,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 46627,
"s": 46597,
"text": "Iterate over a list in Python"
}
] |
Python | Concatenate two lists element-wise - GeeksforGeeks
|
28 Jan, 2019
Sometimes we come across this type of problem in which we require to leave each element of one list with the other. This type of problems usually occurs in developments in which we have the combined information, like names and surnames in different lists. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + zip()List comprehension does the task of concatenating the similar index elements. The task of zip function is concatenating the resultant string into a single list and return list.
# Python3 code to demonstrate # interlist element concatenation# using list comprehension + zip() # initializing lists test_list1 = ["Geeksfor", "i", "be"]test_list2 = ['Geeks', 's', 'st'] # printing original listsprint ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2)) # using list comprehension + zip()# interlist element concatenationres = [i + j for i, j in zip(test_list1, test_list2)] # printing result print ("The list after element concatenation is : " + str(res))
The original list 1 is : ['Geeksfor', 'i', 'be']
The original list 2 is : ['Geeks', 's', 'st']
The list after element concatenation is : ['GeeksforGeeks', 'is', 'best']
Method #2 : Using map() + lambda + zip()The task of mapping each index element with each other is performed by map function in this method and the functionality of addition is performed by lambda function. This method works only in Python2.
# Python code to demonstrate # interlist element concatenation# using map() + lambda + zip() # initializing lists test_list1 = ["Geeksfor", "i", "be"]test_list2 = ['Geeks', 's', 'st'] # printing original listsprint ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2)) # using map() + lambda + zip()# interlist element concatenationres = list(map(lambda(i, j): i + j, zip(test_list1, test_list2))) # printing result print ("The list after element concatenation is : " + str(res))
The original list 1 is : ['Geeksfor', 'i', 'be']
The original list 2 is : ['Geeks', 's', 'st']
The list after element concatenation is : ['GeeksforGeeks', 'is', 'best']
Python list-programs
python-list
Python
Python Programs
python-list
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 ?
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 25613,
"s": 25585,
"text": "\n28 Jan, 2019"
},
{
"code": null,
"e": 25933,
"s": 25613,
"text": "Sometimes we come across this type of problem in which we require to leave each element of one list with the other. This type of problems usually occurs in developments in which we have the combined information, like names and surnames in different lists. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 26154,
"s": 25933,
"text": "Method #1 : Using list comprehension + zip()List comprehension does the task of concatenating the similar index elements. The task of zip function is concatenating the resultant string into a single list and return list."
},
{
"code": "# Python3 code to demonstrate # interlist element concatenation# using list comprehension + zip() # initializing lists test_list1 = [\"Geeksfor\", \"i\", \"be\"]test_list2 = ['Geeks', 's', 'st'] # printing original listsprint (\"The original list 1 is : \" + str(test_list1))print (\"The original list 2 is : \" + str(test_list2)) # using list comprehension + zip()# interlist element concatenationres = [i + j for i, j in zip(test_list1, test_list2)] # printing result print (\"The list after element concatenation is : \" + str(res))",
"e": 26684,
"s": 26154,
"text": null
},
{
"code": null,
"e": 26854,
"s": 26684,
"text": "The original list 1 is : ['Geeksfor', 'i', 'be']\nThe original list 2 is : ['Geeks', 's', 'st']\nThe list after element concatenation is : ['GeeksforGeeks', 'is', 'best']\n"
},
{
"code": null,
"e": 27096,
"s": 26854,
"text": " Method #2 : Using map() + lambda + zip()The task of mapping each index element with each other is performed by map function in this method and the functionality of addition is performed by lambda function. This method works only in Python2."
},
{
"code": "# Python code to demonstrate # interlist element concatenation# using map() + lambda + zip() # initializing lists test_list1 = [\"Geeksfor\", \"i\", \"be\"]test_list2 = ['Geeks', 's', 'st'] # printing original listsprint (\"The original list 1 is : \" + str(test_list1))print (\"The original list 2 is : \" + str(test_list2)) # using map() + lambda + zip()# interlist element concatenationres = list(map(lambda(i, j): i + j, zip(test_list1, test_list2))) # printing result print (\"The list after element concatenation is : \" + str(res))",
"e": 27629,
"s": 27096,
"text": null
},
{
"code": null,
"e": 27799,
"s": 27629,
"text": "The original list 1 is : ['Geeksfor', 'i', 'be']\nThe original list 2 is : ['Geeks', 's', 'st']\nThe list after element concatenation is : ['GeeksforGeeks', 'is', 'best']\n"
},
{
"code": null,
"e": 27820,
"s": 27799,
"text": "Python list-programs"
},
{
"code": null,
"e": 27832,
"s": 27820,
"text": "python-list"
},
{
"code": null,
"e": 27839,
"s": 27832,
"text": "Python"
},
{
"code": null,
"e": 27855,
"s": 27839,
"text": "Python Programs"
},
{
"code": null,
"e": 27867,
"s": 27855,
"text": "python-list"
},
{
"code": null,
"e": 27965,
"s": 27867,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27983,
"s": 27965,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28018,
"s": 27983,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28050,
"s": 28018,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28092,
"s": 28050,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28118,
"s": 28092,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28161,
"s": 28118,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28183,
"s": 28161,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28222,
"s": 28183,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28268,
"s": 28222,
"text": "Python | Split string into list of characters"
}
] |
Check if number is palindrome or not in base B - GeeksforGeeks
|
17 Mar, 2021
Given an integer N, the task is to check if
(N in base B) is palindrome or not.
Examples:
Input: N = 5, B = 2 Output: Yes Explanation: (5)10 = (101)2 which is palindrome. Therefore, the required output is Yes.Input: N = 4, B = 2 Output: No
Approach: The problem can be solved by checking if the decimal value of the reverse of
is equal to N or not. Follow the steps below to solve the problem.
Initialize the variable, rev = 0 to store the reverse of N.Extract the digits of
Initialize the variable, rev = 0 to store the reverse of N.
Extract the digits of
by N % B.For each digit of
by N % B.
For each digit of
Update rev= rev * B + N % BFinally, check if N is equal to rev or not
Update rev= rev * B + N % B
Finally, check if N is equal to rev or not
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 check if N in// base B is palindrome or notint checkPalindromeB(int N, int B){ // Stores the reverse of N int rev = 0; // Stores the value of N int N1 = N; // Extract all the digits of N while (N1) { // Generate its reverse rev = rev * B + N1 % B; N1 = N1 / B; } return N == rev;} // Driver Codeint main(){ int N = 5, B = 2; if (checkPalindromeB(N, B)) { cout << "Yes"; } else { cout << "No"; }}
// Java program to implement// the above approachclass GFG{ // Function to check if N in// base B is palindrome or notstatic boolean checkPalindromeB(int N, int B){ // Stores the reverse of N int rev = 0; // Stores the value of N int N1 = N; // Extract all the digits of N while (N1 > 0) { // Generate its reverse rev = rev * B + N1 % B; N1 = N1 / B; } return N == rev;} // Driver codepublic static void main(String[] args){ int N = 5, B = 2; if (checkPalindromeB(N, B)) { System.out.print("Yes"); } else { System.out.print("No"); }}} // This code is contributed by Dewanti
# Python3 program to implement# the above approach # Function to check if N in# base B is palindrome or notdef checkPalindromeB(N, B): # Stores the reverse of N rev = 0; # Stores the value of N N1 = N; # Extract all the digits of N while (N1 > 0): # Generate its reverse rev = rev * B + N1 % B; N1 = N1 // B; return N == rev; # Driver codeif __name__ == '__main__': N = 5; B = 2; if (checkPalindromeB(N, B)): print("Yes"); else: print("No"); # This code is contributed by Princi Singh
// C# program to implement// the above approachusing System; class GFG{ // Function to check if N in// base B is palindrome or notstatic bool checkPalindromeB(int N, int B){ // Stores the reverse of N int rev = 0; // Stores the value of N int N1 = N; // Extract all the digits of N while (N1 > 0) { // Generate its reverse rev = rev * B + N1 % B; N1 = N1 / B; } return N == rev;} // Driver codepublic static void Main(String[] args){ int N = 5, B = 2; if (checkPalindromeB(N, B)) { Console.Write("Yes"); } else { Console.Write("No"); }}} // This code is contributed by Amit Katiyar
<script> // Javascript program to implement// the above approach // Function to check if N in// base B is palindrome or notfunction checkPalindromeB(N, B){ // Stores the reverse of N var rev = 0; // Stores the value of N var N1 = N; // Extract all the digits of N while (N1) { // Generate its reverse rev = rev * B + N1 % B; N1 = parseInt(N1 / B); } return N == rev;} // Driver Codevar N = 5, B = 2;if (checkPalindromeB(N, B)) { document.write("Yes");}else { document.write("No");} </script>
Yes
Time Complexity:O(logBN) Auxiliary Space:O(1)
dewantipandeydp
amit143katiyar
princi singh
noob2000
palindrome
Reverse
Mathematical
Mathematical
palindrome
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Modular multiplicative inverse
Count all possible paths from top left to bottom right of a mXn matrix
Fizz Buzz Implementation
Check if a number is Palindrome
Program to multiply two matrices
Merge two sorted arrays with O(1) extra space
Generate all permutation of a set in Python
Count ways to reach the n'th stair
|
[
{
"code": null,
"e": 25937,
"s": 25909,
"text": "\n17 Mar, 2021"
},
{
"code": null,
"e": 25982,
"s": 25937,
"text": "Given an integer N, the task is to check if "
},
{
"code": null,
"e": 26020,
"s": 25984,
"text": "(N in base B) is palindrome or not."
},
{
"code": null,
"e": 26033,
"s": 26022,
"text": "Examples: "
},
{
"code": null,
"e": 26187,
"s": 26035,
"text": "Input: N = 5, B = 2 Output: Yes Explanation: (5)10 = (101)2 which is palindrome. Therefore, the required output is Yes.Input: N = 4, B = 2 Output: No "
},
{
"code": null,
"e": 26277,
"s": 26189,
"text": "Approach: The problem can be solved by checking if the decimal value of the reverse of "
},
{
"code": null,
"e": 26347,
"s": 26279,
"text": "is equal to N or not. Follow the steps below to solve the problem. "
},
{
"code": null,
"e": 26430,
"s": 26349,
"text": "Initialize the variable, rev = 0 to store the reverse of N.Extract the digits of"
},
{
"code": null,
"e": 26490,
"s": 26430,
"text": "Initialize the variable, rev = 0 to store the reverse of N."
},
{
"code": null,
"e": 26512,
"s": 26490,
"text": "Extract the digits of"
},
{
"code": null,
"e": 26539,
"s": 26512,
"text": "by N % B.For each digit of"
},
{
"code": null,
"e": 26549,
"s": 26539,
"text": "by N % B."
},
{
"code": null,
"e": 26567,
"s": 26549,
"text": "For each digit of"
},
{
"code": null,
"e": 26637,
"s": 26567,
"text": "Update rev= rev * B + N % BFinally, check if N is equal to rev or not"
},
{
"code": null,
"e": 26665,
"s": 26637,
"text": "Update rev= rev * B + N % B"
},
{
"code": null,
"e": 26708,
"s": 26665,
"text": "Finally, check if N is equal to rev or not"
},
{
"code": null,
"e": 26762,
"s": 26710,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26768,
"s": 26764,
"text": "C++"
},
{
"code": null,
"e": 26773,
"s": 26768,
"text": "Java"
},
{
"code": null,
"e": 26781,
"s": 26773,
"text": "Python3"
},
{
"code": null,
"e": 26784,
"s": 26781,
"text": "C#"
},
{
"code": null,
"e": 26795,
"s": 26784,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to check if N in// base B is palindrome or notint checkPalindromeB(int N, int B){ // Stores the reverse of N int rev = 0; // Stores the value of N int N1 = N; // Extract all the digits of N while (N1) { // Generate its reverse rev = rev * B + N1 % B; N1 = N1 / B; } return N == rev;} // Driver Codeint main(){ int N = 5, B = 2; if (checkPalindromeB(N, B)) { cout << \"Yes\"; } else { cout << \"No\"; }}",
"e": 27377,
"s": 26795,
"text": null
},
{
"code": "// Java program to implement// the above approachclass GFG{ // Function to check if N in// base B is palindrome or notstatic boolean checkPalindromeB(int N, int B){ // Stores the reverse of N int rev = 0; // Stores the value of N int N1 = N; // Extract all the digits of N while (N1 > 0) { // Generate its reverse rev = rev * B + N1 % B; N1 = N1 / B; } return N == rev;} // Driver codepublic static void main(String[] args){ int N = 5, B = 2; if (checkPalindromeB(N, B)) { System.out.print(\"Yes\"); } else { System.out.print(\"No\"); }}} // This code is contributed by Dewanti",
"e": 28086,
"s": 27377,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to check if N in# base B is palindrome or notdef checkPalindromeB(N, B): # Stores the reverse of N rev = 0; # Stores the value of N N1 = N; # Extract all the digits of N while (N1 > 0): # Generate its reverse rev = rev * B + N1 % B; N1 = N1 // B; return N == rev; # Driver codeif __name__ == '__main__': N = 5; B = 2; if (checkPalindromeB(N, B)): print(\"Yes\"); else: print(\"No\"); # This code is contributed by Princi Singh",
"e": 28646,
"s": 28086,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System; class GFG{ // Function to check if N in// base B is palindrome or notstatic bool checkPalindromeB(int N, int B){ // Stores the reverse of N int rev = 0; // Stores the value of N int N1 = N; // Extract all the digits of N while (N1 > 0) { // Generate its reverse rev = rev * B + N1 % B; N1 = N1 / B; } return N == rev;} // Driver codepublic static void Main(String[] args){ int N = 5, B = 2; if (checkPalindromeB(N, B)) { Console.Write(\"Yes\"); } else { Console.Write(\"No\"); }}} // This code is contributed by Amit Katiyar",
"e": 29360,
"s": 28646,
"text": null
},
{
"code": "<script> // Javascript program to implement// the above approach // Function to check if N in// base B is palindrome or notfunction checkPalindromeB(N, B){ // Stores the reverse of N var rev = 0; // Stores the value of N var N1 = N; // Extract all the digits of N while (N1) { // Generate its reverse rev = rev * B + N1 % B; N1 = parseInt(N1 / B); } return N == rev;} // Driver Codevar N = 5, B = 2;if (checkPalindromeB(N, B)) { document.write(\"Yes\");}else { document.write(\"No\");} </script>",
"e": 29907,
"s": 29360,
"text": null
},
{
"code": null,
"e": 29911,
"s": 29907,
"text": "Yes"
},
{
"code": null,
"e": 29959,
"s": 29913,
"text": "Time Complexity:O(logBN) Auxiliary Space:O(1)"
},
{
"code": null,
"e": 29975,
"s": 29959,
"text": "dewantipandeydp"
},
{
"code": null,
"e": 29990,
"s": 29975,
"text": "amit143katiyar"
},
{
"code": null,
"e": 30003,
"s": 29990,
"text": "princi singh"
},
{
"code": null,
"e": 30012,
"s": 30003,
"text": "noob2000"
},
{
"code": null,
"e": 30023,
"s": 30012,
"text": "palindrome"
},
{
"code": null,
"e": 30031,
"s": 30023,
"text": "Reverse"
},
{
"code": null,
"e": 30044,
"s": 30031,
"text": "Mathematical"
},
{
"code": null,
"e": 30057,
"s": 30044,
"text": "Mathematical"
},
{
"code": null,
"e": 30068,
"s": 30057,
"text": "palindrome"
},
{
"code": null,
"e": 30076,
"s": 30068,
"text": "Reverse"
},
{
"code": null,
"e": 30174,
"s": 30076,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30218,
"s": 30174,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 30260,
"s": 30218,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 30291,
"s": 30260,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 30362,
"s": 30291,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 30387,
"s": 30362,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 30419,
"s": 30387,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 30452,
"s": 30419,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 30498,
"s": 30452,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 30542,
"s": 30498,
"text": "Generate all permutation of a set in Python"
}
] |
How to iterate over OrderedDict in Python? - GeeksforGeeks
|
24 Jan, 2021
An OrderedDict is a subclass that preserves the order in which the keys are inserted. The difference between OrderedDict and Dict is that the normal Dict does not keep a track of the way the elements are inserted whereas the OrderedDict remembers the order in which the elements are inserted.
Explanation:
Input : original_dict = { ‘a’:1, ‘b’:2, ‘c’:3, ‘d’:4 }
Output: a 1 b 2 c 3 d 4
Input: original_dict = {‘sayantan’:9, ‘sanjoy’:7, ‘suresh’:5, ‘rony’:2}
Output: sayantan 9 sanjoy 7 suresh 5 rony 2
Steps to perform iteration through Ordereddict in python :
Import the ordereddict from collection in python.
Take the input of the ordereddict.
Iterate through the ordereddict in either of the two approaches given below:
Approach #1
Iterating through the ordereddict and printing the value.
Python3
# Python code to implement iteration# over the ordereddict # import required modulesfrom collections import OrderedDict # create dictionaryod = OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4}) # iterating over the ordereddictfor key, value in od.items(): print(key, value)
Output :
a 1
b 2
c 3
d 4
The above code can also be written as –
Python3
# Python code to implement iteration# over the ordereddict # import required modulesfrom collections import OrderedDict # create dictionaryod = OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4}) # iterating over the ordereddictfor item in od.items(): print(*item)
Output :
a 1
b 2
c 3
d 4
Approach #2
Iterating through the enumerate objects and printing the value. The enumerate() method is a method in which it adds a counter to the iterable object and returns the value in the form of an enumerate object.
Python3
# Python code to implement iteration# over the ordereddict # import required modulesfrom collections import OrderedDict # create dictionaryod = OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4}) # iterating through the enumerate objectsfor i, (key, value) in enumerate(od.items()): print(key, value)
Output:
a 1
b 2
c 3
d 4
Picked
Python collections-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25562,
"s": 25534,
"text": "\n24 Jan, 2021"
},
{
"code": null,
"e": 25856,
"s": 25562,
"text": "An OrderedDict is a subclass that preserves the order in which the keys are inserted. The difference between OrderedDict and Dict is that the normal Dict does not keep a track of the way the elements are inserted whereas the OrderedDict remembers the order in which the elements are inserted. "
},
{
"code": null,
"e": 25870,
"s": 25856,
"text": "Explanation: "
},
{
"code": null,
"e": 25925,
"s": 25870,
"text": "Input : original_dict = { ‘a’:1, ‘b’:2, ‘c’:3, ‘d’:4 }"
},
{
"code": null,
"e": 25949,
"s": 25925,
"text": "Output: a 1 b 2 c 3 d 4"
},
{
"code": null,
"e": 26021,
"s": 25949,
"text": "Input: original_dict = {‘sayantan’:9, ‘sanjoy’:7, ‘suresh’:5, ‘rony’:2}"
},
{
"code": null,
"e": 26065,
"s": 26021,
"text": "Output: sayantan 9 sanjoy 7 suresh 5 rony 2"
},
{
"code": null,
"e": 26125,
"s": 26065,
"text": "Steps to perform iteration through Ordereddict in python : "
},
{
"code": null,
"e": 26175,
"s": 26125,
"text": "Import the ordereddict from collection in python."
},
{
"code": null,
"e": 26210,
"s": 26175,
"text": "Take the input of the ordereddict."
},
{
"code": null,
"e": 26287,
"s": 26210,
"text": "Iterate through the ordereddict in either of the two approaches given below:"
},
{
"code": null,
"e": 26299,
"s": 26287,
"text": "Approach #1"
},
{
"code": null,
"e": 26357,
"s": 26299,
"text": "Iterating through the ordereddict and printing the value."
},
{
"code": null,
"e": 26365,
"s": 26357,
"text": "Python3"
},
{
"code": "# Python code to implement iteration# over the ordereddict # import required modulesfrom collections import OrderedDict # create dictionaryod = OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4}) # iterating over the ordereddictfor key, value in od.items(): print(key, value)",
"e": 26641,
"s": 26365,
"text": null
},
{
"code": null,
"e": 26651,
"s": 26641,
"text": "Output : "
},
{
"code": null,
"e": 26667,
"s": 26651,
"text": "a 1\nb 2\nc 3\nd 4"
},
{
"code": null,
"e": 26708,
"s": 26667,
"text": "The above code can also be written as – "
},
{
"code": null,
"e": 26716,
"s": 26708,
"text": "Python3"
},
{
"code": "# Python code to implement iteration# over the ordereddict # import required modulesfrom collections import OrderedDict # create dictionaryod = OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4}) # iterating over the ordereddictfor item in od.items(): print(*item)",
"e": 26981,
"s": 26716,
"text": null
},
{
"code": null,
"e": 26991,
"s": 26981,
"text": "Output : "
},
{
"code": null,
"e": 27007,
"s": 26991,
"text": "a 1\nb 2\nc 3\nd 4"
},
{
"code": null,
"e": 27019,
"s": 27007,
"text": "Approach #2"
},
{
"code": null,
"e": 27227,
"s": 27019,
"text": "Iterating through the enumerate objects and printing the value. The enumerate() method is a method in which it adds a counter to the iterable object and returns the value in the form of an enumerate object. "
},
{
"code": null,
"e": 27235,
"s": 27227,
"text": "Python3"
},
{
"code": "# Python code to implement iteration# over the ordereddict # import required modulesfrom collections import OrderedDict # create dictionaryod = OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4}) # iterating through the enumerate objectsfor i, (key, value) in enumerate(od.items()): print(key, value)",
"e": 27536,
"s": 27235,
"text": null
},
{
"code": null,
"e": 27544,
"s": 27536,
"text": "Output:"
},
{
"code": null,
"e": 27560,
"s": 27544,
"text": "a 1\nb 2\nc 3\nd 4"
},
{
"code": null,
"e": 27567,
"s": 27560,
"text": "Picked"
},
{
"code": null,
"e": 27593,
"s": 27567,
"text": "Python collections-module"
},
{
"code": null,
"e": 27600,
"s": 27593,
"text": "Python"
},
{
"code": null,
"e": 27698,
"s": 27600,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27730,
"s": 27698,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27772,
"s": 27730,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27814,
"s": 27772,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27870,
"s": 27814,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27897,
"s": 27870,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27936,
"s": 27897,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27967,
"s": 27936,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27989,
"s": 27967,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28018,
"s": 27989,
"text": "Create a directory in Python"
}
] |
Dynamic Method Dispatch or Runtime Polymorphism in Java - GeeksforGeeks
|
07 Sep, 2018
Prerequisite: Overriding in java, Inheritance
Method overriding is one of the ways in which Java supports Runtime Polymorphism. Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time.
When an overridden method is called through a superclass reference, Java determines which version(superclass/subclasses) of that method is to be executed based upon the type of the object being referred to at the time the call occurs. Thus, this determination is made at run time.
At run-time, it depends on the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed
A superclass reference variable can refer to a subclass object. This is also known as upcasting. Java uses this fact to resolve calls to overridden methods at run time.
Therefore, if a superclass contains a method that is overridden by a subclass, then when different types of objects are referred to through a superclass reference variable, different versions of the method are executed. Here is an example that illustrates dynamic method dispatch:
// A Java program to illustrate Dynamic Method// Dispatch using hierarchical inheritanceclass A{ void m1() { System.out.println("Inside A's m1 method"); }} class B extends A{ // overriding m1() void m1() { System.out.println("Inside B's m1 method"); }} class C extends A{ // overriding m1() void m1() { System.out.println("Inside C's m1 method"); }} // Driver classclass Dispatch{ public static void main(String args[]) { // object of type A A a = new A(); // object of type B B b = new B(); // object of type C C c = new C(); // obtain a reference of type A A ref; // ref refers to an A object ref = a; // calling A's version of m1() ref.m1(); // now ref refers to a B object ref = b; // calling B's version of m1() ref.m1(); // now ref refers to a C object ref = c; // calling C's version of m1() ref.m1(); }}
Output:
Inside A's m1 method
Inside B's m1 method
Inside C's m1 method
Explanation :
The above program creates one superclass called A and it’s two subclasses B and C. These subclasses overrides m1( ) method.
Inside the main() method in Dispatch class, initially objects of type A, B, and C are declared.A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
Now a reference of type A, called ref, is also declared, initially it will point to null.A ref; // obtain a reference of type A
Now we are assigning a reference to each type of object (either A’s or B’s or C’s) to ref, one-by-one, and uses that reference to invoke m1( ). As the output shows, the version of m1( ) executed is determined by the type of object being referred to at the time of the call.ref = a; // r refers to an A object
ref.m1(); // calling A's version of m1()
ref = b; // now r refers to a B object
ref.m1(); // calling B's version of m1()
ref = c; // now r refers to a C object
ref.m1(); // calling C's version of m1()
Inside the main() method in Dispatch class, initially objects of type A, B, and C are declared.A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
Now a reference of type A, called ref, is also declared, initially it will point to null.A ref; // obtain a reference of type A
A ref; // obtain a reference of type A
Now we are assigning a reference to each type of object (either A’s or B’s or C’s) to ref, one-by-one, and uses that reference to invoke m1( ). As the output shows, the version of m1( ) executed is determined by the type of object being referred to at the time of the call.ref = a; // r refers to an A object
ref.m1(); // calling A's version of m1()
ref = b; // now r refers to a B object
ref.m1(); // calling B's version of m1()
ref = c; // now r refers to a C object
ref.m1(); // calling C's version of m1()
ref = a; // r refers to an A object
ref.m1(); // calling A's version of m1()
ref = b; // now r refers to a B object
ref.m1(); // calling B's version of m1()
ref = c; // now r refers to a C object
ref.m1(); // calling C's version of m1()
Runtime Polymorphism with Data Members
In Java, we can override methods only, not the variables(data members), so runtime polymorphism cannot be achieved by data members. For example :
// Java program to illustrate the fact that// runtime polymorphism cannot be achieved// by data members // class Aclass A{ int x = 10;} // class Bclass B extends A{ int x = 20;} // Driver classpublic class Test{ public static void main(String args[]) { A a = new B(); // object of type B // Data member of class A will be accessed System.out.println(a.x); }}
Output:
10
Explanation : In above program, both the class A(super class) and B(sub class) have a common variable ‘x’. Now we make object of class B, referred by ‘a’ which is of type of class A. Since variables are not overridden, so the statement “a.x” will always refer to data member of super class.
Advantages of Dynamic Method Dispatch
Dynamic method dispatch allow Java to support overriding of methods which is central for run-time polymorphism.It allows a class to specify methods that will be common to all of its derivatives, while allowing subclasses to define the specific implementation of some or all of those methods.It also allow subclasses to add its specific methods subclasses to define the specific implementation of some.
Dynamic method dispatch allow Java to support overriding of methods which is central for run-time polymorphism.
It allows a class to specify methods that will be common to all of its derivatives, while allowing subclasses to define the specific implementation of some or all of those methods.
It also allow subclasses to add its specific methods subclasses to define the specific implementation of some.
Static vs Dynamic binding
Static binding is done during compile-time while dynamic binding is done during run-time.
private, final and static methods and variables uses static binding and bonded by compiler while overridden methods are bonded during runtime based upon type of runtime object
This article is contributed by Gaurav Miglani. 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.
java-inheritance
Java
School Programming
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Stream In Java
How to iterate any Map in Java
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects
|
[
{
"code": null,
"e": 30197,
"s": 30169,
"text": "\n07 Sep, 2018"
},
{
"code": null,
"e": 30243,
"s": 30197,
"text": "Prerequisite: Overriding in java, Inheritance"
},
{
"code": null,
"e": 30457,
"s": 30243,
"text": "Method overriding is one of the ways in which Java supports Runtime Polymorphism. Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time."
},
{
"code": null,
"e": 30738,
"s": 30457,
"text": "When an overridden method is called through a superclass reference, Java determines which version(superclass/subclasses) of that method is to be executed based upon the type of the object being referred to at the time the call occurs. Thus, this determination is made at run time."
},
{
"code": null,
"e": 30918,
"s": 30738,
"text": "At run-time, it depends on the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed"
},
{
"code": null,
"e": 31087,
"s": 30918,
"text": "A superclass reference variable can refer to a subclass object. This is also known as upcasting. Java uses this fact to resolve calls to overridden methods at run time."
},
{
"code": null,
"e": 31368,
"s": 31087,
"text": "Therefore, if a superclass contains a method that is overridden by a subclass, then when different types of objects are referred to through a superclass reference variable, different versions of the method are executed. Here is an example that illustrates dynamic method dispatch:"
},
{
"code": "// A Java program to illustrate Dynamic Method// Dispatch using hierarchical inheritanceclass A{ void m1() { System.out.println(\"Inside A's m1 method\"); }} class B extends A{ // overriding m1() void m1() { System.out.println(\"Inside B's m1 method\"); }} class C extends A{ // overriding m1() void m1() { System.out.println(\"Inside C's m1 method\"); }} // Driver classclass Dispatch{ public static void main(String args[]) { // object of type A A a = new A(); // object of type B B b = new B(); // object of type C C c = new C(); // obtain a reference of type A A ref; // ref refers to an A object ref = a; // calling A's version of m1() ref.m1(); // now ref refers to a B object ref = b; // calling B's version of m1() ref.m1(); // now ref refers to a C object ref = c; // calling C's version of m1() ref.m1(); }}",
"e": 32412,
"s": 31368,
"text": null
},
{
"code": null,
"e": 32420,
"s": 32412,
"text": "Output:"
},
{
"code": null,
"e": 32484,
"s": 32420,
"text": "Inside A's m1 method\nInside B's m1 method\nInside C's m1 method\n"
},
{
"code": null,
"e": 32498,
"s": 32484,
"text": "Explanation :"
},
{
"code": null,
"e": 32622,
"s": 32498,
"text": "The above program creates one superclass called A and it’s two subclasses B and C. These subclasses overrides m1( ) method."
},
{
"code": null,
"e": 33461,
"s": 32622,
"text": "Inside the main() method in Dispatch class, initially objects of type A, B, and C are declared.A a = new A(); // object of type A\nB b = new B(); // object of type B\nC c = new C(); // object of type C\nNow a reference of type A, called ref, is also declared, initially it will point to null.A ref; // obtain a reference of type A\nNow we are assigning a reference to each type of object (either A’s or B’s or C’s) to ref, one-by-one, and uses that reference to invoke m1( ). As the output shows, the version of m1( ) executed is determined by the type of object being referred to at the time of the call.ref = a; // r refers to an A object\nref.m1(); // calling A's version of m1()\nref = b; // now r refers to a B object\nref.m1(); // calling B's version of m1()\nref = c; // now r refers to a C object\nref.m1(); // calling C's version of m1()\n"
},
{
"code": null,
"e": 33662,
"s": 33461,
"text": "Inside the main() method in Dispatch class, initially objects of type A, B, and C are declared.A a = new A(); // object of type A\nB b = new B(); // object of type B\nC c = new C(); // object of type C\n"
},
{
"code": null,
"e": 33768,
"s": 33662,
"text": "A a = new A(); // object of type A\nB b = new B(); // object of type B\nC c = new C(); // object of type C\n"
},
{
"code": null,
"e": 33897,
"s": 33768,
"text": "Now a reference of type A, called ref, is also declared, initially it will point to null.A ref; // obtain a reference of type A\n"
},
{
"code": null,
"e": 33937,
"s": 33897,
"text": "A ref; // obtain a reference of type A\n"
},
{
"code": null,
"e": 34448,
"s": 33937,
"text": "Now we are assigning a reference to each type of object (either A’s or B’s or C’s) to ref, one-by-one, and uses that reference to invoke m1( ). As the output shows, the version of m1( ) executed is determined by the type of object being referred to at the time of the call.ref = a; // r refers to an A object\nref.m1(); // calling A's version of m1()\nref = b; // now r refers to a B object\nref.m1(); // calling B's version of m1()\nref = c; // now r refers to a C object\nref.m1(); // calling C's version of m1()\n"
},
{
"code": null,
"e": 34526,
"s": 34448,
"text": "ref = a; // r refers to an A object\nref.m1(); // calling A's version of m1()\n"
},
{
"code": null,
"e": 34607,
"s": 34526,
"text": "ref = b; // now r refers to a B object\nref.m1(); // calling B's version of m1()\n"
},
{
"code": null,
"e": 34688,
"s": 34607,
"text": "ref = c; // now r refers to a C object\nref.m1(); // calling C's version of m1()\n"
},
{
"code": null,
"e": 34727,
"s": 34688,
"text": "Runtime Polymorphism with Data Members"
},
{
"code": null,
"e": 34873,
"s": 34727,
"text": "In Java, we can override methods only, not the variables(data members), so runtime polymorphism cannot be achieved by data members. For example :"
},
{
"code": "// Java program to illustrate the fact that// runtime polymorphism cannot be achieved// by data members // class Aclass A{ int x = 10;} // class Bclass B extends A{ int x = 20;} // Driver classpublic class Test{ public static void main(String args[]) { A a = new B(); // object of type B // Data member of class A will be accessed System.out.println(a.x); }}",
"e": 35273,
"s": 34873,
"text": null
},
{
"code": null,
"e": 35281,
"s": 35273,
"text": "Output:"
},
{
"code": null,
"e": 35285,
"s": 35281,
"text": "10\n"
},
{
"code": null,
"e": 35576,
"s": 35285,
"text": "Explanation : In above program, both the class A(super class) and B(sub class) have a common variable ‘x’. Now we make object of class B, referred by ‘a’ which is of type of class A. Since variables are not overridden, so the statement “a.x” will always refer to data member of super class."
},
{
"code": null,
"e": 35614,
"s": 35576,
"text": "Advantages of Dynamic Method Dispatch"
},
{
"code": null,
"e": 36016,
"s": 35614,
"text": "Dynamic method dispatch allow Java to support overriding of methods which is central for run-time polymorphism.It allows a class to specify methods that will be common to all of its derivatives, while allowing subclasses to define the specific implementation of some or all of those methods.It also allow subclasses to add its specific methods subclasses to define the specific implementation of some."
},
{
"code": null,
"e": 36128,
"s": 36016,
"text": "Dynamic method dispatch allow Java to support overriding of methods which is central for run-time polymorphism."
},
{
"code": null,
"e": 36309,
"s": 36128,
"text": "It allows a class to specify methods that will be common to all of its derivatives, while allowing subclasses to define the specific implementation of some or all of those methods."
},
{
"code": null,
"e": 36420,
"s": 36309,
"text": "It also allow subclasses to add its specific methods subclasses to define the specific implementation of some."
},
{
"code": null,
"e": 36446,
"s": 36420,
"text": "Static vs Dynamic binding"
},
{
"code": null,
"e": 36536,
"s": 36446,
"text": "Static binding is done during compile-time while dynamic binding is done during run-time."
},
{
"code": null,
"e": 36712,
"s": 36536,
"text": "private, final and static methods and variables uses static binding and bonded by compiler while overridden methods are bonded during runtime based upon type of runtime object"
},
{
"code": null,
"e": 37014,
"s": 36712,
"text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 37139,
"s": 37014,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 37156,
"s": 37139,
"text": "java-inheritance"
},
{
"code": null,
"e": 37161,
"s": 37156,
"text": "Java"
},
{
"code": null,
"e": 37180,
"s": 37161,
"text": "School Programming"
},
{
"code": null,
"e": 37185,
"s": 37180,
"text": "Java"
},
{
"code": null,
"e": 37283,
"s": 37185,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37327,
"s": 37283,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 37363,
"s": 37327,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 37388,
"s": 37363,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 37403,
"s": 37388,
"text": "Stream In Java"
},
{
"code": null,
"e": 37434,
"s": 37403,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 37452,
"s": 37434,
"text": "Python Dictionary"
},
{
"code": null,
"e": 37468,
"s": 37452,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 37487,
"s": 37468,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 37512,
"s": 37487,
"text": "Reverse a string in Java"
}
] |
Convert a Character to the String in C# - GeeksforGeeks
|
26 May, 2020
Given a character, the task is to character to the string in C#.
Examples:
Input : X = 'a'
Output : string S = "a"
Input : X = 'A'
Output : string S = "A"
Approach: The idea is to use ToString() method, the argument is the character and it returns string converting Unicode character to the string.
// convert the character x
// to string s
public string ToString(IFormatProvider provider);
C#
// C# program to character to the stringusing System; public class GFG{ static string getString(char x) { // Char.ToString() is a System.Char // struct method which is used // to convert the value of this // instance to its equivalent // string representation string str = x.ToString(); return str; } static void Main(string[] args) { char chr = 'A'; Console.WriteLine("Type of "+ chr +" : " + chr.GetType()); string str = getString(chr); Console.WriteLine("Type of "+ str +" : " + str.GetType()); }}
Output:
Type of A : System.Char
Type of A : System.String
CSharp-string
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
Convert String to Character Array in C#
C# | How to insert an element in an Array?
Linked List Implementation in C#
|
[
{
"code": null,
"e": 25547,
"s": 25519,
"text": "\n26 May, 2020"
},
{
"code": null,
"e": 25612,
"s": 25547,
"text": "Given a character, the task is to character to the string in C#."
},
{
"code": null,
"e": 25622,
"s": 25612,
"text": "Examples:"
},
{
"code": null,
"e": 25706,
"s": 25622,
"text": "Input : X = 'a'\nOutput : string S = \"a\"\n\nInput : X = 'A'\nOutput : string S = \"A\"\n"
},
{
"code": null,
"e": 25850,
"s": 25706,
"text": "Approach: The idea is to use ToString() method, the argument is the character and it returns string converting Unicode character to the string."
},
{
"code": null,
"e": 25943,
"s": 25850,
"text": "// convert the character x\n// to string s\npublic string ToString(IFormatProvider provider);\n"
},
{
"code": null,
"e": 25946,
"s": 25943,
"text": "C#"
},
{
"code": "// C# program to character to the stringusing System; public class GFG{ static string getString(char x) { // Char.ToString() is a System.Char // struct method which is used // to convert the value of this // instance to its equivalent // string representation string str = x.ToString(); return str; } static void Main(string[] args) { char chr = 'A'; Console.WriteLine(\"Type of \"+ chr +\" : \" + chr.GetType()); string str = getString(chr); Console.WriteLine(\"Type of \"+ str +\" : \" + str.GetType()); }}",
"e": 26578,
"s": 25946,
"text": null
},
{
"code": null,
"e": 26586,
"s": 26578,
"text": "Output:"
},
{
"code": null,
"e": 26637,
"s": 26586,
"text": "Type of A : System.Char\nType of A : System.String\n"
},
{
"code": null,
"e": 26651,
"s": 26637,
"text": "CSharp-string"
},
{
"code": null,
"e": 26654,
"s": 26651,
"text": "C#"
},
{
"code": null,
"e": 26752,
"s": 26654,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26775,
"s": 26752,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 26803,
"s": 26775,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 26820,
"s": 26803,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 26842,
"s": 26820,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 26871,
"s": 26842,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 26911,
"s": 26871,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 26934,
"s": 26911,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 26974,
"s": 26934,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 27017,
"s": 26974,
"text": "C# | How to insert an element in an Array?"
}
] |
LinkedHashMap removeEldestEntry() Method in Java - GeeksforGeeks
|
03 May, 2021
The java.util.LinkedHashMap.removeEldestEntry() method in Java is used keep a track of whether the map removes any eldest entry from the map. So each time a new element is added to the LinkedHashMap, the eldest entry is removed from the map. This method is generally invoked after the addition of the elements into the map by the use of put() and putall() method.This method allows the map to modify itself as directed by its return value. Although the method is permitted to modify the map directly, if it does so, it must return false which will be indicative of the fact that the map should not attempt any further modification leading to ambiguity. The effects of returning true after modifying the map from within this method are unspecified.This is very useful when the map represents a cache where it allows the map to reduce memory consumption by deleting stale entries one after another. Syntax:
private boolean removeEldestEntry(Map.Entry eldest)
Parameters: The method accepts one parameter eldest that refers to the least recently inserted entry in the map. If the map is of the access order, then eldest refers to the least recently accessed entry and will be removed if this method returns true. If the map was empty prior to the put or putAll invocation, this will be the entry that was just inserted; in other words, if the map contains a single entry, the eldest entry is also the latest and newest entry.Return Value: The map returns true if the eldest entry is to be removed from the map and false if the entry is not to be removed or retained.Below program is used to illustrate the working of java.util.LinkedHashMap.removeEldestEntry() method:
Java
// Java program to illustrate removeEldestEntry()import java.util.*; public class Linked_Hash_Map_Demo { // Refers to the max size of the map following which // the removal takes place of the eldest entry private static final int MAX = 6; public static void main(String[] args) { // Creating the linked hashmap and implementing // removeEldestEntry() to MAX size LinkedHashMap<Integer, String> li_hash_map = new LinkedHashMap<Integer, String>() { protected boolean removeEldestEntry(Map.Entry<Integer, String> eldest) { return size() > MAX; } }; // Adding elements using put() li_hash_map.put(0, "Welcome"); li_hash_map.put(1, "To"); li_hash_map.put(2, "The"); li_hash_map.put(3, "World"); li_hash_map.put(4, "Of"); li_hash_map.put(5, "geeks"); System.out.println("" + li_hash_map); // Adding more elements li_hash_map.put(6, "GeeksforGeeks"); // Displaying the map after adding one more element System.out.println("" + li_hash_map); // Adding more elements li_hash_map.put(7, "Hello"); // Displaying the map after adding one more element System.out.println("" + li_hash_map); }}
{0=Welcome, 1=To, 2=The, 3=World, 4=Of, 5=geeks}
{1=To, 2=The, 3=World, 4=Of, 5=geeks, 6=GeeksforGeeks}
{2=The, 3=World, 4=Of, 5=geeks, 6=GeeksforGeeks, 7=Hello}
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html#removeEldestEntry-java.util.Map.Entry-
simranarora5sos
Java - util package
Java-Collections
Java-LinkedHashMap
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples
Reverse a string in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
|
[
{
"code": null,
"e": 24283,
"s": 24255,
"text": "\n03 May, 2021"
},
{
"code": null,
"e": 25189,
"s": 24283,
"text": "The java.util.LinkedHashMap.removeEldestEntry() method in Java is used keep a track of whether the map removes any eldest entry from the map. So each time a new element is added to the LinkedHashMap, the eldest entry is removed from the map. This method is generally invoked after the addition of the elements into the map by the use of put() and putall() method.This method allows the map to modify itself as directed by its return value. Although the method is permitted to modify the map directly, if it does so, it must return false which will be indicative of the fact that the map should not attempt any further modification leading to ambiguity. The effects of returning true after modifying the map from within this method are unspecified.This is very useful when the map represents a cache where it allows the map to reduce memory consumption by deleting stale entries one after another. Syntax: "
},
{
"code": null,
"e": 25241,
"s": 25189,
"text": "private boolean removeEldestEntry(Map.Entry eldest)"
},
{
"code": null,
"e": 25952,
"s": 25241,
"text": "Parameters: The method accepts one parameter eldest that refers to the least recently inserted entry in the map. If the map is of the access order, then eldest refers to the least recently accessed entry and will be removed if this method returns true. If the map was empty prior to the put or putAll invocation, this will be the entry that was just inserted; in other words, if the map contains a single entry, the eldest entry is also the latest and newest entry.Return Value: The map returns true if the eldest entry is to be removed from the map and false if the entry is not to be removed or retained.Below program is used to illustrate the working of java.util.LinkedHashMap.removeEldestEntry() method: "
},
{
"code": null,
"e": 25957,
"s": 25952,
"text": "Java"
},
{
"code": "// Java program to illustrate removeEldestEntry()import java.util.*; public class Linked_Hash_Map_Demo { // Refers to the max size of the map following which // the removal takes place of the eldest entry private static final int MAX = 6; public static void main(String[] args) { // Creating the linked hashmap and implementing // removeEldestEntry() to MAX size LinkedHashMap<Integer, String> li_hash_map = new LinkedHashMap<Integer, String>() { protected boolean removeEldestEntry(Map.Entry<Integer, String> eldest) { return size() > MAX; } }; // Adding elements using put() li_hash_map.put(0, \"Welcome\"); li_hash_map.put(1, \"To\"); li_hash_map.put(2, \"The\"); li_hash_map.put(3, \"World\"); li_hash_map.put(4, \"Of\"); li_hash_map.put(5, \"geeks\"); System.out.println(\"\" + li_hash_map); // Adding more elements li_hash_map.put(6, \"GeeksforGeeks\"); // Displaying the map after adding one more element System.out.println(\"\" + li_hash_map); // Adding more elements li_hash_map.put(7, \"Hello\"); // Displaying the map after adding one more element System.out.println(\"\" + li_hash_map); }}",
"e": 27258,
"s": 25957,
"text": null
},
{
"code": null,
"e": 27420,
"s": 27258,
"text": "{0=Welcome, 1=To, 2=The, 3=World, 4=Of, 5=geeks}\n{1=To, 2=The, 3=World, 4=Of, 5=geeks, 6=GeeksforGeeks}\n{2=The, 3=World, 4=Of, 5=geeks, 6=GeeksforGeeks, 7=Hello}"
},
{
"code": null,
"e": 27544,
"s": 27422,
"text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html#removeEldestEntry-java.util.Map.Entry- "
},
{
"code": null,
"e": 27560,
"s": 27544,
"text": "simranarora5sos"
},
{
"code": null,
"e": 27580,
"s": 27560,
"text": "Java - util package"
},
{
"code": null,
"e": 27597,
"s": 27580,
"text": "Java-Collections"
},
{
"code": null,
"e": 27616,
"s": 27597,
"text": "Java-LinkedHashMap"
},
{
"code": null,
"e": 27621,
"s": 27616,
"text": "Java"
},
{
"code": null,
"e": 27626,
"s": 27621,
"text": "Java"
},
{
"code": null,
"e": 27643,
"s": 27626,
"text": "Java-Collections"
},
{
"code": null,
"e": 27741,
"s": 27643,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27756,
"s": 27741,
"text": "Arrays in Java"
},
{
"code": null,
"e": 27800,
"s": 27756,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 27822,
"s": 27800,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 27873,
"s": 27822,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27909,
"s": 27873,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 27934,
"s": 27909,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 27964,
"s": 27934,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27983,
"s": 27964,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27998,
"s": 27983,
"text": "Stream In Java"
}
] |
Find k-th character of decrypted string | Set - 2 - GeeksforGeeks
|
21 Apr, 2021
Given an encoded string where repetitions of substrings are represented as substring followed by count of substrings. For example, if encrypted string is “ab2cd2” and k=4, so output will be ‘b’ because decrypted string is “ababcdcd” and 4th character is ‘b’.Note: Frequency of encrypted substring can be of more than one digit. For example, in “ab12c3”, ab is repeated 12 times. No leading 0 is present in frequency of substring.
Examples:
Input: "a2b2c3", k = 5
Output: c
Decrypted string is "aabbccc"
Input: "ab4c2ed3", k = 9
Output : c
Decrypted string is "ababababccededed"
The solution discussed in previous post requires additional O(n) space. The following post discuss a solution that requires constant space. The stepwise algorithm is:
Find length of current substring. Use two pointers. Fix one pointer at beginning of substring and move another pointer until a digit is not found.Find frequency of repetition by moving the second pointer further until an alphabet is not found.Find length of substring if it is repeated by multiplying frequency and its original length.If this length is less than k, then required character lies in substring that follows. Subtract this length from k to keep count of number of characters that are required to be covered.If length is less than or equal to k, then required character lies in current substring. As k is 1-indexed reduce it by 1 and then take its mod with original substring length. Required character is kth character from starting of substring which is pointed by first pointer.
Find length of current substring. Use two pointers. Fix one pointer at beginning of substring and move another pointer until a digit is not found.
Find frequency of repetition by moving the second pointer further until an alphabet is not found.
Find length of substring if it is repeated by multiplying frequency and its original length.
If this length is less than k, then required character lies in substring that follows. Subtract this length from k to keep count of number of characters that are required to be covered.
If length is less than or equal to k, then required character lies in current substring. As k is 1-indexed reduce it by 1 and then take its mod with original substring length. Required character is kth character from starting of substring which is pointed by first pointer.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find K'th character in// decrypted string#include <bits/stdc++.h>using namespace std; // Function to find K'th character in// Encoded Stringchar encodedChar(string str, int k){ int i, j; int n = str.length(); // To store length of substring int len; // To store length of substring when // it is repeated int num; // To store frequency of substring int freq; i = 0; while (i < n) { j = i; len = 0; freq = 0; // Find length of substring by // traversing the string until // no digit is found. while (j < n && isalpha(str[j])) { j++; len++; } // Find frequency of preceding substring. while (j < n && isdigit(str[j])) { freq = freq * 10 + (str[j] - '0'); j++; } // Find length of substring when // it is repeated. num = freq * len; // If length of repeated substring is less than // k then required character is present in next // substring. Subtract length of repeated // substring from k to keep account of number of // characters required to be visited. if (k > num) { k -= num; i = j; } // If length of repeated substring is // more or equal to k then required // character lies in current substring. else { k--; k %= len; return str[i + k]; } } // This is for the case when there // are no repetition in string. // e.g. str="abced". return str[k - 1];} // Driver Codeint main(){ string str = "abced"; int k = 4; cout << encodedChar(str, k) << endl; return 0;}
// Java program to find K'th character in// decrypted stringimport java.util.*; class GFG{ // Function to find K'th character in// Encoded Stringstatic char encodedChar(char[] str, int k){ int i, j; int n = str.length; // To store length of substring int len; // To store length of substring when // it is repeated int num; // To store frequency of substring int freq; i = 0; while (i < n) { j = i; len = 0; freq = 0; // Find length of substring by // traversing the string until // no digit is found. while (j < n && Character.isAlphabetic(str[j])) { j++; len++; } // Find frequency of preceding substring. while (j < n && Character.isDigit(str[j])) { freq = freq * 10 + (str[j] - '0'); j++; } // Find length of substring when // it is repeated. num = freq * len; // If length of repeated substring is less than // k then required character is present in next // substring. Subtract length of repeated // substring from k to keep account of number of // characters required to be visited. if (k > num) { k -= num; i = j; } // If length of repeated substring is // more or equal to k then required // character lies in current substring. else { k--; k %= len; return str[i + k]; } } // This is for the case when there // are no repetition in string. // e.g. str="abced". return str[k - 1];} // Driver Codepublic static void main(String[] args){ String str = "abced"; int k = 4; System.out.println(encodedChar(str.toCharArray(), k));}} // This code is contributed by 29AjayKumar
# Python3 program to find K'th# character in decrypted string # Function to find K'th character# in Encoded Stringdef encodedChar(string, k): n = len(string) i = 0 while i < n: j = i length = 0 freq = 0 # Find length of substring by # traversing the string until # no digit is found. while j < n and string[j].isalpha(): j += 1 length += 1 # Find frequency of preceding substring. while j < n and string[j].isdigit(): freq = freq * 10 + int(string[j]) j += 1 # Find the length of the substring # when it is repeated. num = freq * length # If the length of the repeated substring # is less than k then required character # is present in next substring. Subtract # the length of repeated substring from # k to keep account of the number # of characters required to be visited. if k > num: k -= num i = j # If length of repeated substring is # more or equal to k then required # character lies in current substring. else: k -= 1 k %= length return string[i + k] # This is for the case when there are no # repetition in string. e.g. str="abced". return string[k - 1] # Driver Codeif __name__ == "__main__": string = "abced" k = 4 print(encodedChar(string, k)) # This code is contributed# by Rituraj Jain
// C# program to find K'th character in// decrypted stringusing System; class GFG{ // Function to find K'th character in// Encoded Stringstatic char encodedChar(char[] str, int k){ int i, j; int n = str.Length; // To store length of substring int len; // To store length of substring when // it is repeated int num; // To store frequency of substring int freq; i = 0; while (i < n) { j = i; len = 0; freq = 0; // Find length of substring by // traversing the string until // no digit is found. while (j < n && char.IsLetter(str[j])) { j++; len++; } // Find frequency of preceding substring. while (j < n && char.IsDigit(str[j])) { freq = freq * 10 + (str[j] - '0'); j++; } // Find length of substring when // it is repeated. num = freq * len; // If length of repeated substring is less than // k then required character is present in next // substring. Subtract length of repeated // substring from k to keep account of number of // characters required to be visited. if (k > num) { k -= num; i = j; } // If length of repeated substring is // more or equal to k then required // character lies in current substring. else { k--; k %= len; return str[i + k]; } } // This is for the case when there // are no repetition in string. // e.g. str="abced". return str[k - 1];} // Driver Codepublic static void Main(String[] args){ String str = "abced"; int k = 4; Console.WriteLine(encodedChar(str.ToCharArray(), k));}} // This code is contributed by PrinciRaj1992
<script> // Javascript program to find K'th character in// decrypted string // Function to find K'th character in// Encoded Stringfunction encodedChar(str, k){ var i, j; var n = str.length; // To store length of substring var len; // To store length of substring when // it is repeated var num; // To store frequency of substring var freq; i = 0; while (i < n) { j = i; len = 0; freq = 0; // Find length of substring by // traversing the string until // no digit is found. while (j < n && str[j].match(/^[0-9a-z]+$/)) { j++; len++; } // Find frequency of preceding substring. while (j < n && str[j].match(/^[0-9]+$/)) { freq = freq * 10 + (str[j] - '0'); j++; } // Find length of substring when // it is repeated. num = freq * len; // If length of repeated substring is less than // k then required character is present in next // substring. Subtract length of repeated // substring from k to keep account of number of // characters required to be visited. if (k > num) { k -= num; i = j; } // If length of repeated substring is // more or equal to k then required // character lies in current substring. else { k--; k %= len; return str[i + k]; } } // This is for the case when there // are no repetition in string. // e.g. str="abced". return str[k - 1];} // Driver Codevar str = "abced";var k = 4; document.write(encodedChar(str, k)); // This code is contributed by rutvik_56 </script>
e
Time Complexity: O(n) Auxiliary Space: O(1)
rituraj_jain
29AjayKumar
princiraj1992
rutvik_56
encoding-decoding
String-Run Length Encoding
Data Structures
Strings
Data Structures
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
How to Start Learning DSA?
Hash Map in Python
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Longest Common Subsequence | DP-4
|
[
{
"code": null,
"e": 26385,
"s": 26357,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 26815,
"s": 26385,
"text": "Given an encoded string where repetitions of substrings are represented as substring followed by count of substrings. For example, if encrypted string is “ab2cd2” and k=4, so output will be ‘b’ because decrypted string is “ababcdcd” and 4th character is ‘b’.Note: Frequency of encrypted substring can be of more than one digit. For example, in “ab12c3”, ab is repeated 12 times. No leading 0 is present in frequency of substring."
},
{
"code": null,
"e": 26826,
"s": 26815,
"text": "Examples: "
},
{
"code": null,
"e": 26969,
"s": 26826,
"text": "Input: \"a2b2c3\", k = 5\nOutput: c\nDecrypted string is \"aabbccc\"\n\nInput: \"ab4c2ed3\", k = 9\nOutput : c\nDecrypted string is \"ababababccededed\""
},
{
"code": null,
"e": 27137,
"s": 26969,
"text": "The solution discussed in previous post requires additional O(n) space. The following post discuss a solution that requires constant space. The stepwise algorithm is: "
},
{
"code": null,
"e": 27931,
"s": 27137,
"text": "Find length of current substring. Use two pointers. Fix one pointer at beginning of substring and move another pointer until a digit is not found.Find frequency of repetition by moving the second pointer further until an alphabet is not found.Find length of substring if it is repeated by multiplying frequency and its original length.If this length is less than k, then required character lies in substring that follows. Subtract this length from k to keep count of number of characters that are required to be covered.If length is less than or equal to k, then required character lies in current substring. As k is 1-indexed reduce it by 1 and then take its mod with original substring length. Required character is kth character from starting of substring which is pointed by first pointer."
},
{
"code": null,
"e": 28078,
"s": 27931,
"text": "Find length of current substring. Use two pointers. Fix one pointer at beginning of substring and move another pointer until a digit is not found."
},
{
"code": null,
"e": 28176,
"s": 28078,
"text": "Find frequency of repetition by moving the second pointer further until an alphabet is not found."
},
{
"code": null,
"e": 28269,
"s": 28176,
"text": "Find length of substring if it is repeated by multiplying frequency and its original length."
},
{
"code": null,
"e": 28455,
"s": 28269,
"text": "If this length is less than k, then required character lies in substring that follows. Subtract this length from k to keep count of number of characters that are required to be covered."
},
{
"code": null,
"e": 28729,
"s": 28455,
"text": "If length is less than or equal to k, then required character lies in current substring. As k is 1-indexed reduce it by 1 and then take its mod with original substring length. Required character is kth character from starting of substring which is pointed by first pointer."
},
{
"code": null,
"e": 28781,
"s": 28729,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 28785,
"s": 28781,
"text": "C++"
},
{
"code": null,
"e": 28790,
"s": 28785,
"text": "Java"
},
{
"code": null,
"e": 28798,
"s": 28790,
"text": "Python3"
},
{
"code": null,
"e": 28801,
"s": 28798,
"text": "C#"
},
{
"code": null,
"e": 28812,
"s": 28801,
"text": "Javascript"
},
{
"code": "// C++ program to find K'th character in// decrypted string#include <bits/stdc++.h>using namespace std; // Function to find K'th character in// Encoded Stringchar encodedChar(string str, int k){ int i, j; int n = str.length(); // To store length of substring int len; // To store length of substring when // it is repeated int num; // To store frequency of substring int freq; i = 0; while (i < n) { j = i; len = 0; freq = 0; // Find length of substring by // traversing the string until // no digit is found. while (j < n && isalpha(str[j])) { j++; len++; } // Find frequency of preceding substring. while (j < n && isdigit(str[j])) { freq = freq * 10 + (str[j] - '0'); j++; } // Find length of substring when // it is repeated. num = freq * len; // If length of repeated substring is less than // k then required character is present in next // substring. Subtract length of repeated // substring from k to keep account of number of // characters required to be visited. if (k > num) { k -= num; i = j; } // If length of repeated substring is // more or equal to k then required // character lies in current substring. else { k--; k %= len; return str[i + k]; } } // This is for the case when there // are no repetition in string. // e.g. str=\"abced\". return str[k - 1];} // Driver Codeint main(){ string str = \"abced\"; int k = 4; cout << encodedChar(str, k) << endl; return 0;}",
"e": 30548,
"s": 28812,
"text": null
},
{
"code": "// Java program to find K'th character in// decrypted stringimport java.util.*; class GFG{ // Function to find K'th character in// Encoded Stringstatic char encodedChar(char[] str, int k){ int i, j; int n = str.length; // To store length of substring int len; // To store length of substring when // it is repeated int num; // To store frequency of substring int freq; i = 0; while (i < n) { j = i; len = 0; freq = 0; // Find length of substring by // traversing the string until // no digit is found. while (j < n && Character.isAlphabetic(str[j])) { j++; len++; } // Find frequency of preceding substring. while (j < n && Character.isDigit(str[j])) { freq = freq * 10 + (str[j] - '0'); j++; } // Find length of substring when // it is repeated. num = freq * len; // If length of repeated substring is less than // k then required character is present in next // substring. Subtract length of repeated // substring from k to keep account of number of // characters required to be visited. if (k > num) { k -= num; i = j; } // If length of repeated substring is // more or equal to k then required // character lies in current substring. else { k--; k %= len; return str[i + k]; } } // This is for the case when there // are no repetition in string. // e.g. str=\"abced\". return str[k - 1];} // Driver Codepublic static void main(String[] args){ String str = \"abced\"; int k = 4; System.out.println(encodedChar(str.toCharArray(), k));}} // This code is contributed by 29AjayKumar",
"e": 32408,
"s": 30548,
"text": null
},
{
"code": "# Python3 program to find K'th# character in decrypted string # Function to find K'th character# in Encoded Stringdef encodedChar(string, k): n = len(string) i = 0 while i < n: j = i length = 0 freq = 0 # Find length of substring by # traversing the string until # no digit is found. while j < n and string[j].isalpha(): j += 1 length += 1 # Find frequency of preceding substring. while j < n and string[j].isdigit(): freq = freq * 10 + int(string[j]) j += 1 # Find the length of the substring # when it is repeated. num = freq * length # If the length of the repeated substring # is less than k then required character # is present in next substring. Subtract # the length of repeated substring from # k to keep account of the number # of characters required to be visited. if k > num: k -= num i = j # If length of repeated substring is # more or equal to k then required # character lies in current substring. else: k -= 1 k %= length return string[i + k] # This is for the case when there are no # repetition in string. e.g. str=\"abced\". return string[k - 1] # Driver Codeif __name__ == \"__main__\": string = \"abced\" k = 4 print(encodedChar(string, k)) # This code is contributed# by Rituraj Jain",
"e": 33905,
"s": 32408,
"text": null
},
{
"code": "// C# program to find K'th character in// decrypted stringusing System; class GFG{ // Function to find K'th character in// Encoded Stringstatic char encodedChar(char[] str, int k){ int i, j; int n = str.Length; // To store length of substring int len; // To store length of substring when // it is repeated int num; // To store frequency of substring int freq; i = 0; while (i < n) { j = i; len = 0; freq = 0; // Find length of substring by // traversing the string until // no digit is found. while (j < n && char.IsLetter(str[j])) { j++; len++; } // Find frequency of preceding substring. while (j < n && char.IsDigit(str[j])) { freq = freq * 10 + (str[j] - '0'); j++; } // Find length of substring when // it is repeated. num = freq * len; // If length of repeated substring is less than // k then required character is present in next // substring. Subtract length of repeated // substring from k to keep account of number of // characters required to be visited. if (k > num) { k -= num; i = j; } // If length of repeated substring is // more or equal to k then required // character lies in current substring. else { k--; k %= len; return str[i + k]; } } // This is for the case when there // are no repetition in string. // e.g. str=\"abced\". return str[k - 1];} // Driver Codepublic static void Main(String[] args){ String str = \"abced\"; int k = 4; Console.WriteLine(encodedChar(str.ToCharArray(), k));}} // This code is contributed by PrinciRaj1992",
"e": 35744,
"s": 33905,
"text": null
},
{
"code": "<script> // Javascript program to find K'th character in// decrypted string // Function to find K'th character in// Encoded Stringfunction encodedChar(str, k){ var i, j; var n = str.length; // To store length of substring var len; // To store length of substring when // it is repeated var num; // To store frequency of substring var freq; i = 0; while (i < n) { j = i; len = 0; freq = 0; // Find length of substring by // traversing the string until // no digit is found. while (j < n && str[j].match(/^[0-9a-z]+$/)) { j++; len++; } // Find frequency of preceding substring. while (j < n && str[j].match(/^[0-9]+$/)) { freq = freq * 10 + (str[j] - '0'); j++; } // Find length of substring when // it is repeated. num = freq * len; // If length of repeated substring is less than // k then required character is present in next // substring. Subtract length of repeated // substring from k to keep account of number of // characters required to be visited. if (k > num) { k -= num; i = j; } // If length of repeated substring is // more or equal to k then required // character lies in current substring. else { k--; k %= len; return str[i + k]; } } // This is for the case when there // are no repetition in string. // e.g. str=\"abced\". return str[k - 1];} // Driver Codevar str = \"abced\";var k = 4; document.write(encodedChar(str, k)); // This code is contributed by rutvik_56 </script>",
"e": 37505,
"s": 35744,
"text": null
},
{
"code": null,
"e": 37507,
"s": 37505,
"text": "e"
},
{
"code": null,
"e": 37554,
"s": 37509,
"text": "Time Complexity: O(n) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 37567,
"s": 37554,
"text": "rituraj_jain"
},
{
"code": null,
"e": 37579,
"s": 37567,
"text": "29AjayKumar"
},
{
"code": null,
"e": 37593,
"s": 37579,
"text": "princiraj1992"
},
{
"code": null,
"e": 37603,
"s": 37593,
"text": "rutvik_56"
},
{
"code": null,
"e": 37621,
"s": 37603,
"text": "encoding-decoding"
},
{
"code": null,
"e": 37648,
"s": 37621,
"text": "String-Run Length Encoding"
},
{
"code": null,
"e": 37664,
"s": 37648,
"text": "Data Structures"
},
{
"code": null,
"e": 37672,
"s": 37664,
"text": "Strings"
},
{
"code": null,
"e": 37688,
"s": 37672,
"text": "Data Structures"
},
{
"code": null,
"e": 37696,
"s": 37688,
"text": "Strings"
},
{
"code": null,
"e": 37794,
"s": 37696,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37843,
"s": 37794,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 37868,
"s": 37843,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 37895,
"s": 37868,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 37922,
"s": 37895,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 37941,
"s": 37922,
"text": "Hash Map in Python"
},
{
"code": null,
"e": 37987,
"s": 37941,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 38012,
"s": 37987,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 38072,
"s": 38012,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 38087,
"s": 38072,
"text": "C++ Data Types"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.