title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Build Shiny Dashboard with Elasticsearch | by Andy Kwan | Towards Data Science
|
In enterprise, presumably multiple data sources are required to be handled because of the possession of vast amount of data. When attempting to build a dashboard to showcase business ideas, typically one needs to integrate data from NoSQL database, relational database and search engine. Thus dashboards like Kibana or Google Data Studio are not suitable choices as the flexibility of multiple data source is limited. One then need an alternative that is as straightforward. For this scenario, I recommend Shiny Dashboard for the task as it fulfills the requirements: flexible, straight forward and aesthetic. However, while building the dashboard, there is an immediate implementation barrier of connecting Amazon Elasticsearch Service and that motivates me to write this article.
This article demonstrates the integration of Elasticsearch data into a Shiny dashboard. The programming language used is mainly R and the back-end connection is performed with Python. Meanwhile, for the data visualization part, graphs are drawn with 3 different graphing packages in R, namely: ggplot2, plotly and wordcloud2.
The contents for the article:
Elasticsearch Connection (with Amazon Elasticsearch Service)Data Manipulation using R.Showcase the tool Shiny Dashboard to bring data to live without much styling customization.
Elasticsearch Connection (with Amazon Elasticsearch Service)
Data Manipulation using R.
Showcase the tool Shiny Dashboard to bring data to live without much styling customization.
Environment used:
R version 3.4.4
Python 3.7.4
Ubuntu 18.04
Elasticsearch is a popular search engine in enterprise. Generally speaking, I would recommend it to be added into the data infrastructure when making summary statistics or locating specific batch of large amount of data in a timely manner is necessary. For setup, a convenient way is to make use of Amazon Elasticsearch Service since it one would only need to take care of high-level parameters like number of shards. Moreover, a comprehensive documentation and sample codes are provided and there is not much reason of not using it when a company has already built the infrastructure in AWS. Amazon provides sample code which is well-documented but the supporting languages do not contain R. Although there are various packages for Elasticsearch connection in R but the way to integrate it with Amazon Web Services version 4 authentication (AWS4Auth) is not straight forward. To build the dashboard, the crucial part is to overcoming this implementation barrier.
First, we need to locate the Python path. I suggest two ways to search for it:
Display in Python environment
Display in Python environment
import sys# Python search for libraries at the ordering of the pathprint(sys.path[0])
2. Display in command line with the chosen Python environment activated
which python
Both ways can locate the system path for your Python executable.
Once the python path is known, we can start the connection. We will be using the reticulate package in R which provides a comprehensive set of tools for interoperability between Python and R. The details can be found here and I recommend you to read this awesome cheat sheet!
This simple way works! It is always a good idea to learn both R and Python to avoid being stuck.
As we do not have a hosted Elasticsearch Instance at the moment. For demonstration purpose, let's create some sample data in the local machine.
Steps for setting up Elasticsearch with sample data in the local machine:
Download and follow the instructions of Elasticsearch.Download and follow the instructions of Kibana.Host both Elasticsearch and Kibana.Load the Sample Flight data to Kibana. Kibana is hosted on http://localhost:5601/.
Download and follow the instructions of Elasticsearch.
Download and follow the instructions of Kibana.
Host both Elasticsearch and Kibana.
Load the Sample Flight data to Kibana. Kibana is hosted on http://localhost:5601/.
5. Connect to Elasticsearch
elasticsearch <- import("elasticsearch")host <- "localhost:9200"es <- elasticsearch$Elasticsearch(hosts = host)
There are various way for the connection since AWS4Auth is not used. You may use a R only approach as well.
6. Install the necessary packages for the Shiny dashboard including Shiny, shinyWidgets and shinydashboard.
Upon connection, we are now ready to start writing functionalities in the dashboard. First let's start with the structure:
├── global.R├── server.R└── ui.R
To better organize the code, I have separate the files into the above 3 parts.
global.R
As its name implies, this file stored the global variables and functions that is run once prior to app starts. Thus I have included the Elasticsearch connection and queries.
server.R
It handles back-end duties once the dashboard app is started. Logic about for example how to render the plots and when to re-run queries should be included in the file.
The response data from Elasticsearch using Elasticsearch.search is in dictionary format and it is convert to a named list according to the reticulate. For the ease of making plots, it is better to transform all the response data to R data frame format and there are 2 options for us:
Transform the data in R.Transform the data in Python and convert pandas.DataFrame to Data Frame in R.
Transform the data in R.
Transform the data in Python and convert pandas.DataFrame to Data Frame in R.
For the demonstration, we will be using R. Given the complexity of the named list response data, the way to write a suitable data transformation function more efficiently is to keep observing the structure of the object using str.
After multiple rounds of trail and error in the R console, we then come up with two functions that converts data from single and double aggregation queries.
Now we prepare data frames for charts plotting. First we create data frame and plot a pie chart for number of flights using Plotly R.
The transformed data frame of of the below form.
Plotly is a popular tool for chart visualization, it allows users to create interactivity visualizations with options for interactivity. Features like zoom in and out and hover text are supported for figures made with Plotly. However rendering a chart in Plotly will be quite slow when it comes to displaying a vast amount of data compared with ggplot.
Then we create data frame and plot a stacked bar chart for flight delay time series data using ggplot. We are going to make a time slider in the dashboard for user to select the time range of the chart and therefore we have to filter by the selected time inputs.
The transformed data frame of of the below form.
ggplot allows users to quickly visualize trends, and add customization in layers. If a more interactive chart is desired, you may convert your figure to Plotly by the code ggplotly(p) .
Finally we create data frame and word cloud for weather data using wordcloud2. Additionally, we are going to make a slider in the dashboard for user to adjust a desired wordcloud size.
The transformed data frame of of the below form.
Word clouds made with wordcloud2 automatically calculated sizes and positions for words and it supports display of raw values when mouse hover. Users can thus get an overview of the data as well as targeting specific words for data insights.
ui.R
It handles front-end appearance of the app. The code for the Shiny widgets and style should be placed here. Basically all the desired appearance of the dashboard should be located here. Essential elements for an interactive dashboard are the use of widgets. There are many resources for creating Shiny widgets, for example here. Once you have an idea in mind then you can simply search for the right widget and place that into the ui.R file. Apart from that, some Shiny dashboard elements can be found here. Simply make sure you have handled the data logic each time when you added a new widget.
As an example of demonstration, for our word cloud box, we create a sliderInput to control its overall size.
For further details of the UI, you are welcome to read my source code.
Finally lets host the Shiny app in the R console:
runApp(host="0.0.0.0", port=1234)
Visiting http://localhost:1234/ and you can view the demo dashboard.
In this article, we have walked through the essential steps to create a Shiny Dashboard to bring data to life. In particular, we have
Connect Elasticsearch using Python back-end and converted the data to R named list.Creates multiple data transformation functions with R.Utilize Plotly, ggplot and wordcloud2 packages for graphs.
Connect Elasticsearch using Python back-end and converted the data to R named list.
Creates multiple data transformation functions with R.
Utilize Plotly, ggplot and wordcloud2 packages for graphs.
Thanks for reading! Hope you find this article useful. The source code is posted in my GitHub repository. Feel free to drop me a comment to tell me what you think about the article. Do tell me if you have a more convenient way for the task :)
|
[
{
"code": null,
"e": 954,
"s": 172,
"text": "In enterprise, presumably multiple data sources are required to be handled because of the possession of vast amount of data. When attempting to build a dashboard to showcase business ideas, typically one needs to integrate data from NoSQL database, relational database and search engine. Thus dashboards like Kibana or Google Data Studio are not suitable choices as the flexibility of multiple data source is limited. One then need an alternative that is as straightforward. For this scenario, I recommend Shiny Dashboard for the task as it fulfills the requirements: flexible, straight forward and aesthetic. However, while building the dashboard, there is an immediate implementation barrier of connecting Amazon Elasticsearch Service and that motivates me to write this article."
},
{
"code": null,
"e": 1280,
"s": 954,
"text": "This article demonstrates the integration of Elasticsearch data into a Shiny dashboard. The programming language used is mainly R and the back-end connection is performed with Python. Meanwhile, for the data visualization part, graphs are drawn with 3 different graphing packages in R, namely: ggplot2, plotly and wordcloud2."
},
{
"code": null,
"e": 1310,
"s": 1280,
"text": "The contents for the article:"
},
{
"code": null,
"e": 1488,
"s": 1310,
"text": "Elasticsearch Connection (with Amazon Elasticsearch Service)Data Manipulation using R.Showcase the tool Shiny Dashboard to bring data to live without much styling customization."
},
{
"code": null,
"e": 1549,
"s": 1488,
"text": "Elasticsearch Connection (with Amazon Elasticsearch Service)"
},
{
"code": null,
"e": 1576,
"s": 1549,
"text": "Data Manipulation using R."
},
{
"code": null,
"e": 1668,
"s": 1576,
"text": "Showcase the tool Shiny Dashboard to bring data to live without much styling customization."
},
{
"code": null,
"e": 1686,
"s": 1668,
"text": "Environment used:"
},
{
"code": null,
"e": 1702,
"s": 1686,
"text": "R version 3.4.4"
},
{
"code": null,
"e": 1715,
"s": 1702,
"text": "Python 3.7.4"
},
{
"code": null,
"e": 1728,
"s": 1715,
"text": "Ubuntu 18.04"
},
{
"code": null,
"e": 2692,
"s": 1728,
"text": "Elasticsearch is a popular search engine in enterprise. Generally speaking, I would recommend it to be added into the data infrastructure when making summary statistics or locating specific batch of large amount of data in a timely manner is necessary. For setup, a convenient way is to make use of Amazon Elasticsearch Service since it one would only need to take care of high-level parameters like number of shards. Moreover, a comprehensive documentation and sample codes are provided and there is not much reason of not using it when a company has already built the infrastructure in AWS. Amazon provides sample code which is well-documented but the supporting languages do not contain R. Although there are various packages for Elasticsearch connection in R but the way to integrate it with Amazon Web Services version 4 authentication (AWS4Auth) is not straight forward. To build the dashboard, the crucial part is to overcoming this implementation barrier."
},
{
"code": null,
"e": 2771,
"s": 2692,
"text": "First, we need to locate the Python path. I suggest two ways to search for it:"
},
{
"code": null,
"e": 2801,
"s": 2771,
"text": "Display in Python environment"
},
{
"code": null,
"e": 2831,
"s": 2801,
"text": "Display in Python environment"
},
{
"code": null,
"e": 2917,
"s": 2831,
"text": "import sys# Python search for libraries at the ordering of the pathprint(sys.path[0])"
},
{
"code": null,
"e": 2989,
"s": 2917,
"text": "2. Display in command line with the chosen Python environment activated"
},
{
"code": null,
"e": 3002,
"s": 2989,
"text": "which python"
},
{
"code": null,
"e": 3067,
"s": 3002,
"text": "Both ways can locate the system path for your Python executable."
},
{
"code": null,
"e": 3343,
"s": 3067,
"text": "Once the python path is known, we can start the connection. We will be using the reticulate package in R which provides a comprehensive set of tools for interoperability between Python and R. The details can be found here and I recommend you to read this awesome cheat sheet!"
},
{
"code": null,
"e": 3440,
"s": 3343,
"text": "This simple way works! It is always a good idea to learn both R and Python to avoid being stuck."
},
{
"code": null,
"e": 3584,
"s": 3440,
"text": "As we do not have a hosted Elasticsearch Instance at the moment. For demonstration purpose, let's create some sample data in the local machine."
},
{
"code": null,
"e": 3658,
"s": 3584,
"text": "Steps for setting up Elasticsearch with sample data in the local machine:"
},
{
"code": null,
"e": 3877,
"s": 3658,
"text": "Download and follow the instructions of Elasticsearch.Download and follow the instructions of Kibana.Host both Elasticsearch and Kibana.Load the Sample Flight data to Kibana. Kibana is hosted on http://localhost:5601/."
},
{
"code": null,
"e": 3932,
"s": 3877,
"text": "Download and follow the instructions of Elasticsearch."
},
{
"code": null,
"e": 3980,
"s": 3932,
"text": "Download and follow the instructions of Kibana."
},
{
"code": null,
"e": 4016,
"s": 3980,
"text": "Host both Elasticsearch and Kibana."
},
{
"code": null,
"e": 4099,
"s": 4016,
"text": "Load the Sample Flight data to Kibana. Kibana is hosted on http://localhost:5601/."
},
{
"code": null,
"e": 4127,
"s": 4099,
"text": "5. Connect to Elasticsearch"
},
{
"code": null,
"e": 4239,
"s": 4127,
"text": "elasticsearch <- import(\"elasticsearch\")host <- \"localhost:9200\"es <- elasticsearch$Elasticsearch(hosts = host)"
},
{
"code": null,
"e": 4347,
"s": 4239,
"text": "There are various way for the connection since AWS4Auth is not used. You may use a R only approach as well."
},
{
"code": null,
"e": 4455,
"s": 4347,
"text": "6. Install the necessary packages for the Shiny dashboard including Shiny, shinyWidgets and shinydashboard."
},
{
"code": null,
"e": 4578,
"s": 4455,
"text": "Upon connection, we are now ready to start writing functionalities in the dashboard. First let's start with the structure:"
},
{
"code": null,
"e": 4611,
"s": 4578,
"text": "├── global.R├── server.R└── ui.R"
},
{
"code": null,
"e": 4690,
"s": 4611,
"text": "To better organize the code, I have separate the files into the above 3 parts."
},
{
"code": null,
"e": 4699,
"s": 4690,
"text": "global.R"
},
{
"code": null,
"e": 4873,
"s": 4699,
"text": "As its name implies, this file stored the global variables and functions that is run once prior to app starts. Thus I have included the Elasticsearch connection and queries."
},
{
"code": null,
"e": 4882,
"s": 4873,
"text": "server.R"
},
{
"code": null,
"e": 5051,
"s": 4882,
"text": "It handles back-end duties once the dashboard app is started. Logic about for example how to render the plots and when to re-run queries should be included in the file."
},
{
"code": null,
"e": 5335,
"s": 5051,
"text": "The response data from Elasticsearch using Elasticsearch.search is in dictionary format and it is convert to a named list according to the reticulate. For the ease of making plots, it is better to transform all the response data to R data frame format and there are 2 options for us:"
},
{
"code": null,
"e": 5437,
"s": 5335,
"text": "Transform the data in R.Transform the data in Python and convert pandas.DataFrame to Data Frame in R."
},
{
"code": null,
"e": 5462,
"s": 5437,
"text": "Transform the data in R."
},
{
"code": null,
"e": 5540,
"s": 5462,
"text": "Transform the data in Python and convert pandas.DataFrame to Data Frame in R."
},
{
"code": null,
"e": 5771,
"s": 5540,
"text": "For the demonstration, we will be using R. Given the complexity of the named list response data, the way to write a suitable data transformation function more efficiently is to keep observing the structure of the object using str."
},
{
"code": null,
"e": 5928,
"s": 5771,
"text": "After multiple rounds of trail and error in the R console, we then come up with two functions that converts data from single and double aggregation queries."
},
{
"code": null,
"e": 6062,
"s": 5928,
"text": "Now we prepare data frames for charts plotting. First we create data frame and plot a pie chart for number of flights using Plotly R."
},
{
"code": null,
"e": 6111,
"s": 6062,
"text": "The transformed data frame of of the below form."
},
{
"code": null,
"e": 6464,
"s": 6111,
"text": "Plotly is a popular tool for chart visualization, it allows users to create interactivity visualizations with options for interactivity. Features like zoom in and out and hover text are supported for figures made with Plotly. However rendering a chart in Plotly will be quite slow when it comes to displaying a vast amount of data compared with ggplot."
},
{
"code": null,
"e": 6727,
"s": 6464,
"text": "Then we create data frame and plot a stacked bar chart for flight delay time series data using ggplot. We are going to make a time slider in the dashboard for user to select the time range of the chart and therefore we have to filter by the selected time inputs."
},
{
"code": null,
"e": 6776,
"s": 6727,
"text": "The transformed data frame of of the below form."
},
{
"code": null,
"e": 6962,
"s": 6776,
"text": "ggplot allows users to quickly visualize trends, and add customization in layers. If a more interactive chart is desired, you may convert your figure to Plotly by the code ggplotly(p) ."
},
{
"code": null,
"e": 7147,
"s": 6962,
"text": "Finally we create data frame and word cloud for weather data using wordcloud2. Additionally, we are going to make a slider in the dashboard for user to adjust a desired wordcloud size."
},
{
"code": null,
"e": 7196,
"s": 7147,
"text": "The transformed data frame of of the below form."
},
{
"code": null,
"e": 7438,
"s": 7196,
"text": "Word clouds made with wordcloud2 automatically calculated sizes and positions for words and it supports display of raw values when mouse hover. Users can thus get an overview of the data as well as targeting specific words for data insights."
},
{
"code": null,
"e": 7443,
"s": 7438,
"text": "ui.R"
},
{
"code": null,
"e": 8039,
"s": 7443,
"text": "It handles front-end appearance of the app. The code for the Shiny widgets and style should be placed here. Basically all the desired appearance of the dashboard should be located here. Essential elements for an interactive dashboard are the use of widgets. There are many resources for creating Shiny widgets, for example here. Once you have an idea in mind then you can simply search for the right widget and place that into the ui.R file. Apart from that, some Shiny dashboard elements can be found here. Simply make sure you have handled the data logic each time when you added a new widget."
},
{
"code": null,
"e": 8148,
"s": 8039,
"text": "As an example of demonstration, for our word cloud box, we create a sliderInput to control its overall size."
},
{
"code": null,
"e": 8219,
"s": 8148,
"text": "For further details of the UI, you are welcome to read my source code."
},
{
"code": null,
"e": 8269,
"s": 8219,
"text": "Finally lets host the Shiny app in the R console:"
},
{
"code": null,
"e": 8303,
"s": 8269,
"text": "runApp(host=\"0.0.0.0\", port=1234)"
},
{
"code": null,
"e": 8372,
"s": 8303,
"text": "Visiting http://localhost:1234/ and you can view the demo dashboard."
},
{
"code": null,
"e": 8506,
"s": 8372,
"text": "In this article, we have walked through the essential steps to create a Shiny Dashboard to bring data to life. In particular, we have"
},
{
"code": null,
"e": 8702,
"s": 8506,
"text": "Connect Elasticsearch using Python back-end and converted the data to R named list.Creates multiple data transformation functions with R.Utilize Plotly, ggplot and wordcloud2 packages for graphs."
},
{
"code": null,
"e": 8786,
"s": 8702,
"text": "Connect Elasticsearch using Python back-end and converted the data to R named list."
},
{
"code": null,
"e": 8841,
"s": 8786,
"text": "Creates multiple data transformation functions with R."
},
{
"code": null,
"e": 8900,
"s": 8841,
"text": "Utilize Plotly, ggplot and wordcloud2 packages for graphs."
}
] |
Boolean booleanValue() method in Java with examples - GeeksforGeeks
|
01 Oct, 2018
The booleanValue() method of Boolean Class is a built in method in java which is used to return the primitive boolean value of instance which is used to call the method booleanValue().
Syntax
BooleanObject.booleanValue()
Return Value: It returns a primitive boolean value.
Below are the examples to illustrate booleanValue() method:
Program 1:
class GeeksforGeeks { // Driver method public static void main(String[] args) { // creating a Boolean object. Boolean b = new Boolean(true); // get primitive data type using booleanValue() boolean value = b.booleanValue(); // Print the result System.out.println(value); }}
true
Example 2:
class GeeksforGeeks { // Driver method public static void main(String[] args) { // creating a Boolean object. Boolean b = new Boolean(false); // get primitive data type using booleanValue() boolean value = b.booleanValue(); // Print the result System.out.println(value); }}
false
Java - util package
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
LinkedList in Java
Overriding in Java
Set in Java
|
[
{
"code": null,
"e": 24512,
"s": 24484,
"text": "\n01 Oct, 2018"
},
{
"code": null,
"e": 24697,
"s": 24512,
"text": "The booleanValue() method of Boolean Class is a built in method in java which is used to return the primitive boolean value of instance which is used to call the method booleanValue()."
},
{
"code": null,
"e": 24704,
"s": 24697,
"text": "Syntax"
},
{
"code": null,
"e": 24733,
"s": 24704,
"text": "BooleanObject.booleanValue()"
},
{
"code": null,
"e": 24785,
"s": 24733,
"text": "Return Value: It returns a primitive boolean value."
},
{
"code": null,
"e": 24845,
"s": 24785,
"text": "Below are the examples to illustrate booleanValue() method:"
},
{
"code": null,
"e": 24856,
"s": 24845,
"text": "Program 1:"
},
{
"code": "class GeeksforGeeks { // Driver method public static void main(String[] args) { // creating a Boolean object. Boolean b = new Boolean(true); // get primitive data type using booleanValue() boolean value = b.booleanValue(); // Print the result System.out.println(value); }}",
"e": 25191,
"s": 24856,
"text": null
},
{
"code": null,
"e": 25197,
"s": 25191,
"text": "true\n"
},
{
"code": null,
"e": 25208,
"s": 25197,
"text": "Example 2:"
},
{
"code": "class GeeksforGeeks { // Driver method public static void main(String[] args) { // creating a Boolean object. Boolean b = new Boolean(false); // get primitive data type using booleanValue() boolean value = b.booleanValue(); // Print the result System.out.println(value); }}",
"e": 25544,
"s": 25208,
"text": null
},
{
"code": null,
"e": 25551,
"s": 25544,
"text": "false\n"
},
{
"code": null,
"e": 25571,
"s": 25551,
"text": "Java - util package"
},
{
"code": null,
"e": 25586,
"s": 25571,
"text": "Java-Functions"
},
{
"code": null,
"e": 25591,
"s": 25586,
"text": "Java"
},
{
"code": null,
"e": 25596,
"s": 25591,
"text": "Java"
},
{
"code": null,
"e": 25694,
"s": 25596,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25703,
"s": 25694,
"text": "Comments"
},
{
"code": null,
"e": 25716,
"s": 25703,
"text": "Old Comments"
},
{
"code": null,
"e": 25748,
"s": 25716,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 25778,
"s": 25748,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 25797,
"s": 25778,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 25828,
"s": 25797,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 25846,
"s": 25828,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 25878,
"s": 25846,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 25898,
"s": 25878,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 25917,
"s": 25898,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 25936,
"s": 25917,
"text": "Overriding in Java"
}
] |
VBA - Split Function
|
A Split Function returns an array that contains a specific number of values split based on a delimiter.
Split(expression[,delimiter[,count[,compare]]])
Expression − A required parameter. The string expression that can contain strings with delimiters.
Expression − A required parameter. The string expression that can contain strings with delimiters.
Delimiter − An optional parameter. The parameter, which is used to convert into arrays based on a delimiter.
Delimiter − An optional parameter. The parameter, which is used to convert into arrays based on a delimiter.
Count − An optional parameter. The number of substrings to be returned, and if specified as -1, then all the substrings are returned.
Count − An optional parameter. The number of substrings to be returned, and if specified as -1, then all the substrings are returned.
Compare − An optional parameter. This parameter specifies which comparison method is to be used.
0 = vbBinaryCompare - Performs a binary comparison
1 = vbTextCompare - Performs a textual comparison
Compare − An optional parameter. This parameter specifies which comparison method is to be used.
0 = vbBinaryCompare - Performs a binary comparison
0 = vbBinaryCompare - Performs a binary comparison
1 = vbTextCompare - Performs a textual comparison
1 = vbTextCompare - Performs a textual comparison
Add a button and add the following function.
Private Sub Constant_demo_Click()
' Splitting based on delimiter comma '$'
Dim a as Variant
Dim b as Variant
a = Split("Red $ Blue $ Yellow","$")
b = ubound(a)
For i = 0 to b
msgbox("The value of array in " & i & " is :" & a(i))
Next
End Sub
When you execute the above function, it produces the following output.
The value of array in 0 is :Red
The value of array in 1 is : Blue
The value of array in 2 is : Yellow
101 Lectures
6 hours
Pavan Lalwani
41 Lectures
3 hours
Arnold Higuit
80 Lectures
5.5 hours
Prashant Panchal
25 Lectures
2 hours
Prashant Panchal
26 Lectures
2 hours
Arnold Higuit
92 Lectures
10.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2039,
"s": 1935,
"text": "A Split Function returns an array that contains a specific number of values split based on a delimiter."
},
{
"code": null,
"e": 2089,
"s": 2039,
"text": "Split(expression[,delimiter[,count[,compare]]]) \n"
},
{
"code": null,
"e": 2188,
"s": 2089,
"text": "Expression − A required parameter. The string expression that can contain strings with delimiters."
},
{
"code": null,
"e": 2287,
"s": 2188,
"text": "Expression − A required parameter. The string expression that can contain strings with delimiters."
},
{
"code": null,
"e": 2396,
"s": 2287,
"text": "Delimiter − An optional parameter. The parameter, which is used to convert into arrays based on a delimiter."
},
{
"code": null,
"e": 2505,
"s": 2396,
"text": "Delimiter − An optional parameter. The parameter, which is used to convert into arrays based on a delimiter."
},
{
"code": null,
"e": 2639,
"s": 2505,
"text": "Count − An optional parameter. The number of substrings to be returned, and if specified as -1, then all the substrings are returned."
},
{
"code": null,
"e": 2773,
"s": 2639,
"text": "Count − An optional parameter. The number of substrings to be returned, and if specified as -1, then all the substrings are returned."
},
{
"code": null,
"e": 2974,
"s": 2773,
"text": "Compare − An optional parameter. This parameter specifies which comparison method is to be used.\n\n0 = vbBinaryCompare - Performs a binary comparison\n1 = vbTextCompare - Performs a textual comparison\n\n"
},
{
"code": null,
"e": 3071,
"s": 2974,
"text": "Compare − An optional parameter. This parameter specifies which comparison method is to be used."
},
{
"code": null,
"e": 3122,
"s": 3071,
"text": "0 = vbBinaryCompare - Performs a binary comparison"
},
{
"code": null,
"e": 3173,
"s": 3122,
"text": "0 = vbBinaryCompare - Performs a binary comparison"
},
{
"code": null,
"e": 3223,
"s": 3173,
"text": "1 = vbTextCompare - Performs a textual comparison"
},
{
"code": null,
"e": 3273,
"s": 3223,
"text": "1 = vbTextCompare - Performs a textual comparison"
},
{
"code": null,
"e": 3318,
"s": 3273,
"text": "Add a button and add the following function."
},
{
"code": null,
"e": 3596,
"s": 3318,
"text": "Private Sub Constant_demo_Click()\n ' Splitting based on delimiter comma '$'\n Dim a as Variant\n Dim b as Variant\n \n a = Split(\"Red $ Blue $ Yellow\",\"$\")\n b = ubound(a)\n \n For i = 0 to b\n msgbox(\"The value of array in \" & i & \" is :\" & a(i))\n Next\nEnd Sub"
},
{
"code": null,
"e": 3667,
"s": 3596,
"text": "When you execute the above function, it produces the following output."
},
{
"code": null,
"e": 3772,
"s": 3667,
"text": "The value of array in 0 is :Red \nThe value of array in 1 is : Blue \nThe value of array in 2 is : Yellow\n"
},
{
"code": null,
"e": 3806,
"s": 3772,
"text": "\n 101 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3821,
"s": 3806,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 3854,
"s": 3821,
"text": "\n 41 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3869,
"s": 3854,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 3904,
"s": 3869,
"text": "\n 80 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3922,
"s": 3904,
"text": " Prashant Panchal"
},
{
"code": null,
"e": 3955,
"s": 3922,
"text": "\n 25 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3973,
"s": 3955,
"text": " Prashant Panchal"
},
{
"code": null,
"e": 4006,
"s": 3973,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4021,
"s": 4006,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 4057,
"s": 4021,
"text": "\n 92 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 4085,
"s": 4057,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 4092,
"s": 4085,
"text": " Print"
},
{
"code": null,
"e": 4103,
"s": 4092,
"text": " Add Notes"
}
] |
Minimum in an array which is first decreasing then increasing - GeeksforGeeks
|
16 Mar, 2021
Given an array of N integers where array elements form a strictly decreasing and increasing sequence. The task is to find the smallest number in such an array. Constraints: N >= 3 Examples:
Input: a[] = {2, 1, 2, 3, 4}
Output: 1
Input: a[] = {8, 5, 4, 3, 4, 10}
Output: 3
A naive approach is to linearly traverse the array and find out the smallest number. The time complexity will be thus O(N). An efficient approach is to modify the binary search and use it. Divide the array into two halves use binary search to check if a[mid] < a[mid+1] or not. If a[mid] < a[mid+1], then the smallest number lies in the first half which is low to mid, else it lies in the second half which is mid+1 to high. Algorithm:
while(lo > 1
if a[mid] < a[mid+1] then hi = mid
else lo = mid+1
}
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find the smallest number// in an array of decrease and increasing numbers#include <bits/stdc++.h>using namespace std; // Function to find the smallest number's indexint minimal(int a[], int n){ int lo = 0, hi = n - 1; // Do a binary search while (lo < hi) { // Find the mid element int mid = (lo + hi) >> 1; // Check for break point if (a[mid] < a[mid + 1]) { hi = mid; } else { lo = mid + 1; } } // Return the index return lo;} // Driver Codeint main(){ int a[] = { 8, 5, 4, 3, 4, 10 }; int n = sizeof(a) / sizeof(a[0]); int ind = minimal(a, n); // Print the smallest number cout << a[ind];}
// Java program to find the smallest number// in an array of decrease and increasing numbersclass Solution{// Function to find the smallest number's indexstatic int minimal(int a[], int n){ int lo = 0, hi = n - 1; // Do a binary search while (lo < hi) { // Find the mid element int mid = (lo + hi) >> 1; // Check for break point if (a[mid] < a[mid + 1]) { hi = mid; } else { lo = mid + 1; } } // Return the index return lo;} // Driver Codepublic static void main(String args[]){ int a[] = { 8, 5, 4, 3, 4, 10 }; int n = a.length; int ind = minimal(a, n); // Print the smallest number System.out.println( a[ind]);}}//contributed by Arnab Kundu
# Python 3 program to find the smallest# number in a array of decrease and# increasing numbers # function to find the smallest# number's indexdef minimal(a, n): lo, hi = 0, n - 1 # Do a binary search while lo < hi: # find the mid element mid = (lo + hi) // 2 # Check for break point if a[mid] < a[mid + 1]: hi = mid else: lo = mid + 1 return lo # Driver codea = [8, 5, 4, 3, 4, 10] n = len(a) ind = minimal(a, n) # print the smallest numberprint(a[ind]) # This code is contributed# by Mohit Kumar
// C# program to find the smallest number// in an array of decrease and increasing numbersusing System;class Solution{// Function to find the smallest number's indexstatic int minimal(int[] a, int n){ int lo = 0, hi = n - 1; // Do a binary search while (lo < hi) { // Find the mid element int mid = (lo + hi) >> 1; // Check for break point if (a[mid] < a[mid + 1]) { hi = mid; } else { lo = mid + 1; } } // Return the index return lo;} // Driver Codepublic static void Main(){ int[] a = { 8, 5, 4, 3, 4, 10 }; int n = a.Length; int ind = minimal(a, n); // Print the smallest number Console.WriteLine( a[ind]);}}//contributed by Mukul singh
<?php// PHP program to find the smallest number// in an array of decrease and increasing numbers // Function to find the smallest// number's indexfunction minimal($a, $n){ $lo = 0; $hi = $n - 1; // Do a binary search while ($lo < $hi) { // Find the mid element $mid = ($lo + $hi) >> 1; // Check for break point if ($a[$mid] < $a[$mid + 1]) { $hi = $mid; } else { $lo = $mid + 1; } } // Return the index return $lo;} // Driver Code$a = array( 8, 5, 4, 3, 4, 10 );$n = sizeof($a);$ind = minimal($a, $n); // Print the smallest numberecho $a[$ind]; // This code is contributed// by Sach_Code?>
<script> // Javascript program to find the smallest number // in an array of decrease and increasing numbers // Function to find the smallest number's index function minimal(a, n) { let lo = 0, hi = n - 1; // Do a binary search while (lo < hi) { // Find the mid element let mid = (lo + hi) >> 1; // Check for break point if (a[mid] < a[mid + 1]) { hi = mid; } else { lo = mid + 1; } } // Return the index return lo; } let a = [ 8, 5, 4, 3, 4, 10 ]; let n = a.length; let ind = minimal(a, n); // Print the smallest number document.write(a[ind]); </script>
3
Time Complexity: O(Log N) Auxiliary Space: O(1)
andrew1234
Code_Mech
mohit kumar 29
Sach_Code
divyeshrabadiya07
Binary Search
Competitive Programming
Divide and Conquer
Searching
Searching
Divide and Conquer
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multistage Graph (Shortest Path)
Breadth First Traversal ( BFS ) on a 2D array
Difference between Backtracking and Branch-N-Bound technique
Most important type of Algorithms
5 Best Languages for Competitive Programming
Merge Sort
QuickSort
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Program for Tower of Hanoi
|
[
{
"code": null,
"e": 26469,
"s": 26441,
"text": "\n16 Mar, 2021"
},
{
"code": null,
"e": 26661,
"s": 26469,
"text": "Given an array of N integers where array elements form a strictly decreasing and increasing sequence. The task is to find the smallest number in such an array. Constraints: N >= 3 Examples: "
},
{
"code": null,
"e": 26745,
"s": 26661,
"text": "Input: a[] = {2, 1, 2, 3, 4}\nOutput: 1\n\nInput: a[] = {8, 5, 4, 3, 4, 10}\nOutput: 3 "
},
{
"code": null,
"e": 27185,
"s": 26747,
"text": "A naive approach is to linearly traverse the array and find out the smallest number. The time complexity will be thus O(N). An efficient approach is to modify the binary search and use it. Divide the array into two halves use binary search to check if a[mid] < a[mid+1] or not. If a[mid] < a[mid+1], then the smallest number lies in the first half which is low to mid, else it lies in the second half which is mid+1 to high. Algorithm: "
},
{
"code": null,
"e": 27262,
"s": 27185,
"text": "while(lo > 1\n\n if a[mid] < a[mid+1] then hi = mid\n\n else lo = mid+1\n} "
},
{
"code": null,
"e": 27315,
"s": 27262,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27319,
"s": 27315,
"text": "C++"
},
{
"code": null,
"e": 27324,
"s": 27319,
"text": "Java"
},
{
"code": null,
"e": 27332,
"s": 27324,
"text": "Python3"
},
{
"code": null,
"e": 27335,
"s": 27332,
"text": "C#"
},
{
"code": null,
"e": 27339,
"s": 27335,
"text": "PHP"
},
{
"code": null,
"e": 27350,
"s": 27339,
"text": "Javascript"
},
{
"code": "// C++ program to find the smallest number// in an array of decrease and increasing numbers#include <bits/stdc++.h>using namespace std; // Function to find the smallest number's indexint minimal(int a[], int n){ int lo = 0, hi = n - 1; // Do a binary search while (lo < hi) { // Find the mid element int mid = (lo + hi) >> 1; // Check for break point if (a[mid] < a[mid + 1]) { hi = mid; } else { lo = mid + 1; } } // Return the index return lo;} // Driver Codeint main(){ int a[] = { 8, 5, 4, 3, 4, 10 }; int n = sizeof(a) / sizeof(a[0]); int ind = minimal(a, n); // Print the smallest number cout << a[ind];}",
"e": 28070,
"s": 27350,
"text": null
},
{
"code": "// Java program to find the smallest number// in an array of decrease and increasing numbersclass Solution{// Function to find the smallest number's indexstatic int minimal(int a[], int n){ int lo = 0, hi = n - 1; // Do a binary search while (lo < hi) { // Find the mid element int mid = (lo + hi) >> 1; // Check for break point if (a[mid] < a[mid + 1]) { hi = mid; } else { lo = mid + 1; } } // Return the index return lo;} // Driver Codepublic static void main(String args[]){ int a[] = { 8, 5, 4, 3, 4, 10 }; int n = a.length; int ind = minimal(a, n); // Print the smallest number System.out.println( a[ind]);}}//contributed by Arnab Kundu",
"e": 28822,
"s": 28070,
"text": null
},
{
"code": "# Python 3 program to find the smallest# number in a array of decrease and# increasing numbers # function to find the smallest# number's indexdef minimal(a, n): lo, hi = 0, n - 1 # Do a binary search while lo < hi: # find the mid element mid = (lo + hi) // 2 # Check for break point if a[mid] < a[mid + 1]: hi = mid else: lo = mid + 1 return lo # Driver codea = [8, 5, 4, 3, 4, 10] n = len(a) ind = minimal(a, n) # print the smallest numberprint(a[ind]) # This code is contributed# by Mohit Kumar",
"e": 29424,
"s": 28822,
"text": null
},
{
"code": "// C# program to find the smallest number// in an array of decrease and increasing numbersusing System;class Solution{// Function to find the smallest number's indexstatic int minimal(int[] a, int n){ int lo = 0, hi = n - 1; // Do a binary search while (lo < hi) { // Find the mid element int mid = (lo + hi) >> 1; // Check for break point if (a[mid] < a[mid + 1]) { hi = mid; } else { lo = mid + 1; } } // Return the index return lo;} // Driver Codepublic static void Main(){ int[] a = { 8, 5, 4, 3, 4, 10 }; int n = a.Length; int ind = minimal(a, n); // Print the smallest number Console.WriteLine( a[ind]);}}//contributed by Mukul singh",
"e": 30173,
"s": 29424,
"text": null
},
{
"code": "<?php// PHP program to find the smallest number// in an array of decrease and increasing numbers // Function to find the smallest// number's indexfunction minimal($a, $n){ $lo = 0; $hi = $n - 1; // Do a binary search while ($lo < $hi) { // Find the mid element $mid = ($lo + $hi) >> 1; // Check for break point if ($a[$mid] < $a[$mid + 1]) { $hi = $mid; } else { $lo = $mid + 1; } } // Return the index return $lo;} // Driver Code$a = array( 8, 5, 4, 3, 4, 10 );$n = sizeof($a);$ind = minimal($a, $n); // Print the smallest numberecho $a[$ind]; // This code is contributed// by Sach_Code?>",
"e": 30876,
"s": 30173,
"text": null
},
{
"code": "<script> // Javascript program to find the smallest number // in an array of decrease and increasing numbers // Function to find the smallest number's index function minimal(a, n) { let lo = 0, hi = n - 1; // Do a binary search while (lo < hi) { // Find the mid element let mid = (lo + hi) >> 1; // Check for break point if (a[mid] < a[mid + 1]) { hi = mid; } else { lo = mid + 1; } } // Return the index return lo; } let a = [ 8, 5, 4, 3, 4, 10 ]; let n = a.length; let ind = minimal(a, n); // Print the smallest number document.write(a[ind]); </script>",
"e": 31659,
"s": 30876,
"text": null
},
{
"code": null,
"e": 31661,
"s": 31659,
"text": "3"
},
{
"code": null,
"e": 31712,
"s": 31663,
"text": "Time Complexity: O(Log N) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 31723,
"s": 31712,
"text": "andrew1234"
},
{
"code": null,
"e": 31733,
"s": 31723,
"text": "Code_Mech"
},
{
"code": null,
"e": 31748,
"s": 31733,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 31758,
"s": 31748,
"text": "Sach_Code"
},
{
"code": null,
"e": 31776,
"s": 31758,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 31790,
"s": 31776,
"text": "Binary Search"
},
{
"code": null,
"e": 31814,
"s": 31790,
"text": "Competitive Programming"
},
{
"code": null,
"e": 31833,
"s": 31814,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 31843,
"s": 31833,
"text": "Searching"
},
{
"code": null,
"e": 31853,
"s": 31843,
"text": "Searching"
},
{
"code": null,
"e": 31872,
"s": 31853,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 31886,
"s": 31872,
"text": "Binary Search"
},
{
"code": null,
"e": 31984,
"s": 31886,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32017,
"s": 31984,
"text": "Multistage Graph (Shortest Path)"
},
{
"code": null,
"e": 32063,
"s": 32017,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 32124,
"s": 32063,
"text": "Difference between Backtracking and Branch-N-Bound technique"
},
{
"code": null,
"e": 32158,
"s": 32124,
"text": "Most important type of Algorithms"
},
{
"code": null,
"e": 32203,
"s": 32158,
"text": "5 Best Languages for Competitive Programming"
},
{
"code": null,
"e": 32214,
"s": 32203,
"text": "Merge Sort"
},
{
"code": null,
"e": 32224,
"s": 32214,
"text": "QuickSort"
},
{
"code": null,
"e": 32238,
"s": 32224,
"text": "Binary Search"
},
{
"code": null,
"e": 32306,
"s": 32238,
"text": "Maximum and minimum of an array using minimum number of comparisons"
}
] |
How to submit a form or a part of a form without a page refresh using jQuery ? - GeeksforGeeks
|
31 Oct, 2021
In this article, we will learn how to submit a form or a part of a form without a page refresh using JQuery, & will understand its implementation through the example.
How to prevent an HTML form to submit?
Generally, when we submit a form then we should click a submit button then our page will navigate to another route as it is mentioned in the form action attribute but we can do it at the background of the webpage without navigating the web page to other routes. And this is possible by using the event.preventDefault() method which blocks the default event and does not allow it to trigger. When we click the submit button then an event is fired, so we need to prevent this event because this event is responsible to take the user to other routes. So, we have to attach an onsubmit event listener to that form, so that when the user clicks the submit button, we can get that event object and prevent that specific event to fire, by using the preventDefault method. After preventing the event using the event.preventDefault() method then we need to get the form values and make a post request to that particular routes where we want to post our values.
Prerequisite: A basic understanding of HTML, CSS, Javascript, and JQuery is required before we proceed.
Approach:
Create an HTML file & add the jquery library CDN above the javascript code.
Create 2 input fields, a submit button, and a span to display the result.
Add an onsubmit listener to the form and take a callback with one single parameter.
Example: In this example, we have taken a fake post request where we need to post some information and the server will return the id as an object.
HTML
<!DOCTYPE html><html> <head> <style> .container { display: flex; flex-direction: column; align-items: center; justify-content: center; } h1 { color: green; } h3 { text-align: center; } input, span { margin-top: 20px; } </style></head> <body> <div> <h1 class="container"> GeeksforGeeks </h1> <h3>Submitting the form without page refresh</h3> </div> <form> <div class="container"> <input placeholder="Name" type="text" name="Name" /> <input placeholder="Job" type="text" name="job" /> <input type="submit" /> </div> <span class="container"></span> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script> <script type="text/javascript"> $(document).ready(function() { $('form').on('submit', function(event) { event.preventDefault(); // It returns a array of object let userinfo = $(this).serializeArray(); let user = {}; userinfo.forEach((value) => { // Dynamically create an object user[value.name] = value.value; }); let url = "https://reqres.in/api/users"; $.ajax({ method: "POST", url: url, data: user }).done(function(msg) { // When the request is successful $('span').text('user is successfully created with Id ' + msg.id); }).fail(function(err, textstatus, error) { $('span').text(textstatus); }); }); }); </script></body> </html>
Output:
CSS-Basics
HTML-Basics
javascript-basics
jQuery-Questions
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show and Hide div elements using radio buttons?
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
jQuery | removeAttr() with Examples
How to get the value in an input text box using jQuery ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 27064,
"s": 27036,
"text": "\n31 Oct, 2021"
},
{
"code": null,
"e": 27231,
"s": 27064,
"text": "In this article, we will learn how to submit a form or a part of a form without a page refresh using JQuery, & will understand its implementation through the example."
},
{
"code": null,
"e": 27270,
"s": 27231,
"text": "How to prevent an HTML form to submit?"
},
{
"code": null,
"e": 28222,
"s": 27270,
"text": "Generally, when we submit a form then we should click a submit button then our page will navigate to another route as it is mentioned in the form action attribute but we can do it at the background of the webpage without navigating the web page to other routes. And this is possible by using the event.preventDefault() method which blocks the default event and does not allow it to trigger. When we click the submit button then an event is fired, so we need to prevent this event because this event is responsible to take the user to other routes. So, we have to attach an onsubmit event listener to that form, so that when the user clicks the submit button, we can get that event object and prevent that specific event to fire, by using the preventDefault method. After preventing the event using the event.preventDefault() method then we need to get the form values and make a post request to that particular routes where we want to post our values."
},
{
"code": null,
"e": 28326,
"s": 28222,
"text": "Prerequisite: A basic understanding of HTML, CSS, Javascript, and JQuery is required before we proceed."
},
{
"code": null,
"e": 28338,
"s": 28328,
"text": "Approach:"
},
{
"code": null,
"e": 28414,
"s": 28338,
"text": "Create an HTML file & add the jquery library CDN above the javascript code."
},
{
"code": null,
"e": 28488,
"s": 28414,
"text": "Create 2 input fields, a submit button, and a span to display the result."
},
{
"code": null,
"e": 28572,
"s": 28488,
"text": "Add an onsubmit listener to the form and take a callback with one single parameter."
},
{
"code": null,
"e": 28719,
"s": 28572,
"text": "Example: In this example, we have taken a fake post request where we need to post some information and the server will return the id as an object."
},
{
"code": null,
"e": 28724,
"s": 28719,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .container { display: flex; flex-direction: column; align-items: center; justify-content: center; } h1 { color: green; } h3 { text-align: center; } input, span { margin-top: 20px; } </style></head> <body> <div> <h1 class=\"container\"> GeeksforGeeks </h1> <h3>Submitting the form without page refresh</h3> </div> <form> <div class=\"container\"> <input placeholder=\"Name\" type=\"text\" name=\"Name\" /> <input placeholder=\"Job\" type=\"text\" name=\"job\" /> <input type=\"submit\" /> </div> <span class=\"container\"></span> </form> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js\"> </script> <script type=\"text/javascript\"> $(document).ready(function() { $('form').on('submit', function(event) { event.preventDefault(); // It returns a array of object let userinfo = $(this).serializeArray(); let user = {}; userinfo.forEach((value) => { // Dynamically create an object user[value.name] = value.value; }); let url = \"https://reqres.in/api/users\"; $.ajax({ method: \"POST\", url: url, data: user }).done(function(msg) { // When the request is successful $('span').text('user is successfully created with Id ' + msg.id); }).fail(function(err, textstatus, error) { $('span').text(textstatus); }); }); }); </script></body> </html>",
"e": 30530,
"s": 28724,
"text": null
},
{
"code": null,
"e": 30538,
"s": 30530,
"text": "Output:"
},
{
"code": null,
"e": 30549,
"s": 30538,
"text": "CSS-Basics"
},
{
"code": null,
"e": 30561,
"s": 30549,
"text": "HTML-Basics"
},
{
"code": null,
"e": 30579,
"s": 30561,
"text": "javascript-basics"
},
{
"code": null,
"e": 30596,
"s": 30579,
"text": "jQuery-Questions"
},
{
"code": null,
"e": 30603,
"s": 30596,
"text": "Picked"
},
{
"code": null,
"e": 30610,
"s": 30603,
"text": "JQuery"
},
{
"code": null,
"e": 30627,
"s": 30610,
"text": "Web Technologies"
},
{
"code": null,
"e": 30725,
"s": 30627,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30780,
"s": 30725,
"text": "How to Show and Hide div elements using radio buttons?"
},
{
"code": null,
"e": 30853,
"s": 30780,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 30876,
"s": 30853,
"text": "jQuery | ajax() Method"
},
{
"code": null,
"e": 30912,
"s": 30876,
"text": "jQuery | removeAttr() with Examples"
},
{
"code": null,
"e": 30969,
"s": 30912,
"text": "How to get the value in an input text box using jQuery ?"
},
{
"code": null,
"e": 31009,
"s": 30969,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31042,
"s": 31009,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31087,
"s": 31042,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31130,
"s": 31087,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
FLAIR - A Framework for NLP - GeeksforGeeks
|
26 Nov, 2020
What is FLAIR?
It is a simple framework for state-of-the-art NLP. It is a very powerful library which is developed by Zalando Research. The Flair framework is built on top of PyTorch.
What are the Features available in Flair?
Flair supports a number of word embeddings used to perform NLP tasks such as FastText, ELMo, GloVe, BERT and its variants, XLM, and Byte Pair Embeddings including Flair Embedding.The Flair Embedding is based on the concept of contextual string embeddings which is used for Sequence Labelling.Using Flair you can also combine different word embeddings together to get better results.Flair supports a number of languages.
Flair supports a number of word embeddings used to perform NLP tasks such as FastText, ELMo, GloVe, BERT and its variants, XLM, and Byte Pair Embeddings including Flair Embedding.
The Flair Embedding is based on the concept of contextual string embeddings which is used for Sequence Labelling.
Using Flair you can also combine different word embeddings together to get better results.
Flair supports a number of languages.
Contextual String Embeddings:
In this word embedding each of the letters in the words are sent to the Character Language Model and then the input representation is taken out from the forward and backward LSTMs.
The input representation for the word ‘Washington’ is been considered based on the context before the word ‘Washington’. The first and last character states of each word is taken in order to generate the word embeddings.
You can see that for the word ‘Washington’ the red mark is the forward LSTM output and the blue mark is the backward LSTM output. Both forward and backward contexts are concatenated to obtain the input representation of the word ‘Washington’.
After getting the input representation it is fed to the forward and backward LSTM to get the particular task that you are dealing with. In the diagram mentioned we are trying to get the NER.
Installation of Flair:
You should have PyTorch >=1.1 and Python >=3.6 installed. To install PyTorch on anaconda run the below command-
conda install -c pytorch pytorch
To install flair, run –
pip install flair
Working of Flair
1) Flair Datatypes:
Flair offers two types of objects. They are:
SentenceTokens
Sentence
Tokens
To get the number of tokens in a sentence:
Python3
import flairfrom flair.data import Sentence # take a sentences= Sentence('GeeksforGeeks is Awesome.')print(s)
Output:
2) NER Tags:
To predict tags for a given sentence we will use a pre-trained model as shown below:
Python3
import flairfrom flair.data import Sentencefrom flair.models import SequenceTagger # input a sentences = Sentence('GeeksforGeeks is Awesome.') # loading NER taggertagger_NER= SequenceTagger.load('ner') # run NER over sentencetagger_NER.predict(s)print(s)print('The following NER tags are found:\n') # iterate and printfor entity in s.get_spans('ner'): print(entity)
Output:
3) Word Embeddings:
Word embeddings give embeddings for each word of the text. As discussed earlier Flair supports many word embeddings including its own Flair Embeddings. Here we will see how to implement some of them.
A) Classic Word Embeddings – This class of word embeddings are static. In this, each distinct word is given only one pre-computed embedding. Most of the common word embeddings lie in this category including the GloVe embedding.
Python3
import flairfrom flair.data import Sentencefrom flair.embeddings import WordEmbeddings # using glove embeddingGloVe_embedding = WordEmbeddings('glove') # input a sentences = Sentence('Geeks for Geeks helps me study.') # embed the sentenceGloVe_embedding.embed(s) # print the embedded tokensfor token in s: print(token) print(token.embedding)
Output:
Note: You can see here that the embeddings for the word ‘Geeks‘ are the same for both the occurrences.
B) Flair Embedding – This works on the concept of contextual string embeddings. It captures latent syntactic-semantic information. The word embeddings are contextualized by their surrounding words. It thus gives different embeddings for the same word depending on it’s surrounding text.
Python3
import flairfrom flair.data import Sentencefrom flair.embeddings import FlairEmbeddings # using forward flair embeddingembeddingforward_flair_embedding= FlairEmbeddings('news-forward-fast') # input the sentences = Sentence('Geeks for Geeks helps me study.') # embed words in the input sentenceforward_flair_embedding.embed(s) # print the embedded tokensfor token in s: print(token) print(token.embedding)
Output:
Note: Here we see that the embeddings for the word ‘Geeks’ are different for both the occurrences depending on the contextual information around them.
C) Stacked Embeddings – Using these embeddings you can combine different embeddings together. Let’s see how to combine GloVe, forward and backward Flair embeddings:
Python3
import flairfrom flair.data import Sentencefrom flair.embeddings import FlairEmbeddings, WordEmbeddingsfrom flair.embeddings import StackedEmbeddings# flair embeddingsforward_flair_embedding= FlairEmbeddings('news-forward-fast')backward_flair_embedding= FlairEmbeddings('news-backward-fast') # glove embeddingGloVe_embedding = WordEmbeddings('glove') # create a object which combines the two embeddingsstacked_embeddings = StackedEmbeddings([forward_flair_embedding, backward_flair_embedding, GloVe_embedding,]) # input the sentences = Sentence('Geeks for Geeks helps me study.') # embed the input sentence with the stacked embeddingstacked_embeddings.embed(s) # print the embedded tokensfor token in s: print(token) print(token.embedding)
Output:
4) Document Embeddings:
, Unlike word embeddings, document embeddings give a single embedding for the entire text. The document embeddings offered in Flair are:
A) Transformer Document Embeddings
B) Sentence Transformer Document Embeddings
C) Document RNN Embeddings
D) Document Pool Embeddings
Let’s have a look at how the Document Pool Embeddings work-
Document Pool Embeddings — It is a very simple document embedding and it pooled over all the word embeddings and returns the average of all of them.
Python3
import flairfrom flair.data import Sentencefrom flair.embeddings import WordEmbeddings, DocumentPoolEmbeddings # init the glove word embeddingGloVe_embedding = WordEmbeddings('glove') # init the document embeddingdoc_embeddings = DocumentPoolEmbeddings([GloVe_embedding]) # input the sentences = Sentence('Geeks for Geeks helps me study.') #embed the input sentence with the document embeddingdoc_embeddings.embed(s) # print the embedded tokensprint(s.embedding)
Output:
Similarly, you can use other Document embeddings as well.
5) Training a Text Classification Model using Flair:
We are going to use the ‘TREC_6’ dataset available in Flair. You can also use your own datasets as well. To train our model we will be using the Document RNN Embeddings which trains an RNN over all the word embeddings in a sentence. The word embeddings which we will be using are the GloVe and the forward flair embedding.
Python3
from flair.data import Corpusfrom flair.datasets import TREC_6from flair.embeddings import WordEmbeddings, FlairEmbeddings, DocumentRNNEmbeddingsfrom flair.models import TextClassifierfrom flair.trainers import ModelTrainer # load the corpuscorpus = TREC_6() # create a label dictionarylabel_Dictionary = corpus.make_label_dictionary() # list of word embeddings to be usedword_embeddings = [WordEmbeddings('glove'),FlairEmbeddings('news-forward-fast')] # init document embeddings and pass the word embeddings listdoc_embeddings = DocumentRNNEmbeddings(word_embeddings,hidden_size = 250) # creating the text classifiertext_classifier = TextClassifier(doc_embeddings,label_dictionary = label_Dictionary) # init the text classifier trainermodel_trainer = ModelTrainer(text_classifier,corpus) # train your modelmodel_trainer.train('resources/taggers/trec',learning_rate=0.1,mini_batch_size=40,anneal_factor=0.5,patience=5,max_epochs=200)
Results of training:
The accuracy of the model is around 95%.
Predictions: Now we can load the model and make predictions-
Python3
from flair.data import Sentencefrom flair.models import TextClassifierc = TextClassifier.load('resources/taggers/trec/final-model.pt') # input example sentences = Sentence('Who is the President of India ?') # predict class and printc.predict(s) # print the labelsprint(s.labels)
Output:
[HUM (1.0)]
Now you would have got a rough idea of how to use the Flair library.
Natural-language-processing
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Support Vector Machine Algorithm
Intuition of Adam Optimizer
Introduction to Recurrent Neural Network
CNN | Introduction to Pooling Layer
Singular Value Decomposition (SVD)
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": 25699,
"s": 25671,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 25714,
"s": 25699,
"text": "What is FLAIR?"
},
{
"code": null,
"e": 25883,
"s": 25714,
"text": "It is a simple framework for state-of-the-art NLP. It is a very powerful library which is developed by Zalando Research. The Flair framework is built on top of PyTorch."
},
{
"code": null,
"e": 25925,
"s": 25883,
"text": "What are the Features available in Flair?"
},
{
"code": null,
"e": 26345,
"s": 25925,
"text": "Flair supports a number of word embeddings used to perform NLP tasks such as FastText, ELMo, GloVe, BERT and its variants, XLM, and Byte Pair Embeddings including Flair Embedding.The Flair Embedding is based on the concept of contextual string embeddings which is used for Sequence Labelling.Using Flair you can also combine different word embeddings together to get better results.Flair supports a number of languages."
},
{
"code": null,
"e": 26525,
"s": 26345,
"text": "Flair supports a number of word embeddings used to perform NLP tasks such as FastText, ELMo, GloVe, BERT and its variants, XLM, and Byte Pair Embeddings including Flair Embedding."
},
{
"code": null,
"e": 26639,
"s": 26525,
"text": "The Flair Embedding is based on the concept of contextual string embeddings which is used for Sequence Labelling."
},
{
"code": null,
"e": 26730,
"s": 26639,
"text": "Using Flair you can also combine different word embeddings together to get better results."
},
{
"code": null,
"e": 26768,
"s": 26730,
"text": "Flair supports a number of languages."
},
{
"code": null,
"e": 26798,
"s": 26768,
"text": "Contextual String Embeddings:"
},
{
"code": null,
"e": 26979,
"s": 26798,
"text": "In this word embedding each of the letters in the words are sent to the Character Language Model and then the input representation is taken out from the forward and backward LSTMs."
},
{
"code": null,
"e": 27200,
"s": 26979,
"text": "The input representation for the word ‘Washington’ is been considered based on the context before the word ‘Washington’. The first and last character states of each word is taken in order to generate the word embeddings."
},
{
"code": null,
"e": 27443,
"s": 27200,
"text": "You can see that for the word ‘Washington’ the red mark is the forward LSTM output and the blue mark is the backward LSTM output. Both forward and backward contexts are concatenated to obtain the input representation of the word ‘Washington’."
},
{
"code": null,
"e": 27634,
"s": 27443,
"text": "After getting the input representation it is fed to the forward and backward LSTM to get the particular task that you are dealing with. In the diagram mentioned we are trying to get the NER."
},
{
"code": null,
"e": 27657,
"s": 27634,
"text": "Installation of Flair:"
},
{
"code": null,
"e": 27769,
"s": 27657,
"text": "You should have PyTorch >=1.1 and Python >=3.6 installed. To install PyTorch on anaconda run the below command-"
},
{
"code": null,
"e": 27803,
"s": 27769,
"text": "conda install -c pytorch pytorch\n"
},
{
"code": null,
"e": 27827,
"s": 27803,
"text": "To install flair, run –"
},
{
"code": null,
"e": 27846,
"s": 27827,
"text": "pip install flair\n"
},
{
"code": null,
"e": 27863,
"s": 27846,
"text": "Working of Flair"
},
{
"code": null,
"e": 27883,
"s": 27863,
"text": "1) Flair Datatypes:"
},
{
"code": null,
"e": 27928,
"s": 27883,
"text": "Flair offers two types of objects. They are:"
},
{
"code": null,
"e": 27943,
"s": 27928,
"text": "SentenceTokens"
},
{
"code": null,
"e": 27952,
"s": 27943,
"text": "Sentence"
},
{
"code": null,
"e": 27959,
"s": 27952,
"text": "Tokens"
},
{
"code": null,
"e": 28002,
"s": 27959,
"text": "To get the number of tokens in a sentence:"
},
{
"code": null,
"e": 28010,
"s": 28002,
"text": "Python3"
},
{
"code": "import flairfrom flair.data import Sentence # take a sentences= Sentence('GeeksforGeeks is Awesome.')print(s)",
"e": 28121,
"s": 28010,
"text": null
},
{
"code": null,
"e": 28129,
"s": 28121,
"text": "Output:"
},
{
"code": null,
"e": 28142,
"s": 28129,
"text": "2) NER Tags:"
},
{
"code": null,
"e": 28227,
"s": 28142,
"text": "To predict tags for a given sentence we will use a pre-trained model as shown below:"
},
{
"code": null,
"e": 28235,
"s": 28227,
"text": "Python3"
},
{
"code": "import flairfrom flair.data import Sentencefrom flair.models import SequenceTagger # input a sentences = Sentence('GeeksforGeeks is Awesome.') # loading NER taggertagger_NER= SequenceTagger.load('ner') # run NER over sentencetagger_NER.predict(s)print(s)print('The following NER tags are found:\\n') # iterate and printfor entity in s.get_spans('ner'): print(entity)",
"e": 28608,
"s": 28235,
"text": null
},
{
"code": null,
"e": 28616,
"s": 28608,
"text": "Output:"
},
{
"code": null,
"e": 28636,
"s": 28616,
"text": "3) Word Embeddings:"
},
{
"code": null,
"e": 28836,
"s": 28636,
"text": "Word embeddings give embeddings for each word of the text. As discussed earlier Flair supports many word embeddings including its own Flair Embeddings. Here we will see how to implement some of them."
},
{
"code": null,
"e": 29064,
"s": 28836,
"text": "A) Classic Word Embeddings – This class of word embeddings are static. In this, each distinct word is given only one pre-computed embedding. Most of the common word embeddings lie in this category including the GloVe embedding."
},
{
"code": null,
"e": 29072,
"s": 29064,
"text": "Python3"
},
{
"code": "import flairfrom flair.data import Sentencefrom flair.embeddings import WordEmbeddings # using glove embeddingGloVe_embedding = WordEmbeddings('glove') # input a sentences = Sentence('Geeks for Geeks helps me study.') # embed the sentenceGloVe_embedding.embed(s) # print the embedded tokensfor token in s: print(token) print(token.embedding)",
"e": 29425,
"s": 29072,
"text": null
},
{
"code": null,
"e": 29433,
"s": 29425,
"text": "Output:"
},
{
"code": null,
"e": 29536,
"s": 29433,
"text": "Note: You can see here that the embeddings for the word ‘Geeks‘ are the same for both the occurrences."
},
{
"code": null,
"e": 29823,
"s": 29536,
"text": "B) Flair Embedding – This works on the concept of contextual string embeddings. It captures latent syntactic-semantic information. The word embeddings are contextualized by their surrounding words. It thus gives different embeddings for the same word depending on it’s surrounding text."
},
{
"code": null,
"e": 29831,
"s": 29823,
"text": "Python3"
},
{
"code": "import flairfrom flair.data import Sentencefrom flair.embeddings import FlairEmbeddings # using forward flair embeddingembeddingforward_flair_embedding= FlairEmbeddings('news-forward-fast') # input the sentences = Sentence('Geeks for Geeks helps me study.') # embed words in the input sentenceforward_flair_embedding.embed(s) # print the embedded tokensfor token in s: print(token) print(token.embedding)",
"e": 30246,
"s": 29831,
"text": null
},
{
"code": null,
"e": 30254,
"s": 30246,
"text": "Output:"
},
{
"code": null,
"e": 30405,
"s": 30254,
"text": "Note: Here we see that the embeddings for the word ‘Geeks’ are different for both the occurrences depending on the contextual information around them."
},
{
"code": null,
"e": 30570,
"s": 30405,
"text": "C) Stacked Embeddings – Using these embeddings you can combine different embeddings together. Let’s see how to combine GloVe, forward and backward Flair embeddings:"
},
{
"code": null,
"e": 30578,
"s": 30570,
"text": "Python3"
},
{
"code": "import flairfrom flair.data import Sentencefrom flair.embeddings import FlairEmbeddings, WordEmbeddingsfrom flair.embeddings import StackedEmbeddings# flair embeddingsforward_flair_embedding= FlairEmbeddings('news-forward-fast')backward_flair_embedding= FlairEmbeddings('news-backward-fast') # glove embeddingGloVe_embedding = WordEmbeddings('glove') # create a object which combines the two embeddingsstacked_embeddings = StackedEmbeddings([forward_flair_embedding, backward_flair_embedding, GloVe_embedding,]) # input the sentences = Sentence('Geeks for Geeks helps me study.') # embed the input sentence with the stacked embeddingstacked_embeddings.embed(s) # print the embedded tokensfor token in s: print(token) print(token.embedding)",
"e": 31447,
"s": 30578,
"text": null
},
{
"code": null,
"e": 31455,
"s": 31447,
"text": "Output:"
},
{
"code": null,
"e": 31479,
"s": 31455,
"text": "4) Document Embeddings:"
},
{
"code": null,
"e": 31616,
"s": 31479,
"text": ", Unlike word embeddings, document embeddings give a single embedding for the entire text. The document embeddings offered in Flair are:"
},
{
"code": null,
"e": 31651,
"s": 31616,
"text": "A) Transformer Document Embeddings"
},
{
"code": null,
"e": 31695,
"s": 31651,
"text": "B) Sentence Transformer Document Embeddings"
},
{
"code": null,
"e": 31722,
"s": 31695,
"text": "C) Document RNN Embeddings"
},
{
"code": null,
"e": 31750,
"s": 31722,
"text": "D) Document Pool Embeddings"
},
{
"code": null,
"e": 31810,
"s": 31750,
"text": "Let’s have a look at how the Document Pool Embeddings work-"
},
{
"code": null,
"e": 31960,
"s": 31810,
"text": "Document Pool Embeddings — It is a very simple document embedding and it pooled over all the word embeddings and returns the average of all of them."
},
{
"code": null,
"e": 31968,
"s": 31960,
"text": "Python3"
},
{
"code": "import flairfrom flair.data import Sentencefrom flair.embeddings import WordEmbeddings, DocumentPoolEmbeddings # init the glove word embeddingGloVe_embedding = WordEmbeddings('glove') # init the document embeddingdoc_embeddings = DocumentPoolEmbeddings([GloVe_embedding]) # input the sentences = Sentence('Geeks for Geeks helps me study.') #embed the input sentence with the document embeddingdoc_embeddings.embed(s) # print the embedded tokensprint(s.embedding)",
"e": 32476,
"s": 31968,
"text": null
},
{
"code": null,
"e": 32484,
"s": 32476,
"text": "Output:"
},
{
"code": null,
"e": 32542,
"s": 32484,
"text": "Similarly, you can use other Document embeddings as well."
},
{
"code": null,
"e": 32595,
"s": 32542,
"text": "5) Training a Text Classification Model using Flair:"
},
{
"code": null,
"e": 32918,
"s": 32595,
"text": "We are going to use the ‘TREC_6’ dataset available in Flair. You can also use your own datasets as well. To train our model we will be using the Document RNN Embeddings which trains an RNN over all the word embeddings in a sentence. The word embeddings which we will be using are the GloVe and the forward flair embedding."
},
{
"code": null,
"e": 32926,
"s": 32918,
"text": "Python3"
},
{
"code": "from flair.data import Corpusfrom flair.datasets import TREC_6from flair.embeddings import WordEmbeddings, FlairEmbeddings, DocumentRNNEmbeddingsfrom flair.models import TextClassifierfrom flair.trainers import ModelTrainer # load the corpuscorpus = TREC_6() # create a label dictionarylabel_Dictionary = corpus.make_label_dictionary() # list of word embeddings to be usedword_embeddings = [WordEmbeddings('glove'),FlairEmbeddings('news-forward-fast')] # init document embeddings and pass the word embeddings listdoc_embeddings = DocumentRNNEmbeddings(word_embeddings,hidden_size = 250) # creating the text classifiertext_classifier = TextClassifier(doc_embeddings,label_dictionary = label_Dictionary) # init the text classifier trainermodel_trainer = ModelTrainer(text_classifier,corpus) # train your modelmodel_trainer.train('resources/taggers/trec',learning_rate=0.1,mini_batch_size=40,anneal_factor=0.5,patience=5,max_epochs=200)",
"e": 33867,
"s": 32926,
"text": null
},
{
"code": null,
"e": 33888,
"s": 33867,
"text": "Results of training:"
},
{
"code": null,
"e": 33929,
"s": 33888,
"text": "The accuracy of the model is around 95%."
},
{
"code": null,
"e": 33990,
"s": 33929,
"text": "Predictions: Now we can load the model and make predictions-"
},
{
"code": null,
"e": 33998,
"s": 33990,
"text": "Python3"
},
{
"code": "from flair.data import Sentencefrom flair.models import TextClassifierc = TextClassifier.load('resources/taggers/trec/final-model.pt') # input example sentences = Sentence('Who is the President of India ?') # predict class and printc.predict(s) # print the labelsprint(s.labels)",
"e": 34280,
"s": 33998,
"text": null
},
{
"code": null,
"e": 34288,
"s": 34280,
"text": "Output:"
},
{
"code": null,
"e": 34300,
"s": 34288,
"text": "[HUM (1.0)]"
},
{
"code": null,
"e": 34369,
"s": 34300,
"text": "Now you would have got a rough idea of how to use the Flair library."
},
{
"code": null,
"e": 34397,
"s": 34369,
"text": "Natural-language-processing"
},
{
"code": null,
"e": 34414,
"s": 34397,
"text": "Machine Learning"
},
{
"code": null,
"e": 34421,
"s": 34414,
"text": "Python"
},
{
"code": null,
"e": 34438,
"s": 34421,
"text": "Machine Learning"
},
{
"code": null,
"e": 34536,
"s": 34438,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34569,
"s": 34536,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 34597,
"s": 34569,
"text": "Intuition of Adam Optimizer"
},
{
"code": null,
"e": 34638,
"s": 34597,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 34674,
"s": 34638,
"text": "CNN | Introduction to Pooling Layer"
},
{
"code": null,
"e": 34709,
"s": 34674,
"text": "Singular Value Decomposition (SVD)"
},
{
"code": null,
"e": 34737,
"s": 34709,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 34787,
"s": 34737,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 34809,
"s": 34787,
"text": "Python map() function"
}
] |
Conditional rendering in React.js
|
Using conditional statements specific components can be rendered and removed . Conditional handling works similarly in JavaScript and React.js
function DisplayUserMessage( props ){
const user = props.user.type;
if(type==’Player’){
return <h1>Player </player>;
}
If( type==’Admin’){
Return <h1>Admin </h1>;
}
}
If statement is used in above example. Type of user decides which message to return.
Local state of component is useful in deciding the conditional rendering as state is flexible to change inside the component.
function MessageSizeChecker(props) {
const message = props.message;
return (
<div>
<h1>Hello!</h1>
{message.length > 100 &&
<h2>
Message size is greater than 100
</h2>
}
</div>
);
}
If the first argument to the && operator evaluates to true then second argument is rendered on the screen.
Inline if else with ternary operator −
Its having a syntax like condition ? ‘ first’ : ‘second’;
function MessageSizeChecker(props) {
const message = props.message;
return (
<div>
<h1>Hello!</h1>
{message.length > 100 ? ‘Message size is greater than 100’: ‘Message size is ok’}
</div>
);
}
This ternary expression can be used on number of block statement but it becomes tedious to understand . So to keep it simple it should be used on simple conditions.
We can decide which component to render.
render() {
const isPlayer = this.state.user.isPlayer;
return (
<div>
{ isPlayer ? (
<Player >
) : (
<Admin />
)
}
</div>
);
}
To prevent the component from rendering , we can return a null as well. But just returning null from render method does not prevent the further applicable lifecycles of React
|
[
{
"code": null,
"e": 1205,
"s": 1062,
"text": "Using conditional statements specific components can be rendered and removed . Conditional handling works similarly in JavaScript and React.js"
},
{
"code": null,
"e": 1399,
"s": 1205,
"text": "function DisplayUserMessage( props ){\n const user = props.user.type;\n if(type==’Player’){\n return <h1>Player </player>;\n }\n If( type==’Admin’){\n Return <h1>Admin </h1>;\n }\n}"
},
{
"code": null,
"e": 1484,
"s": 1399,
"text": "If statement is used in above example. Type of user decides which message to return."
},
{
"code": null,
"e": 1610,
"s": 1484,
"text": "Local state of component is useful in deciding the conditional rendering as state is flexible to change inside the component."
},
{
"code": null,
"e": 1879,
"s": 1610,
"text": "function MessageSizeChecker(props) {\n const message = props.message;\n return (\n <div>\n <h1>Hello!</h1>\n {message.length > 100 &&\n <h2>\n Message size is greater than 100\n </h2>\n }\n </div>\n );\n}"
},
{
"code": null,
"e": 1986,
"s": 1879,
"text": "If the first argument to the && operator evaluates to true then second argument is rendered on the screen."
},
{
"code": null,
"e": 2025,
"s": 1986,
"text": "Inline if else with ternary operator −"
},
{
"code": null,
"e": 2083,
"s": 2025,
"text": "Its having a syntax like condition ? ‘ first’ : ‘second’;"
},
{
"code": null,
"e": 2315,
"s": 2083,
"text": "function MessageSizeChecker(props) {\n const message = props.message;\n return (\n <div>\n <h1>Hello!</h1>\n {message.length > 100 ? ‘Message size is greater than 100’: ‘Message size is ok’}\n </div>\n );\n}"
},
{
"code": null,
"e": 2480,
"s": 2315,
"text": "This ternary expression can be used on number of block statement but it becomes tedious to understand . So to keep it simple it should be used on simple conditions."
},
{
"code": null,
"e": 2521,
"s": 2480,
"text": "We can decide which component to render."
},
{
"code": null,
"e": 2734,
"s": 2521,
"text": "render() {\n const isPlayer = this.state.user.isPlayer;\n return (\n <div>\n { isPlayer ? (\n <Player >\n ) : (\n <Admin />\n )\n }\n </div>\n );\n}"
},
{
"code": null,
"e": 2909,
"s": 2734,
"text": "To prevent the component from rendering , we can return a null as well. But just returning null from render method does not prevent the further applicable lifecycles of React"
}
] |
Replace an element from a Java List using ListIterator
|
Let us first create a Java List and add elements −
ArrayList < String > list = new ArrayList < String > ();
list.add("Katie");
list.add("Tom");
list.add("Jack");
list.add("Amy");
list.add("Andre");
list.add("Brad");
list.add("Peter");
list.add("Bradley");
Now, use ListIterator and return the next element in the List with next() −
ListIterator<String>iterator = list.listIterator();
iterator.next();
Replace the element in the List with set() method. Here, whatever element is set will get replaced as the first element of the Iterator −
iterator.set("Angelina");
Live Demo
import java.util.ArrayList;
import java.util.ListIterator;
public class Demo {
public static void main(String[] args) {
ArrayList<String>list = new ArrayList<String>();
list.add("Katie");
list.add("Tom");
list.add("Jack");
list.add("Amy");
list.add("Andre");
list.add("Brad");
list.add("Peter");
list.add("Bradley");
System.out.println("Initial list..");
for (String str: list) {
System.out.println(str);
}
ListIterator<String>iterator = list.listIterator();
iterator.next();
iterator.set("Angelina");
System.out.println("After replacing an element...");
for (String str: list) {
System.out.println(str);
}
}
}
Initial list..
Katie
Tom
Jack
Amy
Andre
Brad
Peter
Bradley
After replacing an element...
Angelina
Tom
Jack
Amy
Andre
Brad
Peter
Bradley
|
[
{
"code": null,
"e": 1113,
"s": 1062,
"text": "Let us first create a Java List and add elements −"
},
{
"code": null,
"e": 1318,
"s": 1113,
"text": "ArrayList < String > list = new ArrayList < String > ();\nlist.add(\"Katie\");\nlist.add(\"Tom\");\nlist.add(\"Jack\");\nlist.add(\"Amy\");\nlist.add(\"Andre\");\nlist.add(\"Brad\");\nlist.add(\"Peter\");\nlist.add(\"Bradley\");"
},
{
"code": null,
"e": 1394,
"s": 1318,
"text": "Now, use ListIterator and return the next element in the List with next() −"
},
{
"code": null,
"e": 1463,
"s": 1394,
"text": "ListIterator<String>iterator = list.listIterator();\niterator.next();"
},
{
"code": null,
"e": 1601,
"s": 1463,
"text": "Replace the element in the List with set() method. Here, whatever element is set will get replaced as the first element of the Iterator −"
},
{
"code": null,
"e": 1627,
"s": 1601,
"text": "iterator.set(\"Angelina\");"
},
{
"code": null,
"e": 1638,
"s": 1627,
"text": " Live Demo"
},
{
"code": null,
"e": 2381,
"s": 1638,
"text": "import java.util.ArrayList;\nimport java.util.ListIterator;\npublic class Demo {\n public static void main(String[] args) {\n ArrayList<String>list = new ArrayList<String>();\n list.add(\"Katie\");\n list.add(\"Tom\");\n list.add(\"Jack\");\n list.add(\"Amy\");\n list.add(\"Andre\");\n list.add(\"Brad\");\n list.add(\"Peter\");\n list.add(\"Bradley\");\n System.out.println(\"Initial list..\");\n for (String str: list) {\n System.out.println(str);\n }\n ListIterator<String>iterator = list.listIterator();\n iterator.next();\n iterator.set(\"Angelina\");\n System.out.println(\"After replacing an element...\");\n for (String str: list) {\n System.out.println(str);\n }\n }\n}"
},
{
"code": null,
"e": 2517,
"s": 2381,
"text": "Initial list..\nKatie\nTom\nJack\nAmy\nAndre\nBrad\nPeter\nBradley\nAfter replacing an element...\nAngelina\nTom\nJack\nAmy\nAndre\nBrad\nPeter\nBradley"
}
] |
Apache Pig - COUNT()
|
The COUNT() function of Pig Latin is used to get the number of elements in a bag. While counting the number of tuples in a bag, the COUNT() function ignores (will not count) the tuples having a NULL value in the FIRST FIELD.
Note −
To get the global count value (total number of tuples in a bag), we need to perform a Group All operation, and calculate the count value using the COUNT() function.
To get the global count value (total number of tuples in a bag), we need to perform a Group All operation, and calculate the count value using the COUNT() function.
To get the count value of a group (Number of tuples in a group), we need to group it using the Group By operator and proceed with the count function.
To get the count value of a group (Number of tuples in a group), we need to group it using the Group By operator and proceed with the count function.
Given below is the syntax of the COUNT() function.
grunt> COUNT(expression)
Assume that we have a file named student_details.txt in the HDFS directory /pig_data/ as shown below.
student_details.txt
001,Rajiv,Reddy,21,9848022337,Hyderabad,89
002,siddarth,Battacharya,22,9848022338,Kolkata,78
003,Rajesh,Khanna,22,9848022339,Delhi,90
004,Preethi,Agarwal,21,9848022330,Pune,93
005,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar,75
006,Archana,Mishra,23,9848022335,Chennai,87
007,Komal,Nayak,24,9848022334,trivendram,83
008,Bharathi,Nambiayar,24,9848022333,Chennai,72
And we have loaded this file into Pig with the relation named student_details as shown below.
grunt> student_details = LOAD 'hdfs://localhost:9000/pig_data/student_details.txt' USING PigStorage(',')
as (id:int, firstname:chararray, lastname:chararray, age:int, phone:chararray, city:chararray, gpa:int);
We can use the built-in function COUNT() (case sensitive) to calculate the number of tuples in a relation. Let us group the relation student_details using the Group All operator, and store the result in the relation named student_group_all as shown below.
grunt> student_group_all = Group student_details All;
It will produce a relation as shown below.
grunt> Dump student_group_all;
(all,{(8,Bharathi,Nambiayar,24,9848022333,Chennai,72),
(7,Komal,Nayak,24,9848022 334,trivendram,83),
(6,Archana,Mishra,23,9848022335,Chennai,87),
(5,Trupthi,Mohan thy,23,9848022336,Bhuwaneshwar,75),
(4,Preethi,Agarwal,21,9848022330,Pune,93),
(3 ,Rajesh,Khanna,22,9848022339,Delhi,90),
(2,siddarth,Battacharya,22,9848022338,Ko lkata,78),
(1,Rajiv,Reddy,21,9848022337,Hyderabad,89)})
Let us now calculate number of tuples/records in the relation.
grunt> student_count = foreach student_group_all Generate COUNT(student_details.gpa);
Verify the relation student_count using the DUMP operator as shown below.
grunt> Dump student_count;
It will produce the following output, displaying the contents of the relation student_count.
8
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2909,
"s": 2684,
"text": "The COUNT() function of Pig Latin is used to get the number of elements in a bag. While counting the number of tuples in a bag, the COUNT() function ignores (will not count) the tuples having a NULL value in the FIRST FIELD."
},
{
"code": null,
"e": 2916,
"s": 2909,
"text": "Note −"
},
{
"code": null,
"e": 3081,
"s": 2916,
"text": "To get the global count value (total number of tuples in a bag), we need to perform a Group All operation, and calculate the count value using the COUNT() function."
},
{
"code": null,
"e": 3246,
"s": 3081,
"text": "To get the global count value (total number of tuples in a bag), we need to perform a Group All operation, and calculate the count value using the COUNT() function."
},
{
"code": null,
"e": 3396,
"s": 3246,
"text": "To get the count value of a group (Number of tuples in a group), we need to group it using the Group By operator and proceed with the count function."
},
{
"code": null,
"e": 3546,
"s": 3396,
"text": "To get the count value of a group (Number of tuples in a group), we need to group it using the Group By operator and proceed with the count function."
},
{
"code": null,
"e": 3597,
"s": 3546,
"text": "Given below is the syntax of the COUNT() function."
},
{
"code": null,
"e": 3623,
"s": 3597,
"text": "grunt> COUNT(expression)\n"
},
{
"code": null,
"e": 3725,
"s": 3623,
"text": "Assume that we have a file named student_details.txt in the HDFS directory /pig_data/ as shown below."
},
{
"code": null,
"e": 3745,
"s": 3725,
"text": "student_details.txt"
},
{
"code": null,
"e": 4115,
"s": 3745,
"text": "001,Rajiv,Reddy,21,9848022337,Hyderabad,89\n002,siddarth,Battacharya,22,9848022338,Kolkata,78 \n003,Rajesh,Khanna,22,9848022339,Delhi,90 \n004,Preethi,Agarwal,21,9848022330,Pune,93 \n005,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar,75 \n006,Archana,Mishra,23,9848022335,Chennai,87 \n007,Komal,Nayak,24,9848022334,trivendram,83 \n008,Bharathi,Nambiayar,24,9848022333,Chennai,72\n"
},
{
"code": null,
"e": 4209,
"s": 4115,
"text": "And we have loaded this file into Pig with the relation named student_details as shown below."
},
{
"code": null,
"e": 4422,
"s": 4209,
"text": "grunt> student_details = LOAD 'hdfs://localhost:9000/pig_data/student_details.txt' USING PigStorage(',')\n as (id:int, firstname:chararray, lastname:chararray, age:int, phone:chararray, city:chararray, gpa:int);"
},
{
"code": null,
"e": 4678,
"s": 4422,
"text": "We can use the built-in function COUNT() (case sensitive) to calculate the number of tuples in a relation. Let us group the relation student_details using the Group All operator, and store the result in the relation named student_group_all as shown below."
},
{
"code": null,
"e": 4732,
"s": 4678,
"text": "grunt> student_group_all = Group student_details All;"
},
{
"code": null,
"e": 4775,
"s": 4732,
"text": "It will produce a relation as shown below."
},
{
"code": null,
"e": 5192,
"s": 4775,
"text": "grunt> Dump student_group_all;\n \n(all,{(8,Bharathi,Nambiayar,24,9848022333,Chennai,72),\n(7,Komal,Nayak,24,9848022 334,trivendram,83),\n(6,Archana,Mishra,23,9848022335,Chennai,87),\n(5,Trupthi,Mohan thy,23,9848022336,Bhuwaneshwar,75),\n(4,Preethi,Agarwal,21,9848022330,Pune,93),\n(3 ,Rajesh,Khanna,22,9848022339,Delhi,90),\n(2,siddarth,Battacharya,22,9848022338,Ko lkata,78),\n(1,Rajiv,Reddy,21,9848022337,Hyderabad,89)})\n"
},
{
"code": null,
"e": 5255,
"s": 5192,
"text": "Let us now calculate number of tuples/records in the relation."
},
{
"code": null,
"e": 5342,
"s": 5255,
"text": "grunt> student_count = foreach student_group_all Generate COUNT(student_details.gpa);"
},
{
"code": null,
"e": 5416,
"s": 5342,
"text": "Verify the relation student_count using the DUMP operator as shown below."
},
{
"code": null,
"e": 5443,
"s": 5416,
"text": "grunt> Dump student_count;"
},
{
"code": null,
"e": 5536,
"s": 5443,
"text": "It will produce the following output, displaying the contents of the relation student_count."
},
{
"code": null,
"e": 5539,
"s": 5536,
"text": "8\n"
},
{
"code": null,
"e": 5574,
"s": 5539,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5593,
"s": 5574,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5628,
"s": 5593,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5649,
"s": 5628,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 5682,
"s": 5649,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5695,
"s": 5682,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 5730,
"s": 5695,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5748,
"s": 5730,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5781,
"s": 5748,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5799,
"s": 5781,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5832,
"s": 5799,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5850,
"s": 5832,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5857,
"s": 5850,
"text": " Print"
},
{
"code": null,
"e": 5868,
"s": 5857,
"text": " Add Notes"
}
] |
Deep learning with containers. Part 1 | by Alexander Visheratin | Towards Data Science
|
Containers are lightweight software packages that run in isolation on the host computing environment. Using containerized environments for the research is helpful because they are easy to use, reproducible, and keep your primary system clean. You can easily set up a fully functioning multi-container application using Docker Compose. All scripts required for this are available here.
Update 02/2021: the second part of the series is available here.
When doing intensive research, sometimes it becomes hard to maintain what is going on around you. Tons of files with data, dozens of libraries that you don’t use but not sure enough to wipe them out, temporal files saved somewhere in your home directory, you name it. Virtual environments help but not much. You still have to manage them and might end up in the same chaotic position but multiplied by the environments’ number. While setting up my laptop for working on deep NLP models, I came up with the way of creating easy to use and fully disposable environments for experimenting — containers. They allow me to set up ready-to-go Jupyter notebooks with Tensorboard tracking with only one command. And with another command I can pull this all down and not worry about something that is left in the memory or on the hard drive. In this post I will describe how to set up and deploy containers for deep learning in your system, and in the next one I will show how to extend the basic images for a specific task — siamese learning with Hugging Face Transformers.
The stack that I use is the following:
Docker. Platform and software for creating containers. De-facto standard tool in the field.
PyTorch with GPU support. My framework of choice, it’s just awesome.
Jupyter Notebook. Software that enables interactive development in the browser.
Tensorboard. Good starting point for experiments tracking. From that you can switch to Allegro AI or Weights & Biases.
Hugging Face. Simply the best way you can get state-of-the-art models based on Transformers and other architectures.
If you are not familiar with the concept of containers, it would be a good idea to read some introductory articles (e.g. from Docker or Google) and go through tutorials that cover the basics.
We will now create two containers — one for Jupyter Notebook and another for Tensorboard. We start with the Tensorboard container because it is very small and easy to understand. Here is the full Dockerfile for it:
# Use small image with Python pre-installed.FROM python:3.8-slim-buster# Install tensorboardRUN pip3 install tensorboard
For running and operating Tensorboard we need nothing except its package. You can now save this file as tensorboard.Dockerfile, build the container (docker build -t dl-tensorboard:latest -f tensorboard.Dockerfile .) and run it interactively with the command docker run --rm -it dl-tensorboard:latest /bin/bash, the command tensorboard will be available to run. But it will not run on its own, it needs a directory where the data about experimental runs is stored. We shall deal with it later on the services setup stage.
The next part is building an image with the Jupyter Notebook. There are quite a lot nuances here. First of all, we are going to work with deep learning, so we need a GPU support in our containers. Luckily, NVIDIA got us covered with their Container Toolkit. After several simple steps you get GPU-enabled Docker containers at your disposal. Another very useful project from NVIDIA is a set of pre-built images with CUDA installed. A couple versions of Ubuntu ago, it was a huge pain to install NVIDIA drivers and CUDA. Now it is much easier, but with these images you don’t need to do a thing related to CUDA setup, which is pretty cool.
By the time of writing this post, PyTorch supports CUDA version 10.2, so we will use NVIDIA base image with CUDA 10.2. Additionally, NVIDIA provides three flavors of their images — base, runtime, and devel. Our option is runtime because it includes cuDNN.
The next interesting point is that we are going to perform a multi-stage build of our image. It means that during the build, we will have a base image that encapsulates all the logic related to setting things up, and the final image that adds finishing touches depending on the task in hand, e.g. install additional packages or copy required files. This logic will allow us to have a base image resting in the Docker cache so there will be no need to, for example, download PyTorch every time when we add a new package. Without a doubt, we can achieve the same without a multi-stage build by just adding new lines in Dockerfile after the existing and not messing up the order of already added lines (because of the way how Docker cache works), but this approach gives a division of responsibilities, ease of operation, and lays the basis for more advances scenarios that we will cover in next posts.
I would like to clarify a couple more points before we jump into the Dockerfile for a Jupyter image. First, since we use NVIDIA CUDA image as a base, we will need to install Python and some required tools. Second, due to the known issue it is not possible to run a Notebook binary in the container as-is. Some time ago it would require setting up Tini in the Dockerfile, as described in the link. But now Tini is built into the Docker so there is no need for any additional setup, just add --init flag when running the container. A bit later we shall see how to incorporate this to the Docker compose.
Finally, we can have a look at the actual Dockerfile for the Jupyter Notebook image:
# NVIDIA CUDA image as a base# We also mark this image as "jupyter-base" so we could use it by nameFROM nvidia/cuda:10.2-runtime AS jupyter-baseWORKDIR /# Install Python and its toolsRUN apt update && apt install -y --no-install-recommends \ git \ build-essential \ python3-dev \ python3-pip \ python3-setuptoolsRUN pip3 -q install pip --upgrade# Install all basic packagesRUN pip3 install \ # Jupyter itself jupyter \ # Numpy and Pandas are required a-priori numpy pandas \ # PyTorch with CUDA 10.2 support and Torchvision torch torchvision \ # Upgraded version of Tensorboard with more features tensorboardX# Here we use a base image by its name - "jupyter-base"FROM jupyter-base# Install additional packagesRUN pip3 install \ # Hugging Face Transformers transformers \ # Progress bar to track experiments barbar
Having in mind everything that was described before, the script is quite straightforward — take NVIDIA CUDA image, install Python, install basic packages, use this all as a basis for the final image with some additional packages that depend on the specific problem.
The final step of creating the environment is combining both images into the complete multi-container application with the help of Docker Compose. This tool allows to create a YAML file that contains a description of services that form the application. This is a nice tool that is mainly focused on a single-host deployments, which is exactly our use case. One majoe drawback of Compose at the moment of writing this post is the lack of GPU support, despite the fact that Docker and its API have implemented this feature. But there is a workaround that enables usage of GPUs in Compose services. I have integrated it into the latest release of Compose and plan to maintain it until GPU and other device requests are supported. With this regard, you need to install this fork of Compose to be able to run the services.
Let’s look into the docker-compose.yml file:
version: "3.8"services: tensorboard: image: dl-tensorboard build: context: ./ dockerfile: tensorboard.Dockerfile ports: - ${TENSORBOARD_PORT}:${TENSORBOARD_PORT} volumes: - ${ROOT_DIR}:/jupyter command: [ "tensorboard", "--logdir=${TENSORBOARD_DIR}", "--port=${TENSORBOARD_PORT}", "--bind_all", ] jupyter-server: image: dl-jupyter init: true build: context: ./ dockerfile: jupyter.Dockerfile device_requests: - capabilities: - "gpu" env_file: ./.env ports: - ${JUPYTER_PORT}:${JUPYTER_PORT} volumes: - ${ROOT_DIR}:/jupyter command: [ "jupyter", "notebook", "--ip=*", "--port=${JUPYTER_PORT}", "--allow-root", "--notebook-dir=${JUPYTER_DIR}", '--NotebookApp.token=${JUPYTER_TOKEN}' ]
There is a lot to unwrap here. First of all, there are two services defined — tensorboard and jupyter-server. The image section defines the name of the image that will be built for the service. The build section defines a path to the directory or a repository with the Dockerfile that will be used for building the image. In the ports section we specify what ports from the host machine will be exposed to the container. And here the things become interesting – instead of numeric values we see names of environment variables. Docker compose takes these variables from a special file named .env where the user lists all variables that have to be used during compose. This allows to have a single place where you store all parts of the compose script that can differ from environment to environment. For example, the port that is used for the Tensorboard on one machine can be occupied on the other, and this issue can be easily fixed by changing the value of TENSORBOARD_PORT variable in the .env file.
For our scenario, .env file looks like this:
ROOT_DIR=/path/to/application/root/directory # path on the hostJUPYTER_PORT=42065JUPYTER_TOKEN=egmd5hashofsomepasswordJUPYTER_DIR=/jupyter/notebooks # path in the containerTENSORBOARD_PORT=45175TENSORBOARD_DIR=/jupyter/runs # path in the container
ROOT_DIR is a directory that will store all information that is needed by our application (notebooks, data, runs history). As you can see from the volumes section in docker-compose.yml, this directory is mounted to both containers as /jupyter, which explains why both JUPYTER_DIR and TENSORBOARD_DIR variables have this prefix. Other variables in the file define the ports to be exposed and a token for Jupyter Notebook that is used for authentication.
The command section of the service definition contains a set of arguments that combined form a command that will be executed on the container start-up. In order to fix the described above issue with a Notebook binary, we add init: true for the Jupyter service. We also pass environment variables from .env file to the container with the Jupyter Notebook using the section env_file. This is because we will make use of these variables in the notebooks, details on this will be in the next post. And last but not the least feature of the services definition is a device_requests section. This is exactly the workaround that enables a GPU to be available inside the container. Without it you won’t be able to enjoy the power of your top-notch NVIDIA card in the multi-container application.
In the end, we get the following structure of the working directory:
├── .env # File with environment variables.├── docker-compose.yml # Compose file with services.├── jupyter.Dockerfile # Dockerfile for the Jupyter image.├── tensorboard.Dockerfile # Dockerfile for the Tensorboard image.
With all set and done, you can finally run docker-compose up -d inside our working directory. After downloading all base images and installing all required packages both containers should be up and running. The first start takes quite a long time but all next will be very fast – even if you install new packages in the final image, all heavylifting with downloading and installing base packages will be skipped. And when you are done with your work, just run docker-compose down and all containers will disappear and leave your system clean and ready for other fascinating stuff, like developing distributed systems in Go or running complex physics simulations in COMSOL.
In this post, we looked into an example of how to set up a containerized environment with Jupyter Notebook, PyTorch and Tensorboard that can be used for the deep learning research. In the next post, we will dive into how this environment can actually be used for a real use case — siamese learning for a few-shot classification of the news. Key outtakes from this post:
Use multi-stage builds, where the base image does one-time heavy things, and the final image tailors the environment to your needs. You know, like fine-tuning.Docker Compose does not support binding GPU to containers. But if you really want, it does.
Use multi-stage builds, where the base image does one-time heavy things, and the final image tailors the environment to your needs. You know, like fine-tuning.
Docker Compose does not support binding GPU to containers. But if you really want, it does.
|
[
{
"code": null,
"e": 557,
"s": 172,
"text": "Containers are lightweight software packages that run in isolation on the host computing environment. Using containerized environments for the research is helpful because they are easy to use, reproducible, and keep your primary system clean. You can easily set up a fully functioning multi-container application using Docker Compose. All scripts required for this are available here."
},
{
"code": null,
"e": 622,
"s": 557,
"text": "Update 02/2021: the second part of the series is available here."
},
{
"code": null,
"e": 1687,
"s": 622,
"text": "When doing intensive research, sometimes it becomes hard to maintain what is going on around you. Tons of files with data, dozens of libraries that you don’t use but not sure enough to wipe them out, temporal files saved somewhere in your home directory, you name it. Virtual environments help but not much. You still have to manage them and might end up in the same chaotic position but multiplied by the environments’ number. While setting up my laptop for working on deep NLP models, I came up with the way of creating easy to use and fully disposable environments for experimenting — containers. They allow me to set up ready-to-go Jupyter notebooks with Tensorboard tracking with only one command. And with another command I can pull this all down and not worry about something that is left in the memory or on the hard drive. In this post I will describe how to set up and deploy containers for deep learning in your system, and in the next one I will show how to extend the basic images for a specific task — siamese learning with Hugging Face Transformers."
},
{
"code": null,
"e": 1726,
"s": 1687,
"text": "The stack that I use is the following:"
},
{
"code": null,
"e": 1818,
"s": 1726,
"text": "Docker. Platform and software for creating containers. De-facto standard tool in the field."
},
{
"code": null,
"e": 1887,
"s": 1818,
"text": "PyTorch with GPU support. My framework of choice, it’s just awesome."
},
{
"code": null,
"e": 1967,
"s": 1887,
"text": "Jupyter Notebook. Software that enables interactive development in the browser."
},
{
"code": null,
"e": 2086,
"s": 1967,
"text": "Tensorboard. Good starting point for experiments tracking. From that you can switch to Allegro AI or Weights & Biases."
},
{
"code": null,
"e": 2203,
"s": 2086,
"text": "Hugging Face. Simply the best way you can get state-of-the-art models based on Transformers and other architectures."
},
{
"code": null,
"e": 2395,
"s": 2203,
"text": "If you are not familiar with the concept of containers, it would be a good idea to read some introductory articles (e.g. from Docker or Google) and go through tutorials that cover the basics."
},
{
"code": null,
"e": 2610,
"s": 2395,
"text": "We will now create two containers — one for Jupyter Notebook and another for Tensorboard. We start with the Tensorboard container because it is very small and easy to understand. Here is the full Dockerfile for it:"
},
{
"code": null,
"e": 2731,
"s": 2610,
"text": "# Use small image with Python pre-installed.FROM python:3.8-slim-buster# Install tensorboardRUN pip3 install tensorboard"
},
{
"code": null,
"e": 3252,
"s": 2731,
"text": "For running and operating Tensorboard we need nothing except its package. You can now save this file as tensorboard.Dockerfile, build the container (docker build -t dl-tensorboard:latest -f tensorboard.Dockerfile .) and run it interactively with the command docker run --rm -it dl-tensorboard:latest /bin/bash, the command tensorboard will be available to run. But it will not run on its own, it needs a directory where the data about experimental runs is stored. We shall deal with it later on the services setup stage."
},
{
"code": null,
"e": 3890,
"s": 3252,
"text": "The next part is building an image with the Jupyter Notebook. There are quite a lot nuances here. First of all, we are going to work with deep learning, so we need a GPU support in our containers. Luckily, NVIDIA got us covered with their Container Toolkit. After several simple steps you get GPU-enabled Docker containers at your disposal. Another very useful project from NVIDIA is a set of pre-built images with CUDA installed. A couple versions of Ubuntu ago, it was a huge pain to install NVIDIA drivers and CUDA. Now it is much easier, but with these images you don’t need to do a thing related to CUDA setup, which is pretty cool."
},
{
"code": null,
"e": 4146,
"s": 3890,
"text": "By the time of writing this post, PyTorch supports CUDA version 10.2, so we will use NVIDIA base image with CUDA 10.2. Additionally, NVIDIA provides three flavors of their images — base, runtime, and devel. Our option is runtime because it includes cuDNN."
},
{
"code": null,
"e": 5046,
"s": 4146,
"text": "The next interesting point is that we are going to perform a multi-stage build of our image. It means that during the build, we will have a base image that encapsulates all the logic related to setting things up, and the final image that adds finishing touches depending on the task in hand, e.g. install additional packages or copy required files. This logic will allow us to have a base image resting in the Docker cache so there will be no need to, for example, download PyTorch every time when we add a new package. Without a doubt, we can achieve the same without a multi-stage build by just adding new lines in Dockerfile after the existing and not messing up the order of already added lines (because of the way how Docker cache works), but this approach gives a division of responsibilities, ease of operation, and lays the basis for more advances scenarios that we will cover in next posts."
},
{
"code": null,
"e": 5648,
"s": 5046,
"text": "I would like to clarify a couple more points before we jump into the Dockerfile for a Jupyter image. First, since we use NVIDIA CUDA image as a base, we will need to install Python and some required tools. Second, due to the known issue it is not possible to run a Notebook binary in the container as-is. Some time ago it would require setting up Tini in the Dockerfile, as described in the link. But now Tini is built into the Docker so there is no need for any additional setup, just add --init flag when running the container. A bit later we shall see how to incorporate this to the Docker compose."
},
{
"code": null,
"e": 5733,
"s": 5648,
"text": "Finally, we can have a look at the actual Dockerfile for the Jupyter Notebook image:"
},
{
"code": null,
"e": 6599,
"s": 5733,
"text": "# NVIDIA CUDA image as a base# We also mark this image as \"jupyter-base\" so we could use it by nameFROM nvidia/cuda:10.2-runtime AS jupyter-baseWORKDIR /# Install Python and its toolsRUN apt update && apt install -y --no-install-recommends \\ git \\ build-essential \\ python3-dev \\ python3-pip \\ python3-setuptoolsRUN pip3 -q install pip --upgrade# Install all basic packagesRUN pip3 install \\ # Jupyter itself jupyter \\ # Numpy and Pandas are required a-priori numpy pandas \\ # PyTorch with CUDA 10.2 support and Torchvision torch torchvision \\ # Upgraded version of Tensorboard with more features tensorboardX# Here we use a base image by its name - \"jupyter-base\"FROM jupyter-base# Install additional packagesRUN pip3 install \\ # Hugging Face Transformers transformers \\ # Progress bar to track experiments barbar"
},
{
"code": null,
"e": 6865,
"s": 6599,
"text": "Having in mind everything that was described before, the script is quite straightforward — take NVIDIA CUDA image, install Python, install basic packages, use this all as a basis for the final image with some additional packages that depend on the specific problem."
},
{
"code": null,
"e": 7683,
"s": 6865,
"text": "The final step of creating the environment is combining both images into the complete multi-container application with the help of Docker Compose. This tool allows to create a YAML file that contains a description of services that form the application. This is a nice tool that is mainly focused on a single-host deployments, which is exactly our use case. One majoe drawback of Compose at the moment of writing this post is the lack of GPU support, despite the fact that Docker and its API have implemented this feature. But there is a workaround that enables usage of GPUs in Compose services. I have integrated it into the latest release of Compose and plan to maintain it until GPU and other device requests are supported. With this regard, you need to install this fork of Compose to be able to run the services."
},
{
"code": null,
"e": 7728,
"s": 7683,
"text": "Let’s look into the docker-compose.yml file:"
},
{
"code": null,
"e": 8831,
"s": 7728,
"text": "version: \"3.8\"services: tensorboard: image: dl-tensorboard build: context: ./ dockerfile: tensorboard.Dockerfile ports: - ${TENSORBOARD_PORT}:${TENSORBOARD_PORT} volumes: - ${ROOT_DIR}:/jupyter command: [ \"tensorboard\", \"--logdir=${TENSORBOARD_DIR}\", \"--port=${TENSORBOARD_PORT}\", \"--bind_all\", ] jupyter-server: image: dl-jupyter init: true build: context: ./ dockerfile: jupyter.Dockerfile device_requests: - capabilities: - \"gpu\" env_file: ./.env ports: - ${JUPYTER_PORT}:${JUPYTER_PORT} volumes: - ${ROOT_DIR}:/jupyter command: [ \"jupyter\", \"notebook\", \"--ip=*\", \"--port=${JUPYTER_PORT}\", \"--allow-root\", \"--notebook-dir=${JUPYTER_DIR}\", '--NotebookApp.token=${JUPYTER_TOKEN}' ]"
},
{
"code": null,
"e": 9834,
"s": 8831,
"text": "There is a lot to unwrap here. First of all, there are two services defined — tensorboard and jupyter-server. The image section defines the name of the image that will be built for the service. The build section defines a path to the directory or a repository with the Dockerfile that will be used for building the image. In the ports section we specify what ports from the host machine will be exposed to the container. And here the things become interesting – instead of numeric values we see names of environment variables. Docker compose takes these variables from a special file named .env where the user lists all variables that have to be used during compose. This allows to have a single place where you store all parts of the compose script that can differ from environment to environment. For example, the port that is used for the Tensorboard on one machine can be occupied on the other, and this issue can be easily fixed by changing the value of TENSORBOARD_PORT variable in the .env file."
},
{
"code": null,
"e": 9879,
"s": 9834,
"text": "For our scenario, .env file looks like this:"
},
{
"code": null,
"e": 10156,
"s": 9879,
"text": "ROOT_DIR=/path/to/application/root/directory # path on the hostJUPYTER_PORT=42065JUPYTER_TOKEN=egmd5hashofsomepasswordJUPYTER_DIR=/jupyter/notebooks # path in the containerTENSORBOARD_PORT=45175TENSORBOARD_DIR=/jupyter/runs # path in the container"
},
{
"code": null,
"e": 10609,
"s": 10156,
"text": "ROOT_DIR is a directory that will store all information that is needed by our application (notebooks, data, runs history). As you can see from the volumes section in docker-compose.yml, this directory is mounted to both containers as /jupyter, which explains why both JUPYTER_DIR and TENSORBOARD_DIR variables have this prefix. Other variables in the file define the ports to be exposed and a token for Jupyter Notebook that is used for authentication."
},
{
"code": null,
"e": 11397,
"s": 10609,
"text": "The command section of the service definition contains a set of arguments that combined form a command that will be executed on the container start-up. In order to fix the described above issue with a Notebook binary, we add init: true for the Jupyter service. We also pass environment variables from .env file to the container with the Jupyter Notebook using the section env_file. This is because we will make use of these variables in the notebooks, details on this will be in the next post. And last but not the least feature of the services definition is a device_requests section. This is exactly the workaround that enables a GPU to be available inside the container. Without it you won’t be able to enjoy the power of your top-notch NVIDIA card in the multi-container application."
},
{
"code": null,
"e": 11466,
"s": 11397,
"text": "In the end, we get the following structure of the working directory:"
},
{
"code": null,
"e": 11720,
"s": 11466,
"text": "├── .env # File with environment variables.├── docker-compose.yml # Compose file with services.├── jupyter.Dockerfile # Dockerfile for the Jupyter image.├── tensorboard.Dockerfile # Dockerfile for the Tensorboard image."
},
{
"code": null,
"e": 12393,
"s": 11720,
"text": "With all set and done, you can finally run docker-compose up -d inside our working directory. After downloading all base images and installing all required packages both containers should be up and running. The first start takes quite a long time but all next will be very fast – even if you install new packages in the final image, all heavylifting with downloading and installing base packages will be skipped. And when you are done with your work, just run docker-compose down and all containers will disappear and leave your system clean and ready for other fascinating stuff, like developing distributed systems in Go or running complex physics simulations in COMSOL."
},
{
"code": null,
"e": 12763,
"s": 12393,
"text": "In this post, we looked into an example of how to set up a containerized environment with Jupyter Notebook, PyTorch and Tensorboard that can be used for the deep learning research. In the next post, we will dive into how this environment can actually be used for a real use case — siamese learning for a few-shot classification of the news. Key outtakes from this post:"
},
{
"code": null,
"e": 13014,
"s": 12763,
"text": "Use multi-stage builds, where the base image does one-time heavy things, and the final image tailors the environment to your needs. You know, like fine-tuning.Docker Compose does not support binding GPU to containers. But if you really want, it does."
},
{
"code": null,
"e": 13174,
"s": 13014,
"text": "Use multi-stage builds, where the base image does one-time heavy things, and the final image tailors the environment to your needs. You know, like fine-tuning."
}
] |
How to execute a static block without main method in Java?
|
VM first looks for the main method (at least the latest versions) and then, starts executing the program including static block. Therefore, you cannot execute a static block without main method.
public class Sample {
static {
System.out.println("Hello how are you");
}
}
Since the above program doesn’t have a main method, If you compile and execute it you will get an error message.
C:\Sample>javac StaticBlockExample.java
C:\Sample>java StaticBlockExample
Error: Main method not found in class StaticBlockExample, please define the main method as: public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
If you want to execute static block you need to have Main method and, static blocks of the class gets executed before main method.
Live Demo
public class StaticBlockExample {
static {
System.out.println("This is static block");
}
public static void main(String args[]){
System.out.println("This is main method");
}
}
This is static block
This is main method
|
[
{
"code": null,
"e": 1257,
"s": 1062,
"text": "VM first looks for the main method (at least the latest versions) and then, starts executing the program including static block. Therefore, you cannot execute a static block without main method."
},
{
"code": null,
"e": 1345,
"s": 1257,
"text": "public class Sample {\n static {\n System.out.println(\"Hello how are you\");\n }\n}"
},
{
"code": null,
"e": 1458,
"s": 1345,
"text": "Since the above program doesn’t have a main method, If you compile and execute it you will get an error message."
},
{
"code": null,
"e": 1737,
"s": 1458,
"text": "C:\\Sample>javac StaticBlockExample.java\nC:\\Sample>java StaticBlockExample\nError: Main method not found in class StaticBlockExample, please define the main method as: public static void main(String[] args)\nor a JavaFX application class must extend javafx.application.Application\n"
},
{
"code": null,
"e": 1868,
"s": 1737,
"text": "If you want to execute static block you need to have Main method and, static blocks of the class gets executed before main method."
},
{
"code": null,
"e": 1879,
"s": 1868,
"text": " Live Demo"
},
{
"code": null,
"e": 2079,
"s": 1879,
"text": "public class StaticBlockExample {\n static {\n System.out.println(\"This is static block\");\n }\n public static void main(String args[]){\n System.out.println(\"This is main method\");\n }\n}"
},
{
"code": null,
"e": 2121,
"s": 2079,
"text": "This is static block\nThis is main method\n"
}
] |
Redis - String Setex Command
|
Redis SETEX command is used to set some string value with a specified timeout in Redis key.
Simple string reply. OK, if the value is set in key. Null, if the value is not set.
Following is the basic syntax of Redis SETEX command.
redis 127.0.0.1:6379> SETEX KEY_NAME TIMEOUT VALUE
redis 127.0.0.1:6379> SETEX mykey 60 redis
OK
redis 127.0.0.1:6379> TTL mykey
60
redis 127.0.0.1:6379> GET mykey
"redis
22 Lectures
40 mins
Skillbakerystudios
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2137,
"s": 2045,
"text": "Redis SETEX command is used to set some string value with a specified timeout in Redis key."
},
{
"code": null,
"e": 2221,
"s": 2137,
"text": "Simple string reply. OK, if the value is set in key. Null, if the value is not set."
},
{
"code": null,
"e": 2275,
"s": 2221,
"text": "Following is the basic syntax of Redis SETEX command."
},
{
"code": null,
"e": 2327,
"s": 2275,
"text": "redis 127.0.0.1:6379> SETEX KEY_NAME TIMEOUT VALUE\n"
},
{
"code": null,
"e": 2454,
"s": 2327,
"text": "redis 127.0.0.1:6379> SETEX mykey 60 redis \nOK \nredis 127.0.0.1:6379> TTL mykey \n60 \nredis 127.0.0.1:6379> GET mykey \n\"redis \n"
},
{
"code": null,
"e": 2486,
"s": 2454,
"text": "\n 22 Lectures \n 40 mins\n"
},
{
"code": null,
"e": 2506,
"s": 2486,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 2513,
"s": 2506,
"text": " Print"
},
{
"code": null,
"e": 2524,
"s": 2513,
"text": " Add Notes"
}
] |
Beginner’s Guide to K-Nearest Neighbors in R: from Zero to Hero | by Leihua Ye, PhD | Towards Data Science
|
Updated on Jan-10–2021
1
2
3
4
5
6
7
8
9
10
Powered by Play.ht
Create audio with Play.ht
Powered by Play.ht
“If you live 5 minutes away from Bill Gates, I bet you are rich.”
In the realm of Machine Learning, K-Nearest Neighbors, KNN, makes the most intuitive sense and thus easily accessible to Data Science enthusiasts who want to break into the field. To decide the classification label of an observation, KNN looks at its neighbors and assign the neighbors’ label to the observation of interest. This is the underlying ideology of the KNN method, just like the Bill Games analogy used in the beginning. No higher dimensional calculations are needed to understand how the algorithm works.
But there is a catch. Looking at one neighbor may introduce bias and inaccuracy to the model, and we have to set up several “Rules of Engagement” for the method. For example, KNN can adopt the majority case of its “k” numbers of neighbors, as the name suggested.
To decide the label for new observations, we look at the closest neighbors.
To select the number of neighbors, we need to adopt a single number quantifying the similarity or dissimilarity among neighbors (Practical Statistics for Data Scientists). To that purpose, KNN has two sets of distance metrics depending on the data type.
For discrete variables, KNN adopts Hamming Distance. It measures the minimum number of replacements needed to make two strings similar (Wikipedia).
For continuous variables, we use Euclidean distance. To account for the distance between two vectors (x1, x2, ..., xp) and (μ1, μ2, ..., μp), we take their individual differences, square up, take the sum, and take the square root, shown as:
As a side note, selecting distance metrics for KNN is a heavily tested topic in Data Science Interviews. They typically ask for the justifications of choosing one metric over the others, along with their tradeoffs. I’ve elaborated on how to approach this type of question in a related post:
towardsdatascience.com
As noted, the key to KNN is to set on the number of neighbors, and we resort to cross-validation (CV) to decide the premium K neighbors.
Cross-validation can be briefly described in the following steps:
Divide the data into K equally distributed chunks/foldsChoose 1 chunk/fold as a test set and the rest K-1 as a training setDevelop a KNN model based on the training setCompare the predicted value VS actual values on the test set onlyApply the ML model to the test set and repeat K times using each chunkAdd up the metrics score for the model and average over K folds
Divide the data into K equally distributed chunks/folds
Choose 1 chunk/fold as a test set and the rest K-1 as a training set
Develop a KNN model based on the training set
Compare the predicted value VS actual values on the test set only
Apply the ML model to the test set and repeat K times using each chunk
Add up the metrics score for the model and average over K folds
Technically speaking, we can set K to any value between 1 and sample size n. Setting K = n, CV takes 1 observation out as the training set and the rest n-1 cases as the test set, and repeat the process to the entire dataset. This type of CV is called “Leave-one-out cross-validation” (LOOCV).
However, LOOCV makes intuitive sense but requires a ton of computational power. It runs forever for a significantly large dataset.
To choose the best K folds, we have to balance the tradeoffs between bias and variance. For a small K, the model has a high bias but a low variance for estimating test error. For a big K, we have a low bias but a high variance (Crack Data Science Interviews).
# install.packages(“ISLR”)# install.packages(“ggplot2”) # install.packages(“plyr”)# install.packages(“dplyr”) # install.packages(“class”)# Load librarieslibrary(ISLR) library(ggplot2) library(reshape2) library(plyr) library(dplyr) library(class)# load data and clean the datasetbanking=read.csv(“bank-additional-full.csv”,sep =”;”,header=T)##check for missing data and make sure no missing databanking[!complete.cases(banking),]#re-code qualitative (factor) variables into numericbanking$job= recode(banking$job, “‘admin.’=1;’blue-collar’=2;’entrepreneur’=3;’housemaid’=4;’management’=5;’retired’=6;’self-employed’=7;’services’=8;’student’=9;’technician’=10;’unemployed’=11;’unknown’=12”)#recode variable againbanking$marital = recode(banking$marital, “‘divorced’=1;’married’=2;’single’=3;’unknown’=4”)banking$education = recode(banking$education, “‘basic.4y’=1;’basic.6y’=2;’basic.9y’=3;’high.school’=4;’illiterate’=5;’professional.course’=6;’university.degree’=7;’unknown’=8”)banking$default = recode(banking$default, “‘no’=1;’yes’=2;’unknown’=3”)banking$housing = recode(banking$housing, “‘no’=1;’yes’=2;’unknown’=3”)banking$loan = recode(banking$loan, “‘no’=1;’yes’=2;’unknown’=3”)banking$contact = recode(banking$loan, “‘cellular’=1;’telephone’=2;”)banking$month = recode(banking$month, “‘mar’=1;’apr’=2;’may’=3;’jun’=4;’jul’=5;’aug’=6;’sep’=7;’oct’=8;’nov’=9;’dec’=10”)banking$day_of_week = recode(banking$day_of_week, “‘mon’=1;’tue’=2;’wed’=3;’thu’=4;’fri’=5;”)banking$poutcome = recode(banking$poutcome, “‘failure’=1;’nonexistent’=2;’success’=3;”)#remove variable “pdays”, b/c it has no variationbanking$pdays=NULL #remove variable “duration”, b/c itis collinear with the DVbanking$duration=NULL
After loading and cleaning the original dataset, it is a common practice to visually examine the distribution of our variables, checking for seasonality, patterns, outliers, etc.
#EDA of the DVplot(banking$y,main="Plot 1: Distribution of Dependent Variable")
As can be seen, the outcome variable (Banking Service Subscription) is not balanced distributed, with many more “No”s than “Yes”s, which causes inconvenience for Machine Learning classification questions. The rate of False Positive is high as many minority cases would be classified as the majority case. For such a rare event with unequal distribution, a non-parametric classification method is the preferred method.
towardsdatascience.com
We split the dataset into a training set and a test set. A rule of thumb, we stick to the “80–20” division, namely 80% of the data as the training set and 20% as the test set.
#split the dataset into training and test sets randomly, but we need to set seed so as to generate the same value each time we run the codeset.seed(1)#create an index to split the data: 80% training and 20% testindex = round(nrow(banking)*0.2,digits=0)#sample randomly throughout the dataset and keep the total number equal to the value of indextest.indices = sample(1:nrow(banking), index)#80% training setbanking.train=banking[-test.indices,] #20% test setbanking.test=banking[test.indices,] #Select the training set except the DVYTrain = banking.train$yXTrain = banking.train %>% select(-y)# Select the test set except the DVYTest = banking.test$yXTest = banking.test %>% select(-y)
Let’s create a new function (“calc_error_rate”) to record the misclassification rate. The function calculates the rate when the predicted label using the training model does not match the actual outcome label. It measures classification accuracy.
#define an error rate function and apply it to obtain test/training errorscalc_error_rate <- function(predicted.value, true.value){ return(mean(true.value!=predicted.value)) }
Then, we need another function, “do.chunk()”, to do k-fold Cross-Validation. The function returns a data frame of the possible values of folds.
The main purpose of this step is to select the best K value for KNN.
nfold = 10set.seed(1)# cut() divides the range into several intervalsfolds = seq.int(nrow(banking.train)) %>% cut(breaks = nfold, labels=FALSE) %>% sampledo.chunk <- function(chunkid, folddef, Xdat, Ydat, k){ train = (folddef!=chunkid)# training indexXtr = Xdat[train,] # training set by the indexYtr = Ydat[train] # true label in training setXvl = Xdat[!train,] # test setYvl = Ydat[!train] # true label in test setpredYtr = knn(train = Xtr, test = Xtr, cl = Ytr, k = k) # predict training labelspredYvl = knn(train = Xtr, test = Xvl, cl = Ytr, k = k) # predict test labelsdata.frame(fold =chunkid, # k folds train.error = calc_error_rate(predYtr, Ytr),#training error per fold val.error = calc_error_rate(predYvl, Yvl)) # test error per fold }# set error.folds to save validation errorserror.folds=NULL# create a sequence of data with an interval of 10kvec = c(1, seq(10, 50, length.out=5))set.seed(1)for (j in kvec){ tmp = ldply(1:nfold, do.chunk, # apply do.function to each fold folddef=folds, Xdat=XTrain, Ydat=YTrain, k=j) # required arguments tmp$neighbors = j # track each value of neighbors error.folds = rbind(error.folds, tmp) # combine the results }#melt() in the package reshape2 melts wide-format data into long-format dataerrors = melt(error.folds, id.vars=c(“fold”,”neighbors”), value.name= “error”)
The upcoming step is to find the number of k that minimizes validation error
val.error.means = errors %>% #select all rows of validation errors filter(variable== “val.error” ) %>% #group the selected data by neighbors group_by(neighbors, variable) %>% #cacluate CV error for each k summarise_each(funs(mean), error) %>% #remove existing grouping ungroup() %>% filter(error==min(error))# Best number of neighbors# if there is a tie, pick larger number of neighbors for simpler modelnumneighbor = max(val.error.means$neighbors)numneighbor## [20]
Therefore, the best number of neighbors is 20 after using 10-fold cross-validation.
#training errorset.seed(20)pred.YTtrain = knn(train=XTrain, test=XTrain, cl=YTrain, k=20)knn_traing_error <- calc_error_rate(predicted.value=pred.YTtrain, true.value=YTrain)knn_traing_error[1] 0.101214
The training error is 0.10.
#test errorset.seed(20)pred.YTest = knn(train=XTrain, test=XTest, cl=YTrain, k=20)knn_test_error <- calc_error_rate(predicted.value=pred.YTest, true.value=YTest)knn_test_error[1] 0.1100995
The test error is 0.11.
#confusion matrixconf.matrix = table(predicted=pred.YTest, true=YTest)
Based on the above confusion matrix, we can calculate the following values and prepare for plotting the ROC curve.
Accuracy = (TP +TN)/(TP+FP+FN+TN)
TPR/Recall/Sensitivity = TP/(TP+FN)
Precision = TP/(TP+FP)
Specificity = TN/(TN+FP)
FPR = 1 — Specificity = FP/(TN+FP)
F1 Score = 2*TP/(2*TP+FP+FN) = Precision*Recall /(Precision +Recall)
# Test accuracy ratesum(diag(conf.matrix)/sum(conf.matrix))[1] 0.8899005# Test error rate1 - sum(drag(conf.matrix)/sum(conf.matrix))[1] 0.1100995
As you may notice, test accuracy rate + test error rate = 1, and I’m providing multiple ways of calculating each value.
# ROC and AUCknn_model = knn(train=XTrain, test=XTrain, cl=YTrain, k=20,prob=TRUE)prob <- attr(knn_model, “prob”)prob <- 2*ifelse(knn_model == “-1”, prob,1-prob) — 1pred_knn <- prediction(prob, YTrain)performance_knn <- performance(pred_knn, “tpr”, “fpr”)# AUCauc_knn <- performance(pred_knn,”auc”)@y.valuesauc_knn[1] 0.8470583plot(performance_knn,col=2,lwd=2,main=”ROC Curves for KNN”)
In conclusion, we have learned what KNN is and the pipeline of building a KNN model in R. Also, we have mastered the skills of conducting K-Fold Cross-Validation and how to implement the code in R.
The complete Python code is available on my Github.
Medium recently evolved its Writer Partner Program, which supports ordinary writers like myself. If you are not a subscriber yet and sign up via the following link, I’ll receive a portion of the membership fees.
leihua-ye.medium.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
Please find me on LinkedIn and Youtube.
Also, check my other posts on Artificial Intelligence and Machine Learning.
|
[
{
"code": null,
"e": 195,
"s": 172,
"text": "Updated on Jan-10–2021"
},
{
"code": null,
"e": 197,
"s": 195,
"text": "1"
},
{
"code": null,
"e": 199,
"s": 197,
"text": "2"
},
{
"code": null,
"e": 201,
"s": 199,
"text": "3"
},
{
"code": null,
"e": 203,
"s": 201,
"text": "4"
},
{
"code": null,
"e": 205,
"s": 203,
"text": "5"
},
{
"code": null,
"e": 207,
"s": 205,
"text": "6"
},
{
"code": null,
"e": 209,
"s": 207,
"text": "7"
},
{
"code": null,
"e": 211,
"s": 209,
"text": "8"
},
{
"code": null,
"e": 213,
"s": 211,
"text": "9"
},
{
"code": null,
"e": 216,
"s": 213,
"text": "10"
},
{
"code": null,
"e": 235,
"s": 216,
"text": "Powered by Play.ht"
},
{
"code": null,
"e": 261,
"s": 235,
"text": "Create audio with Play.ht"
},
{
"code": null,
"e": 280,
"s": 261,
"text": "Powered by Play.ht"
},
{
"code": null,
"e": 346,
"s": 280,
"text": "“If you live 5 minutes away from Bill Gates, I bet you are rich.”"
},
{
"code": null,
"e": 863,
"s": 346,
"text": "In the realm of Machine Learning, K-Nearest Neighbors, KNN, makes the most intuitive sense and thus easily accessible to Data Science enthusiasts who want to break into the field. To decide the classification label of an observation, KNN looks at its neighbors and assign the neighbors’ label to the observation of interest. This is the underlying ideology of the KNN method, just like the Bill Games analogy used in the beginning. No higher dimensional calculations are needed to understand how the algorithm works."
},
{
"code": null,
"e": 1126,
"s": 863,
"text": "But there is a catch. Looking at one neighbor may introduce bias and inaccuracy to the model, and we have to set up several “Rules of Engagement” for the method. For example, KNN can adopt the majority case of its “k” numbers of neighbors, as the name suggested."
},
{
"code": null,
"e": 1202,
"s": 1126,
"text": "To decide the label for new observations, we look at the closest neighbors."
},
{
"code": null,
"e": 1456,
"s": 1202,
"text": "To select the number of neighbors, we need to adopt a single number quantifying the similarity or dissimilarity among neighbors (Practical Statistics for Data Scientists). To that purpose, KNN has two sets of distance metrics depending on the data type."
},
{
"code": null,
"e": 1604,
"s": 1456,
"text": "For discrete variables, KNN adopts Hamming Distance. It measures the minimum number of replacements needed to make two strings similar (Wikipedia)."
},
{
"code": null,
"e": 1845,
"s": 1604,
"text": "For continuous variables, we use Euclidean distance. To account for the distance between two vectors (x1, x2, ..., xp) and (μ1, μ2, ..., μp), we take their individual differences, square up, take the sum, and take the square root, shown as:"
},
{
"code": null,
"e": 2136,
"s": 1845,
"text": "As a side note, selecting distance metrics for KNN is a heavily tested topic in Data Science Interviews. They typically ask for the justifications of choosing one metric over the others, along with their tradeoffs. I’ve elaborated on how to approach this type of question in a related post:"
},
{
"code": null,
"e": 2159,
"s": 2136,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2296,
"s": 2159,
"text": "As noted, the key to KNN is to set on the number of neighbors, and we resort to cross-validation (CV) to decide the premium K neighbors."
},
{
"code": null,
"e": 2362,
"s": 2296,
"text": "Cross-validation can be briefly described in the following steps:"
},
{
"code": null,
"e": 2729,
"s": 2362,
"text": "Divide the data into K equally distributed chunks/foldsChoose 1 chunk/fold as a test set and the rest K-1 as a training setDevelop a KNN model based on the training setCompare the predicted value VS actual values on the test set onlyApply the ML model to the test set and repeat K times using each chunkAdd up the metrics score for the model and average over K folds"
},
{
"code": null,
"e": 2785,
"s": 2729,
"text": "Divide the data into K equally distributed chunks/folds"
},
{
"code": null,
"e": 2854,
"s": 2785,
"text": "Choose 1 chunk/fold as a test set and the rest K-1 as a training set"
},
{
"code": null,
"e": 2900,
"s": 2854,
"text": "Develop a KNN model based on the training set"
},
{
"code": null,
"e": 2966,
"s": 2900,
"text": "Compare the predicted value VS actual values on the test set only"
},
{
"code": null,
"e": 3037,
"s": 2966,
"text": "Apply the ML model to the test set and repeat K times using each chunk"
},
{
"code": null,
"e": 3101,
"s": 3037,
"text": "Add up the metrics score for the model and average over K folds"
},
{
"code": null,
"e": 3394,
"s": 3101,
"text": "Technically speaking, we can set K to any value between 1 and sample size n. Setting K = n, CV takes 1 observation out as the training set and the rest n-1 cases as the test set, and repeat the process to the entire dataset. This type of CV is called “Leave-one-out cross-validation” (LOOCV)."
},
{
"code": null,
"e": 3525,
"s": 3394,
"text": "However, LOOCV makes intuitive sense but requires a ton of computational power. It runs forever for a significantly large dataset."
},
{
"code": null,
"e": 3785,
"s": 3525,
"text": "To choose the best K folds, we have to balance the tradeoffs between bias and variance. For a small K, the model has a high bias but a low variance for estimating test error. For a big K, we have a low bias but a high variance (Crack Data Science Interviews)."
},
{
"code": null,
"e": 5489,
"s": 3785,
"text": "# install.packages(“ISLR”)# install.packages(“ggplot2”) # install.packages(“plyr”)# install.packages(“dplyr”) # install.packages(“class”)# Load librarieslibrary(ISLR) library(ggplot2) library(reshape2) library(plyr) library(dplyr) library(class)# load data and clean the datasetbanking=read.csv(“bank-additional-full.csv”,sep =”;”,header=T)##check for missing data and make sure no missing databanking[!complete.cases(banking),]#re-code qualitative (factor) variables into numericbanking$job= recode(banking$job, “‘admin.’=1;’blue-collar’=2;’entrepreneur’=3;’housemaid’=4;’management’=5;’retired’=6;’self-employed’=7;’services’=8;’student’=9;’technician’=10;’unemployed’=11;’unknown’=12”)#recode variable againbanking$marital = recode(banking$marital, “‘divorced’=1;’married’=2;’single’=3;’unknown’=4”)banking$education = recode(banking$education, “‘basic.4y’=1;’basic.6y’=2;’basic.9y’=3;’high.school’=4;’illiterate’=5;’professional.course’=6;’university.degree’=7;’unknown’=8”)banking$default = recode(banking$default, “‘no’=1;’yes’=2;’unknown’=3”)banking$housing = recode(banking$housing, “‘no’=1;’yes’=2;’unknown’=3”)banking$loan = recode(banking$loan, “‘no’=1;’yes’=2;’unknown’=3”)banking$contact = recode(banking$loan, “‘cellular’=1;’telephone’=2;”)banking$month = recode(banking$month, “‘mar’=1;’apr’=2;’may’=3;’jun’=4;’jul’=5;’aug’=6;’sep’=7;’oct’=8;’nov’=9;’dec’=10”)banking$day_of_week = recode(banking$day_of_week, “‘mon’=1;’tue’=2;’wed’=3;’thu’=4;’fri’=5;”)banking$poutcome = recode(banking$poutcome, “‘failure’=1;’nonexistent’=2;’success’=3;”)#remove variable “pdays”, b/c it has no variationbanking$pdays=NULL #remove variable “duration”, b/c itis collinear with the DVbanking$duration=NULL"
},
{
"code": null,
"e": 5668,
"s": 5489,
"text": "After loading and cleaning the original dataset, it is a common practice to visually examine the distribution of our variables, checking for seasonality, patterns, outliers, etc."
},
{
"code": null,
"e": 5748,
"s": 5668,
"text": "#EDA of the DVplot(banking$y,main=\"Plot 1: Distribution of Dependent Variable\")"
},
{
"code": null,
"e": 6166,
"s": 5748,
"text": "As can be seen, the outcome variable (Banking Service Subscription) is not balanced distributed, with many more “No”s than “Yes”s, which causes inconvenience for Machine Learning classification questions. The rate of False Positive is high as many minority cases would be classified as the majority case. For such a rare event with unequal distribution, a non-parametric classification method is the preferred method."
},
{
"code": null,
"e": 6189,
"s": 6166,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6365,
"s": 6189,
"text": "We split the dataset into a training set and a test set. A rule of thumb, we stick to the “80–20” division, namely 80% of the data as the training set and 20% as the test set."
},
{
"code": null,
"e": 7051,
"s": 6365,
"text": "#split the dataset into training and test sets randomly, but we need to set seed so as to generate the same value each time we run the codeset.seed(1)#create an index to split the data: 80% training and 20% testindex = round(nrow(banking)*0.2,digits=0)#sample randomly throughout the dataset and keep the total number equal to the value of indextest.indices = sample(1:nrow(banking), index)#80% training setbanking.train=banking[-test.indices,] #20% test setbanking.test=banking[test.indices,] #Select the training set except the DVYTrain = banking.train$yXTrain = banking.train %>% select(-y)# Select the test set except the DVYTest = banking.test$yXTest = banking.test %>% select(-y)"
},
{
"code": null,
"e": 7298,
"s": 7051,
"text": "Let’s create a new function (“calc_error_rate”) to record the misclassification rate. The function calculates the rate when the predicted label using the training model does not match the actual outcome label. It measures classification accuracy."
},
{
"code": null,
"e": 7474,
"s": 7298,
"text": "#define an error rate function and apply it to obtain test/training errorscalc_error_rate <- function(predicted.value, true.value){ return(mean(true.value!=predicted.value)) }"
},
{
"code": null,
"e": 7618,
"s": 7474,
"text": "Then, we need another function, “do.chunk()”, to do k-fold Cross-Validation. The function returns a data frame of the possible values of folds."
},
{
"code": null,
"e": 7687,
"s": 7618,
"text": "The main purpose of this step is to select the best K value for KNN."
},
{
"code": null,
"e": 9021,
"s": 7687,
"text": "nfold = 10set.seed(1)# cut() divides the range into several intervalsfolds = seq.int(nrow(banking.train)) %>% cut(breaks = nfold, labels=FALSE) %>% sampledo.chunk <- function(chunkid, folddef, Xdat, Ydat, k){ train = (folddef!=chunkid)# training indexXtr = Xdat[train,] # training set by the indexYtr = Ydat[train] # true label in training setXvl = Xdat[!train,] # test setYvl = Ydat[!train] # true label in test setpredYtr = knn(train = Xtr, test = Xtr, cl = Ytr, k = k) # predict training labelspredYvl = knn(train = Xtr, test = Xvl, cl = Ytr, k = k) # predict test labelsdata.frame(fold =chunkid, # k folds train.error = calc_error_rate(predYtr, Ytr),#training error per fold val.error = calc_error_rate(predYvl, Yvl)) # test error per fold }# set error.folds to save validation errorserror.folds=NULL# create a sequence of data with an interval of 10kvec = c(1, seq(10, 50, length.out=5))set.seed(1)for (j in kvec){ tmp = ldply(1:nfold, do.chunk, # apply do.function to each fold folddef=folds, Xdat=XTrain, Ydat=YTrain, k=j) # required arguments tmp$neighbors = j # track each value of neighbors error.folds = rbind(error.folds, tmp) # combine the results }#melt() in the package reshape2 melts wide-format data into long-format dataerrors = melt(error.folds, id.vars=c(“fold”,”neighbors”), value.name= “error”)"
},
{
"code": null,
"e": 9098,
"s": 9021,
"text": "The upcoming step is to find the number of k that minimizes validation error"
},
{
"code": null,
"e": 9594,
"s": 9098,
"text": "val.error.means = errors %>% #select all rows of validation errors filter(variable== “val.error” ) %>% #group the selected data by neighbors group_by(neighbors, variable) %>% #cacluate CV error for each k summarise_each(funs(mean), error) %>% #remove existing grouping ungroup() %>% filter(error==min(error))# Best number of neighbors# if there is a tie, pick larger number of neighbors for simpler modelnumneighbor = max(val.error.means$neighbors)numneighbor## [20]"
},
{
"code": null,
"e": 9678,
"s": 9594,
"text": "Therefore, the best number of neighbors is 20 after using 10-fold cross-validation."
},
{
"code": null,
"e": 9880,
"s": 9678,
"text": "#training errorset.seed(20)pred.YTtrain = knn(train=XTrain, test=XTrain, cl=YTrain, k=20)knn_traing_error <- calc_error_rate(predicted.value=pred.YTtrain, true.value=YTrain)knn_traing_error[1] 0.101214"
},
{
"code": null,
"e": 9908,
"s": 9880,
"text": "The training error is 0.10."
},
{
"code": null,
"e": 10097,
"s": 9908,
"text": "#test errorset.seed(20)pred.YTest = knn(train=XTrain, test=XTest, cl=YTrain, k=20)knn_test_error <- calc_error_rate(predicted.value=pred.YTest, true.value=YTest)knn_test_error[1] 0.1100995"
},
{
"code": null,
"e": 10121,
"s": 10097,
"text": "The test error is 0.11."
},
{
"code": null,
"e": 10192,
"s": 10121,
"text": "#confusion matrixconf.matrix = table(predicted=pred.YTest, true=YTest)"
},
{
"code": null,
"e": 10307,
"s": 10192,
"text": "Based on the above confusion matrix, we can calculate the following values and prepare for plotting the ROC curve."
},
{
"code": null,
"e": 10341,
"s": 10307,
"text": "Accuracy = (TP +TN)/(TP+FP+FN+TN)"
},
{
"code": null,
"e": 10377,
"s": 10341,
"text": "TPR/Recall/Sensitivity = TP/(TP+FN)"
},
{
"code": null,
"e": 10400,
"s": 10377,
"text": "Precision = TP/(TP+FP)"
},
{
"code": null,
"e": 10425,
"s": 10400,
"text": "Specificity = TN/(TN+FP)"
},
{
"code": null,
"e": 10460,
"s": 10425,
"text": "FPR = 1 — Specificity = FP/(TN+FP)"
},
{
"code": null,
"e": 10529,
"s": 10460,
"text": "F1 Score = 2*TP/(2*TP+FP+FN) = Precision*Recall /(Precision +Recall)"
},
{
"code": null,
"e": 10675,
"s": 10529,
"text": "# Test accuracy ratesum(diag(conf.matrix)/sum(conf.matrix))[1] 0.8899005# Test error rate1 - sum(drag(conf.matrix)/sum(conf.matrix))[1] 0.1100995"
},
{
"code": null,
"e": 10795,
"s": 10675,
"text": "As you may notice, test accuracy rate + test error rate = 1, and I’m providing multiple ways of calculating each value."
},
{
"code": null,
"e": 11182,
"s": 10795,
"text": "# ROC and AUCknn_model = knn(train=XTrain, test=XTrain, cl=YTrain, k=20,prob=TRUE)prob <- attr(knn_model, “prob”)prob <- 2*ifelse(knn_model == “-1”, prob,1-prob) — 1pred_knn <- prediction(prob, YTrain)performance_knn <- performance(pred_knn, “tpr”, “fpr”)# AUCauc_knn <- performance(pred_knn,”auc”)@y.valuesauc_knn[1] 0.8470583plot(performance_knn,col=2,lwd=2,main=”ROC Curves for KNN”)"
},
{
"code": null,
"e": 11380,
"s": 11182,
"text": "In conclusion, we have learned what KNN is and the pipeline of building a KNN model in R. Also, we have mastered the skills of conducting K-Fold Cross-Validation and how to implement the code in R."
},
{
"code": null,
"e": 11432,
"s": 11380,
"text": "The complete Python code is available on my Github."
},
{
"code": null,
"e": 11644,
"s": 11432,
"text": "Medium recently evolved its Writer Partner Program, which supports ordinary writers like myself. If you are not a subscriber yet and sign up via the following link, I’ll receive a portion of the membership fees."
},
{
"code": null,
"e": 11665,
"s": 11644,
"text": "leihua-ye.medium.com"
},
{
"code": null,
"e": 11688,
"s": 11665,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 11711,
"s": 11688,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 11734,
"s": 11711,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 11774,
"s": 11734,
"text": "Please find me on LinkedIn and Youtube."
}
] |
D3.js rollup() method - GeeksforGeeks
|
14 Sep, 2020
With the help of d3.rollup() method, we can get the reduced map from iterable data structure having key and values.
Syntax:
d3.rollup(iterable, reduce, ...keys)
Return value: It will return the reduced map from iterables.
Note: To execute the below examples you have to install the d3 library by using the command prompt for the following command.
npm install d3
Example 1: In this example, we can see that by using the d3.rollup() method, we are able to get the reduced map from iterable data structure having key and values.
Javascript
// Defining d3 contrib variable var d3 = require('d3'); data = [ {name: "ABC", amount: "34.0", date: "11/12/2015"}, {name: "DEF", amount: "120.11", date: "11/12/2015"}, {name: "MNO", amount: "12.01", date: "01/04/2016"}, {name: "ABC", amount: "34.05", date: "01/04/2016"}] var gfg = d3.rollup(data, g => g.length, d => d.amount);console.log(gfg);
Output:
Map { '34.0' => 1, '120.11' => 1, '12.01' => 1, '34.05' => 1 }
Example 2:
Javascript
// Defining d3 contrib variable var d3 = require('d3'); data = [ {name: "ABC", amount: "34.0", date: "11/12/2019"}, {name: "DEF", amount: "120.11", date: "11/02/2020"}, {name: "MNO", amount: "12.01", date: "01/04/2020"}, {name: "DEF", amount: "34.05", date: "03/04/2020"}] var gfg = d3.rollup(data, g => g.length, d => d.name, d => d.date); console.log(gfg);
Output:
Map {
'ABC' => Map { '11/12/2019' => 1 },
'DEF' => Map { '11/02/2020' => 1, '03/04/2020' => 1 },
'MNO' => Map { '01/04/2020' => 1 }
}
D3.js
JavaScript
Node.js
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
How to create a link in JavaScript ?
How to Show Images on Click using HTML ?
How to remove an HTML element using JavaScript ?
Remove elements from a JavaScript Array
Express.js express.Router() Function
Installation of Node.js on Linux
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
Express.js res.render() Function
|
[
{
"code": null,
"e": 25169,
"s": 25141,
"text": "\n14 Sep, 2020"
},
{
"code": null,
"e": 25285,
"s": 25169,
"text": "With the help of d3.rollup() method, we can get the reduced map from iterable data structure having key and values."
},
{
"code": null,
"e": 25293,
"s": 25285,
"text": "Syntax:"
},
{
"code": null,
"e": 25331,
"s": 25293,
"text": "d3.rollup(iterable, reduce, ...keys)\n"
},
{
"code": null,
"e": 25392,
"s": 25331,
"text": "Return value: It will return the reduced map from iterables."
},
{
"code": null,
"e": 25518,
"s": 25392,
"text": "Note: To execute the below examples you have to install the d3 library by using the command prompt for the following command."
},
{
"code": null,
"e": 25534,
"s": 25518,
"text": "npm install d3\n"
},
{
"code": null,
"e": 25698,
"s": 25534,
"text": "Example 1: In this example, we can see that by using the d3.rollup() method, we are able to get the reduced map from iterable data structure having key and values."
},
{
"code": null,
"e": 25709,
"s": 25698,
"text": "Javascript"
},
{
"code": "// Defining d3 contrib variable var d3 = require('d3'); data = [ {name: \"ABC\", amount: \"34.0\", date: \"11/12/2015\"}, {name: \"DEF\", amount: \"120.11\", date: \"11/12/2015\"}, {name: \"MNO\", amount: \"12.01\", date: \"01/04/2016\"}, {name: \"ABC\", amount: \"34.05\", date: \"01/04/2016\"}] var gfg = d3.rollup(data, g => g.length, d => d.amount);console.log(gfg);",
"e": 26070,
"s": 25709,
"text": null
},
{
"code": null,
"e": 26078,
"s": 26070,
"text": "Output:"
},
{
"code": null,
"e": 26142,
"s": 26078,
"text": "Map { '34.0' => 1, '120.11' => 1, '12.01' => 1, '34.05' => 1 }\n"
},
{
"code": null,
"e": 26153,
"s": 26142,
"text": "Example 2:"
},
{
"code": null,
"e": 26164,
"s": 26153,
"text": "Javascript"
},
{
"code": "// Defining d3 contrib variable var d3 = require('d3'); data = [ {name: \"ABC\", amount: \"34.0\", date: \"11/12/2019\"}, {name: \"DEF\", amount: \"120.11\", date: \"11/02/2020\"}, {name: \"MNO\", amount: \"12.01\", date: \"01/04/2020\"}, {name: \"DEF\", amount: \"34.05\", date: \"03/04/2020\"}] var gfg = d3.rollup(data, g => g.length, d => d.name, d => d.date); console.log(gfg);",
"e": 26538,
"s": 26164,
"text": null
},
{
"code": null,
"e": 26546,
"s": 26538,
"text": "Output:"
},
{
"code": null,
"e": 26691,
"s": 26546,
"text": "Map {\n 'ABC' => Map { '11/12/2019' => 1 },\n 'DEF' => Map { '11/02/2020' => 1, '03/04/2020' => 1 },\n 'MNO' => Map { '01/04/2020' => 1 } \n }\n\n"
},
{
"code": null,
"e": 26697,
"s": 26691,
"text": "D3.js"
},
{
"code": null,
"e": 26708,
"s": 26697,
"text": "JavaScript"
},
{
"code": null,
"e": 26716,
"s": 26708,
"text": "Node.js"
},
{
"code": null,
"e": 26814,
"s": 26716,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26823,
"s": 26814,
"text": "Comments"
},
{
"code": null,
"e": 26836,
"s": 26823,
"text": "Old Comments"
},
{
"code": null,
"e": 26897,
"s": 26836,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26934,
"s": 26897,
"text": "How to create a link in JavaScript ?"
},
{
"code": null,
"e": 26975,
"s": 26934,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 27024,
"s": 26975,
"text": "How to remove an HTML element using JavaScript ?"
},
{
"code": null,
"e": 27064,
"s": 27024,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27101,
"s": 27064,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 27134,
"s": 27101,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27167,
"s": 27134,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 27197,
"s": 27167,
"text": "Node.js fs.writeFile() Method"
}
] |
Python 3 - Strings
|
Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable. For example −
var1 = 'Hello World!'
var2 = "Python Programming"
Python does not support a character type; these are treated as strings of length one, thus also considered a substring.
To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. For example −
#!/usr/bin/python3
var1 = 'Hello World!'
var2 = "Python Programming"
print ("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5])
When the above code is executed, it produces the following result −
var1[0]: H
var2[1:5]: ytho
You can "update" an existing string by (re)assigning a variable to another string. The new value can be related to its previous value or to a completely different string altogether. For example −
#!/usr/bin/python3
var1 = 'Hello World!'
print ("Updated String :- ", var1[:6] + 'Python')
When the above code is executed, it produces the following result −
Updated String :- Hello Python
Following table is a list of escape or non-printable characters that can be represented with backslash notation.
An escape character gets interpreted; in a single quoted as well as double quoted strings.
Assume string variable a holds 'Hello' and variable b holds 'Python', then −
One of Python's coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C's printf() family. Following is a simple example −
#!/usr/bin/python3
print ("My name is %s and weight is %d kg!" % ('Zara', 21))
When the above code is executed, it produces the following result −
My name is Zara and weight is 21 kg!
Here is the list of complete set of symbols which can be used along with % −
%c
character
%s
string conversion via str() prior to formatting
%i
signed decimal integer
%d
signed decimal integer
%u
unsigned decimal integer
%o
octal integer
%x
hexadecimal integer (lowercase letters)
%X
hexadecimal integer (UPPERcase letters)
%e
exponential notation (with lowercase 'e')
%E
exponential notation (with UPPERcase 'E')
%f
floating point real number
%g
the shorter of %f and %e
%G
the shorter of %f and %E
Other supported symbols and functionality are listed in the following table −
*
argument specifies width or precision
-
left justification
+
display the sign
<sp>
leave a blank space before a positive number
#
add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X', depending on whether 'x' or 'X' were used.
0
pad from left with zeros (instead of spaces)
%
'%%' leaves you with a single literal '%'
(var)
mapping variable (dictionary arguments)
m.n.
m is the minimum total width and n is the number of digits to display after the decimal point (if appl.)
Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim NEWLINEs, TABs, and any other special characters.
The syntax for triple quotes consists of three consecutive single or double quotes.
#!/usr/bin/python3
para_str = """this is a long string that is made up of
several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ \n ], or just a NEWLINE within
the variable assignment will also show up.
"""
print (para_str)
When the above code is executed, it produces the following result. Note how every single special character has been converted to its printed form, right down to the last NEWLINE at the end of the string between the "up." and closing triple quotes. Also note that NEWLINEs occur either with an explicit carriage return at the end of a line or its escape code (\n) −
this is a long string that is made up of
several lines and non-printable characters such as
TAB ( ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [
], or just a NEWLINE within
the variable assignment will also show up.
Raw strings do not treat the backslash as a special character at all. Every character you put into a raw string stays the way you wrote it −
#!/usr/bin/python3
print ('C:\\nowhere')
When the above code is executed, it produces the following result −
C:\nowhere
Now let's make use of raw string. We would put expression in r'expression' as follows −
#!/usr/bin/python3
print (r'C:\\nowhere')
When the above code is executed, it produces the following result −
C:\\nowhere
In Python 3, all strings are represented in Unicode.In Python 2 are stored internally as 8-bit ASCII, hence it is required to attach 'u' to make it Unicode. It is no longer necessary now.
Python includes the following built-in methods to manipulate strings −
Capitalizes first letter of string
Returns a string padded with fillchar with the original string centered to a total of width columns.
Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given.
Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding.
Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with 'ignore' or 'replace'.
Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise.
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.
Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.
Same as find(), but raises an exception if str not found.
Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.
Returns true if string contains only digits and false otherwise.
Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.
Returns true if a unicode string contains only numeric characters and false otherwise.
Returns true if string contains only whitespace characters and false otherwise.
Returns true if string is properly "titlecased" and false otherwise.
Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.
Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string.
Returns the length of the string
Returns a space-padded string with the original string left-justified to a total of width columns.
Converts all uppercase letters in string to lowercase.
Removes all leading whitespace in string.
Returns a translation table to be used in translate function.
Returns the max alphabetical character from the string str.
Returns the min alphabetical character from the string str.
Replaces all occurrences of old in string with new or at most max occurrences if max given.
Same as find(), but search backwards in string.
Same as index(), but search backwards in string.
Returns a space-padded string with the original string right-justified to a total of width columns.
Removes all trailing whitespace of string.
Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given.
Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed.
Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring str; returns true if so and false otherwise.
Performs both lstrip() and rstrip() on string
Inverts case for all letters in string.
Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are lowercase.
Translates string according to translation table str(256 chars), removing those in the del string.
Converts lowercase letters in string to uppercase.
Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero).
Returns true if a unicode string contains only decimal characters and false otherwise.
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": 2590,
"s": 2340,
"text": "Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable. For example −"
},
{
"code": null,
"e": 2640,
"s": 2590,
"text": "var1 = 'Hello World!'\nvar2 = \"Python Programming\""
},
{
"code": null,
"e": 2760,
"s": 2640,
"text": "Python does not support a character type; these are treated as strings of length one, thus also considered a substring."
},
{
"code": null,
"e": 2890,
"s": 2760,
"text": "To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. For example −"
},
{
"code": null,
"e": 3023,
"s": 2890,
"text": "#!/usr/bin/python3\n\nvar1 = 'Hello World!'\nvar2 = \"Python Programming\"\n\nprint (\"var1[0]: \", var1[0])\nprint (\"var2[1:5]: \", var2[1:5])"
},
{
"code": null,
"e": 3091,
"s": 3023,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3121,
"s": 3091,
"text": "var1[0]: H\nvar2[1:5]: ytho\n"
},
{
"code": null,
"e": 3317,
"s": 3121,
"text": "You can \"update\" an existing string by (re)assigning a variable to another string. The new value can be related to its previous value or to a completely different string altogether. For example −"
},
{
"code": null,
"e": 3409,
"s": 3317,
"text": "#!/usr/bin/python3\n\nvar1 = 'Hello World!'\nprint (\"Updated String :- \", var1[:6] + 'Python')"
},
{
"code": null,
"e": 3477,
"s": 3409,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3510,
"s": 3477,
"text": "Updated String :- Hello Python\n"
},
{
"code": null,
"e": 3623,
"s": 3510,
"text": "Following table is a list of escape or non-printable characters that can be represented with backslash notation."
},
{
"code": null,
"e": 3714,
"s": 3623,
"text": "An escape character gets interpreted; in a single quoted as well as double quoted strings."
},
{
"code": null,
"e": 3791,
"s": 3714,
"text": "Assume string variable a holds 'Hello' and variable b holds 'Python', then −"
},
{
"code": null,
"e": 3996,
"s": 3791,
"text": "One of Python's coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C's printf() family. Following is a simple example −"
},
{
"code": null,
"e": 4077,
"s": 3996,
"text": "#!/usr/bin/python3\n\nprint (\"My name is %s and weight is %d kg!\" % ('Zara', 21)) "
},
{
"code": null,
"e": 4145,
"s": 4077,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 4183,
"s": 4145,
"text": "My name is Zara and weight is 21 kg!\n"
},
{
"code": null,
"e": 4260,
"s": 4183,
"text": "Here is the list of complete set of symbols which can be used along with % −"
},
{
"code": null,
"e": 4263,
"s": 4260,
"text": "%c"
},
{
"code": null,
"e": 4273,
"s": 4263,
"text": "character"
},
{
"code": null,
"e": 4276,
"s": 4273,
"text": "%s"
},
{
"code": null,
"e": 4324,
"s": 4276,
"text": "string conversion via str() prior to formatting"
},
{
"code": null,
"e": 4327,
"s": 4324,
"text": "%i"
},
{
"code": null,
"e": 4350,
"s": 4327,
"text": "signed decimal integer"
},
{
"code": null,
"e": 4353,
"s": 4350,
"text": "%d"
},
{
"code": null,
"e": 4376,
"s": 4353,
"text": "signed decimal integer"
},
{
"code": null,
"e": 4379,
"s": 4376,
"text": "%u"
},
{
"code": null,
"e": 4404,
"s": 4379,
"text": "unsigned decimal integer"
},
{
"code": null,
"e": 4407,
"s": 4404,
"text": "%o"
},
{
"code": null,
"e": 4421,
"s": 4407,
"text": "octal integer"
},
{
"code": null,
"e": 4424,
"s": 4421,
"text": "%x"
},
{
"code": null,
"e": 4464,
"s": 4424,
"text": "hexadecimal integer (lowercase letters)"
},
{
"code": null,
"e": 4467,
"s": 4464,
"text": "%X"
},
{
"code": null,
"e": 4507,
"s": 4467,
"text": "hexadecimal integer (UPPERcase letters)"
},
{
"code": null,
"e": 4510,
"s": 4507,
"text": "%e"
},
{
"code": null,
"e": 4552,
"s": 4510,
"text": "exponential notation (with lowercase 'e')"
},
{
"code": null,
"e": 4555,
"s": 4552,
"text": "%E"
},
{
"code": null,
"e": 4597,
"s": 4555,
"text": "exponential notation (with UPPERcase 'E')"
},
{
"code": null,
"e": 4600,
"s": 4597,
"text": "%f"
},
{
"code": null,
"e": 4627,
"s": 4600,
"text": "floating point real number"
},
{
"code": null,
"e": 4630,
"s": 4627,
"text": "%g"
},
{
"code": null,
"e": 4655,
"s": 4630,
"text": "the shorter of %f and %e"
},
{
"code": null,
"e": 4658,
"s": 4655,
"text": "%G"
},
{
"code": null,
"e": 4683,
"s": 4658,
"text": "the shorter of %f and %E"
},
{
"code": null,
"e": 4761,
"s": 4683,
"text": "Other supported symbols and functionality are listed in the following table −"
},
{
"code": null,
"e": 4763,
"s": 4761,
"text": "*"
},
{
"code": null,
"e": 4801,
"s": 4763,
"text": "argument specifies width or precision"
},
{
"code": null,
"e": 4803,
"s": 4801,
"text": "-"
},
{
"code": null,
"e": 4822,
"s": 4803,
"text": "left justification"
},
{
"code": null,
"e": 4824,
"s": 4822,
"text": "+"
},
{
"code": null,
"e": 4841,
"s": 4824,
"text": "display the sign"
},
{
"code": null,
"e": 4846,
"s": 4841,
"text": "<sp>"
},
{
"code": null,
"e": 4891,
"s": 4846,
"text": "leave a blank space before a positive number"
},
{
"code": null,
"e": 4893,
"s": 4891,
"text": "#"
},
{
"code": null,
"e": 5008,
"s": 4893,
"text": "add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X', depending on whether 'x' or 'X' were used."
},
{
"code": null,
"e": 5010,
"s": 5008,
"text": "0"
},
{
"code": null,
"e": 5055,
"s": 5010,
"text": "pad from left with zeros (instead of spaces)"
},
{
"code": null,
"e": 5057,
"s": 5055,
"text": "%"
},
{
"code": null,
"e": 5099,
"s": 5057,
"text": "'%%' leaves you with a single literal '%'"
},
{
"code": null,
"e": 5105,
"s": 5099,
"text": "(var)"
},
{
"code": null,
"e": 5145,
"s": 5105,
"text": "mapping variable (dictionary arguments)"
},
{
"code": null,
"e": 5150,
"s": 5145,
"text": "m.n."
},
{
"code": null,
"e": 5255,
"s": 5150,
"text": "m is the minimum total width and n is the number of digits to display after the decimal point (if appl.)"
},
{
"code": null,
"e": 5411,
"s": 5255,
"text": "Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim NEWLINEs, TABs, and any other special characters."
},
{
"code": null,
"e": 5495,
"s": 5411,
"text": "The syntax for triple quotes consists of three consecutive single or double quotes."
},
{
"code": null,
"e": 5859,
"s": 5495,
"text": "#!/usr/bin/python3\n\npara_str = \"\"\"this is a long string that is made up of\nseveral lines and non-printable characters such as\nTAB ( \\t ) and they will show up that way when displayed.\nNEWLINEs within the string, whether explicitly given like\nthis within the brackets [ \\n ], or just a NEWLINE within\nthe variable assignment will also show up.\n\"\"\"\nprint (para_str)"
},
{
"code": null,
"e": 6224,
"s": 5859,
"text": "When the above code is executed, it produces the following result. Note how every single special character has been converted to its printed form, right down to the last NEWLINE at the end of the string between the \"up.\" and closing triple quotes. Also note that NEWLINEs occur either with an explicit carriage return at the end of a line or its escape code (\\n) −"
},
{
"code": null,
"e": 6532,
"s": 6224,
"text": "this is a long string that is made up of\nseveral lines and non-printable characters such as\nTAB ( ) and they will show up that way when displayed.\nNEWLINEs within the string, whether explicitly given like\nthis within the brackets [\n ], or just a NEWLINE within\nthe variable assignment will also show up.\n"
},
{
"code": null,
"e": 6673,
"s": 6532,
"text": "Raw strings do not treat the backslash as a special character at all. Every character you put into a raw string stays the way you wrote it −"
},
{
"code": null,
"e": 6715,
"s": 6673,
"text": "#!/usr/bin/python3\n\nprint ('C:\\\\nowhere')"
},
{
"code": null,
"e": 6783,
"s": 6715,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 6795,
"s": 6783,
"text": "C:\\nowhere\n"
},
{
"code": null,
"e": 6883,
"s": 6795,
"text": "Now let's make use of raw string. We would put expression in r'expression' as follows −"
},
{
"code": null,
"e": 6926,
"s": 6883,
"text": "#!/usr/bin/python3\n\nprint (r'C:\\\\nowhere')"
},
{
"code": null,
"e": 6994,
"s": 6926,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 7007,
"s": 6994,
"text": "C:\\\\nowhere\n"
},
{
"code": null,
"e": 7195,
"s": 7007,
"text": "In Python 3, all strings are represented in Unicode.In Python 2 are stored internally as 8-bit ASCII, hence it is required to attach 'u' to make it Unicode. It is no longer necessary now."
},
{
"code": null,
"e": 7266,
"s": 7195,
"text": "Python includes the following built-in methods to manipulate strings −"
},
{
"code": null,
"e": 7301,
"s": 7266,
"text": "Capitalizes first letter of string"
},
{
"code": null,
"e": 7402,
"s": 7301,
"text": "Returns a string padded with fillchar with the original string centered to a total of width columns."
},
{
"code": null,
"e": 7527,
"s": 7402,
"text": "Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given."
},
{
"code": null,
"e": 7637,
"s": 7527,
"text": "Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding."
},
{
"code": null,
"e": 7773,
"s": 7637,
"text": "Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with 'ignore' or 'replace'."
},
{
"code": null,
"e": 7932,
"s": 7773,
"text": "Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise."
},
{
"code": null,
"e": 8029,
"s": 7932,
"text": "Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided."
},
{
"code": null,
"e": 8185,
"s": 8029,
"text": "Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise."
},
{
"code": null,
"e": 8243,
"s": 8185,
"text": "Same as find(), but raises an exception if str not found."
},
{
"code": null,
"e": 8348,
"s": 8243,
"text": "Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise."
},
{
"code": null,
"e": 8451,
"s": 8348,
"text": "Returns true if string has at least 1 character and all characters are alphabetic and false otherwise."
},
{
"code": null,
"e": 8516,
"s": 8451,
"text": "Returns true if string contains only digits and false otherwise."
},
{
"code": null,
"e": 8633,
"s": 8516,
"text": "Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise."
},
{
"code": null,
"e": 8720,
"s": 8633,
"text": "Returns true if a unicode string contains only numeric characters and false otherwise."
},
{
"code": null,
"e": 8800,
"s": 8720,
"text": "Returns true if string contains only whitespace characters and false otherwise."
},
{
"code": null,
"e": 8869,
"s": 8800,
"text": "Returns true if string is properly \"titlecased\" and false otherwise."
},
{
"code": null,
"e": 8988,
"s": 8869,
"text": "Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise."
},
{
"code": null,
"e": 9103,
"s": 8988,
"text": "Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string."
},
{
"code": null,
"e": 9136,
"s": 9103,
"text": "Returns the length of the string"
},
{
"code": null,
"e": 9235,
"s": 9136,
"text": "Returns a space-padded string with the original string left-justified to a total of width columns."
},
{
"code": null,
"e": 9290,
"s": 9235,
"text": "Converts all uppercase letters in string to lowercase."
},
{
"code": null,
"e": 9332,
"s": 9290,
"text": "Removes all leading whitespace in string."
},
{
"code": null,
"e": 9394,
"s": 9332,
"text": "Returns a translation table to be used in translate function."
},
{
"code": null,
"e": 9454,
"s": 9394,
"text": "Returns the max alphabetical character from the string str."
},
{
"code": null,
"e": 9514,
"s": 9454,
"text": "Returns the min alphabetical character from the string str."
},
{
"code": null,
"e": 9606,
"s": 9514,
"text": "Replaces all occurrences of old in string with new or at most max occurrences if max given."
},
{
"code": null,
"e": 9654,
"s": 9606,
"text": "Same as find(), but search backwards in string."
},
{
"code": null,
"e": 9703,
"s": 9654,
"text": "Same as index(), but search backwards in string."
},
{
"code": null,
"e": 9803,
"s": 9703,
"text": "Returns a space-padded string with the original string right-justified to a total of width columns."
},
{
"code": null,
"e": 9846,
"s": 9803,
"text": "Removes all trailing whitespace of string."
},
{
"code": null,
"e": 9987,
"s": 9846,
"text": "Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given."
},
{
"code": null,
"e": 10081,
"s": 9987,
"text": "Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed."
},
{
"code": null,
"e": 10249,
"s": 10081,
"text": "Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring str; returns true if so and false otherwise."
},
{
"code": null,
"e": 10295,
"s": 10249,
"text": "Performs both lstrip() and rstrip() on string"
},
{
"code": null,
"e": 10335,
"s": 10295,
"text": "Inverts case for all letters in string."
},
{
"code": null,
"e": 10443,
"s": 10335,
"text": "Returns \"titlecased\" version of string, that is, all words begin with uppercase and the rest are lowercase."
},
{
"code": null,
"e": 10542,
"s": 10443,
"text": "Translates string according to translation table str(256 chars), removing those in the del string."
},
{
"code": null,
"e": 10593,
"s": 10542,
"text": "Converts lowercase letters in string to uppercase."
},
{
"code": null,
"e": 10741,
"s": 10593,
"text": "Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero)."
},
{
"code": null,
"e": 10828,
"s": 10741,
"text": "Returns true if a unicode string contains only decimal characters and false otherwise."
},
{
"code": null,
"e": 10865,
"s": 10828,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 10881,
"s": 10865,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 10914,
"s": 10881,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 10933,
"s": 10914,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 10968,
"s": 10933,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 10990,
"s": 10968,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 11024,
"s": 10990,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 11052,
"s": 11024,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 11087,
"s": 11052,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 11101,
"s": 11087,
"text": " Lets Kode It"
},
{
"code": null,
"e": 11134,
"s": 11101,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 11151,
"s": 11134,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 11158,
"s": 11151,
"text": " Print"
},
{
"code": null,
"e": 11169,
"s": 11158,
"text": " Add Notes"
}
] |
Variable number of arguments in Lua Programming
|
There are functions in Lua that accept a variable number of arguments. These are very helpful in cases where we want to run the same function with many different arguments that might vary in length. So, instead of creating a different function, we pass them in a variable arguments fashion.
function add(...)
-- function code
end
It should be noted that the three dots (...) in the parameter list indicate that the function has a variable number of arguments. Whenever this function will be called, all its arguments will be collected in a single table, which the function addresses as a hidden parameter named arg.
Now let’s consider an example where we will pass variable number of arguments to a function. The function will be used to calculate the minimum value present in the array that was passed to it as an argument. Also, it will be used to find the minimum values index and we will print both the minimum value and the minimum index.
function minimumvalue (...)
local mi = 1 -- maximum index
local m = 100 -- maximum value
local args = {...}
for i,val in ipairs(args) do
if val < m then
mi = i
m = val
end
end
return m, mi
end
print(minimumvalue(8,10,23,12,5))
5 5
Notice that now we can make use of the fact that we can have a variable number of arguments in the same function, and hence, when we call the same function again, we will get the minimum value and the minimum index.
function minimumvalue (...)
local mi = 1 -- maximum index
local m = 100 -- maximum value
local args = {...}
for i,val in ipairs(args) do
if val < m then
mi = i
m = val
end
end
return m, mi
end
print(minimumvalue(8,10,23,12,5))
print(minimumvalue(1,2,3))
5 5
1 1
|
[
{
"code": null,
"e": 1353,
"s": 1062,
"text": "There are functions in Lua that accept a variable number of arguments. These are very helpful in cases where we want to run the same function with many different arguments that might vary in length. So, instead of creating a different function, we pass them in a variable arguments fashion."
},
{
"code": null,
"e": 1395,
"s": 1353,
"text": "function add(...)\n -- function code\nend"
},
{
"code": null,
"e": 1681,
"s": 1395,
"text": "It should be noted that the three dots (...) in the parameter list indicate that the function has a variable number of arguments. Whenever this function will be called, all its arguments will be collected in a single table, which the function addresses as a hidden parameter named arg."
},
{
"code": null,
"e": 2009,
"s": 1681,
"text": "Now let’s consider an example where we will pass variable number of arguments to a function. The function will be used to calculate the minimum value present in the array that was passed to it as an argument. Also, it will be used to find the minimum values index and we will print both the minimum value and the minimum index."
},
{
"code": null,
"e": 2285,
"s": 2009,
"text": "function minimumvalue (...)\n local mi = 1 -- maximum index\n local m = 100 -- maximum value\n local args = {...}\n for i,val in ipairs(args) do\n if val < m then\n mi = i\n m = val\n end\n end\n return m, mi\nend\n\nprint(minimumvalue(8,10,23,12,5))"
},
{
"code": null,
"e": 2291,
"s": 2285,
"text": "5 5"
},
{
"code": null,
"e": 2507,
"s": 2291,
"text": "Notice that now we can make use of the fact that we can have a variable number of arguments in the same function, and hence, when we call the same function again, we will get the minimum value and the minimum index."
},
{
"code": null,
"e": 2811,
"s": 2507,
"text": "function minimumvalue (...)\n local mi = 1 -- maximum index\n local m = 100 -- maximum value\n local args = {...}\n for i,val in ipairs(args) do\n if val < m then\n mi = i\n m = val\n end\n end\n return m, mi\nend\n\nprint(minimumvalue(8,10,23,12,5))\n\nprint(minimumvalue(1,2,3))"
},
{
"code": null,
"e": 2823,
"s": 2811,
"text": "5 5\n1 1"
}
] |
Deploy a Node.js Application With the App Engine in 10 Minutes! | by Andrew Didinchuk | Towards Data Science
|
Google Cloud’s App Engine allows you to deploy scalable web applications on a platform fully managed by Google. These applications can range from back-end services and API layers to front-end applications running on Angular and React frameworks. Google provides 28 daily hours of run time with this service for free so you can get away with some free hosting!
In this article, I will walk you through the deployment of a simple Node.js application on this App Engine platform.
To follow along, you should have the following:
A basic understanding of how Node.js worksNode installed on your local machineA Google Cloud Platform account and a project
A basic understanding of how Node.js works
Node installed on your local machine
A Google Cloud Platform account and a project
Somewhere on your local machine initialize a new Node.js project.
mkdir helloworldcd helloworldnpm init
Create a simple execution file index.js with the following content in the helloworld folder:
const express = require('express');const app = express();app.get('/', (req, res) => { res.send('GCP App Engine!');});const PORT = process.env.PORT || 8080;app.listen(PORT, () => { console.log(`Server listening on port ${PORT}...`);});
Our application won’t do much and just returns a 'GCP App Engine!' string when called.
Add the following start script and express dependency to the created package.json file:
{ ... "scripts": { "start": "node index.js" }, "dependencies": { "express": "^4.16.3" }}
Express is not required and I am using it to make deployment easier. The start script will be used by the App Engine to launch your application. Note that index.js matches the name of my main execution file created above.
Install dependencies (express) and make sure your app runs locally:
npm installnode index.js
Navigate to http://localhost:8080 and you should see:
The application is ready to go but we need to provide some information to the App Engine so that it knows how to deploy our code. We do this using a YAML file. The configuration in this file can get pretty complicated and there are a lot of options to configure but in our case, I will keep it simple. Create a file called app.yaml in the helloworld folder and add the following content:
runtime: nodejs14env: standardinstance_class: F1automatic_scaling: min_idle_instances: automatic max_idle_instances: automatic min_pending_latency: automatic max_pending_latency: automatic
My Node.js runtime is version is 14.16.0, feel free to change the runtime if your version is different. We will be using a standard environment and an F1 instance as these are covered by GCP’s free quota.
At this point, you should have the below file structure and we are ready to start migrating our code to GCP.
├── helloworld│ ├── index.js│ ├── package.json│ ├── app.yaml
Before deploying the application you will need to make the code available to GCP. You can do this by leveraging Cloud SDK on your local machine or by using the Cloud Shell as I will be doing in this walk-through.
I will be using a Cloud Storage bucket to stage my code before pushing it to the App Engine. Create a new bucket to house your source code (you can reuse an existing bucket if desired). For the region, you should set Regional and the rest of the settings can be left default. In my case, I am creating a bucket called sample-code-repo and uploading the entire helloworld folder to the root.
Next, we need to get the code uploaded to the Cloud Shell VM, you can do this by opening the Cloud Shell terminal from any GCP console page or just click here.
To create the required folder structure on the Cloud Shell VM and sync the code from the bucket run the following commands, replacing sample-code-repo/helloworld with <source-code-bucket-name>/<app-folder-name> :
mkdir helloworldcd helloworldgsutil rsync -r gs://sample-code-repo/helloworld .
You will be asked to authorize the bucket access (pop-up) and once done running the ls command should confirm data replication:
If you have another preferred method to migrate code to Cloud Shell (e.g. git), feel free to use it. At this point, our project is ready for deployment.
To deploy the application on the App Engine we need to head back to our Cloud Shell VM and run the following:
cd helloworldgcloud app deploy
For your first App Engine deployment, you will need to specify a region — I used us-central for mine. The code will take a minute to compile and once done running gcloud app browse will output a link that you can use to access your now deployed application!
Google’s App Engine is a great platform for rapidly deploying applications online at no cost. In this article, I walked you through how this platform can be used for Node.js applications but the same result can be accomplished with Java, Python, PHP, and Go. I hope that you were able to learn something from this post.
Good luck and happy coding!
Originally published at https://theappliedarchitect.com on April 11, 2021.
|
[
{
"code": null,
"e": 532,
"s": 172,
"text": "Google Cloud’s App Engine allows you to deploy scalable web applications on a platform fully managed by Google. These applications can range from back-end services and API layers to front-end applications running on Angular and React frameworks. Google provides 28 daily hours of run time with this service for free so you can get away with some free hosting!"
},
{
"code": null,
"e": 649,
"s": 532,
"text": "In this article, I will walk you through the deployment of a simple Node.js application on this App Engine platform."
},
{
"code": null,
"e": 697,
"s": 649,
"text": "To follow along, you should have the following:"
},
{
"code": null,
"e": 821,
"s": 697,
"text": "A basic understanding of how Node.js worksNode installed on your local machineA Google Cloud Platform account and a project"
},
{
"code": null,
"e": 864,
"s": 821,
"text": "A basic understanding of how Node.js works"
},
{
"code": null,
"e": 901,
"s": 864,
"text": "Node installed on your local machine"
},
{
"code": null,
"e": 947,
"s": 901,
"text": "A Google Cloud Platform account and a project"
},
{
"code": null,
"e": 1013,
"s": 947,
"text": "Somewhere on your local machine initialize a new Node.js project."
},
{
"code": null,
"e": 1051,
"s": 1013,
"text": "mkdir helloworldcd helloworldnpm init"
},
{
"code": null,
"e": 1144,
"s": 1051,
"text": "Create a simple execution file index.js with the following content in the helloworld folder:"
},
{
"code": null,
"e": 1381,
"s": 1144,
"text": "const express = require('express');const app = express();app.get('/', (req, res) => { res.send('GCP App Engine!');});const PORT = process.env.PORT || 8080;app.listen(PORT, () => { console.log(`Server listening on port ${PORT}...`);});"
},
{
"code": null,
"e": 1468,
"s": 1381,
"text": "Our application won’t do much and just returns a 'GCP App Engine!' string when called."
},
{
"code": null,
"e": 1556,
"s": 1468,
"text": "Add the following start script and express dependency to the created package.json file:"
},
{
"code": null,
"e": 1649,
"s": 1556,
"text": "{ ... \"scripts\": { \"start\": \"node index.js\" }, \"dependencies\": { \"express\": \"^4.16.3\" }}"
},
{
"code": null,
"e": 1871,
"s": 1649,
"text": "Express is not required and I am using it to make deployment easier. The start script will be used by the App Engine to launch your application. Note that index.js matches the name of my main execution file created above."
},
{
"code": null,
"e": 1939,
"s": 1871,
"text": "Install dependencies (express) and make sure your app runs locally:"
},
{
"code": null,
"e": 1964,
"s": 1939,
"text": "npm installnode index.js"
},
{
"code": null,
"e": 2018,
"s": 1964,
"text": "Navigate to http://localhost:8080 and you should see:"
},
{
"code": null,
"e": 2406,
"s": 2018,
"text": "The application is ready to go but we need to provide some information to the App Engine so that it knows how to deploy our code. We do this using a YAML file. The configuration in this file can get pretty complicated and there are a lot of options to configure but in our case, I will keep it simple. Create a file called app.yaml in the helloworld folder and add the following content:"
},
{
"code": null,
"e": 2599,
"s": 2406,
"text": "runtime: nodejs14env: standardinstance_class: F1automatic_scaling: min_idle_instances: automatic max_idle_instances: automatic min_pending_latency: automatic max_pending_latency: automatic"
},
{
"code": null,
"e": 2804,
"s": 2599,
"text": "My Node.js runtime is version is 14.16.0, feel free to change the runtime if your version is different. We will be using a standard environment and an F1 instance as these are covered by GCP’s free quota."
},
{
"code": null,
"e": 2913,
"s": 2804,
"text": "At this point, you should have the below file structure and we are ready to start migrating our code to GCP."
},
{
"code": null,
"e": 2974,
"s": 2913,
"text": "├── helloworld│ ├── index.js│ ├── package.json│ ├── app.yaml"
},
{
"code": null,
"e": 3187,
"s": 2974,
"text": "Before deploying the application you will need to make the code available to GCP. You can do this by leveraging Cloud SDK on your local machine or by using the Cloud Shell as I will be doing in this walk-through."
},
{
"code": null,
"e": 3578,
"s": 3187,
"text": "I will be using a Cloud Storage bucket to stage my code before pushing it to the App Engine. Create a new bucket to house your source code (you can reuse an existing bucket if desired). For the region, you should set Regional and the rest of the settings can be left default. In my case, I am creating a bucket called sample-code-repo and uploading the entire helloworld folder to the root."
},
{
"code": null,
"e": 3738,
"s": 3578,
"text": "Next, we need to get the code uploaded to the Cloud Shell VM, you can do this by opening the Cloud Shell terminal from any GCP console page or just click here."
},
{
"code": null,
"e": 3951,
"s": 3738,
"text": "To create the required folder structure on the Cloud Shell VM and sync the code from the bucket run the following commands, replacing sample-code-repo/helloworld with <source-code-bucket-name>/<app-folder-name> :"
},
{
"code": null,
"e": 4031,
"s": 3951,
"text": "mkdir helloworldcd helloworldgsutil rsync -r gs://sample-code-repo/helloworld ."
},
{
"code": null,
"e": 4159,
"s": 4031,
"text": "You will be asked to authorize the bucket access (pop-up) and once done running the ls command should confirm data replication:"
},
{
"code": null,
"e": 4312,
"s": 4159,
"text": "If you have another preferred method to migrate code to Cloud Shell (e.g. git), feel free to use it. At this point, our project is ready for deployment."
},
{
"code": null,
"e": 4422,
"s": 4312,
"text": "To deploy the application on the App Engine we need to head back to our Cloud Shell VM and run the following:"
},
{
"code": null,
"e": 4453,
"s": 4422,
"text": "cd helloworldgcloud app deploy"
},
{
"code": null,
"e": 4711,
"s": 4453,
"text": "For your first App Engine deployment, you will need to specify a region — I used us-central for mine. The code will take a minute to compile and once done running gcloud app browse will output a link that you can use to access your now deployed application!"
},
{
"code": null,
"e": 5031,
"s": 4711,
"text": "Google’s App Engine is a great platform for rapidly deploying applications online at no cost. In this article, I walked you through how this platform can be used for Node.js applications but the same result can be accomplished with Java, Python, PHP, and Go. I hope that you were able to learn something from this post."
},
{
"code": null,
"e": 5059,
"s": 5031,
"text": "Good luck and happy coding!"
}
] |
Classification Using Neural Networks | by Oliver Knocklein | Towards Data Science
|
Neural networks are one of those cool words that are often used to lend credence to research. But what exactly are they? After reading this article you should have a rough understanding of the internal mechanics of neural nets, and convolution neural networks, and be able to code your own simple neural network model in Python.
What are Neural Networks
Neural nets take inspiration from the learning process occurring in human brains. They consists of an artificial network of functions, called parameters, which allows the computer to learn, and to fine tune itself, by analyzing new data. Each parameter, sometimes also referred to as neurons, is a function which produces an output, after receiving one or multiple inputs. Those outputs are then passed to the next layer of neurons, which use them as inputs of their own function, and produce further outputs. Those outputs are then passed on to the next layer of neurons, and so it continues until every layer of neurons have been considered, and the terminal neurons have received their input. Those terminal neurons then output the final result for the model.
Figure 1 shows a visual representation of such a network. The initial input is x, which is then passed to the first layer of neurons (the h bubbles in Figure 1), where three functions consider the input that they receive, and generate an output. That output is then passed to the second layer (the g bubbles in Figure 1). There further output is calculated, based on the output from the first layer. That secondary output is then combined to yield a final output of the model.
Figure 1: A Visual Representation of a Simple Neural Net
How Do Neural Networks Learn?
An alternative way of thinking about a neural net is to think of it as one massive function which takes inputs and arrives at a final output. The intermediary functions, which are done by the neurons in their many layers, are usually unobserved, and thankfully automated. The mathematics behind them is as interesting as it is complex, and deserves a further look.
As previously mentioned, the neurons within the network interact with the neurons in the next layer, with every output acting as an input for a future function. Every function, including the initial neuron receives a numeric input, and produces a numeric output, based on a internalized function, which includes the addition of a bias term, which is unique for every neuron. That output is then converted to the numeric input for the function in the next layer, by being multiplied with an appropriate weight. This continues until one final output for the network is produced.
The difficulty lies in determining the optimal value for each bias term, as well as finding the best weighted value for each pass in the neural network. To accomplish this, one must choose a cost function. A cost function is a way of calculating how far a particular solution is from the best possible solution. There are many different possible cost functions, each with advantages and drawbacks, each best suited under certain conditions. Thus, the cost function should be tailored and selected based on individual research needs. Once a cost function has been determined, the neural net can be altered in a way to minimize that cost function.
A simple way of optimizing the weights and bias, is therefore to simply run the network multiple times. On the first try, the predictions will by necessity be random. After each iteration, the cost function will be analyzed, to determine how the model performed, and how it can be improved. The information gotten from the cost function is then passed onto the optimizing function, which calculates new weight values, as well as new bias values. With those new values integrated into the model, the model is rerun. This is continued until no alteration improves the cost function.
There are three methods of learning: supervised, unsupervised, and reinforcement learning. The simplest of these learning paradigms is supervised learning, where the neural net is given labelled inputs. The labelled examples, are then used to infer generalizable rules which can be applied to unlabeled cases. It is the simplest learning method, since it can be thought of operating with a ‘teacher’, in the form of a function that allows the net to compare its predictions to the true, and desired results. Unsupervised methods do not require labelled initial inputs, but rather infers the rules and functions, based not only on the given data, but also on the output of the net. This hampers the type of predictions which can be made. Instead of being able to classify, such a model is limited to clustering.
What are Convolution Neural Networks?
A variation of the vanilla neural network is the convolution neural network. ConvNets, as they are sometimes known offer some significant advantages over normal neural nets, especially when it comes to image classification. In such a case, the initial inputs would be images, made up of pixels. The traditional issue with image classification is that with big images, with many color channels, is that it quickly becomes computationally infeasible to train some models. What CNN tries to do is transform the images into a form which is easier to process, while still retaining the most important features. This is done by passing a filter over the initial image, which conducts matrix multiplication over a subsection of the pixels in the initial image, it iterates through subsets until it has considered all subsets. The filter aims at capturing the most crucial features, while allowing the redundant features to be eliminated. This passing of a filter over the initial pixels is known as the Convolution Layer.
After the convolution layer comes the pooling layer, where the spatial size of the convoluted features will be attempted to be reduced. The reduction in complexity, sometimes known as dimensionality reduction will decrease the computational cost of performing analysis on the data set, allowing the method to be more robust. In this layer, a kernel once again passes over all subsets of pixels of the image. There are two types of pooling kernels which are commonly used. The first one is Max Pooling, which retains the maximum value of the subset. The alternative kernel is average pooling, which does exactly what you’d expect: it retains the average value of all the pixels in the subset. Figure 2 visually shows the processes of the pooling phase.
Figure 2: The Pooling Phase of Convolution Neural Networks
After the pooling phase, the information will hopefully be compressed enough to be used in a regular neural network model. The last remaining thing to do is to flatten the final output of the pooling phase and feed it into the model. The flattening is done by changing the matrix of pixels into a vector of pixels, which can then be used for the neural net model.
From there, the convolution neural network acts just like a regular neural network, in that the information will be passed to a set of neurons, which will pass on values to other layers until a final output is reached. Convolution neural networks thus allow neural networks to be feasible for large data sets, or for complex images, since it reduces the computational power needed for the analysis.
What are Some Applications of Neural Networks?
There are many applications for machine learning methods such as neural nets. Most of these applications focus on classification of images. Those images could be of anything, from whether or not something is a hot dog, to identifying handwriting. The practical possibilities of such a model are broad, and lucrative. Let’s have a look at an example.
Many companies would love to be able to automate a model which would classify articles of clothing. Doing so would allow them to draw insight into fashion trends, buying habits, and differences between cultural, and socio-economic groups. To that end we will use a neural network, to see if an adequate classification model can be constructed, when given a set of 60,000 images, with labels identifying what type of clothing they were.
All of those pictures are made up of pixels, which since we will be doing a simple neural network, and not a convolution neural net, will be passed directly into the network as a vector of pixels.
In order to create a neural network, one must specify the number of layers within the model. For the sake of simplicity, I shall limit the model to two layers. One must also select the type of activation for each layer. Again, to keep it simple, I will select a sigmoid activation for the first layers, with the final layer having 10 nodes, and set to return 10 probability scores, indicating the probability whether the image belongs to one of the ten possible articles of clothing. To compile the model, a loss function must be defined, which will be how the model evaluates its own performance. An optimizer must also be determined, which is how the information from the cost function is used to change the weights and the bias of each node.
model = keras.Sequential([keras.layers.Flatten(input_shape (28,28)), keras.layers.Dense(128,activation = tf.nn.sigmoid), keras.layers.Dense(10,activation = tf.nn.softmax)])model.compile(optimizer = 'adam',loss='sparse_categorical_crossentropy',metrics =['accuracy'])
With those parameters input, a model can be trained. Once the model has been trained, it must be evaluated based on the testing data. To accomplish that, one must denote the number of epochs which the model will consider. Epochs determine how many iterations through the data shall be done. More epochs will be more computationally expensive, but should allow for a better fit. I shall consider 5 epochs. One can see how the accuracy of the model on the training data improves after each iteration, as the optimizing function alters the weights.
model.fit(x_train, y_train,epochs = 5)
The real fit of how a model performs is by running the model on a testing set, which was not used to construct the model. In this case, the neural net had an accuracy of 0.7203: Not Bad!
Summary
Neural networks are complex models, which try to mimic the way the human brain develops classification rules. A neural net consists of many different layers of neurons, with each layer receiving inputs from previous layers, and passing outputs to further layers. The way each layer output becomes the input for the next layer depends on the weight given to that specific link, which depends on the cost function, and the optimizer. The neural net iterates for a predetermined number of iterations, called epochs. After each epoch, the cost function is analyzed to see where the model could be improved. The optimizing function then alters the internal mechanics of the network, such as the weights, and the biases, based on the information provided by the cost function, until the cost function is minimized.
A convolution neural network is a twist of a normal neural network, which attempts to deal with the issue of high dimensionality by reducing the number of pixels in image classification through two separate phases: the convolution phase, and the pooling phase. After that it performs much like an ordinary neural network.
Key Word
Neural Networks
Convolution Neural Network
|
[
{
"code": null,
"e": 500,
"s": 171,
"text": "Neural networks are one of those cool words that are often used to lend credence to research. But what exactly are they? After reading this article you should have a rough understanding of the internal mechanics of neural nets, and convolution neural networks, and be able to code your own simple neural network model in Python."
},
{
"code": null,
"e": 525,
"s": 500,
"text": "What are Neural Networks"
},
{
"code": null,
"e": 1288,
"s": 525,
"text": "Neural nets take inspiration from the learning process occurring in human brains. They consists of an artificial network of functions, called parameters, which allows the computer to learn, and to fine tune itself, by analyzing new data. Each parameter, sometimes also referred to as neurons, is a function which produces an output, after receiving one or multiple inputs. Those outputs are then passed to the next layer of neurons, which use them as inputs of their own function, and produce further outputs. Those outputs are then passed on to the next layer of neurons, and so it continues until every layer of neurons have been considered, and the terminal neurons have received their input. Those terminal neurons then output the final result for the model."
},
{
"code": null,
"e": 1765,
"s": 1288,
"text": "Figure 1 shows a visual representation of such a network. The initial input is x, which is then passed to the first layer of neurons (the h bubbles in Figure 1), where three functions consider the input that they receive, and generate an output. That output is then passed to the second layer (the g bubbles in Figure 1). There further output is calculated, based on the output from the first layer. That secondary output is then combined to yield a final output of the model."
},
{
"code": null,
"e": 1822,
"s": 1765,
"text": "Figure 1: A Visual Representation of a Simple Neural Net"
},
{
"code": null,
"e": 1852,
"s": 1822,
"text": "How Do Neural Networks Learn?"
},
{
"code": null,
"e": 2217,
"s": 1852,
"text": "An alternative way of thinking about a neural net is to think of it as one massive function which takes inputs and arrives at a final output. The intermediary functions, which are done by the neurons in their many layers, are usually unobserved, and thankfully automated. The mathematics behind them is as interesting as it is complex, and deserves a further look."
},
{
"code": null,
"e": 2794,
"s": 2217,
"text": "As previously mentioned, the neurons within the network interact with the neurons in the next layer, with every output acting as an input for a future function. Every function, including the initial neuron receives a numeric input, and produces a numeric output, based on a internalized function, which includes the addition of a bias term, which is unique for every neuron. That output is then converted to the numeric input for the function in the next layer, by being multiplied with an appropriate weight. This continues until one final output for the network is produced."
},
{
"code": null,
"e": 3440,
"s": 2794,
"text": "The difficulty lies in determining the optimal value for each bias term, as well as finding the best weighted value for each pass in the neural network. To accomplish this, one must choose a cost function. A cost function is a way of calculating how far a particular solution is from the best possible solution. There are many different possible cost functions, each with advantages and drawbacks, each best suited under certain conditions. Thus, the cost function should be tailored and selected based on individual research needs. Once a cost function has been determined, the neural net can be altered in a way to minimize that cost function."
},
{
"code": null,
"e": 4021,
"s": 3440,
"text": "A simple way of optimizing the weights and bias, is therefore to simply run the network multiple times. On the first try, the predictions will by necessity be random. After each iteration, the cost function will be analyzed, to determine how the model performed, and how it can be improved. The information gotten from the cost function is then passed onto the optimizing function, which calculates new weight values, as well as new bias values. With those new values integrated into the model, the model is rerun. This is continued until no alteration improves the cost function."
},
{
"code": null,
"e": 4832,
"s": 4021,
"text": "There are three methods of learning: supervised, unsupervised, and reinforcement learning. The simplest of these learning paradigms is supervised learning, where the neural net is given labelled inputs. The labelled examples, are then used to infer generalizable rules which can be applied to unlabeled cases. It is the simplest learning method, since it can be thought of operating with a ‘teacher’, in the form of a function that allows the net to compare its predictions to the true, and desired results. Unsupervised methods do not require labelled initial inputs, but rather infers the rules and functions, based not only on the given data, but also on the output of the net. This hampers the type of predictions which can be made. Instead of being able to classify, such a model is limited to clustering."
},
{
"code": null,
"e": 4870,
"s": 4832,
"text": "What are Convolution Neural Networks?"
},
{
"code": null,
"e": 5885,
"s": 4870,
"text": "A variation of the vanilla neural network is the convolution neural network. ConvNets, as they are sometimes known offer some significant advantages over normal neural nets, especially when it comes to image classification. In such a case, the initial inputs would be images, made up of pixels. The traditional issue with image classification is that with big images, with many color channels, is that it quickly becomes computationally infeasible to train some models. What CNN tries to do is transform the images into a form which is easier to process, while still retaining the most important features. This is done by passing a filter over the initial image, which conducts matrix multiplication over a subsection of the pixels in the initial image, it iterates through subsets until it has considered all subsets. The filter aims at capturing the most crucial features, while allowing the redundant features to be eliminated. This passing of a filter over the initial pixels is known as the Convolution Layer."
},
{
"code": null,
"e": 6637,
"s": 5885,
"text": "After the convolution layer comes the pooling layer, where the spatial size of the convoluted features will be attempted to be reduced. The reduction in complexity, sometimes known as dimensionality reduction will decrease the computational cost of performing analysis on the data set, allowing the method to be more robust. In this layer, a kernel once again passes over all subsets of pixels of the image. There are two types of pooling kernels which are commonly used. The first one is Max Pooling, which retains the maximum value of the subset. The alternative kernel is average pooling, which does exactly what you’d expect: it retains the average value of all the pixels in the subset. Figure 2 visually shows the processes of the pooling phase."
},
{
"code": null,
"e": 6696,
"s": 6637,
"text": "Figure 2: The Pooling Phase of Convolution Neural Networks"
},
{
"code": null,
"e": 7060,
"s": 6696,
"text": "After the pooling phase, the information will hopefully be compressed enough to be used in a regular neural network model. The last remaining thing to do is to flatten the final output of the pooling phase and feed it into the model. The flattening is done by changing the matrix of pixels into a vector of pixels, which can then be used for the neural net model."
},
{
"code": null,
"e": 7459,
"s": 7060,
"text": "From there, the convolution neural network acts just like a regular neural network, in that the information will be passed to a set of neurons, which will pass on values to other layers until a final output is reached. Convolution neural networks thus allow neural networks to be feasible for large data sets, or for complex images, since it reduces the computational power needed for the analysis."
},
{
"code": null,
"e": 7506,
"s": 7459,
"text": "What are Some Applications of Neural Networks?"
},
{
"code": null,
"e": 7856,
"s": 7506,
"text": "There are many applications for machine learning methods such as neural nets. Most of these applications focus on classification of images. Those images could be of anything, from whether or not something is a hot dog, to identifying handwriting. The practical possibilities of such a model are broad, and lucrative. Let’s have a look at an example."
},
{
"code": null,
"e": 8292,
"s": 7856,
"text": "Many companies would love to be able to automate a model which would classify articles of clothing. Doing so would allow them to draw insight into fashion trends, buying habits, and differences between cultural, and socio-economic groups. To that end we will use a neural network, to see if an adequate classification model can be constructed, when given a set of 60,000 images, with labels identifying what type of clothing they were."
},
{
"code": null,
"e": 8489,
"s": 8292,
"text": "All of those pictures are made up of pixels, which since we will be doing a simple neural network, and not a convolution neural net, will be passed directly into the network as a vector of pixels."
},
{
"code": null,
"e": 9234,
"s": 8489,
"text": "In order to create a neural network, one must specify the number of layers within the model. For the sake of simplicity, I shall limit the model to two layers. One must also select the type of activation for each layer. Again, to keep it simple, I will select a sigmoid activation for the first layers, with the final layer having 10 nodes, and set to return 10 probability scores, indicating the probability whether the image belongs to one of the ten possible articles of clothing. To compile the model, a loss function must be defined, which will be how the model evaluates its own performance. An optimizer must also be determined, which is how the information from the cost function is used to change the weights and the bias of each node."
},
{
"code": null,
"e": 9557,
"s": 9234,
"text": "model = keras.Sequential([keras.layers.Flatten(input_shape (28,28)), keras.layers.Dense(128,activation = tf.nn.sigmoid), keras.layers.Dense(10,activation = tf.nn.softmax)])model.compile(optimizer = 'adam',loss='sparse_categorical_crossentropy',metrics =['accuracy'])"
},
{
"code": null,
"e": 10103,
"s": 9557,
"text": "With those parameters input, a model can be trained. Once the model has been trained, it must be evaluated based on the testing data. To accomplish that, one must denote the number of epochs which the model will consider. Epochs determine how many iterations through the data shall be done. More epochs will be more computationally expensive, but should allow for a better fit. I shall consider 5 epochs. One can see how the accuracy of the model on the training data improves after each iteration, as the optimizing function alters the weights."
},
{
"code": null,
"e": 10142,
"s": 10103,
"text": "model.fit(x_train, y_train,epochs = 5)"
},
{
"code": null,
"e": 10329,
"s": 10142,
"text": "The real fit of how a model performs is by running the model on a testing set, which was not used to construct the model. In this case, the neural net had an accuracy of 0.7203: Not Bad!"
},
{
"code": null,
"e": 10337,
"s": 10329,
"text": "Summary"
},
{
"code": null,
"e": 11146,
"s": 10337,
"text": "Neural networks are complex models, which try to mimic the way the human brain develops classification rules. A neural net consists of many different layers of neurons, with each layer receiving inputs from previous layers, and passing outputs to further layers. The way each layer output becomes the input for the next layer depends on the weight given to that specific link, which depends on the cost function, and the optimizer. The neural net iterates for a predetermined number of iterations, called epochs. After each epoch, the cost function is analyzed to see where the model could be improved. The optimizing function then alters the internal mechanics of the network, such as the weights, and the biases, based on the information provided by the cost function, until the cost function is minimized."
},
{
"code": null,
"e": 11468,
"s": 11146,
"text": "A convolution neural network is a twist of a normal neural network, which attempts to deal with the issue of high dimensionality by reducing the number of pixels in image classification through two separate phases: the convolution phase, and the pooling phase. After that it performs much like an ordinary neural network."
},
{
"code": null,
"e": 11477,
"s": 11468,
"text": "Key Word"
},
{
"code": null,
"e": 11493,
"s": 11477,
"text": "Neural Networks"
}
] |
Get all occurrences of the string between any two specific characters in SAP ABAP
|
I usually use REGEX in all such cases as it is faster and easily readable and would recommend the same to you.
You can use something similar as the snippet to get your job done.
DATA: lv_para TYPE string.
lv_para = ' You &are like& kite &flying& in a &hurricane&'.
REPLACE ALL OCCURRENCES OF REGEX '&[^&]+&' IN lv_para WITH ''.
WRITE lv_para.
Let me explain the regex for you. It should match the first ‘&’, then you can have any combination with multiple occurrences of ‘&’ and the last occurrence of ‘&’ must be matched.
|
[
{
"code": null,
"e": 1173,
"s": 1062,
"text": "I usually use REGEX in all such cases as it is faster and easily readable and would recommend the same to you."
},
{
"code": null,
"e": 1240,
"s": 1173,
"text": "You can use something similar as the snippet to get your job done."
},
{
"code": null,
"e": 1405,
"s": 1240,
"text": "DATA: lv_para TYPE string.\nlv_para = ' You &are like& kite &flying& in a &hurricane&'.\nREPLACE ALL OCCURRENCES OF REGEX '&[^&]+&' IN lv_para WITH ''.\nWRITE lv_para."
},
{
"code": null,
"e": 1585,
"s": 1405,
"text": "Let me explain the regex for you. It should match the first ‘&’, then you can have any combination with multiple occurrences of ‘&’ and the last occurrence of ‘&’ must be matched."
}
] |
How to get the build/version number of an iOS App?
|
In this post we will learn how to fetch and show the iOS build and version number
Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “ShowBuildAndVersion”
Step 2 − Open Main.storyboard and add two labels as shown below.
Step 3 − Attach @IBOutLets for the two labels
@IBOutlet weak var buildLabel: UILabel!
@IBOutlet weak var versionLabel: UILabel!
Step 4 − Change the build and version from project settings.
Step 5 − In viewDidLoad of ViewController get the build and version number for infoDictionary of main bundle. Show it on the corresponding labels.
override func viewDidLoad() {
super.viewDidLoad()
if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
versionLabel.text = "Version: \(version)"
}
if let build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String {
buildLabel.text = "Build: \(build)"
}
}
The infoDictionary in main bundle contains these values, with ‘CFBundleShortVersionString’ and ‘CFBundleVersion’ keys.
We can refer these keys to get the version and build number respectively
Step 6 − Run the project, you should see the build and version number.
|
[
{
"code": null,
"e": 1144,
"s": 1062,
"text": "In this post we will learn how to fetch and show the iOS build and version number"
},
{
"code": null,
"e": 1242,
"s": 1144,
"text": "Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “ShowBuildAndVersion”"
},
{
"code": null,
"e": 1307,
"s": 1242,
"text": "Step 2 − Open Main.storyboard and add two labels as shown below."
},
{
"code": null,
"e": 1353,
"s": 1307,
"text": "Step 3 − Attach @IBOutLets for the two labels"
},
{
"code": null,
"e": 1435,
"s": 1353,
"text": "@IBOutlet weak var buildLabel: UILabel!\n@IBOutlet weak var versionLabel: UILabel!"
},
{
"code": null,
"e": 1496,
"s": 1435,
"text": "Step 4 − Change the build and version from project settings."
},
{
"code": null,
"e": 1643,
"s": 1496,
"text": "Step 5 − In viewDidLoad of ViewController get the build and version number for infoDictionary of main bundle. Show it on the corresponding labels."
},
{
"code": null,
"e": 1967,
"s": 1643,
"text": "override func viewDidLoad() {\n super.viewDidLoad()\n if let version = Bundle.main.infoDictionary?[\"CFBundleShortVersionString\"] as? String {\n versionLabel.text = \"Version: \\(version)\"\n }\n if let build = Bundle.main.infoDictionary?[\"CFBundleVersion\"] as? String {\n buildLabel.text = \"Build: \\(build)\"\n }\n}"
},
{
"code": null,
"e": 2086,
"s": 1967,
"text": "The infoDictionary in main bundle contains these values, with ‘CFBundleShortVersionString’ and ‘CFBundleVersion’ keys."
},
{
"code": null,
"e": 2159,
"s": 2086,
"text": "We can refer these keys to get the version and build number respectively"
},
{
"code": null,
"e": 2230,
"s": 2159,
"text": "Step 6 − Run the project, you should see the build and version number."
}
] |
Importance of Thread.onSpinWait() method in Java 9?
|
Thread.onSpinWait() method has been introduced in Java 9. It is a static method of Thread class and can be optionally called in busy-waiting loops. It allows the JVM to issue processor instructions on some system architectures to improve reaction time in such spin-wait loops, and also reduce the power consumed by the core thread. It can benefit the overall power consumption of a java program and allows other core threads to execute at faster speeds within the same power consumption envelope.
public static void onSpinWait()
public class ThreadOnSpinWaitTest {
public static void main(final String args[]) throws InterruptedException {
final NormalTask task1 = new NormalTask();
final SpinWaitTask task2 = new SpinWaitTask();
final Thread thread1 = new Thread(task1);
thread1.start();
final Thread thread2 = new Thread(task2);
thread2.start();
new Thread(() -> {
try {
Thread.sleep(1000);
} catch(final InterruptedException e) {
e.printStackTrace();
} finally {
task1.start();
task2.sta*rt();
}
}).start();
thread1.join();
thread2.join();
}
private abstract static class Task implements Runnable {
volatile boolean canStart;
void start() {
this.canStart = true;
}
}
private static class NormalTask extends Task {
@Override
public void run() {
while(!this.canStart) {
}
System.out.println("Done!");
}
}
private static class SpinWaitTask extends Task {
@Override
public void run() {
while(!this.canStart) {
Thread.onSpinWait();
}
System.out.println("Done!");
}
}
}
Done!
Done!
|
[
{
"code": null,
"e": 1559,
"s": 1062,
"text": "Thread.onSpinWait() method has been introduced in Java 9. It is a static method of Thread class and can be optionally called in busy-waiting loops. It allows the JVM to issue processor instructions on some system architectures to improve reaction time in such spin-wait loops, and also reduce the power consumed by the core thread. It can benefit the overall power consumption of a java program and allows other core threads to execute at faster speeds within the same power consumption envelope."
},
{
"code": null,
"e": 1591,
"s": 1559,
"text": "public static void onSpinWait()"
},
{
"code": null,
"e": 2826,
"s": 1591,
"text": "public class ThreadOnSpinWaitTest {\n public static void main(final String args[]) throws InterruptedException {\n final NormalTask task1 = new NormalTask();\n final SpinWaitTask task2 = new SpinWaitTask();\n final Thread thread1 = new Thread(task1);\n thread1.start();\n final Thread thread2 = new Thread(task2);\n thread2.start();\n new Thread(() -> {\n try {\n Thread.sleep(1000);\n } catch(final InterruptedException e) {\n e.printStackTrace();\n } finally {\n task1.start();\n task2.sta*rt();\n }\n }).start();\n thread1.join();\n thread2.join();\n }\n private abstract static class Task implements Runnable {\n volatile boolean canStart;\n void start() {\n this.canStart = true;\n }\n }\n private static class NormalTask extends Task {\n @Override\n public void run() {\n while(!this.canStart) {\n }\n System.out.println(\"Done!\");\n }\n }\n private static class SpinWaitTask extends Task {\n @Override\n public void run() {\n while(!this.canStart) {\n Thread.onSpinWait();\n }\n System.out.println(\"Done!\");\n }\n }\n}"
},
{
"code": null,
"e": 2838,
"s": 2826,
"text": "Done!\nDone!"
}
] |
Creating an Animated Bar Chart Race with Tableau | by Ewe Zi Yi | Towards Data Science
|
A while ago I posted an animated bar chart on /r/dataisbeautiful on Reddit showing the changes in the number of international students by their country of origin in Australia. Such animated bar charts are perfect for showing the evolution of numerical data corresponding to different categories over a period of time in a very eye-catching (or sometimes annoying) way.
I didn’t quite get around to documenting how it was done half a month ago but I recently decided that it was probably best to document the steps that I had followed and my thought processes somewhere before forgetting them so here’s an article detailing the stuff that went through my head then:
Before I go on, I’d just like to say this article is heavily inspired by a tutorial that I read from Ludovic Tavernier on his blog greatified. I have the utmost respect and admiration for his discovery of this method to simulate animation frames for bar charts with Tableau so kudos to him for all that work!
In fact, I followed his steps closely to create the bar chart that I posted but after going through the tutorial, I thought that it’d probably be useful to refine and elaborate certain parts to make the tutorial more comprehensive and easily-understandable for beginners to Tableau, and to outline the motivation and logic behind the steps in the method involved. All the code in this article (except for some tweaks) were taken from Ludovic’s so once again, thanks a lot to him!
In the step-by-step guide I’ll be showing you how to create your own animated bar chart with Tableau, with my dataset on student numbers as an example. Hopefully, you get to see something moving by the end of the tutorial!
Tableau does not automatically create animated bar charts from a dataset. A quick workaround to this is to make Tableau create individual frames that simulate an animation when you string them together. This works the same way how cartoons are made.
Now to do this you would ideally want to get Tableau to create these frames automatically, which in turn are created from data you provide to Tableau. But unless you really like manually creating datasets, how do you actually create these “pseudo-data” automatically?
This method revolves around doing just that.
You’ll need to create 3 sheets of data (preferably all on the same Excel file) in this step. The goal is to create an even larger dataset containing additional rows such that each additional row represents 1) each animation frame and for 2) each point of the animation bar (more on this below).
Don’t get it? Here’s a simple example: you start off with a table containing 20 entries in the ‘year’ column, numbering from 2001 to 2020. Right now you’d like to keep more information about each month of each year so you create an additional column for ‘month’. And with each year containing 12 months, you need to ensure that each year, say 2001, gets repeated 12 times for each month. As a result, you get 20 x 12 entries. This is what we call a cartesian product.
Going back to what we are supposed to do, we’d like to duplicate entries in our dataset but we would want to do it in a more elegant manner than just creating rows for each entry manually. So we’ll do this by creating new generic entries (or in the case of the previous analogy, for each individual month) for each new column we’d like to introduce, in separate sheets. We then get Tableau to carry out a cartesian join on these sheets automatically.
Your first sheet will contain your original data, whereas the two other sheets will contain the new generic entries.
The first sheet is essentially the main dataset that you’d like to animate. It should contain basic information like year, category, and value. Besides that, you need to create an additional column link, which will be used later to to join data on the other data sheets.
year: a numerical value for the unit of time you’re observing
category: a name for whatever you’ll like to observe like country name
value: a numerical value for the value you are interested in like count
link: an identifier that acts as an anchor to join the various data sheets (use same value throughout all sheets; 1 in this case for simplicity)
This sheet essentially creates the 4 corners of a bar (that’ll appear in the chart) for each category in your dataset. Point 1 represents the point at the top left of a rectangle, with each subsequent point going clockwise and ending with point 4 representing the bottom left.
link: an identifier that acts as an anchor to join the various data sheets (use the same value throughout the entire dataset; 1 in this case for simplicity)
point: a point representing a certain corner of a bar(number them 1–4)
Your second sheet should look exactly like this:
This sheet creates animation frames to animate the time interval between the fixed intervals specified in your dataset. For example, if the smallest time interval in your data set is 1 year, this sheet will create k number of frames to animate the gap between how the bar chart looks like in year n to year n+1.
link: an identifier that acts as an anchor to join the various data sheets (use the same value throughout the entire dataset; 1 in this case for simplicity)
anim: an identifier for each frame created (number them 1 to k, the number of frames you’d like to create for each interval)
Your third sheet should look exactly like this:
Once you have the three sheets, open a new Tableau workbook and select the Excel file that you have created in the previous step. Perform a cartesian join on all the sheets on the link column.
Look back at the new data entries Tableau has created and you should see that each data entry in your original dataset should have been replicated with entries for each point of the bar, and for each animation frame:
Now with out dataset expanded greatly to accommodate more data entries for each animation frame and each animation bar, our goal now is to compute some values for these entries, which will define the sizes and positions of the bars at each particular frame.
Switching over to an empty Tableau sheet, we then proceed to create several calculated fields using the data contained in the columns of our dataset:
anim_inter: a number that contains the ratio current frame/total frame number per interval (eg. 2/10 = 0.2)
[Anim]/{MAX([Anim])}
frame: a number indicating the exact animation frame within a certain interval (eg. year 2001.2)
[Year]+[anim_inter]
value_current: a number indicating the actual value of the bar at the beginning of the interval (eg. 190 at the beginning of the interval between 2001 and 2002)
{FIXED [Year],[Category]:MIN([Value])}
value_next: a number indicating the actual value of the bar the end of the interval (eg. 195 at the end of the interval between 2001 and 2002)
LOOKUP(ATTR([value_current]),1)
value_inter: a number indicating the interpolated value of the bar at an exact animation frame within the interval (eg. 193.2 at the interval 2001.3)
ATTR([value_current])+([value_next]-ATTR([value_current]))*ATTR([anim_inter])
rank_current: a number showing the rank of the bar relative to other bars, based on their value_current at the beginning of the interval
RANK_UNIQUE(ATTR([value_current]),”desc”)
rank_next: a number showing the rank of the bar at the end of the interval
LOOKUP([rank_current],1)
rank_inter: a number showing the ‘intermediate’ rank of the bar at an exact animation frame within the interval
[rank_current]+([rank_next]-[rank_current])*ATTR([anim_inter])
@x_inter: a number indicating the x-value of the specified corner of the bar (i.e. the values for points 1 and 4 should always be 0 as the left side the bar doesn’t move; while those for points 2 and 3 should always indicate the current length of the bar)
IF ATTR([Point])=1 THEN 0ELSEIF ATTR([Point])=2 THEN [value_inter]*1.0ELSEIF ATTR([Point])=3 THEN [value_inter]*1.0ELSEIF ATTR([Point])=4 THEN 0END
@y_inter: a number indicating the y-value of the specified corner of the bar (i.e. the values for points 1 and 2 should always be the same and represent the height of the top edge of the bar; while those for 3 and 4 should always be the same and represent the bottom edge of the bar. Any difference between the y-values indicates the height of the bar)
IF ATTR([Point])=1 THEN [rank_inter]*1.0 ELSEIF ATTR([Point])=2 THEN [rank_inter]*1.0ELSEIF ATTR([Point])=3 THEN [rank_inter]+0.5ELSEIF ATTR([Point])=4 THEN [rank_inter]+0.5END
filter: a number showing the rank of the value_inter of the bar; we’ll use this to filter out all the other bars that are not within the top x number of bars
RANK_UNIQUE([value_inter],”desc”)
label: a string to indicate the category and value_inter of the bar; category gets shown above the point 1 of the bar, while value_inter gets shown above point 3
IF ATTR([Point])=1 THEN ATTR([Category])ELSEIF ATTR([Point])=3 THEN STR(INT([value_inter]/1000))+”K”END
With the nitty-gritty details all worked out, we can now finally focus on the exciting part of this process: visualisation!
Let’s begin by setting up all the shelves and cards on the Tableau worksheet:
Drag @x_inter to the Columns shelf. Modify the table calculationsDrag @y_inter to the Rows shelf, and then repeat the exact same step once again. Set the second @y_inter as a Dual Axis.Right-click on any of the two y-axes on the view pane and select Synchronize Axis. Set the range of the axis to be fixed from 0 to 11, and reverse its scale.Drag frame to the Pages shelf and ensure that it is a discrete dimension.Drag filter to the Filters shelf.Select the Polygon mark under the @y_inter Marks card and add Year, Category, and anim_inter as Details, and lastly Point as a Path. Ensure that these are all added as dimensions.Select the Circle mark under the @y_inter(2) Marks card and add Category and label as Labels, as well as Year, anim_inter and Point as Details. Ensure that these are all added as dimensions.
Drag @x_inter to the Columns shelf. Modify the table calculations
Drag @y_inter to the Rows shelf, and then repeat the exact same step once again. Set the second @y_inter as a Dual Axis.
Right-click on any of the two y-axes on the view pane and select Synchronize Axis. Set the range of the axis to be fixed from 0 to 11, and reverse its scale.
Drag frame to the Pages shelf and ensure that it is a discrete dimension.
Drag filter to the Filters shelf.
Select the Polygon mark under the @y_inter Marks card and add Year, Category, and anim_inter as Details, and lastly Point as a Path. Ensure that these are all added as dimensions.
Select the Circle mark under the @y_inter(2) Marks card and add Category and label as Labels, as well as Year, anim_inter and Point as Details. Ensure that these are all added as dimensions.
At the end of this series of steps, your Tableau worksheet should look something like this:
With all the fields set up, it’s time to configure some table calculations to ensure that the calculated fields we have created earlier function well in the view pane:
Right-click on @x_inter on the Columns shelf to configure table calculations. Compute @x_inter using Year and frame. This makes Tableau calculate @x_inter by Year and frame for every anim_inter, Category and Point*.Right-click on the @y_inter on the Rows shelf to configure table calculations. Set it to compute rank_current using Category, and to compute rank_next using Category, Year and frame, with Restarting every Category selected. Repeat this for both @y_inter axes.Right-click on filter under the Filters card to set table calculations. Compute filter using Category and compute value_next using Year and frame. Specify 0–10 as the range of values.
Right-click on @x_inter on the Columns shelf to configure table calculations. Compute @x_inter using Year and frame. This makes Tableau calculate @x_inter by Year and frame for every anim_inter, Category and Point*.
Right-click on the @y_inter on the Rows shelf to configure table calculations. Set it to compute rank_current using Category, and to compute rank_next using Category, Year and frame, with Restarting every Category selected. Repeat this for both @y_inter axes.
Right-click on filter under the Filters card to set table calculations. Compute filter using Category and compute value_next using Year and frame. Specify 0–10 as the range of values.
*For those of you who don’t really understand what’s going on with table calculations, check out this awesome explanation by Andy Kriebel here.
Voilà! You finally have some semblance of a bar chart after working through so many steps! Click on play (top right of the interface) to see your bar chart move!
However as you can certainly notice, you chart is probably still on the ugly side and there’re still things to do to touch up a little on some aesthetics:
Under the @y_inter(2) Marks card, select Label. Edit the text by clicking on ‘...’. Delete <Category> from the field, and justify <AGG(label)> to the right. Next, change the Alignment of the Label from Automatic to Top Right. Lastly select the checkbox Allow labels to overlap other marks.Click on Size and select the smallest size on the slider. Now you no longer have goofy-looking rectangles!To add some cool colour gradients to your bars, add value_inter to the @y_inter Marks card as Color. Compute value_inter (just as in the previous series of steps) using Year and frame, and lastly select your desired colour gradient.
Under the @y_inter(2) Marks card, select Label. Edit the text by clicking on ‘...’. Delete <Category> from the field, and justify <AGG(label)> to the right. Next, change the Alignment of the Label from Automatic to Top Right. Lastly select the checkbox Allow labels to overlap other marks.
Click on Size and select the smallest size on the slider. Now you no longer have goofy-looking rectangles!
To add some cool colour gradients to your bars, add value_inter to the @y_inter Marks card as Color. Compute value_inter (just as in the previous series of steps) using Year and frame, and lastly select your desired colour gradient.
Those are some steps I believe are necessary to make your chart look presentable at the very least though there are other things you should also try out yourself to make your chart look better — try renaming/hiding your axes, axis titles, and chart titles!
You can also create a Tableau dashboard to feature multiple view panes in addition to the one with the bar chart. One such view pane can feature the year of the animation ticking away as your graph moves.
Let me know if you discover interesting ways to personalise your bar chart!
Last but not least, it’s currently not possible to export your simulated animated bar chart as an image or video directly using Tableau. For those of you who’d like to save your animated chart in another format, consider using the screen recording function on your computer (or on a 3rd party application) to record the animated frames on Tableau. You can then use a free tool on the internet to convert your video file to a .gif like I did if you’d like one. And there you go, a smart looking animated chart!
So that should be it for this tutorial! I think I’ve probably noted down most of my thoughts and the steps I followed to get to a pleasant-looking animated bar chart race, so it’ll probably be easy for me to get back and recreate one in the future should I not touch Tableau again for some time.
Let me know if you have any questions or issues following the tutorial and thanks for reading! Hope you have fun creating your charts!
For those of you who’d like to read a short reflection on the animated bar chart race that I created (the one on Australia right on top) and the huge discussion it generated on the Reddit, check out my other article!
|
[
{
"code": null,
"e": 541,
"s": 172,
"text": "A while ago I posted an animated bar chart on /r/dataisbeautiful on Reddit showing the changes in the number of international students by their country of origin in Australia. Such animated bar charts are perfect for showing the evolution of numerical data corresponding to different categories over a period of time in a very eye-catching (or sometimes annoying) way."
},
{
"code": null,
"e": 837,
"s": 541,
"text": "I didn’t quite get around to documenting how it was done half a month ago but I recently decided that it was probably best to document the steps that I had followed and my thought processes somewhere before forgetting them so here’s an article detailing the stuff that went through my head then:"
},
{
"code": null,
"e": 1146,
"s": 837,
"text": "Before I go on, I’d just like to say this article is heavily inspired by a tutorial that I read from Ludovic Tavernier on his blog greatified. I have the utmost respect and admiration for his discovery of this method to simulate animation frames for bar charts with Tableau so kudos to him for all that work!"
},
{
"code": null,
"e": 1626,
"s": 1146,
"text": "In fact, I followed his steps closely to create the bar chart that I posted but after going through the tutorial, I thought that it’d probably be useful to refine and elaborate certain parts to make the tutorial more comprehensive and easily-understandable for beginners to Tableau, and to outline the motivation and logic behind the steps in the method involved. All the code in this article (except for some tweaks) were taken from Ludovic’s so once again, thanks a lot to him!"
},
{
"code": null,
"e": 1849,
"s": 1626,
"text": "In the step-by-step guide I’ll be showing you how to create your own animated bar chart with Tableau, with my dataset on student numbers as an example. Hopefully, you get to see something moving by the end of the tutorial!"
},
{
"code": null,
"e": 2099,
"s": 1849,
"text": "Tableau does not automatically create animated bar charts from a dataset. A quick workaround to this is to make Tableau create individual frames that simulate an animation when you string them together. This works the same way how cartoons are made."
},
{
"code": null,
"e": 2367,
"s": 2099,
"text": "Now to do this you would ideally want to get Tableau to create these frames automatically, which in turn are created from data you provide to Tableau. But unless you really like manually creating datasets, how do you actually create these “pseudo-data” automatically?"
},
{
"code": null,
"e": 2412,
"s": 2367,
"text": "This method revolves around doing just that."
},
{
"code": null,
"e": 2707,
"s": 2412,
"text": "You’ll need to create 3 sheets of data (preferably all on the same Excel file) in this step. The goal is to create an even larger dataset containing additional rows such that each additional row represents 1) each animation frame and for 2) each point of the animation bar (more on this below)."
},
{
"code": null,
"e": 3175,
"s": 2707,
"text": "Don’t get it? Here’s a simple example: you start off with a table containing 20 entries in the ‘year’ column, numbering from 2001 to 2020. Right now you’d like to keep more information about each month of each year so you create an additional column for ‘month’. And with each year containing 12 months, you need to ensure that each year, say 2001, gets repeated 12 times for each month. As a result, you get 20 x 12 entries. This is what we call a cartesian product."
},
{
"code": null,
"e": 3626,
"s": 3175,
"text": "Going back to what we are supposed to do, we’d like to duplicate entries in our dataset but we would want to do it in a more elegant manner than just creating rows for each entry manually. So we’ll do this by creating new generic entries (or in the case of the previous analogy, for each individual month) for each new column we’d like to introduce, in separate sheets. We then get Tableau to carry out a cartesian join on these sheets automatically."
},
{
"code": null,
"e": 3743,
"s": 3626,
"text": "Your first sheet will contain your original data, whereas the two other sheets will contain the new generic entries."
},
{
"code": null,
"e": 4014,
"s": 3743,
"text": "The first sheet is essentially the main dataset that you’d like to animate. It should contain basic information like year, category, and value. Besides that, you need to create an additional column link, which will be used later to to join data on the other data sheets."
},
{
"code": null,
"e": 4076,
"s": 4014,
"text": "year: a numerical value for the unit of time you’re observing"
},
{
"code": null,
"e": 4147,
"s": 4076,
"text": "category: a name for whatever you’ll like to observe like country name"
},
{
"code": null,
"e": 4219,
"s": 4147,
"text": "value: a numerical value for the value you are interested in like count"
},
{
"code": null,
"e": 4364,
"s": 4219,
"text": "link: an identifier that acts as an anchor to join the various data sheets (use same value throughout all sheets; 1 in this case for simplicity)"
},
{
"code": null,
"e": 4641,
"s": 4364,
"text": "This sheet essentially creates the 4 corners of a bar (that’ll appear in the chart) for each category in your dataset. Point 1 represents the point at the top left of a rectangle, with each subsequent point going clockwise and ending with point 4 representing the bottom left."
},
{
"code": null,
"e": 4798,
"s": 4641,
"text": "link: an identifier that acts as an anchor to join the various data sheets (use the same value throughout the entire dataset; 1 in this case for simplicity)"
},
{
"code": null,
"e": 4869,
"s": 4798,
"text": "point: a point representing a certain corner of a bar(number them 1–4)"
},
{
"code": null,
"e": 4918,
"s": 4869,
"text": "Your second sheet should look exactly like this:"
},
{
"code": null,
"e": 5230,
"s": 4918,
"text": "This sheet creates animation frames to animate the time interval between the fixed intervals specified in your dataset. For example, if the smallest time interval in your data set is 1 year, this sheet will create k number of frames to animate the gap between how the bar chart looks like in year n to year n+1."
},
{
"code": null,
"e": 5387,
"s": 5230,
"text": "link: an identifier that acts as an anchor to join the various data sheets (use the same value throughout the entire dataset; 1 in this case for simplicity)"
},
{
"code": null,
"e": 5512,
"s": 5387,
"text": "anim: an identifier for each frame created (number them 1 to k, the number of frames you’d like to create for each interval)"
},
{
"code": null,
"e": 5560,
"s": 5512,
"text": "Your third sheet should look exactly like this:"
},
{
"code": null,
"e": 5753,
"s": 5560,
"text": "Once you have the three sheets, open a new Tableau workbook and select the Excel file that you have created in the previous step. Perform a cartesian join on all the sheets on the link column."
},
{
"code": null,
"e": 5970,
"s": 5753,
"text": "Look back at the new data entries Tableau has created and you should see that each data entry in your original dataset should have been replicated with entries for each point of the bar, and for each animation frame:"
},
{
"code": null,
"e": 6228,
"s": 5970,
"text": "Now with out dataset expanded greatly to accommodate more data entries for each animation frame and each animation bar, our goal now is to compute some values for these entries, which will define the sizes and positions of the bars at each particular frame."
},
{
"code": null,
"e": 6378,
"s": 6228,
"text": "Switching over to an empty Tableau sheet, we then proceed to create several calculated fields using the data contained in the columns of our dataset:"
},
{
"code": null,
"e": 6486,
"s": 6378,
"text": "anim_inter: a number that contains the ratio current frame/total frame number per interval (eg. 2/10 = 0.2)"
},
{
"code": null,
"e": 6507,
"s": 6486,
"text": "[Anim]/{MAX([Anim])}"
},
{
"code": null,
"e": 6604,
"s": 6507,
"text": "frame: a number indicating the exact animation frame within a certain interval (eg. year 2001.2)"
},
{
"code": null,
"e": 6624,
"s": 6604,
"text": "[Year]+[anim_inter]"
},
{
"code": null,
"e": 6785,
"s": 6624,
"text": "value_current: a number indicating the actual value of the bar at the beginning of the interval (eg. 190 at the beginning of the interval between 2001 and 2002)"
},
{
"code": null,
"e": 6824,
"s": 6785,
"text": "{FIXED [Year],[Category]:MIN([Value])}"
},
{
"code": null,
"e": 6967,
"s": 6824,
"text": "value_next: a number indicating the actual value of the bar the end of the interval (eg. 195 at the end of the interval between 2001 and 2002)"
},
{
"code": null,
"e": 6999,
"s": 6967,
"text": "LOOKUP(ATTR([value_current]),1)"
},
{
"code": null,
"e": 7149,
"s": 6999,
"text": "value_inter: a number indicating the interpolated value of the bar at an exact animation frame within the interval (eg. 193.2 at the interval 2001.3)"
},
{
"code": null,
"e": 7227,
"s": 7149,
"text": "ATTR([value_current])+([value_next]-ATTR([value_current]))*ATTR([anim_inter])"
},
{
"code": null,
"e": 7364,
"s": 7227,
"text": "rank_current: a number showing the rank of the bar relative to other bars, based on their value_current at the beginning of the interval"
},
{
"code": null,
"e": 7406,
"s": 7364,
"text": "RANK_UNIQUE(ATTR([value_current]),”desc”)"
},
{
"code": null,
"e": 7481,
"s": 7406,
"text": "rank_next: a number showing the rank of the bar at the end of the interval"
},
{
"code": null,
"e": 7506,
"s": 7481,
"text": "LOOKUP([rank_current],1)"
},
{
"code": null,
"e": 7618,
"s": 7506,
"text": "rank_inter: a number showing the ‘intermediate’ rank of the bar at an exact animation frame within the interval"
},
{
"code": null,
"e": 7681,
"s": 7618,
"text": "[rank_current]+([rank_next]-[rank_current])*ATTR([anim_inter])"
},
{
"code": null,
"e": 7937,
"s": 7681,
"text": "@x_inter: a number indicating the x-value of the specified corner of the bar (i.e. the values for points 1 and 4 should always be 0 as the left side the bar doesn’t move; while those for points 2 and 3 should always indicate the current length of the bar)"
},
{
"code": null,
"e": 8085,
"s": 7937,
"text": "IF ATTR([Point])=1 THEN 0ELSEIF ATTR([Point])=2 THEN [value_inter]*1.0ELSEIF ATTR([Point])=3 THEN [value_inter]*1.0ELSEIF ATTR([Point])=4 THEN 0END"
},
{
"code": null,
"e": 8438,
"s": 8085,
"text": "@y_inter: a number indicating the y-value of the specified corner of the bar (i.e. the values for points 1 and 2 should always be the same and represent the height of the top edge of the bar; while those for 3 and 4 should always be the same and represent the bottom edge of the bar. Any difference between the y-values indicates the height of the bar)"
},
{
"code": null,
"e": 8615,
"s": 8438,
"text": "IF ATTR([Point])=1 THEN [rank_inter]*1.0 ELSEIF ATTR([Point])=2 THEN [rank_inter]*1.0ELSEIF ATTR([Point])=3 THEN [rank_inter]+0.5ELSEIF ATTR([Point])=4 THEN [rank_inter]+0.5END"
},
{
"code": null,
"e": 8773,
"s": 8615,
"text": "filter: a number showing the rank of the value_inter of the bar; we’ll use this to filter out all the other bars that are not within the top x number of bars"
},
{
"code": null,
"e": 8807,
"s": 8773,
"text": "RANK_UNIQUE([value_inter],”desc”)"
},
{
"code": null,
"e": 8969,
"s": 8807,
"text": "label: a string to indicate the category and value_inter of the bar; category gets shown above the point 1 of the bar, while value_inter gets shown above point 3"
},
{
"code": null,
"e": 9073,
"s": 8969,
"text": "IF ATTR([Point])=1 THEN ATTR([Category])ELSEIF ATTR([Point])=3 THEN STR(INT([value_inter]/1000))+”K”END"
},
{
"code": null,
"e": 9197,
"s": 9073,
"text": "With the nitty-gritty details all worked out, we can now finally focus on the exciting part of this process: visualisation!"
},
{
"code": null,
"e": 9275,
"s": 9197,
"text": "Let’s begin by setting up all the shelves and cards on the Tableau worksheet:"
},
{
"code": null,
"e": 10093,
"s": 9275,
"text": "Drag @x_inter to the Columns shelf. Modify the table calculationsDrag @y_inter to the Rows shelf, and then repeat the exact same step once again. Set the second @y_inter as a Dual Axis.Right-click on any of the two y-axes on the view pane and select Synchronize Axis. Set the range of the axis to be fixed from 0 to 11, and reverse its scale.Drag frame to the Pages shelf and ensure that it is a discrete dimension.Drag filter to the Filters shelf.Select the Polygon mark under the @y_inter Marks card and add Year, Category, and anim_inter as Details, and lastly Point as a Path. Ensure that these are all added as dimensions.Select the Circle mark under the @y_inter(2) Marks card and add Category and label as Labels, as well as Year, anim_inter and Point as Details. Ensure that these are all added as dimensions."
},
{
"code": null,
"e": 10159,
"s": 10093,
"text": "Drag @x_inter to the Columns shelf. Modify the table calculations"
},
{
"code": null,
"e": 10280,
"s": 10159,
"text": "Drag @y_inter to the Rows shelf, and then repeat the exact same step once again. Set the second @y_inter as a Dual Axis."
},
{
"code": null,
"e": 10438,
"s": 10280,
"text": "Right-click on any of the two y-axes on the view pane and select Synchronize Axis. Set the range of the axis to be fixed from 0 to 11, and reverse its scale."
},
{
"code": null,
"e": 10512,
"s": 10438,
"text": "Drag frame to the Pages shelf and ensure that it is a discrete dimension."
},
{
"code": null,
"e": 10546,
"s": 10512,
"text": "Drag filter to the Filters shelf."
},
{
"code": null,
"e": 10726,
"s": 10546,
"text": "Select the Polygon mark under the @y_inter Marks card and add Year, Category, and anim_inter as Details, and lastly Point as a Path. Ensure that these are all added as dimensions."
},
{
"code": null,
"e": 10917,
"s": 10726,
"text": "Select the Circle mark under the @y_inter(2) Marks card and add Category and label as Labels, as well as Year, anim_inter and Point as Details. Ensure that these are all added as dimensions."
},
{
"code": null,
"e": 11009,
"s": 10917,
"text": "At the end of this series of steps, your Tableau worksheet should look something like this:"
},
{
"code": null,
"e": 11177,
"s": 11009,
"text": "With all the fields set up, it’s time to configure some table calculations to ensure that the calculated fields we have created earlier function well in the view pane:"
},
{
"code": null,
"e": 11835,
"s": 11177,
"text": "Right-click on @x_inter on the Columns shelf to configure table calculations. Compute @x_inter using Year and frame. This makes Tableau calculate @x_inter by Year and frame for every anim_inter, Category and Point*.Right-click on the @y_inter on the Rows shelf to configure table calculations. Set it to compute rank_current using Category, and to compute rank_next using Category, Year and frame, with Restarting every Category selected. Repeat this for both @y_inter axes.Right-click on filter under the Filters card to set table calculations. Compute filter using Category and compute value_next using Year and frame. Specify 0–10 as the range of values."
},
{
"code": null,
"e": 12051,
"s": 11835,
"text": "Right-click on @x_inter on the Columns shelf to configure table calculations. Compute @x_inter using Year and frame. This makes Tableau calculate @x_inter by Year and frame for every anim_inter, Category and Point*."
},
{
"code": null,
"e": 12311,
"s": 12051,
"text": "Right-click on the @y_inter on the Rows shelf to configure table calculations. Set it to compute rank_current using Category, and to compute rank_next using Category, Year and frame, with Restarting every Category selected. Repeat this for both @y_inter axes."
},
{
"code": null,
"e": 12495,
"s": 12311,
"text": "Right-click on filter under the Filters card to set table calculations. Compute filter using Category and compute value_next using Year and frame. Specify 0–10 as the range of values."
},
{
"code": null,
"e": 12639,
"s": 12495,
"text": "*For those of you who don’t really understand what’s going on with table calculations, check out this awesome explanation by Andy Kriebel here."
},
{
"code": null,
"e": 12802,
"s": 12639,
"text": "Voilà! You finally have some semblance of a bar chart after working through so many steps! Click on play (top right of the interface) to see your bar chart move!"
},
{
"code": null,
"e": 12957,
"s": 12802,
"text": "However as you can certainly notice, you chart is probably still on the ugly side and there’re still things to do to touch up a little on some aesthetics:"
},
{
"code": null,
"e": 13585,
"s": 12957,
"text": "Under the @y_inter(2) Marks card, select Label. Edit the text by clicking on ‘...’. Delete <Category> from the field, and justify <AGG(label)> to the right. Next, change the Alignment of the Label from Automatic to Top Right. Lastly select the checkbox Allow labels to overlap other marks.Click on Size and select the smallest size on the slider. Now you no longer have goofy-looking rectangles!To add some cool colour gradients to your bars, add value_inter to the @y_inter Marks card as Color. Compute value_inter (just as in the previous series of steps) using Year and frame, and lastly select your desired colour gradient."
},
{
"code": null,
"e": 13875,
"s": 13585,
"text": "Under the @y_inter(2) Marks card, select Label. Edit the text by clicking on ‘...’. Delete <Category> from the field, and justify <AGG(label)> to the right. Next, change the Alignment of the Label from Automatic to Top Right. Lastly select the checkbox Allow labels to overlap other marks."
},
{
"code": null,
"e": 13982,
"s": 13875,
"text": "Click on Size and select the smallest size on the slider. Now you no longer have goofy-looking rectangles!"
},
{
"code": null,
"e": 14215,
"s": 13982,
"text": "To add some cool colour gradients to your bars, add value_inter to the @y_inter Marks card as Color. Compute value_inter (just as in the previous series of steps) using Year and frame, and lastly select your desired colour gradient."
},
{
"code": null,
"e": 14472,
"s": 14215,
"text": "Those are some steps I believe are necessary to make your chart look presentable at the very least though there are other things you should also try out yourself to make your chart look better — try renaming/hiding your axes, axis titles, and chart titles!"
},
{
"code": null,
"e": 14677,
"s": 14472,
"text": "You can also create a Tableau dashboard to feature multiple view panes in addition to the one with the bar chart. One such view pane can feature the year of the animation ticking away as your graph moves."
},
{
"code": null,
"e": 14753,
"s": 14677,
"text": "Let me know if you discover interesting ways to personalise your bar chart!"
},
{
"code": null,
"e": 15263,
"s": 14753,
"text": "Last but not least, it’s currently not possible to export your simulated animated bar chart as an image or video directly using Tableau. For those of you who’d like to save your animated chart in another format, consider using the screen recording function on your computer (or on a 3rd party application) to record the animated frames on Tableau. You can then use a free tool on the internet to convert your video file to a .gif like I did if you’d like one. And there you go, a smart looking animated chart!"
},
{
"code": null,
"e": 15559,
"s": 15263,
"text": "So that should be it for this tutorial! I think I’ve probably noted down most of my thoughts and the steps I followed to get to a pleasant-looking animated bar chart race, so it’ll probably be easy for me to get back and recreate one in the future should I not touch Tableau again for some time."
},
{
"code": null,
"e": 15694,
"s": 15559,
"text": "Let me know if you have any questions or issues following the tutorial and thanks for reading! Hope you have fun creating your charts!"
}
] |
numpy.compress() in Python - GeeksforGeeks
|
22 Oct, 2020
The numpy.compress() function returns selected slices of an array along mentioned axis, that satisfies an axis.
Syntax: numpy.compress(condition, array, axis = None, out = None)
Parameters :
condition : [array_like]Condition on the basis of which user extract elements.
Applying condition on input_array, if we print condition, it will return an arra
filled with either True or False. Array elements are extracted from the Indices having
True value.
array : Input array. User apply conditions on input_array elements
axis : [optional, int]Indicating which slice to select.
By Default, work on flattened array[1-D]
out : [optional, ndarray]Output_array with elements of input_array,
that satisfies condition
Return :
Copy of array with elements of input_array,
that satisfies condition and along given axis
# Python Program illustrating# numpy.compress method import numpy as geek array = geek.arange(10).reshape(5, 2)print("Original array : \n", array) a = geek.compress([0, 1], array, axis=0)print("\nSliced array : \n", a) a = geek.compress([False, True], array, axis=0)print("\nSliced array : \n", a)
Output :
Original array :
[[0 1]
[2 3]
[4 5]
[6 7]
[8 9]]
Sliced array :
[[2 3]]
Sliced array :
[[2 3]]
References :https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.compress.htmlNote :This codes won’t run on online-ID. Please run them on your systems to explore the working..This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using 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.
Python numpy-Indexing
Python-numpy
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 ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Bar Plot in Matplotlib
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n22 Oct, 2020"
},
{
"code": null,
"e": 24404,
"s": 24292,
"text": "The numpy.compress() function returns selected slices of an array along mentioned axis, that satisfies an axis."
},
{
"code": null,
"e": 24470,
"s": 24404,
"text": "Syntax: numpy.compress(condition, array, axis = None, out = None)"
},
{
"code": null,
"e": 24483,
"s": 24470,
"text": "Parameters :"
},
{
"code": null,
"e": 25061,
"s": 24483,
"text": "condition : [array_like]Condition on the basis of which user extract elements. \n Applying condition on input_array, if we print condition, it will return an arra\n filled with either True or False. Array elements are extracted from the Indices having \n True value.\narray : Input array. User apply conditions on input_array elements\naxis : [optional, int]Indicating which slice to select. \n By Default, work on flattened array[1-D]\nout : [optional, ndarray]Output_array with elements of input_array, \n that satisfies condition\n"
},
{
"code": null,
"e": 25070,
"s": 25061,
"text": "Return :"
},
{
"code": null,
"e": 25161,
"s": 25070,
"text": "Copy of array with elements of input_array,\nthat satisfies condition and along given axis\n"
},
{
"code": "# Python Program illustrating# numpy.compress method import numpy as geek array = geek.arange(10).reshape(5, 2)print(\"Original array : \\n\", array) a = geek.compress([0, 1], array, axis=0)print(\"\\nSliced array : \\n\", a) a = geek.compress([False, True], array, axis=0)print(\"\\nSliced array : \\n\", a)",
"e": 25463,
"s": 25161,
"text": null
},
{
"code": null,
"e": 25472,
"s": 25463,
"text": "Output :"
},
{
"code": null,
"e": 25580,
"s": 25472,
"text": "Original array : \n [[0 1]\n [2 3]\n [4 5]\n [6 7]\n [8 9]]\n\nSliced array : \n [[2 3]]\n\nSliced array : \n [[2 3]]\n"
},
{
"code": null,
"e": 26069,
"s": 25580,
"text": "References :https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.compress.htmlNote :This codes won’t run on online-ID. Please run them on your systems to explore the working..This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using 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": 26194,
"s": 26069,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 26216,
"s": 26194,
"text": "Python numpy-Indexing"
},
{
"code": null,
"e": 26229,
"s": 26216,
"text": "Python-numpy"
},
{
"code": null,
"e": 26236,
"s": 26229,
"text": "Python"
},
{
"code": null,
"e": 26334,
"s": 26236,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26343,
"s": 26334,
"text": "Comments"
},
{
"code": null,
"e": 26356,
"s": 26343,
"text": "Old Comments"
},
{
"code": null,
"e": 26388,
"s": 26356,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26443,
"s": 26388,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26499,
"s": 26443,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26538,
"s": 26499,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26580,
"s": 26538,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26622,
"s": 26580,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26644,
"s": 26622,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26675,
"s": 26644,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26704,
"s": 26675,
"text": "Create a directory in Python"
}
] |
HashSet add() Method in Java
|
26 Nov, 2018
The Java.util.HashSet.add() method in Java HashSet is used to add a specific element into a HashSet. This method will add the element only if the specified element is not present in the HashSet else the function will return False if the element is already present in the HashSet.
Syntax:
Hash_Set.add(Object element)
Parameters: The parameter element is of the type HashSet and refers to the element to be added to the Set.
Return Value: The function returns True if the element is not present in the HashSet otherwise False if the element is already present in the HashSet.
Below program illustrate the Java.util.HashSet.add() method:
// Java code to illustrate add()import java.io.*;import java.util.HashSet; public class HashSetDemo { public static void main(String args[]) { // Creating an empty HashSet HashSet<String> set = new HashSet<String>(); // Use add() method to add elements into the Set set.add("Welcome"); set.add("To"); set.add("Geeks"); set.add("4"); set.add("Geeks"); // Displaying the HashSet System.out.println("HashSet: " + set); }}
HashSet: [4, Geeks, Welcome, To]
Java - util package
Java-Collections
Java-Functions
java-hashset
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Stream In Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Stack Class in Java
Introduction to Java
Constructors in Java
Initializing a List in Java
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n26 Nov, 2018"
},
{
"code": null,
"e": 334,
"s": 54,
"text": "The Java.util.HashSet.add() method in Java HashSet is used to add a specific element into a HashSet. This method will add the element only if the specified element is not present in the HashSet else the function will return False if the element is already present in the HashSet."
},
{
"code": null,
"e": 342,
"s": 334,
"text": "Syntax:"
},
{
"code": null,
"e": 371,
"s": 342,
"text": "Hash_Set.add(Object element)"
},
{
"code": null,
"e": 478,
"s": 371,
"text": "Parameters: The parameter element is of the type HashSet and refers to the element to be added to the Set."
},
{
"code": null,
"e": 629,
"s": 478,
"text": "Return Value: The function returns True if the element is not present in the HashSet otherwise False if the element is already present in the HashSet."
},
{
"code": null,
"e": 690,
"s": 629,
"text": "Below program illustrate the Java.util.HashSet.add() method:"
},
{
"code": "// Java code to illustrate add()import java.io.*;import java.util.HashSet; public class HashSetDemo { public static void main(String args[]) { // Creating an empty HashSet HashSet<String> set = new HashSet<String>(); // Use add() method to add elements into the Set set.add(\"Welcome\"); set.add(\"To\"); set.add(\"Geeks\"); set.add(\"4\"); set.add(\"Geeks\"); // Displaying the HashSet System.out.println(\"HashSet: \" + set); }}",
"e": 1193,
"s": 690,
"text": null
},
{
"code": null,
"e": 1227,
"s": 1193,
"text": "HashSet: [4, Geeks, Welcome, To]\n"
},
{
"code": null,
"e": 1247,
"s": 1227,
"text": "Java - util package"
},
{
"code": null,
"e": 1264,
"s": 1247,
"text": "Java-Collections"
},
{
"code": null,
"e": 1279,
"s": 1264,
"text": "Java-Functions"
},
{
"code": null,
"e": 1292,
"s": 1279,
"text": "java-hashset"
},
{
"code": null,
"e": 1297,
"s": 1292,
"text": "Java"
},
{
"code": null,
"e": 1302,
"s": 1297,
"text": "Java"
},
{
"code": null,
"e": 1319,
"s": 1302,
"text": "Java-Collections"
},
{
"code": null,
"e": 1417,
"s": 1319,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1436,
"s": 1417,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 1454,
"s": 1436,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 1469,
"s": 1454,
"text": "Stream In Java"
},
{
"code": null,
"e": 1489,
"s": 1469,
"text": "Collections in Java"
},
{
"code": null,
"e": 1513,
"s": 1489,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 1545,
"s": 1513,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 1565,
"s": 1545,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 1586,
"s": 1565,
"text": "Introduction to Java"
},
{
"code": null,
"e": 1607,
"s": 1586,
"text": "Constructors in Java"
}
] |
Function based Views – Django Rest Framework
|
16 Feb, 2021
Django REST Framework allows us to work with regular Django views. It facilitates processing the HTTP requests and providing appropriate HTTP responses. In this section, you will understand how to implement Django views for the Restful Web service. We also make use of the @api_view decorator.
Before working on Django REST Framework serializers, you should make sure that you already installed Django and Django REST Framework in your virtual environment. You can check the below tutorials:
Create virtual environment using venv | Python
Django Installation
Django REST Framework Installation
Next, you can create a project named emt and an app named transformers. Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django?
In this section, we will be using PostgreSQL. You have to create a database named emt in PostgreSQL. You can check the below link for installation.
Install PostgreSQL on Windows
Note: if you need to work with SQLite, you can continue using the default database.
To make use of PostgreSQL, we need to install a Python-PostgreSQL Database Adapter (psycopg2). This package helps Django to interact with a PostgreSQL database. You can use the below command to install the psycopg2 package. Make sure the PostgreSQL bin folder is included in the PATH environmental variables, and the virtual environment is activated before executing the command.
pip install psycopg2
Now, you need to configure the PostgreSQL database in your Django project. By default, the database configuration has an SQLite database engine and database file name. You can check the setting.py Python file and replace the default database configuration with the PostgreSQL database configuration.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'emt',
'USER': 'username',
'PASSWORD': 'password',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
Here, the name refers to the database name, the user and the password refers to the Postgres username and password.
At last, we need to install the httpie package in our virtual environment. We will be composing HTTPie commands for CRUD operation. You can activate the virtual environment and run the below command
pip install –upgrade httpie
Now, let’s create the Model and Serializer.
Before getting into class-based views let’s create a model and its serializer, which helps to demonstrate the working of function-based views.
In Django, Models are classes that deal with databases in an object-oriented way. Each model class refers to a database table and each attribute in the model class refers to a database column. Here, we will create a simple Transformer model in Django, which stores the transformer character name, alternate mode, description, and whether the character is alive or dead. We require the following attributes for our Transformer entity:
name
alternate_mode
description
alive
In a RESTFul web service, each resource is accessed using a unique URL, which means each employee has their unique URL. And, each method of the model is composed of an HTTP Verb and Scope.
Let’s get into the implementation of the Transformer model in Django. You can replace the models.py Python file with the below code:
Python3
from django.db import models class Transformer(models.Model): name = models.CharField(max_length=150, unique=True) alternate_mode = models.CharField( max_length=250, blank=True, null=True) description = models.CharField( max_length=500, blank=True, null=True) alive = models.BooleanField(default=False) class Meta: ordering = ('name',) def __str__(self): return self.name
The Transformer model is a subclass of the django.db.models.Model class and defines the attributes and a Meta inner class. It has an ordering attribute that orders the result in an ascending order based on the name. Let’s make the initial migrations using the below command (Make sure you defined your app (‘transformers.apps.TransformersConfig’) in INSTALLED_APPS in settings.py Python file)
python manage.py makemigrations
Next, apply all generated migrations using the below command:
python manage.py migrate
Applying generated migrations will create a Transformer table in the database.
Create a new serializers.py Python file in your app (transformers) folder and add the below code:
Python3
from rest_framework import serializersfrom transformers.models import Transformer class TransformerSerializer(serializers.ModelSerializer): class Meta: model = Transformer fields = "__all__"
Here, we created a TransformerSerializer class that inherits from the rest_framework.serializers.ModelSerializer. If you would like to dig deep into different types of serialized, you can check Django REST Framework (DRF) Serialization. Now, it’s time to begin our journey towards function-based Views. We will start with regular Django views and after then we will take advantage of the @api_view decorator.
Django views facilitate processing the HTTP requests and providing HTTP responses. On receiving an HTTP request, Django creates an HttpRequest instance, and it is passed as the first argument to the view function. This instance contains HTTP verbs such as GET, POST, PUT, PATCH, or DELETE. The view function checks the value and executes the code based on the HTTP verb. Here the code uses @csrf_exempt decorator to set a CSRF (Cross-Site Request Forgery) cookie. This makes it possible to POST to this view from clients that won’t have a CSRF token. Let’s get into the implementation process. You can add the below code in the views.py file.
Python3
from django.http import HttpResponse, JsonResponsefrom django.views.decorators.csrf import csrf_exemptfrom rest_framework.parsers import JSONParser from transformers.models import Transformerfrom transformers.serializers import TransformerSerializer @csrf_exemptdef transformer_list(request): """ List all transformers, or create a new transformer """ if request.method == 'GET': transformer = Transformer.objects.all() serializer = TransformerSerializer(transformer, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = TransformerSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) @csrf_exemptdef transformer_detail(request, pk): try: transformer = Transformer.objects.get(pk=pk) except Transformer.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = TransformerSerializer(transformer) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = TransformerSerializer(transformer, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': transformer.delete() return HttpResponse(status=204)
Let’s evaluate the code. Here we have two functions.
transformer_list()
transformer_detail()
The ransformer_list() function is capable of processing two HTTP verbs – GET and POST.
If the verb is GET, the code retrieves all the transformer instances.
if request.method == 'GET':
transformer = Transformer.objects.all()
serializer = TransformerSerializer(transformer, many=True)
return JsonResponse(serializer.data, safe=False)
It retrieves all the transformer’s data using the objects.all() method.
Serializes the tasks using TransformerSerializer.
Then the serialized data is rendered using JsonResponse() and returns the result
Note: The many=True argument specified serializes multiple Transformer instances.
If the verb is POST, the code creates a new transformer. Here the data is provided in JSON format while composing the HTTP request.
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = TransformerSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
Uses JSONParser to parse the request,
Serialize the parsed data using TransformerSerializer,
If data is valid, it is saved in the database and returns the rendered result with the status code.
The transformer_detail() function is capable of processing three HTTP verbs – GET, PUT, and DELETE. If the verb is GET, then the code retrieves a single transformer instance based on the primary key. If the verb is PUT, the code updates the instance and save it to the database, and if it is DELETE, then the code deletes the instance from the database.
As a next step, we need to route URLs to views. You need to create a new Python file name urls.py in the app (transformers) folder and add the below code.
Python3
from django.urls import pathfrom transformers import views urlpatterns = [ path('transformers/', views.transformer_list, name = 'employee-list'), path('transformers/<int:pk>/', views.transformer_detail, name = 'employee-detail'),]
Now, let’s update the root URL configuration. You can add the below code to the urls.py file (the same folder that has the settings.py file).
Python3
from django.contrib import adminfrom django.urls import path, include urlpatterns = [ path('', include('transformers.urls')),]
Now it’s time to compose and send HTTP requests to test our views.
Let’s create a new entry. The HTTPie command is:
http POST :8000/transformers/ name=”Wheeljack” alternate_mode=”1977 Lancia Stratos Turbo” description=”Always inventing new weapons and gadgets” alive=”False”
Output
HTTP/1.1 201 Created
Content-Length: 152
Content-Type: application/json
Date: Mon, 25 Jan 2021 05:23:10 GMT
Referrer-Policy: same-origin
Server: WSGIServer/0.2 CPython/3.7.5
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
{
"alive": false,
"alternate_mode": "1977 Lancia Stratos Turbo",
"description": "Always inventing new weapons and gadgets",
"id": 7,
"name": "Wheeljack"
}
Sharing the command prompt screenshot for your reference
Let’s update the alive field of the transformer (id=7) to True. The HTTPie command is:
http PUT :8000/transformers/7/ name=”Wheeljack” alternate_mode=”1977 Lancia Stratos Turbo” description=”Always inventing new weapons and gadgets” alive=”True”
Output
HTTP/1.1 200 OK
Content-Length: 151
Content-Type: application/json
Date: Mon, 25 Jan 2021 05:26:22 GMT
Referrer-Policy: same-origin
Server: WSGIServer/0.2 CPython/3.7.5
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
{
"alive": true,
"alternate_mode": "1977 Lancia Stratos Turbo",
"description": "Always inventing new weapons and gadgets",
"id": 7,
"name": "Wheeljack"
}
Let’s retrieve all the transformers. The HTTPie command is:
http GET :8000/transformers/
Output
HTTP/1.1 200 OK
Allow: GET, POST, OPTIONS
Content-Length: 629
Content-Type: application/json
Date: Mon, 25 Jan 2021 05:43:36 GMT
Referrer-Policy: same-origin
Server: WSGIServer/0.2 CPython/3.7.5
Vary: Accept, Cookie
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
[
{
"alive": true,
"alternate_mode": "1977 Lancia Stratos Turbo",
"description": "Always inventing new weapons and gadgets",
"id": 7,
"name": "Wheeljack"
},
{
"alive": true,
"alternate_mode": "1979 Porsche 924",
"description": "Eager and Daring",
"id": 5,
"name": "Cliffjumper"
},
{
"alive": true,
"alternate_mode": "1979 VW Beetle",
"description": "Small, eager, and brave. Acts as a messenger, scout, and spy",
"id": 3,
"name": "Bumblebee"
},
{
"alive": false,
"alternate_mode": "1979 Freightliner Semi",
"description": "Optimus Prime is the strongest and most courageous and leader of all Autobots",
"id": 1,
"name": "Optimus Prime"
}
]
Sharing the command prompt screenshot
The @api_view is a decorator in the rest_framework.decorators module, and it is the base class for all the Django REST framework views. We can provide the allowed HTTP verbs as the http_methods_names argument (list of strings) in the @api_view decorator. If the RESTful Web service receives an unsupported HTTP Verb, the decorator returns an appropriate response rather than an unexpected error in Django.
@api_view(http_method_names=['GET'])
You can replace the views.py file with the below code.
Python3
from rest_framework.decorators import api_viewfrom rest_framework.response import Responsefrom rest_framework import status from transformers.models import Transformerfrom transformers.serializers import TransformerSerializer @api_view(['GET','POST'])def transformer_list(request): """ List all transformers, or create a new transformer """ if request.method == 'GET': transformer = Transformer.objects.all() serializer = TransformerSerializer(transformer, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = TransformerSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET','PUT','PATCH','DELETE'])def transformer_detail(request, pk): try: transformer = Transformer.objects.get(pk=pk) except Transformer.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = TransformerSerializer(transformer) return Response(serializer.data) elif request.method == 'PUT': serializer = TransformerSerializer(transformer, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'PATCH': serializer = TransformerSerializer(transformer, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': transformer.delete() return Response(status=status.HTTP_204_NO_CONTENT)
In the new code, the transformer_list and transformer_detail functions are wrapped with the @api_vew decorator. The transformer_list function supports GET and POST Verbs, whereas, transformer_detail method supports GET, PUT, PATCH, and DELETE verbs. These supported verbs are passed as decorator parameters for each method. Here, we removed rest_framework.parsers.JSONParser class. This way we can let the code work with different parsers. We also replaced the JSONResponse class with a more generic rest_framework.response.Response class.
Let’s run the HTTPie command with OPTIONS verb to list the supported methods and verbs in the transformer_list method.
http OPTIONS :8000/transformers/
Output
HTTP/1.1 200 OK
Allow: GET, OPTIONS, POST
Content-Length: 225
Content-Type: application/json
Date: Mon, 25 Jan 2021 16:52:10 GMT
Referrer-Policy: same-origin
Server: WSGIServer/0.2 CPython/3.7.5
Vary: Accept, Cookie
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
{
"description": "List all transformers, or create a new transformer",
"name": "Transformer List",
"parses": [
"application/json",
"application/x-www-form-urlencoded",
"multipart/form-data"
],
"renders": [
"application/json",
"text/html"
]
}
Sharing the command prompt screenshot
The output displays the details of the transformer_list method. It allows GET, OPTIONS, and POST HTTP Verbs. It also displays the different parses and renders that the function supports.
Let’s look at the transformer_detail function. The HTTPie command is
http OPTIONS :8000/transformers/1/
Output
HTTP/1.1 200 OK
Allow: OPTIONS, DELETE, GET, PATCH, PUT
Content-Length: 177
Content-Type: application/json
Date: Mon, 25 Jan 2021 16:59:23 GMT
Referrer-Policy: same-origin
Server: WSGIServer/0.2 CPython/3.7.5
Vary: Accept, Cookie
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
{
"description": "",
"name": "Transformer Detail",
"parses": [
"application/json",
"application/x-www-form-urlencoded",
"multipart/form-data"
],
"renders": [
"application/json",
"text/html"
]
}
You can notice that the transformer_detail() function supports OPTIONS, DELETE, GET, PATCH, and PUT HTTP verbs. It also displays the different parses and renders that the function supports.
The @api_view decorator can parse different content types by choosing the appropriate parser. From the above output, we can notice the different parsers supported in the @api_view decorator. When we use the @api_view decorator, it automatically makes use of APIView class and its settings. This way we will be able to use the parsers and renders.
The @api_view decorator helps the Django REST framework to examine the Content-Type header in the data attribute and identifies the exact parser to parse the request. It also invokes the rest_framework.negotiation.DefaultContentNegotiation class to select the suitable renderer for the request.
Now, it’s time to compose and send different HTTP requests. Let’s create a new entry. The HTTPie command is
http POST :8000/transformers/ name=”Prowl” alternate_mode=”1979 Nissan 280ZX Police Car” description=”Strives to find reason and logic in everything” alive=”False”
Output
HTTP/1.1 201 Created
Allow: GET, POST, OPTIONS
Content-Length: 149
Content-Type: application/json
Date: Mon, 25 Jan 2021 16:18:56 GMT
Referrer-Policy: same-origin
Server: WSGIServer/0.2 CPython/3.7.5
Vary: Accept, Cookie
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
{
"alive": false,
"alternate_mode": "1979 Nissan 280ZX Police Car",
"description": "Strives to find reason and logic in everything",
"id": 10,
"name": "Prowl"
}
Sharing the command prompt screenshot
Let’s update the alive field value to True. The HTTPie command is:
http PATCH :8000/transformers/10/ alive=”True”
Output
HTTP/1.1 200 OK
Allow: PATCH, PUT, DELETE, OPTIONS, GET
Content-Length: 148
Content-Type: application/json
Date: Mon, 25 Jan 2021 16:22:35 GMT
Referrer-Policy: same-origin
Server: WSGIServer/0.2 CPython/3.7.5
Vary: Accept, Cookie
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
{
"alive": true,
"alternate_mode": "1979 Nissan 280ZX Police Car",
"description": "Strives to find reason and logic in everything",
"id": 10,
"name": "Prowl"
}
Sharing the command prompt screenshot
Let’s retrieve all the entries. The HTTPie command is:
http GET :8000/transformers/
Output
HTTP/1.1 200 OK
Allow: GET, POST, OPTIONS
Content-Length: 739
Content-Type: application/json
Date: Mon, 25 Jan 2021 16:23:52 GMT
Referrer-Policy: same-origin
Server: WSGIServer/0.2 CPython/3.7.5
Vary: Accept, Cookie
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
[
{
"alive": true,
"alternate_mode": "1979 Nissan 280ZX Police Car",
"description": "Strives to find reason and logic in everything",
"id": 10,
"name": "Prowl"
},
{
"alive": true,
"alternate_mode": "1977 Lancia Stratos Turbo",
"description": "Always inventing new weapons and gadgets",
"id": 7,
"name": "Wheeljack"
},
{
"alive": true,
"alternate_mode": "1979 Porsche 924",
"description": "Eager and Daring",
"id": 5,
"name": "Cliffjumper"
},
{
"alive": true,
"alternate_mode": "1979 VW Beetle",
"description": "Small, eager, and brave. Acts as a messenger, scout, and spy",
"id": 3,
"name": "Bumblebee"
},
{
"alive": false,
"alternate_mode": "1979 Freightliner Semi",
"description": "Optimus Prime is the strongest and most courageous and leader of all Autobots",
"id": 1,
"name": "Optimus Prime"
}
]
Sharing the command prompt screenshot
In this section, we understood how to code Django views to process HTTP Request and returns HTTP Response. We also realized the importance of wrapping our views with the @api_view decorator. Finally, we composed and sent different requests including the OPTIONS HTTP request, which displays the supported HTTP verbs, parsers, and renderers.
Django-REST
Django-views
Python Django
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Feb, 2021"
},
{
"code": null,
"e": 322,
"s": 28,
"text": "Django REST Framework allows us to work with regular Django views. It facilitates processing the HTTP requests and providing appropriate HTTP responses. In this section, you will understand how to implement Django views for the Restful Web service. We also make use of the @api_view decorator."
},
{
"code": null,
"e": 520,
"s": 322,
"text": "Before working on Django REST Framework serializers, you should make sure that you already installed Django and Django REST Framework in your virtual environment. You can check the below tutorials:"
},
{
"code": null,
"e": 567,
"s": 520,
"text": "Create virtual environment using venv | Python"
},
{
"code": null,
"e": 587,
"s": 567,
"text": "Django Installation"
},
{
"code": null,
"e": 622,
"s": 587,
"text": "Django REST Framework Installation"
},
{
"code": null,
"e": 781,
"s": 622,
"text": "Next, you can create a project named emt and an app named transformers. Refer to the following articles to check how to create a project and an app in Django."
},
{
"code": null,
"e": 832,
"s": 781,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 864,
"s": 832,
"text": "How to Create an App in Django?"
},
{
"code": null,
"e": 1012,
"s": 864,
"text": "In this section, we will be using PostgreSQL. You have to create a database named emt in PostgreSQL. You can check the below link for installation."
},
{
"code": null,
"e": 1042,
"s": 1012,
"text": "Install PostgreSQL on Windows"
},
{
"code": null,
"e": 1126,
"s": 1042,
"text": "Note: if you need to work with SQLite, you can continue using the default database."
},
{
"code": null,
"e": 1506,
"s": 1126,
"text": "To make use of PostgreSQL, we need to install a Python-PostgreSQL Database Adapter (psycopg2). This package helps Django to interact with a PostgreSQL database. You can use the below command to install the psycopg2 package. Make sure the PostgreSQL bin folder is included in the PATH environmental variables, and the virtual environment is activated before executing the command."
},
{
"code": null,
"e": 1527,
"s": 1506,
"text": "pip install psycopg2"
},
{
"code": null,
"e": 1827,
"s": 1527,
"text": "Now, you need to configure the PostgreSQL database in your Django project. By default, the database configuration has an SQLite database engine and database file name. You can check the setting.py Python file and replace the default database configuration with the PostgreSQL database configuration."
},
{
"code": null,
"e": 2045,
"s": 1827,
"text": "DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql',\n 'NAME': 'emt',\n 'USER': 'username',\n 'PASSWORD': 'password',\n 'HOST': '127.0.0.1',\n 'PORT': '5432',\n }\n}"
},
{
"code": null,
"e": 2161,
"s": 2045,
"text": "Here, the name refers to the database name, the user and the password refers to the Postgres username and password."
},
{
"code": null,
"e": 2360,
"s": 2161,
"text": "At last, we need to install the httpie package in our virtual environment. We will be composing HTTPie commands for CRUD operation. You can activate the virtual environment and run the below command"
},
{
"code": null,
"e": 2388,
"s": 2360,
"text": "pip install –upgrade httpie"
},
{
"code": null,
"e": 2432,
"s": 2388,
"text": "Now, let’s create the Model and Serializer."
},
{
"code": null,
"e": 2575,
"s": 2432,
"text": "Before getting into class-based views let’s create a model and its serializer, which helps to demonstrate the working of function-based views."
},
{
"code": null,
"e": 3009,
"s": 2575,
"text": "In Django, Models are classes that deal with databases in an object-oriented way. Each model class refers to a database table and each attribute in the model class refers to a database column. Here, we will create a simple Transformer model in Django, which stores the transformer character name, alternate mode, description, and whether the character is alive or dead. We require the following attributes for our Transformer entity:"
},
{
"code": null,
"e": 3014,
"s": 3009,
"text": "name"
},
{
"code": null,
"e": 3029,
"s": 3014,
"text": "alternate_mode"
},
{
"code": null,
"e": 3041,
"s": 3029,
"text": "description"
},
{
"code": null,
"e": 3047,
"s": 3041,
"text": "alive"
},
{
"code": null,
"e": 3236,
"s": 3047,
"text": "In a RESTFul web service, each resource is accessed using a unique URL, which means each employee has their unique URL. And, each method of the model is composed of an HTTP Verb and Scope."
},
{
"code": null,
"e": 3369,
"s": 3236,
"text": "Let’s get into the implementation of the Transformer model in Django. You can replace the models.py Python file with the below code:"
},
{
"code": null,
"e": 3377,
"s": 3369,
"text": "Python3"
},
{
"code": "from django.db import models class Transformer(models.Model): name = models.CharField(max_length=150, unique=True) alternate_mode = models.CharField( max_length=250, blank=True, null=True) description = models.CharField( max_length=500, blank=True, null=True) alive = models.BooleanField(default=False) class Meta: ordering = ('name',) def __str__(self): return self.name",
"e": 3828,
"s": 3377,
"text": null
},
{
"code": null,
"e": 4222,
"s": 3828,
"text": "The Transformer model is a subclass of the django.db.models.Model class and defines the attributes and a Meta inner class. It has an ordering attribute that orders the result in an ascending order based on the name. Let’s make the initial migrations using the below command (Make sure you defined your app (‘transformers.apps.TransformersConfig’) in INSTALLED_APPS in settings.py Python file)"
},
{
"code": null,
"e": 4254,
"s": 4222,
"text": "python manage.py makemigrations"
},
{
"code": null,
"e": 4316,
"s": 4254,
"text": "Next, apply all generated migrations using the below command:"
},
{
"code": null,
"e": 4341,
"s": 4316,
"text": "python manage.py migrate"
},
{
"code": null,
"e": 4420,
"s": 4341,
"text": "Applying generated migrations will create a Transformer table in the database."
},
{
"code": null,
"e": 4518,
"s": 4420,
"text": "Create a new serializers.py Python file in your app (transformers) folder and add the below code:"
},
{
"code": null,
"e": 4526,
"s": 4518,
"text": "Python3"
},
{
"code": "from rest_framework import serializersfrom transformers.models import Transformer class TransformerSerializer(serializers.ModelSerializer): class Meta: model = Transformer fields = \"__all__\"",
"e": 4735,
"s": 4526,
"text": null
},
{
"code": null,
"e": 5144,
"s": 4735,
"text": "Here, we created a TransformerSerializer class that inherits from the rest_framework.serializers.ModelSerializer. If you would like to dig deep into different types of serialized, you can check Django REST Framework (DRF) Serialization. Now, it’s time to begin our journey towards function-based Views. We will start with regular Django views and after then we will take advantage of the @api_view decorator."
},
{
"code": null,
"e": 5792,
"s": 5144,
"text": "Django views facilitate processing the HTTP requests and providing HTTP responses. On receiving an HTTP request, Django creates an HttpRequest instance, and it is passed as the first argument to the view function. This instance contains HTTP verbs such as GET, POST, PUT, PATCH, or DELETE. The view function checks the value and executes the code based on the HTTP verb. Here the code uses @csrf_exempt decorator to set a CSRF (Cross-Site Request Forgery) cookie. This makes it possible to POST to this view from clients that won’t have a CSRF token. Let’s get into the implementation process. You can add the below code in the views.py file. "
},
{
"code": null,
"e": 5800,
"s": 5792,
"text": "Python3"
},
{
"code": "from django.http import HttpResponse, JsonResponsefrom django.views.decorators.csrf import csrf_exemptfrom rest_framework.parsers import JSONParser from transformers.models import Transformerfrom transformers.serializers import TransformerSerializer @csrf_exemptdef transformer_list(request): \"\"\" List all transformers, or create a new transformer \"\"\" if request.method == 'GET': transformer = Transformer.objects.all() serializer = TransformerSerializer(transformer, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = TransformerSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) @csrf_exemptdef transformer_detail(request, pk): try: transformer = Transformer.objects.get(pk=pk) except Transformer.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = TransformerSerializer(transformer) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = TransformerSerializer(transformer, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': transformer.delete() return HttpResponse(status=204)",
"e": 7409,
"s": 5800,
"text": null
},
{
"code": null,
"e": 7462,
"s": 7409,
"text": "Let’s evaluate the code. Here we have two functions."
},
{
"code": null,
"e": 7481,
"s": 7462,
"text": "transformer_list()"
},
{
"code": null,
"e": 7502,
"s": 7481,
"text": "transformer_detail()"
},
{
"code": null,
"e": 7591,
"s": 7502,
"text": "The ransformer_list() function is capable of processing two HTTP verbs – GET and POST. "
},
{
"code": null,
"e": 7662,
"s": 7591,
"text": "If the verb is GET, the code retrieves all the transformer instances. "
},
{
"code": null,
"e": 7866,
"s": 7662,
"text": " if request.method == 'GET':\n transformer = Transformer.objects.all()\n serializer = TransformerSerializer(transformer, many=True)\n return JsonResponse(serializer.data, safe=False)"
},
{
"code": null,
"e": 7938,
"s": 7866,
"text": "It retrieves all the transformer’s data using the objects.all() method."
},
{
"code": null,
"e": 7988,
"s": 7938,
"text": "Serializes the tasks using TransformerSerializer."
},
{
"code": null,
"e": 8069,
"s": 7988,
"text": "Then the serialized data is rendered using JsonResponse() and returns the result"
},
{
"code": null,
"e": 8152,
"s": 8069,
"text": "Note: The many=True argument specified serializes multiple Transformer instances."
},
{
"code": null,
"e": 8284,
"s": 8152,
"text": "If the verb is POST, the code creates a new transformer. Here the data is provided in JSON format while composing the HTTP request."
},
{
"code": null,
"e": 8600,
"s": 8284,
"text": " elif request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = TransformerSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data, status=201)\n return JsonResponse(serializer.errors, status=400)"
},
{
"code": null,
"e": 8638,
"s": 8600,
"text": "Uses JSONParser to parse the request,"
},
{
"code": null,
"e": 8693,
"s": 8638,
"text": "Serialize the parsed data using TransformerSerializer,"
},
{
"code": null,
"e": 8793,
"s": 8693,
"text": "If data is valid, it is saved in the database and returns the rendered result with the status code."
},
{
"code": null,
"e": 9147,
"s": 8793,
"text": "The transformer_detail() function is capable of processing three HTTP verbs – GET, PUT, and DELETE. If the verb is GET, then the code retrieves a single transformer instance based on the primary key. If the verb is PUT, the code updates the instance and save it to the database, and if it is DELETE, then the code deletes the instance from the database."
},
{
"code": null,
"e": 9302,
"s": 9147,
"text": "As a next step, we need to route URLs to views. You need to create a new Python file name urls.py in the app (transformers) folder and add the below code."
},
{
"code": null,
"e": 9310,
"s": 9302,
"text": "Python3"
},
{
"code": "from django.urls import pathfrom transformers import views urlpatterns = [ path('transformers/', views.transformer_list, name = 'employee-list'), path('transformers/<int:pk>/', views.transformer_detail, name = 'employee-detail'),]",
"e": 9580,
"s": 9310,
"text": null
},
{
"code": null,
"e": 9724,
"s": 9580,
"text": "Now, let’s update the root URL configuration. You can add the below code to the urls.py file (the same folder that has the settings.py file). "
},
{
"code": null,
"e": 9732,
"s": 9724,
"text": "Python3"
},
{
"code": "from django.contrib import adminfrom django.urls import path, include urlpatterns = [ path('', include('transformers.urls')),]",
"e": 9863,
"s": 9732,
"text": null
},
{
"code": null,
"e": 9930,
"s": 9863,
"text": "Now it’s time to compose and send HTTP requests to test our views."
},
{
"code": null,
"e": 9979,
"s": 9930,
"text": "Let’s create a new entry. The HTTPie command is:"
},
{
"code": null,
"e": 10138,
"s": 9979,
"text": "http POST :8000/transformers/ name=”Wheeljack” alternate_mode=”1977 Lancia Stratos Turbo” description=”Always inventing new weapons and gadgets” alive=”False”"
},
{
"code": null,
"e": 10145,
"s": 10138,
"text": "Output"
},
{
"code": null,
"e": 10549,
"s": 10145,
"text": "HTTP/1.1 201 Created\nContent-Length: 152\nContent-Type: application/json\nDate: Mon, 25 Jan 2021 05:23:10 GMT\nReferrer-Policy: same-origin\nServer: WSGIServer/0.2 CPython/3.7.5\nX-Content-Type-Options: nosniff\nX-Frame-Options: DENY\n\n{\n \"alive\": false,\n \"alternate_mode\": \"1977 Lancia Stratos Turbo\",\n \"description\": \"Always inventing new weapons and gadgets\",\n \"id\": 7,\n \"name\": \"Wheeljack\"\n}"
},
{
"code": null,
"e": 10606,
"s": 10549,
"text": "Sharing the command prompt screenshot for your reference"
},
{
"code": null,
"e": 10693,
"s": 10606,
"text": "Let’s update the alive field of the transformer (id=7) to True. The HTTPie command is:"
},
{
"code": null,
"e": 10852,
"s": 10693,
"text": "http PUT :8000/transformers/7/ name=”Wheeljack” alternate_mode=”1977 Lancia Stratos Turbo” description=”Always inventing new weapons and gadgets” alive=”True”"
},
{
"code": null,
"e": 10859,
"s": 10852,
"text": "Output"
},
{
"code": null,
"e": 11257,
"s": 10859,
"text": "HTTP/1.1 200 OK\nContent-Length: 151\nContent-Type: application/json\nDate: Mon, 25 Jan 2021 05:26:22 GMT\nReferrer-Policy: same-origin\nServer: WSGIServer/0.2 CPython/3.7.5\nX-Content-Type-Options: nosniff\nX-Frame-Options: DENY\n\n{\n \"alive\": true,\n \"alternate_mode\": \"1977 Lancia Stratos Turbo\",\n \"description\": \"Always inventing new weapons and gadgets\",\n \"id\": 7,\n \"name\": \"Wheeljack\"\n}"
},
{
"code": null,
"e": 11317,
"s": 11257,
"text": "Let’s retrieve all the transformers. The HTTPie command is:"
},
{
"code": null,
"e": 11346,
"s": 11317,
"text": "http GET :8000/transformers/"
},
{
"code": null,
"e": 11353,
"s": 11346,
"text": "Output"
},
{
"code": null,
"e": 12456,
"s": 11353,
"text": "HTTP/1.1 200 OK\nAllow: GET, POST, OPTIONS\nContent-Length: 629\nContent-Type: application/json\nDate: Mon, 25 Jan 2021 05:43:36 GMT\nReferrer-Policy: same-origin\nServer: WSGIServer/0.2 CPython/3.7.5\nVary: Accept, Cookie\nX-Content-Type-Options: nosniff\nX-Frame-Options: DENY\n\n[\n {\n \"alive\": true,\n \"alternate_mode\": \"1977 Lancia Stratos Turbo\",\n \"description\": \"Always inventing new weapons and gadgets\",\n \"id\": 7,\n \"name\": \"Wheeljack\"\n },\n {\n \"alive\": true,\n \"alternate_mode\": \"1979 Porsche 924\",\n \"description\": \"Eager and Daring\",\n \"id\": 5,\n \"name\": \"Cliffjumper\"\n },\n {\n \"alive\": true,\n \"alternate_mode\": \"1979 VW Beetle\",\n \"description\": \"Small, eager, and brave. Acts as a messenger, scout, and spy\",\n \"id\": 3,\n \"name\": \"Bumblebee\"\n },\n {\n \"alive\": false,\n \"alternate_mode\": \"1979 Freightliner Semi\",\n \"description\": \"Optimus Prime is the strongest and most courageous and leader of all Autobots\",\n \"id\": 1,\n \"name\": \"Optimus Prime\"\n }\n]"
},
{
"code": null,
"e": 12494,
"s": 12456,
"text": "Sharing the command prompt screenshot"
},
{
"code": null,
"e": 12905,
"s": 12494,
"text": "The @api_view is a decorator in the rest_framework.decorators module, and it is the base class for all the Django REST framework views. We can provide the allowed HTTP verbs as the http_methods_names argument (list of strings) in the @api_view decorator. If the RESTful Web service receives an unsupported HTTP Verb, the decorator returns an appropriate response rather than an unexpected error in Django. "
},
{
"code": null,
"e": 12942,
"s": 12905,
"text": "@api_view(http_method_names=['GET'])"
},
{
"code": null,
"e": 12997,
"s": 12942,
"text": "You can replace the views.py file with the below code."
},
{
"code": null,
"e": 13005,
"s": 12997,
"text": "Python3"
},
{
"code": "from rest_framework.decorators import api_viewfrom rest_framework.response import Responsefrom rest_framework import status from transformers.models import Transformerfrom transformers.serializers import TransformerSerializer @api_view(['GET','POST'])def transformer_list(request): \"\"\" List all transformers, or create a new transformer \"\"\" if request.method == 'GET': transformer = Transformer.objects.all() serializer = TransformerSerializer(transformer, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = TransformerSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET','PUT','PATCH','DELETE'])def transformer_detail(request, pk): try: transformer = Transformer.objects.get(pk=pk) except Transformer.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = TransformerSerializer(transformer) return Response(serializer.data) elif request.method == 'PUT': serializer = TransformerSerializer(transformer, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'PATCH': serializer = TransformerSerializer(transformer, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': transformer.delete() return Response(status=status.HTTP_204_NO_CONTENT)",
"e": 15122,
"s": 13005,
"text": null
},
{
"code": null,
"e": 15663,
"s": 15122,
"text": "In the new code, the transformer_list and transformer_detail functions are wrapped with the @api_vew decorator. The transformer_list function supports GET and POST Verbs, whereas, transformer_detail method supports GET, PUT, PATCH, and DELETE verbs. These supported verbs are passed as decorator parameters for each method. Here, we removed rest_framework.parsers.JSONParser class. This way we can let the code work with different parsers. We also replaced the JSONResponse class with a more generic rest_framework.response.Response class."
},
{
"code": null,
"e": 15782,
"s": 15663,
"text": "Let’s run the HTTPie command with OPTIONS verb to list the supported methods and verbs in the transformer_list method."
},
{
"code": null,
"e": 15815,
"s": 15782,
"text": "http OPTIONS :8000/transformers/"
},
{
"code": null,
"e": 15822,
"s": 15815,
"text": "Output"
},
{
"code": null,
"e": 16399,
"s": 15822,
"text": "HTTP/1.1 200 OK\nAllow: GET, OPTIONS, POST\nContent-Length: 225\nContent-Type: application/json\nDate: Mon, 25 Jan 2021 16:52:10 GMT\nReferrer-Policy: same-origin\nServer: WSGIServer/0.2 CPython/3.7.5\nVary: Accept, Cookie\nX-Content-Type-Options: nosniff\nX-Frame-Options: DENY\n\n{\n \"description\": \"List all transformers, or create a new transformer\",\n \"name\": \"Transformer List\",\n \"parses\": [\n \"application/json\",\n \"application/x-www-form-urlencoded\",\n \"multipart/form-data\"\n ],\n \"renders\": [\n \"application/json\",\n \"text/html\"\n ]\n}"
},
{
"code": null,
"e": 16437,
"s": 16399,
"text": "Sharing the command prompt screenshot"
},
{
"code": null,
"e": 16624,
"s": 16437,
"text": "The output displays the details of the transformer_list method. It allows GET, OPTIONS, and POST HTTP Verbs. It also displays the different parses and renders that the function supports."
},
{
"code": null,
"e": 16693,
"s": 16624,
"text": "Let’s look at the transformer_detail function. The HTTPie command is"
},
{
"code": null,
"e": 16728,
"s": 16693,
"text": "http OPTIONS :8000/transformers/1/"
},
{
"code": null,
"e": 16735,
"s": 16728,
"text": "Output"
},
{
"code": null,
"e": 17278,
"s": 16735,
"text": "HTTP/1.1 200 OK\nAllow: OPTIONS, DELETE, GET, PATCH, PUT\nContent-Length: 177\nContent-Type: application/json\nDate: Mon, 25 Jan 2021 16:59:23 GMT\nReferrer-Policy: same-origin\nServer: WSGIServer/0.2 CPython/3.7.5\nVary: Accept, Cookie\nX-Content-Type-Options: nosniff\nX-Frame-Options: DENY\n\n{\n \"description\": \"\",\n \"name\": \"Transformer Detail\",\n \"parses\": [\n \"application/json\",\n \"application/x-www-form-urlencoded\",\n \"multipart/form-data\"\n ],\n \"renders\": [\n \"application/json\",\n \"text/html\"\n ]\n}"
},
{
"code": null,
"e": 17468,
"s": 17278,
"text": "You can notice that the transformer_detail() function supports OPTIONS, DELETE, GET, PATCH, and PUT HTTP verbs. It also displays the different parses and renders that the function supports."
},
{
"code": null,
"e": 17816,
"s": 17468,
"text": "The @api_view decorator can parse different content types by choosing the appropriate parser. From the above output, we can notice the different parsers supported in the @api_view decorator. When we use the @api_view decorator, it automatically makes use of APIView class and its settings. This way we will be able to use the parsers and renders. "
},
{
"code": null,
"e": 18112,
"s": 17816,
"text": "The @api_view decorator helps the Django REST framework to examine the Content-Type header in the data attribute and identifies the exact parser to parse the request. It also invokes the rest_framework.negotiation.DefaultContentNegotiation class to select the suitable renderer for the request. "
},
{
"code": null,
"e": 18220,
"s": 18112,
"text": "Now, it’s time to compose and send different HTTP requests. Let’s create a new entry. The HTTPie command is"
},
{
"code": null,
"e": 18384,
"s": 18220,
"text": "http POST :8000/transformers/ name=”Prowl” alternate_mode=”1979 Nissan 280ZX Police Car” description=”Strives to find reason and logic in everything” alive=”False”"
},
{
"code": null,
"e": 18391,
"s": 18384,
"text": "Output"
},
{
"code": null,
"e": 18848,
"s": 18391,
"text": "HTTP/1.1 201 Created\nAllow: GET, POST, OPTIONS\nContent-Length: 149\nContent-Type: application/json\nDate: Mon, 25 Jan 2021 16:18:56 GMT\nReferrer-Policy: same-origin\nServer: WSGIServer/0.2 CPython/3.7.5\nVary: Accept, Cookie\nX-Content-Type-Options: nosniff\nX-Frame-Options: DENY\n\n{\n \"alive\": false,\n \"alternate_mode\": \"1979 Nissan 280ZX Police Car\",\n \"description\": \"Strives to find reason and logic in everything\",\n \"id\": 10,\n \"name\": \"Prowl\"\n}"
},
{
"code": null,
"e": 18887,
"s": 18848,
"text": "Sharing the command prompt screenshot "
},
{
"code": null,
"e": 18954,
"s": 18887,
"text": "Let’s update the alive field value to True. The HTTPie command is:"
},
{
"code": null,
"e": 19001,
"s": 18954,
"text": "http PATCH :8000/transformers/10/ alive=”True”"
},
{
"code": null,
"e": 19008,
"s": 19001,
"text": "Output"
},
{
"code": null,
"e": 19473,
"s": 19008,
"text": "HTTP/1.1 200 OK\nAllow: PATCH, PUT, DELETE, OPTIONS, GET\nContent-Length: 148\nContent-Type: application/json\nDate: Mon, 25 Jan 2021 16:22:35 GMT\nReferrer-Policy: same-origin\nServer: WSGIServer/0.2 CPython/3.7.5\nVary: Accept, Cookie\nX-Content-Type-Options: nosniff\nX-Frame-Options: DENY\n\n{\n \"alive\": true,\n \"alternate_mode\": \"1979 Nissan 280ZX Police Car\",\n \"description\": \"Strives to find reason and logic in everything\",\n \"id\": 10,\n \"name\": \"Prowl\"\n}"
},
{
"code": null,
"e": 19511,
"s": 19473,
"text": "Sharing the command prompt screenshot"
},
{
"code": null,
"e": 19566,
"s": 19511,
"text": "Let’s retrieve all the entries. The HTTPie command is:"
},
{
"code": null,
"e": 19595,
"s": 19566,
"text": "http GET :8000/transformers/"
},
{
"code": null,
"e": 19602,
"s": 19595,
"text": "Output"
},
{
"code": null,
"e": 20914,
"s": 19602,
"text": "HTTP/1.1 200 OK\nAllow: GET, POST, OPTIONS\nContent-Length: 739\nContent-Type: application/json\nDate: Mon, 25 Jan 2021 16:23:52 GMT\nReferrer-Policy: same-origin\nServer: WSGIServer/0.2 CPython/3.7.5\nVary: Accept, Cookie\nX-Content-Type-Options: nosniff\nX-Frame-Options: DENY\n\n[\n {\n \"alive\": true,\n \"alternate_mode\": \"1979 Nissan 280ZX Police Car\",\n \"description\": \"Strives to find reason and logic in everything\",\n \"id\": 10,\n \"name\": \"Prowl\"\n },\n {\n \"alive\": true,\n \"alternate_mode\": \"1977 Lancia Stratos Turbo\",\n \"description\": \"Always inventing new weapons and gadgets\",\n \"id\": 7,\n \"name\": \"Wheeljack\"\n },\n {\n \"alive\": true,\n \"alternate_mode\": \"1979 Porsche 924\",\n \"description\": \"Eager and Daring\",\n \"id\": 5,\n \"name\": \"Cliffjumper\"\n },\n {\n \"alive\": true,\n \"alternate_mode\": \"1979 VW Beetle\",\n \"description\": \"Small, eager, and brave. Acts as a messenger, scout, and spy\",\n \"id\": 3,\n \"name\": \"Bumblebee\"\n },\n {\n \"alive\": false,\n \"alternate_mode\": \"1979 Freightliner Semi\",\n \"description\": \"Optimus Prime is the strongest and most courageous and leader of all Autobots\",\n \"id\": 1,\n \"name\": \"Optimus Prime\"\n }\n]"
},
{
"code": null,
"e": 20952,
"s": 20914,
"text": "Sharing the command prompt screenshot"
},
{
"code": null,
"e": 21293,
"s": 20952,
"text": "In this section, we understood how to code Django views to process HTTP Request and returns HTTP Response. We also realized the importance of wrapping our views with the @api_view decorator. Finally, we composed and sent different requests including the OPTIONS HTTP request, which displays the supported HTTP verbs, parsers, and renderers."
},
{
"code": null,
"e": 21305,
"s": 21293,
"text": "Django-REST"
},
{
"code": null,
"e": 21318,
"s": 21305,
"text": "Django-views"
},
{
"code": null,
"e": 21332,
"s": 21318,
"text": "Python Django"
},
{
"code": null,
"e": 21339,
"s": 21332,
"text": "Python"
},
{
"code": null,
"e": 21437,
"s": 21339,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 21469,
"s": 21437,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 21496,
"s": 21469,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 21517,
"s": 21496,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 21540,
"s": 21517,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 21571,
"s": 21540,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 21627,
"s": 21571,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 21669,
"s": 21627,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 21711,
"s": 21669,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 21750,
"s": 21711,
"text": "Python | Get unique values from a list"
}
] |
<mat-radio-button> in Angular Material - GeeksforGeeks
|
06 Oct, 2021
Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it. <mat-radio-button> is used to select one option when we have multiple options.
Installation syntax:
ng add @angular/material
Approach:
First, install the angular material using the above-mentioned command.
After completing the installation, Import ‘MatRadioModule’ from ‘@angular/material/radio’ in the app.module.ts file.
Then we need to use the <mat-radio-button> tag for displaying the radio button.
We can also disable the radio button by using the disabled input property.
If we want to change the theme then we can change it by using the color property. In angular we have 3 themes, they are primary, accent, and warn.
Once done with the above steps then serve or start the project.
Project Structure: It will look like the following:
Filename: app.module.ts
Javascript
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms'; import { MatRadioModule } from '@angular/material/radio';import { AppComponent } from './app.component';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; @NgModule({ imports: [ BrowserModule, FormsModule, MatRadioModule, BrowserAnimationsModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ]}) export class AppModule { }
Filename: app.component.html
HTML
<h3> Radio buttons in Angular material </h3> <mat-radio-button value="1" color="primary"> Primary Theme radio button</mat-radio-button><br><br> <mat-radio-button value="2" color="warn"> Warn Theme Radio button</mat-radio-button><br><br> <mat-radio-button value="3" color="accent"> Accent Theme Radio button</mat-radio-button> <br><br> <mat-radio-button value="4" color="accent" disabled> Disabled Radio Button</mat-radio-button>
Output:
prachisoda1234
Angular-material
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular PrimeNG Messages Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 26464,
"s": 26436,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 26836,
"s": 26464,
"text": "Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it. <mat-radio-button> is used to select one option when we have multiple options."
},
{
"code": null,
"e": 26857,
"s": 26836,
"text": "Installation syntax:"
},
{
"code": null,
"e": 26882,
"s": 26857,
"text": "ng add @angular/material"
},
{
"code": null,
"e": 26892,
"s": 26882,
"text": "Approach:"
},
{
"code": null,
"e": 26963,
"s": 26892,
"text": "First, install the angular material using the above-mentioned command."
},
{
"code": null,
"e": 27080,
"s": 26963,
"text": "After completing the installation, Import ‘MatRadioModule’ from ‘@angular/material/radio’ in the app.module.ts file."
},
{
"code": null,
"e": 27160,
"s": 27080,
"text": "Then we need to use the <mat-radio-button> tag for displaying the radio button."
},
{
"code": null,
"e": 27235,
"s": 27160,
"text": "We can also disable the radio button by using the disabled input property."
},
{
"code": null,
"e": 27382,
"s": 27235,
"text": "If we want to change the theme then we can change it by using the color property. In angular we have 3 themes, they are primary, accent, and warn."
},
{
"code": null,
"e": 27446,
"s": 27382,
"text": "Once done with the above steps then serve or start the project."
},
{
"code": null,
"e": 27498,
"s": 27446,
"text": "Project Structure: It will look like the following:"
},
{
"code": null,
"e": 27522,
"s": 27498,
"text": "Filename: app.module.ts"
},
{
"code": null,
"e": 27533,
"s": 27522,
"text": "Javascript"
},
{
"code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms'; import { MatRadioModule } from '@angular/material/radio';import { AppComponent } from './app.component';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; @NgModule({ imports: [ BrowserModule, FormsModule, MatRadioModule, BrowserAnimationsModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ]}) export class AppModule { }",
"e": 28062,
"s": 27533,
"text": null
},
{
"code": null,
"e": 28091,
"s": 28062,
"text": "Filename: app.component.html"
},
{
"code": null,
"e": 28096,
"s": 28091,
"text": "HTML"
},
{
"code": "<h3> Radio buttons in Angular material </h3> <mat-radio-button value=\"1\" color=\"primary\"> Primary Theme radio button</mat-radio-button><br><br> <mat-radio-button value=\"2\" color=\"warn\"> Warn Theme Radio button</mat-radio-button><br><br> <mat-radio-button value=\"3\" color=\"accent\"> Accent Theme Radio button</mat-radio-button> <br><br> <mat-radio-button value=\"4\" color=\"accent\" disabled> Disabled Radio Button</mat-radio-button>",
"e": 28529,
"s": 28096,
"text": null
},
{
"code": null,
"e": 28537,
"s": 28529,
"text": "Output:"
},
{
"code": null,
"e": 28554,
"s": 28539,
"text": "prachisoda1234"
},
{
"code": null,
"e": 28571,
"s": 28554,
"text": "Angular-material"
},
{
"code": null,
"e": 28581,
"s": 28571,
"text": "AngularJS"
},
{
"code": null,
"e": 28598,
"s": 28581,
"text": "Web Technologies"
},
{
"code": null,
"e": 28696,
"s": 28598,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28731,
"s": 28696,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 28766,
"s": 28731,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 28801,
"s": 28766,
"text": "Angular PrimeNG Messages Component"
},
{
"code": null,
"e": 28825,
"s": 28801,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 28878,
"s": 28825,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 28918,
"s": 28878,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28951,
"s": 28918,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28996,
"s": 28951,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29039,
"s": 28996,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Ten awesome R Markdown tricks. R Markdown is more versatile than you... | by Keith McNulty | Towards Data Science
|
Though I code in both R and Python, R Markdown is my only route for writing reports, blogs or books. It is incredibly flexible, has many beautiful design options and supports many output formats really nicely.
If you have never worked in R Markdown, I highly recommend it. If you have worked in it before, here are ten little tricks I’ve learned which have served me well in numerous projects, and which highlight how flexible it is.
So you write a lovely R Markdown document where you’ve analyzed a whole bunch of facts about dogs. And then you get told — ‘nah, I’m more interested in cats’. Never fear. You can automate a similar report about cats in just one command if you parameterize your R markdown document.
You can do this by defining parameters in the YAML header of your R Markdown document, and giving each parameter a value. For example:
---title: "Animal Analysis"author: "Keith McNulty"date: "18 December 2020"output: html_document: code_folding: "hide"params: animal_name: value: Dog choices: - Dog - Cat - Rabbit years_of_study: input: slider min: 2000 max: 2019 step: 1 round: 1 sep: '' value: [2010, 2017]---
Now you can write these variables into the R code in your document as params$animal_name and params$years_of_study. If you knit your document as normal, it will knit with the default values of these parameters as per the value variable. However, if you knit with parameters by selecting this option in RStudio’s Knit dropdown (or by using knit_with_parameters()), a lovely menu option appears for you to select your parameters before you knit the document. Awesome! More instructions here.
xaringan is an R package that uses R markdown to create pretty, professional slide presentations that look neat but also print well (not something you can take for granted with web slides).
It’s easy to customize thexaringan layout, highlight code and output, insert graphics, code and all the other good things that you’d expect to do in R Markdown. Here is an example of a recent training presentation I created with xaringan and a link to its Github code. More on xaringan here.
You don’t have to embed R code in R Markdown. It accepts and runs a wide range of languages. In particular you can run Python code and even use Python outputs in later R code.
To run Python code inside R Markdown, you need to have the reticulate package installed make sure that your session is pointing to a Python environment that has all of the packages you need. One way to do this is to set the RETICULATE_PYTHON environment variable to the path to the python executable in the conda environment or virtualenv that you want to work. You can do this by adding this to a .Rprofile file which will run every time you launch your project.
Sys.setenv(RETICULATE_PYTHON = "path_to_env/bin/python3")
Then, to write and execute Python code you just need to wrap it as follows:
```{python}# write python code```
You can see an example in action in the Python section of my book here, and if you follow the links to the source you can see the code behind it.
prettydoc is a package by Yixuan Qiu which offers a simple set of themes to create a different, prettier look and feel to your RMarkdown documents. This is super helpful when you just want to jazz up your documents a little but don’t have time to get into the styling of them yourself.
It’s really easy to use. Simple edits to the YAML header of your document can invoke a specific style theme throughout the document, with numerous themes available. For example, this will invoke a lovely clean blue coloring and style across titles, tables, embedded code and graphics:
---title: "My doc"author: "Me"date: June 3, 2019output: prettydoc::html_pretty: theme: architect highlight: github---
More on prettydoc here.
RMarkdown is a great way to record your work, allowing you to write a narrative and capture your code all in one place. But sometimes your code can be overwhelming and not particularly pleasant for non-coders who are trying to read just the narrative of your work and are not interested in the intricacies of how you conducted the analysis.
Previously the only options we had were to either set echo = TRUE or echo = FALSE in our knitr options to either show our code in the document or not. But now we can set an option in the YAML header that gives us the best of both worlds. Setting code_folding: hide in the YAML header will hide the code chunks by default, but provide little click-down boxes in the document so that the reader can view all the code, or particular chunks, as and when they want to, like this:
Maybe you want to write a technical book, or maybe your paper/write-up is so big that you need to split it into chapters. bookdown is an R package which allows you to construct a book structure to your output. You can write your chapters in separate R Markdown files headed with # level headings. You can employ an easy reference format to reference a bibliography or other other sections, chapters, figures or tables. You can then render the entire book in some neat HTML formats like Gitbook or Bootstrap, or you can render it as a pdf or epub format. Here’s an example of a recent book I wrote in Gitbook and in Bootstrap 4 (development version of bookdown). More on bookdown here.
It’s a really effective teaching tool to allow your readers to interact with your data or graphics as part of your R markdown documents. Personally I love plotly for generating interactive graphics in 2D and 3D. You can insert plotly code into a code chunk in an R Markdown document (it can be coded in R or Python — see Point 3), and this will generate a beautiful graphic that the reader can interact with to see data points, rotate, or whatever. Here’s an example. More on plotly here.
If you want to generate your document or book in multiple formats — like in HTML and PDF — you might need to adjust your output for each. For example, you can’t put the interactive graphic above in a PDF. But you also don’t want to be managing multiple versions of the same source files for the different outputs.
It’s easy to make the code in your code chunks conditional on the output format. For example, if you want to use a static graphic for PDF and an interactive graphic for HTML, this will work in your code chunk:
if (knitr::is_latex_output()) { # insert code for static graphic} else { # insert code for interactive graphic}
If you have to put math in R Markdown you can use LaTeX math notation. You’ll need to install LaTeX, and the best way to do that is to install the tinytex package (this is an easier and much smaller installation than the full LaTeX installation which is about 5 Gigabytes!!!). You can write math inline by placing it between $ symbols. If you want the math in its own section you can place it between $$ symbols in a new paragraph. If you know LaTeX, you can take advantage of all its features inside the $$ symbols. Here’s an excellent guide to LaTeX, and here is an example of some beautifully aligned math derivations:
If you are putting multiple ggplots together, the patchwork package uses an intuitive and simple grammar so that you don't have to use more complicated functions like grid.arrange(). It also has more capabilities than cowplot to handle complex layouts.
With each plot assigned to an object, you can use characters like | and / to specify what you want aligned in columns and what you want in rows, and the package will do the alignment for you. Here's an example from the package Github repo using mtcars:
library(ggplot2)library(patchwork)p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))p3 <- ggplot(mtcars) + geom_smooth(aes(disp, qsec)) p4 <- ggplot(mtcars) + geom_bar(aes(carb)) (p1 | p2 | p3) / p4
I hope these little examples help you see how amazingly versatile R Markdown is. There is a wide and growing range of output formats and designs, and an increasingly flexible codebase to help you tailor your documents to achieve the precise look and content you want. Increasingly, also, R Markdown is the basic building block of other publishing tools like bookdown and blogdown. If you haven’t used R Markdown yet, here is a great starting point.
Originally I was a Pure Mathematician, then I became a Psychometrician and a Data Scientist. I am passionate about applying the rigor of all those disciplines to complex people questions. I’m also a coding geek and a massive fan of Japanese RPGs. Find me on LinkedIn or on Twitter. Also check out my blog on drkeithmcnulty.com.
|
[
{
"code": null,
"e": 382,
"s": 172,
"text": "Though I code in both R and Python, R Markdown is my only route for writing reports, blogs or books. It is incredibly flexible, has many beautiful design options and supports many output formats really nicely."
},
{
"code": null,
"e": 606,
"s": 382,
"text": "If you have never worked in R Markdown, I highly recommend it. If you have worked in it before, here are ten little tricks I’ve learned which have served me well in numerous projects, and which highlight how flexible it is."
},
{
"code": null,
"e": 888,
"s": 606,
"text": "So you write a lovely R Markdown document where you’ve analyzed a whole bunch of facts about dogs. And then you get told — ‘nah, I’m more interested in cats’. Never fear. You can automate a similar report about cats in just one command if you parameterize your R markdown document."
},
{
"code": null,
"e": 1023,
"s": 888,
"text": "You can do this by defining parameters in the YAML header of your R Markdown document, and giving each parameter a value. For example:"
},
{
"code": null,
"e": 1348,
"s": 1023,
"text": "---title: \"Animal Analysis\"author: \"Keith McNulty\"date: \"18 December 2020\"output: html_document: code_folding: \"hide\"params: animal_name: value: Dog choices: - Dog - Cat - Rabbit years_of_study: input: slider min: 2000 max: 2019 step: 1 round: 1 sep: '' value: [2010, 2017]---"
},
{
"code": null,
"e": 1838,
"s": 1348,
"text": "Now you can write these variables into the R code in your document as params$animal_name and params$years_of_study. If you knit your document as normal, it will knit with the default values of these parameters as per the value variable. However, if you knit with parameters by selecting this option in RStudio’s Knit dropdown (or by using knit_with_parameters()), a lovely menu option appears for you to select your parameters before you knit the document. Awesome! More instructions here."
},
{
"code": null,
"e": 2028,
"s": 1838,
"text": "xaringan is an R package that uses R markdown to create pretty, professional slide presentations that look neat but also print well (not something you can take for granted with web slides)."
},
{
"code": null,
"e": 2320,
"s": 2028,
"text": "It’s easy to customize thexaringan layout, highlight code and output, insert graphics, code and all the other good things that you’d expect to do in R Markdown. Here is an example of a recent training presentation I created with xaringan and a link to its Github code. More on xaringan here."
},
{
"code": null,
"e": 2496,
"s": 2320,
"text": "You don’t have to embed R code in R Markdown. It accepts and runs a wide range of languages. In particular you can run Python code and even use Python outputs in later R code."
},
{
"code": null,
"e": 2960,
"s": 2496,
"text": "To run Python code inside R Markdown, you need to have the reticulate package installed make sure that your session is pointing to a Python environment that has all of the packages you need. One way to do this is to set the RETICULATE_PYTHON environment variable to the path to the python executable in the conda environment or virtualenv that you want to work. You can do this by adding this to a .Rprofile file which will run every time you launch your project."
},
{
"code": null,
"e": 3018,
"s": 2960,
"text": "Sys.setenv(RETICULATE_PYTHON = \"path_to_env/bin/python3\")"
},
{
"code": null,
"e": 3094,
"s": 3018,
"text": "Then, to write and execute Python code you just need to wrap it as follows:"
},
{
"code": null,
"e": 3128,
"s": 3094,
"text": "```{python}# write python code```"
},
{
"code": null,
"e": 3274,
"s": 3128,
"text": "You can see an example in action in the Python section of my book here, and if you follow the links to the source you can see the code behind it."
},
{
"code": null,
"e": 3560,
"s": 3274,
"text": "prettydoc is a package by Yixuan Qiu which offers a simple set of themes to create a different, prettier look and feel to your RMarkdown documents. This is super helpful when you just want to jazz up your documents a little but don’t have time to get into the styling of them yourself."
},
{
"code": null,
"e": 3845,
"s": 3560,
"text": "It’s really easy to use. Simple edits to the YAML header of your document can invoke a specific style theme throughout the document, with numerous themes available. For example, this will invoke a lovely clean blue coloring and style across titles, tables, embedded code and graphics:"
},
{
"code": null,
"e": 3970,
"s": 3845,
"text": "---title: \"My doc\"author: \"Me\"date: June 3, 2019output: prettydoc::html_pretty: theme: architect highlight: github---"
},
{
"code": null,
"e": 3994,
"s": 3970,
"text": "More on prettydoc here."
},
{
"code": null,
"e": 4335,
"s": 3994,
"text": "RMarkdown is a great way to record your work, allowing you to write a narrative and capture your code all in one place. But sometimes your code can be overwhelming and not particularly pleasant for non-coders who are trying to read just the narrative of your work and are not interested in the intricacies of how you conducted the analysis."
},
{
"code": null,
"e": 4810,
"s": 4335,
"text": "Previously the only options we had were to either set echo = TRUE or echo = FALSE in our knitr options to either show our code in the document or not. But now we can set an option in the YAML header that gives us the best of both worlds. Setting code_folding: hide in the YAML header will hide the code chunks by default, but provide little click-down boxes in the document so that the reader can view all the code, or particular chunks, as and when they want to, like this:"
},
{
"code": null,
"e": 5495,
"s": 4810,
"text": "Maybe you want to write a technical book, or maybe your paper/write-up is so big that you need to split it into chapters. bookdown is an R package which allows you to construct a book structure to your output. You can write your chapters in separate R Markdown files headed with # level headings. You can employ an easy reference format to reference a bibliography or other other sections, chapters, figures or tables. You can then render the entire book in some neat HTML formats like Gitbook or Bootstrap, or you can render it as a pdf or epub format. Here’s an example of a recent book I wrote in Gitbook and in Bootstrap 4 (development version of bookdown). More on bookdown here."
},
{
"code": null,
"e": 5984,
"s": 5495,
"text": "It’s a really effective teaching tool to allow your readers to interact with your data or graphics as part of your R markdown documents. Personally I love plotly for generating interactive graphics in 2D and 3D. You can insert plotly code into a code chunk in an R Markdown document (it can be coded in R or Python — see Point 3), and this will generate a beautiful graphic that the reader can interact with to see data points, rotate, or whatever. Here’s an example. More on plotly here."
},
{
"code": null,
"e": 6298,
"s": 5984,
"text": "If you want to generate your document or book in multiple formats — like in HTML and PDF — you might need to adjust your output for each. For example, you can’t put the interactive graphic above in a PDF. But you also don’t want to be managing multiple versions of the same source files for the different outputs."
},
{
"code": null,
"e": 6508,
"s": 6298,
"text": "It’s easy to make the code in your code chunks conditional on the output format. For example, if you want to use a static graphic for PDF and an interactive graphic for HTML, this will work in your code chunk:"
},
{
"code": null,
"e": 6622,
"s": 6508,
"text": "if (knitr::is_latex_output()) { # insert code for static graphic} else { # insert code for interactive graphic}"
},
{
"code": null,
"e": 7244,
"s": 6622,
"text": "If you have to put math in R Markdown you can use LaTeX math notation. You’ll need to install LaTeX, and the best way to do that is to install the tinytex package (this is an easier and much smaller installation than the full LaTeX installation which is about 5 Gigabytes!!!). You can write math inline by placing it between $ symbols. If you want the math in its own section you can place it between $$ symbols in a new paragraph. If you know LaTeX, you can take advantage of all its features inside the $$ symbols. Here’s an excellent guide to LaTeX, and here is an example of some beautifully aligned math derivations:"
},
{
"code": null,
"e": 7497,
"s": 7244,
"text": "If you are putting multiple ggplots together, the patchwork package uses an intuitive and simple grammar so that you don't have to use more complicated functions like grid.arrange(). It also has more capabilities than cowplot to handle complex layouts."
},
{
"code": null,
"e": 7750,
"s": 7497,
"text": "With each plot assigned to an object, you can use characters like | and / to specify what you want aligned in columns and what you want in rows, and the package will do the alignment for you. Here's an example from the package Github repo using mtcars:"
},
{
"code": null,
"e": 8020,
"s": 7750,
"text": "library(ggplot2)library(patchwork)p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))p3 <- ggplot(mtcars) + geom_smooth(aes(disp, qsec)) p4 <- ggplot(mtcars) + geom_bar(aes(carb)) (p1 | p2 | p3) / p4"
},
{
"code": null,
"e": 8469,
"s": 8020,
"text": "I hope these little examples help you see how amazingly versatile R Markdown is. There is a wide and growing range of output formats and designs, and an increasingly flexible codebase to help you tailor your documents to achieve the precise look and content you want. Increasingly, also, R Markdown is the basic building block of other publishing tools like bookdown and blogdown. If you haven’t used R Markdown yet, here is a great starting point."
}
] |
Dealing with Apply functions in R | by vikashraj luhaniwal | Towards Data Science
|
Iterative control structures (loops like for, while, repeat, etc.) allow repetition of instructions for several numbers of times. However, at large scale data processing usage of these loops can consume more time and space. R language has a more efficient and quick approach to perform iterations with the help of Apply functions.
In this post, I am going to discuss the efficiency of apply functions over loops from a visual perspective and then further members of apply family.
Before proceeding further with apply functions let us first see how code execution takes less time for iterations using apply functions compared to basic loops.
Consider the FARS(Fatality Analysis Recording System) dataset available in gamclass package of R. It contains 151158 observations of 17 different features. The dataset includes every accident in which there was at least one fatality and the data is limited to vehicles where the front seat passenger seat was occupied.
Now let us assume we want to calculate the mean of age column. This can be done using traditional loops and also using apply functions.
Method 1: Using for loop
library("gamclass")data(FARS)mean_age <- NULLtotal <- NULLfor(i in 1:length(FARS$age)){ total <- sum(total, FARS$age[i]) }mean_age <- total/length(FARS$age)mean_age
Method 2: Using apply() function
apply(FARS[3],2, mean)
Now let us compare both the approaches through visual mode with the help of Profvis package.
Profvis is a code-profiling tool, which provides an interactive graphical interface for visualizing the memory and time consumption of instructions throughout the execution.
To make use of profvis, enclose the instructions in profvis(), it opens an interactive profile visualizer in a new tab inside R studio.
#for method 1profvis({mean_age <- NULLtotal <- NULLfor(i in 1:length(FARS$age)){ total <- sum(total, FARS$age[i]) }mean_age <- total/length(FARS$age)mean_age})
Output using method 1
Under Flame Graph tab we can inspect the time taken (in ms) by the instructions.
#for method 2profvis({ apply(FARS[3],2, mean)})
Output using method 2
Here, one can easily notice that the time taken using method 1 is almost 1990 ms (1960 +30) whereas for method 2 it is only 20 ms. So this is the actual power of apply() functions in terms of time consumption.
Much more efficient and faster in execution.Easy to follow syntax (rather than writing a block of instructions only one line of code using apply functions)
Much more efficient and faster in execution.
Easy to follow syntax (rather than writing a block of instructions only one line of code using apply functions)
Apply family contains various flavored functions which are applicable to different data structures like list, matrix, array, data frame etc. The members of the apply family are apply(), lapply(), sapply(), tapply(), mapply() etc. These functions are substitutes/alternatives to loops.
Each of the apply functions requires a minimum of two arguments: an object and another function. The function can be any inbuilt (like mean, sum, max etc.) or user-defined function.
The syntax of apply() is as follows
where X is an input data object, MARGIN indicates how the function is applicable whether row-wise or column-wise, margin = 1 indicates row-wise and margin = 2 indicates column-wise, FUN points to an inbuilt or user-defined function.
The output object type depends on the input object and the function specified. apply() can return a vector, list, matrix or array for different input objects as mentioned in the below table.
#---------- apply() function ---------- #case 1. matrix as an input argumentm1 <- matrix(1:9, nrow =3)m1result <- apply(m1,1,mean) #mean of elements for each rowresultclass(result) #class is a vectorresult <- apply(m1,2,sum) #sum of elements for each columnresultclass(result) #class is a vectorresult <- apply(m1,1,cumsum) #cumulative sum of elements for each rowresult #by default column-wise orderclass(result) #class is a matrixmatrix(apply(m1,1,cumsum), nrow = 3, byrow = T) #for row-wise order #user defined function check<-function(x){ return(x[x>5])}result <- apply(m1,1,check) #user defined function as an argumentresultclass(result) #class is a list#case 2. data frame as an inputratings <- c(4.2, 4.4, 3.4, 3.9, 5, 4.1, 3.2, 3.9, 4.6, 4.8, 5, 4, 4.5, 3.9, 4.7, 3.6)employee.mat <- matrix(ratings,byrow=TRUE,nrow=4,dimnames = list(c("Quarter1","Quarter2","Quarter3","Quarter4"),c("Hari","Shri","John","Albert")))employee <- as.data.frame(employee.mat)employeeresult <- apply(employee,2,sum) #sum of elements for each columnresultclass(result) #class is a vectorresult <- apply(employee,1,cumsum) #cumulative sum of elements for each rowresult #by default column-wise orderclass(result) #class is a matrix#user defined function check<-function(x){ return(x[x>4.2])}result <- apply(employee,2,check) #user defined function as an argumentresultclass(result) #class is a list
lapply() always returns a list, ‘l’ in lapply() refers to ‘list’. lapply() deals with list and data frames in the input. MARGIN argument is not required here, the specified function is applicable only through columns. Refer to the below table for input objects and the corresponding output objects.
#---------- lapply() function ---------- #case 1. vector as an input argumentresult <- lapply(ratings,mean)resultclass(result) #class is a list#case 2. list as an input argumentlist1<-list(maths=c(64,45,89,67),english=c(79,84,62,80),physics=c(68,72,69,80),chemistry = c(99,91,84,89))list1result <- lapply(list1,mean)resultclass(result) #class is a list#user defined functioncheck<-function(x){ return(x[x>75])}result <- lapply(list1,check) #user defined function as an argumentresultclass(result) #class is a list#case 3. dataframe as an input argumentresult <- lapply(employee,sum) #sum of elements for each columnresultclass(result) #class is a listresult <- lapply(employee,cumsum) #cumulative sum of elements for each rowresult class(result) #class is a list#user defined function check<-function(x){ return(x[x>4.2])}result <- lapply(employee,check) #user defined function as an argumentresultclass(result) #class is a list
apply() vs. lapply()
lapply() always returns a list whereas apply() can return a vector, list, matrix or array.
No scope of MARGIN in lapply().
sapply() is a simplified form of lapply(). It has one additional argument simplify with default value as true, if simplify = F then sapply() returns a list similar to lapply(), otherwise, it returns the simplest output form possible.
Refer to the below table for input objects and the corresponding output objects.
#---------- sapply() function ---------- #case 1. vector as an input argumentresult <- sapply(ratings,mean)resultclass(result) #class is a vectorresult <- sapply(ratings,mean, simplify = FALSE)result class(result) #class is a listresult <- sapply(ratings,range)resultclass(result) #class is a matrix#case 2. list as an input argumentresult <- sapply(list1,mean)resultclass(result) #class is a vectorresult <- sapply(list1,range)resultclass(result) #class is a matrix#user defined functioncheck<-function(x){ return(x[x>75])}result <- sapply(list1,check) #user defined function as an argumentresultclass(result) #class is a list#case 3. dataframe as an input argumentresult <- sapply(employee,mean)resultclass(result) #class is a vectorresult <- sapply(employee,range)resultclass(result) #class is a matrix#user defined functioncheck<-function(x){ return(x[x>4])}result <- sapply(employee,check) #user defined function as an argumentresultclass(result) #class is a list
tapply() is helpful while dealing with categorical variables, it applies a function to numeric data distributed across various categories. The simplest form of tapply() can be understood as
tapply(column 1, column 2, FUN)
where column 1 is the numeric column on which function is applied, column 2 is a factor object and FUN is for the function to be performed.
#---------- tapply() function ---------- salary <- c(21000,29000,32000,34000,45000)designation<-c("Programmer","Senior Programmer","Senior Programmer","Senior Programmer","Manager")gender <- c("M","F","F","M","M")result <- tapply(salary,designation,mean)resultclass(result) #class is an arrayresult <- tapply(salary,list(designation,gender),mean)resultclass(result) #class is a matrix
by() does a similar job to tapply() i.e. it applies an operation to numeric vector values distributed across various categories. by() is a wrapper function of tapply().
#---------- by() function ---------- result <- by(salary,designation,mean)resultclass(result) #class is of "by" typeresult[2] #accessing as a vector elementas.list(result) #converting into a listresult <- by(salary,list(designation,gender),mean)resultclass(result) #class is of "by" typelibrary("gamclass")data("FARS")by(FARS[2:4], FARS$airbagAvail, colMeans)
The ‘m’ in mapply() refers to ‘multivariate’. It applies the specified functions to the arguments one by one. Note that here function is specified as the first argument whereas in other apply functions as the third argument.
#---------- mapply() function ---------- result <- mapply(rep, 1:4, 4:1)resultclass(result) #class is a listresult <- mapply(rep, 1:4, 4:4)class(result) #class is a matrix
Conclusion
I believe I have covered all the most useful and popular apply functions with all possible combinations of input objects. If you think something is missing or more inputs are required. Let me know in the comments and I’ll add it in!
|
[
{
"code": null,
"e": 503,
"s": 172,
"text": "Iterative control structures (loops like for, while, repeat, etc.) allow repetition of instructions for several numbers of times. However, at large scale data processing usage of these loops can consume more time and space. R language has a more efficient and quick approach to perform iterations with the help of Apply functions."
},
{
"code": null,
"e": 652,
"s": 503,
"text": "In this post, I am going to discuss the efficiency of apply functions over loops from a visual perspective and then further members of apply family."
},
{
"code": null,
"e": 813,
"s": 652,
"text": "Before proceeding further with apply functions let us first see how code execution takes less time for iterations using apply functions compared to basic loops."
},
{
"code": null,
"e": 1132,
"s": 813,
"text": "Consider the FARS(Fatality Analysis Recording System) dataset available in gamclass package of R. It contains 151158 observations of 17 different features. The dataset includes every accident in which there was at least one fatality and the data is limited to vehicles where the front seat passenger seat was occupied."
},
{
"code": null,
"e": 1268,
"s": 1132,
"text": "Now let us assume we want to calculate the mean of age column. This can be done using traditional loops and also using apply functions."
},
{
"code": null,
"e": 1293,
"s": 1268,
"text": "Method 1: Using for loop"
},
{
"code": null,
"e": 1459,
"s": 1293,
"text": "library(\"gamclass\")data(FARS)mean_age <- NULLtotal <- NULLfor(i in 1:length(FARS$age)){ total <- sum(total, FARS$age[i]) }mean_age <- total/length(FARS$age)mean_age"
},
{
"code": null,
"e": 1492,
"s": 1459,
"text": "Method 2: Using apply() function"
},
{
"code": null,
"e": 1515,
"s": 1492,
"text": "apply(FARS[3],2, mean)"
},
{
"code": null,
"e": 1608,
"s": 1515,
"text": "Now let us compare both the approaches through visual mode with the help of Profvis package."
},
{
"code": null,
"e": 1782,
"s": 1608,
"text": "Profvis is a code-profiling tool, which provides an interactive graphical interface for visualizing the memory and time consumption of instructions throughout the execution."
},
{
"code": null,
"e": 1918,
"s": 1782,
"text": "To make use of profvis, enclose the instructions in profvis(), it opens an interactive profile visualizer in a new tab inside R studio."
},
{
"code": null,
"e": 2079,
"s": 1918,
"text": "#for method 1profvis({mean_age <- NULLtotal <- NULLfor(i in 1:length(FARS$age)){ total <- sum(total, FARS$age[i]) }mean_age <- total/length(FARS$age)mean_age})"
},
{
"code": null,
"e": 2101,
"s": 2079,
"text": "Output using method 1"
},
{
"code": null,
"e": 2182,
"s": 2101,
"text": "Under Flame Graph tab we can inspect the time taken (in ms) by the instructions."
},
{
"code": null,
"e": 2231,
"s": 2182,
"text": "#for method 2profvis({ apply(FARS[3],2, mean)})"
},
{
"code": null,
"e": 2253,
"s": 2231,
"text": "Output using method 2"
},
{
"code": null,
"e": 2463,
"s": 2253,
"text": "Here, one can easily notice that the time taken using method 1 is almost 1990 ms (1960 +30) whereas for method 2 it is only 20 ms. So this is the actual power of apply() functions in terms of time consumption."
},
{
"code": null,
"e": 2619,
"s": 2463,
"text": "Much more efficient and faster in execution.Easy to follow syntax (rather than writing a block of instructions only one line of code using apply functions)"
},
{
"code": null,
"e": 2664,
"s": 2619,
"text": "Much more efficient and faster in execution."
},
{
"code": null,
"e": 2776,
"s": 2664,
"text": "Easy to follow syntax (rather than writing a block of instructions only one line of code using apply functions)"
},
{
"code": null,
"e": 3061,
"s": 2776,
"text": "Apply family contains various flavored functions which are applicable to different data structures like list, matrix, array, data frame etc. The members of the apply family are apply(), lapply(), sapply(), tapply(), mapply() etc. These functions are substitutes/alternatives to loops."
},
{
"code": null,
"e": 3243,
"s": 3061,
"text": "Each of the apply functions requires a minimum of two arguments: an object and another function. The function can be any inbuilt (like mean, sum, max etc.) or user-defined function."
},
{
"code": null,
"e": 3279,
"s": 3243,
"text": "The syntax of apply() is as follows"
},
{
"code": null,
"e": 3512,
"s": 3279,
"text": "where X is an input data object, MARGIN indicates how the function is applicable whether row-wise or column-wise, margin = 1 indicates row-wise and margin = 2 indicates column-wise, FUN points to an inbuilt or user-defined function."
},
{
"code": null,
"e": 3703,
"s": 3512,
"text": "The output object type depends on the input object and the function specified. apply() can return a vector, list, matrix or array for different input objects as mentioned in the below table."
},
{
"code": null,
"e": 5277,
"s": 3703,
"text": "#---------- apply() function ---------- #case 1. matrix as an input argumentm1 <- matrix(1:9, nrow =3)m1result <- apply(m1,1,mean) #mean of elements for each rowresultclass(result) #class is a vectorresult <- apply(m1,2,sum) #sum of elements for each columnresultclass(result) #class is a vectorresult <- apply(m1,1,cumsum) #cumulative sum of elements for each rowresult #by default column-wise orderclass(result) #class is a matrixmatrix(apply(m1,1,cumsum), nrow = 3, byrow = T) #for row-wise order #user defined function check<-function(x){ return(x[x>5])}result <- apply(m1,1,check) #user defined function as an argumentresultclass(result) #class is a list#case 2. data frame as an inputratings <- c(4.2, 4.4, 3.4, 3.9, 5, 4.1, 3.2, 3.9, 4.6, 4.8, 5, 4, 4.5, 3.9, 4.7, 3.6)employee.mat <- matrix(ratings,byrow=TRUE,nrow=4,dimnames = list(c(\"Quarter1\",\"Quarter2\",\"Quarter3\",\"Quarter4\"),c(\"Hari\",\"Shri\",\"John\",\"Albert\")))employee <- as.data.frame(employee.mat)employeeresult <- apply(employee,2,sum) #sum of elements for each columnresultclass(result) #class is a vectorresult <- apply(employee,1,cumsum) #cumulative sum of elements for each rowresult #by default column-wise orderclass(result) #class is a matrix#user defined function check<-function(x){ return(x[x>4.2])}result <- apply(employee,2,check) #user defined function as an argumentresultclass(result) #class is a list"
},
{
"code": null,
"e": 5576,
"s": 5277,
"text": "lapply() always returns a list, ‘l’ in lapply() refers to ‘list’. lapply() deals with list and data frames in the input. MARGIN argument is not required here, the specified function is applicable only through columns. Refer to the below table for input objects and the corresponding output objects."
},
{
"code": null,
"e": 6680,
"s": 5576,
"text": "#---------- lapply() function ---------- #case 1. vector as an input argumentresult <- lapply(ratings,mean)resultclass(result) #class is a list#case 2. list as an input argumentlist1<-list(maths=c(64,45,89,67),english=c(79,84,62,80),physics=c(68,72,69,80),chemistry = c(99,91,84,89))list1result <- lapply(list1,mean)resultclass(result) #class is a list#user defined functioncheck<-function(x){ return(x[x>75])}result <- lapply(list1,check) #user defined function as an argumentresultclass(result) #class is a list#case 3. dataframe as an input argumentresult <- lapply(employee,sum) #sum of elements for each columnresultclass(result) #class is a listresult <- lapply(employee,cumsum) #cumulative sum of elements for each rowresult class(result) #class is a list#user defined function check<-function(x){ return(x[x>4.2])}result <- lapply(employee,check) #user defined function as an argumentresultclass(result) #class is a list"
},
{
"code": null,
"e": 6701,
"s": 6680,
"text": "apply() vs. lapply()"
},
{
"code": null,
"e": 6792,
"s": 6701,
"text": "lapply() always returns a list whereas apply() can return a vector, list, matrix or array."
},
{
"code": null,
"e": 6824,
"s": 6792,
"text": "No scope of MARGIN in lapply()."
},
{
"code": null,
"e": 7058,
"s": 6824,
"text": "sapply() is a simplified form of lapply(). It has one additional argument simplify with default value as true, if simplify = F then sapply() returns a list similar to lapply(), otherwise, it returns the simplest output form possible."
},
{
"code": null,
"e": 7139,
"s": 7058,
"text": "Refer to the below table for input objects and the corresponding output objects."
},
{
"code": null,
"e": 8317,
"s": 7139,
"text": "#---------- sapply() function ---------- #case 1. vector as an input argumentresult <- sapply(ratings,mean)resultclass(result) #class is a vectorresult <- sapply(ratings,mean, simplify = FALSE)result class(result) #class is a listresult <- sapply(ratings,range)resultclass(result) #class is a matrix#case 2. list as an input argumentresult <- sapply(list1,mean)resultclass(result) #class is a vectorresult <- sapply(list1,range)resultclass(result) #class is a matrix#user defined functioncheck<-function(x){ return(x[x>75])}result <- sapply(list1,check) #user defined function as an argumentresultclass(result) #class is a list#case 3. dataframe as an input argumentresult <- sapply(employee,mean)resultclass(result) #class is a vectorresult <- sapply(employee,range)resultclass(result) #class is a matrix#user defined functioncheck<-function(x){ return(x[x>4])}result <- sapply(employee,check) #user defined function as an argumentresultclass(result) #class is a list"
},
{
"code": null,
"e": 8507,
"s": 8317,
"text": "tapply() is helpful while dealing with categorical variables, it applies a function to numeric data distributed across various categories. The simplest form of tapply() can be understood as"
},
{
"code": null,
"e": 8539,
"s": 8507,
"text": "tapply(column 1, column 2, FUN)"
},
{
"code": null,
"e": 8679,
"s": 8539,
"text": "where column 1 is the numeric column on which function is applied, column 2 is a factor object and FUN is for the function to be performed."
},
{
"code": null,
"e": 9108,
"s": 8679,
"text": "#---------- tapply() function ---------- salary <- c(21000,29000,32000,34000,45000)designation<-c(\"Programmer\",\"Senior Programmer\",\"Senior Programmer\",\"Senior Programmer\",\"Manager\")gender <- c(\"M\",\"F\",\"F\",\"M\",\"M\")result <- tapply(salary,designation,mean)resultclass(result) #class is an arrayresult <- tapply(salary,list(designation,gender),mean)resultclass(result) #class is a matrix"
},
{
"code": null,
"e": 9277,
"s": 9108,
"text": "by() does a similar job to tapply() i.e. it applies an operation to numeric vector values distributed across various categories. by() is a wrapper function of tapply()."
},
{
"code": null,
"e": 9727,
"s": 9277,
"text": "#---------- by() function ---------- result <- by(salary,designation,mean)resultclass(result) #class is of \"by\" typeresult[2] #accessing as a vector elementas.list(result) #converting into a listresult <- by(salary,list(designation,gender),mean)resultclass(result) #class is of \"by\" typelibrary(\"gamclass\")data(\"FARS\")by(FARS[2:4], FARS$airbagAvail, colMeans)"
},
{
"code": null,
"e": 9952,
"s": 9727,
"text": "The ‘m’ in mapply() refers to ‘multivariate’. It applies the specified functions to the arguments one by one. Note that here function is specified as the first argument whereas in other apply functions as the third argument."
},
{
"code": null,
"e": 10168,
"s": 9952,
"text": "#---------- mapply() function ---------- result <- mapply(rep, 1:4, 4:1)resultclass(result) #class is a listresult <- mapply(rep, 1:4, 4:4)class(result) #class is a matrix"
},
{
"code": null,
"e": 10179,
"s": 10168,
"text": "Conclusion"
}
] |
8085 program to determine if the number is prime or not - GeeksforGeeks
|
13 Jun, 2018
Problem – Write an assembly language program for determining if a given number is prime or not using 8085 microprocessor.
If the number is prime, store 01H at the memory location which stores the result, else 00H.
Examples:
Input : 03H
Output : 01H
The number 3 only has two divisors, 1 and 3.
Hence, it is prime.
Input : 09H
Output : 00H
The number 9 has three divisors, 1, 3 and 9.
Hence, it is composite.
A prime number is the one which has only two divisors, 1 and the number itself.A composite number, on the other hand, has 3 or more divisors.
Algorithm:
Take n as inputRun a loop from i = n to 1. For each iteration, check if i divides n completely or not. If it does, then i is n’s divisorKeep a count of the total number of divisors of nIf the count of divisors is 2, then the number is prime, else composite
Take n as input
Run a loop from i = n to 1. For each iteration, check if i divides n completely or not. If it does, then i is n’s divisor
Keep a count of the total number of divisors of n
If the count of divisors is 2, then the number is prime, else composite
How to find out if i is a divisor or not?Keep subtracting i from the dividend till the dividend either becomes 0 or less than 0. Now, check the value of dividend. If it’s 0, then i is a divisor, otherwise it’s not.
Steps:
Load the data from the memory location (2029H, arbitrary choice) into the accumulatorInitialize register C with 00H. This stores the number of divisors of nMove the value in the accumulator in E. This will act as an iterator for the loop from n to 1.Move the value in the accumulator in B. B permanently stores n because the value in the accumulator will changeMove the value in E to D and perform division with the accumulator as the dividend and D as the divisor.Division: Keep subtracting D from A till the value in A either becomes 0 or less than 0. After this, check the value in the accumulator. If it’s equal to 0, then increment the count of divisors by incrementing the value in C by oneRestore the value of the accumulator by moving the value in B to A and continue with the loop till E becomes 0Now, move the number of divisors from C to A and check if it’s equal to 2 or not. If it is, then store 01H to 202AH (arbitrary), else store 00H.
Load the data from the memory location (2029H, arbitrary choice) into the accumulator
Initialize register C with 00H. This stores the number of divisors of n
Move the value in the accumulator in E. This will act as an iterator for the loop from n to 1.
Move the value in the accumulator in B. B permanently stores n because the value in the accumulator will change
Move the value in E to D and perform division with the accumulator as the dividend and D as the divisor.
Division: Keep subtracting D from A till the value in A either becomes 0 or less than 0. After this, check the value in the accumulator. If it’s equal to 0, then increment the count of divisors by incrementing the value in C by one
Restore the value of the accumulator by moving the value in B to A and continue with the loop till E becomes 0
Now, move the number of divisors from C to A and check if it’s equal to 2 or not. If it is, then store 01H to 202AH (arbitrary), else store 00H.
202AH contains the result.
microprocessor
system-programming
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Direct Access Media (DMA) Controller in Computer Architecture
Architecture of 8085 microprocessor
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
Pin diagram of 8086 microprocessor
Difference between Hardwired and Micro-programmed Control Unit | Set 2
I2C Communication Protocol
Memory mapped I/O and Isolated I/O
Computer Architecture | Flynn's taxonomy
Computer Organization | Different Instruction Cycles
Introduction of Control Unit and its Design
|
[
{
"code": null,
"e": 26135,
"s": 26107,
"text": "\n13 Jun, 2018"
},
{
"code": null,
"e": 26257,
"s": 26135,
"text": "Problem – Write an assembly language program for determining if a given number is prime or not using 8085 microprocessor."
},
{
"code": null,
"e": 26349,
"s": 26257,
"text": "If the number is prime, store 01H at the memory location which stores the result, else 00H."
},
{
"code": null,
"e": 26359,
"s": 26349,
"text": "Examples:"
},
{
"code": null,
"e": 26546,
"s": 26359,
"text": "Input : 03H\nOutput : 01H\nThe number 3 only has two divisors, 1 and 3. \nHence, it is prime.\nInput : 09H\nOutput : 00H\nThe number 9 has three divisors, 1, 3 and 9. \nHence, it is composite.\n"
},
{
"code": null,
"e": 26688,
"s": 26546,
"text": "A prime number is the one which has only two divisors, 1 and the number itself.A composite number, on the other hand, has 3 or more divisors."
},
{
"code": null,
"e": 26699,
"s": 26688,
"text": "Algorithm:"
},
{
"code": null,
"e": 26956,
"s": 26699,
"text": "Take n as inputRun a loop from i = n to 1. For each iteration, check if i divides n completely or not. If it does, then i is n’s divisorKeep a count of the total number of divisors of nIf the count of divisors is 2, then the number is prime, else composite"
},
{
"code": null,
"e": 26972,
"s": 26956,
"text": "Take n as input"
},
{
"code": null,
"e": 27094,
"s": 26972,
"text": "Run a loop from i = n to 1. For each iteration, check if i divides n completely or not. If it does, then i is n’s divisor"
},
{
"code": null,
"e": 27144,
"s": 27094,
"text": "Keep a count of the total number of divisors of n"
},
{
"code": null,
"e": 27216,
"s": 27144,
"text": "If the count of divisors is 2, then the number is prime, else composite"
},
{
"code": null,
"e": 27431,
"s": 27216,
"text": "How to find out if i is a divisor or not?Keep subtracting i from the dividend till the dividend either becomes 0 or less than 0. Now, check the value of dividend. If it’s 0, then i is a divisor, otherwise it’s not."
},
{
"code": null,
"e": 27438,
"s": 27431,
"text": "Steps:"
},
{
"code": null,
"e": 28389,
"s": 27438,
"text": "Load the data from the memory location (2029H, arbitrary choice) into the accumulatorInitialize register C with 00H. This stores the number of divisors of nMove the value in the accumulator in E. This will act as an iterator for the loop from n to 1.Move the value in the accumulator in B. B permanently stores n because the value in the accumulator will changeMove the value in E to D and perform division with the accumulator as the dividend and D as the divisor.Division: Keep subtracting D from A till the value in A either becomes 0 or less than 0. After this, check the value in the accumulator. If it’s equal to 0, then increment the count of divisors by incrementing the value in C by oneRestore the value of the accumulator by moving the value in B to A and continue with the loop till E becomes 0Now, move the number of divisors from C to A and check if it’s equal to 2 or not. If it is, then store 01H to 202AH (arbitrary), else store 00H."
},
{
"code": null,
"e": 28475,
"s": 28389,
"text": "Load the data from the memory location (2029H, arbitrary choice) into the accumulator"
},
{
"code": null,
"e": 28547,
"s": 28475,
"text": "Initialize register C with 00H. This stores the number of divisors of n"
},
{
"code": null,
"e": 28642,
"s": 28547,
"text": "Move the value in the accumulator in E. This will act as an iterator for the loop from n to 1."
},
{
"code": null,
"e": 28754,
"s": 28642,
"text": "Move the value in the accumulator in B. B permanently stores n because the value in the accumulator will change"
},
{
"code": null,
"e": 28859,
"s": 28754,
"text": "Move the value in E to D and perform division with the accumulator as the dividend and D as the divisor."
},
{
"code": null,
"e": 29091,
"s": 28859,
"text": "Division: Keep subtracting D from A till the value in A either becomes 0 or less than 0. After this, check the value in the accumulator. If it’s equal to 0, then increment the count of divisors by incrementing the value in C by one"
},
{
"code": null,
"e": 29202,
"s": 29091,
"text": "Restore the value of the accumulator by moving the value in B to A and continue with the loop till E becomes 0"
},
{
"code": null,
"e": 29347,
"s": 29202,
"text": "Now, move the number of divisors from C to A and check if it’s equal to 2 or not. If it is, then store 01H to 202AH (arbitrary), else store 00H."
},
{
"code": null,
"e": 29374,
"s": 29347,
"text": "202AH contains the result."
},
{
"code": null,
"e": 29389,
"s": 29374,
"text": "microprocessor"
},
{
"code": null,
"e": 29408,
"s": 29389,
"text": "system-programming"
},
{
"code": null,
"e": 29445,
"s": 29408,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 29460,
"s": 29445,
"text": "microprocessor"
},
{
"code": null,
"e": 29558,
"s": 29460,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29620,
"s": 29558,
"text": "Direct Access Media (DMA) Controller in Computer Architecture"
},
{
"code": null,
"e": 29656,
"s": 29620,
"text": "Architecture of 8085 microprocessor"
},
{
"code": null,
"e": 29747,
"s": 29656,
"text": "Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)"
},
{
"code": null,
"e": 29782,
"s": 29747,
"text": "Pin diagram of 8086 microprocessor"
},
{
"code": null,
"e": 29853,
"s": 29782,
"text": "Difference between Hardwired and Micro-programmed Control Unit | Set 2"
},
{
"code": null,
"e": 29880,
"s": 29853,
"text": "I2C Communication Protocol"
},
{
"code": null,
"e": 29915,
"s": 29880,
"text": "Memory mapped I/O and Isolated I/O"
},
{
"code": null,
"e": 29956,
"s": 29915,
"text": "Computer Architecture | Flynn's taxonomy"
},
{
"code": null,
"e": 30009,
"s": 29956,
"text": "Computer Organization | Different Instruction Cycles"
}
] |
Disable the underlying window when a popup is created in Python TKinter
|
We are familiar with popup and used it in many applications. Popup in a tkinter application can be created by creating an instance of Toplevel(root) window. For a particular application, we can trigger the popup on a button object.
Let us create a Python script to close the underlying or the main window after displaying the popup. We can close the main window while residing in a popup window by using the withdraw() method.
Through this example, we will create a popup dialog that can be triggered after clicking a button. Once the popup will open, the parent window will close automatically.
#Import the required library
from tkinter import*
#Create an instance of tkinter frame
win= Tk()
#Define geometry of the window
win.geometry("750x250")
#Define a function to close the popup window
def close_win(top):
top.destroy()
win.destroy()
#Define a function to open the Popup Dialogue
def popupwin():
#withdraw the main window
win.withdraw()
#Create a Toplevel window
top= Toplevel(win)
top.geometry("750x250")
#Create an Entry Widget in the Toplevel window
entry= Entry(top, width= 25)
entry.insert(INSERT, "Enter Your Email ID")
entry.pack()
#Create a Button Widget in the Toplevel Window
button= Button(top, text="Ok", command=lambda:close_win(top))
button.pack(pady=5, side= TOP)
#Create a Label
label= Label(win, text="Click the Button to Open the Popup Dialogue", font= ('Helvetica 15 bold'))
label.pack(pady=20)
#Create a Button
button= Button(win, text= "Click Me!", command= popupwin, font= ('Helvetica 14 bold'))
button.pack(pady=20)
win.mainloop()
When we execute the above code snippet, it will display a window.
Now click the "Click Me" button. It will open a Popup window and close the parent window.
|
[
{
"code": null,
"e": 1294,
"s": 1062,
"text": "We are familiar with popup and used it in many applications. Popup in a tkinter application can be created by creating an instance of Toplevel(root) window. For a particular application, we can trigger the popup on a button object."
},
{
"code": null,
"e": 1489,
"s": 1294,
"text": "Let us create a Python script to close the underlying or the main window after displaying the popup. We can close the main window while residing in a popup window by using the withdraw() method."
},
{
"code": null,
"e": 1658,
"s": 1489,
"text": "Through this example, we will create a popup dialog that can be triggered after clicking a button. Once the popup will open, the parent window will close automatically."
},
{
"code": null,
"e": 2665,
"s": 1658,
"text": "#Import the required library\nfrom tkinter import*\n#Create an instance of tkinter frame\nwin= Tk()\n#Define geometry of the window\nwin.geometry(\"750x250\")\n#Define a function to close the popup window\ndef close_win(top):\n top.destroy()\n win.destroy()\n#Define a function to open the Popup Dialogue\ndef popupwin():\n #withdraw the main window\n win.withdraw()\n #Create a Toplevel window\n top= Toplevel(win)\n top.geometry(\"750x250\")\n #Create an Entry Widget in the Toplevel window\n entry= Entry(top, width= 25)\n entry.insert(INSERT, \"Enter Your Email ID\")\n entry.pack()\n #Create a Button Widget in the Toplevel Window\n button= Button(top, text=\"Ok\", command=lambda:close_win(top))\n button.pack(pady=5, side= TOP)\n#Create a Label\nlabel= Label(win, text=\"Click the Button to Open the Popup Dialogue\", font= ('Helvetica 15 bold'))\nlabel.pack(pady=20)\n#Create a Button\nbutton= Button(win, text= \"Click Me!\", command= popupwin, font= ('Helvetica 14 bold'))\nbutton.pack(pady=20)\nwin.mainloop()"
},
{
"code": null,
"e": 2731,
"s": 2665,
"text": "When we execute the above code snippet, it will display a window."
},
{
"code": null,
"e": 2821,
"s": 2731,
"text": "Now click the \"Click Me\" button. It will open a Popup window and close the parent window."
}
] |
How to Draw a Curved Edge Hexagon using CSS ? - GeeksforGeeks
|
16 Apr, 2020
We can make a curved edge hexagon by using the pseudo-element property of CSS.
Use a div element to create a rectangle and also add border-radius to it.
Now create a pseudo-element after using CSS and rotate it by using 60deg.
Also create another pseudo-element before by using CSS and rotate it by -60deg.
Example 1: This example draws a curve edge hexagon using CSS.
<!DOCTYPE html><html> <head> <title> Draw a Curved Edge Hexagon using CSS </title> <style> .hexagon { top: 30vh; left: 40%; position: absolute; margin: 0 auto; background-color: dodgerblue; border-radius: 10px; width: 100px; height: 63px; box-sizing: border-box; transition: all 1s; border: 0.4vh solid transparent; } /* Creating pseudo-class */ .hexagon:before, .hexagon:after { content: ""; border: inherit; position: absolute; top: -0.5vh; left: -0.5vh; background-color: dodgerblue; border-radius: inherit; height: 100%; width: 100%; } /* Align them in such a way that they form a hexagon */ .hexagon:before { transform: rotate(60deg); } .hexagon:after { transform: rotate(-60deg); } </style></head> <body style="text-align: center;"> <h1 style="color:forestgreen;"> Geeks For Geeks </h1> <!-- Hexagon Division --> <div class="hexagon" id="hexagon"> </div></body> </html>
Output:
Example 2: How to draw a curved edge hexagon using CSS with some effect.
<!DOCTYPE html><html> <head> <title> Draw a Curved Edge Hexagon using CSS </title> <style> .hexagon { top: 30vh; left: 40%; position: absolute; margin: 0 auto; /*To Add effect on the background*/ background: linear-gradient(to left, DarkBlue, DodgerBlue); border-radius: 10px; width: 100px; height: 63px; box-sizing: border-box; transition: all 1s; border: 0.4vh solid transparent; border-top-color: dodgerblue; border-bottom-color: dodgerblue; } /*To create pseudo-class */ .hexagon:before, .hexagon:after { content: ""; border: inherit; position: absolute; top: -0.5vh; left: -0.5vh; /*To Add effect on the background*/ background: linear-gradient(to left, DarkBlue, DodgerBlue); border-radius: inherit; height: 100%; width: 100%; } /* Align them in such a way that they form a hexagon */ .hexagon:before { transform: rotate(60deg); } .hexagon:after { transform: rotate(-60deg); } </style></head> <body style="text-align:center;"> <h1 style="color:forestgreen;"> Geeks For Geeks </h1> <!-- Hexagon Division --> <div class="hexagon" id="hexagon"></div></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
How to apply style to parent if it has child with CSS?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
How to set space between the flexbox ?
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
|
[
{
"code": null,
"e": 25615,
"s": 25587,
"text": "\n16 Apr, 2020"
},
{
"code": null,
"e": 25694,
"s": 25615,
"text": "We can make a curved edge hexagon by using the pseudo-element property of CSS."
},
{
"code": null,
"e": 25768,
"s": 25694,
"text": "Use a div element to create a rectangle and also add border-radius to it."
},
{
"code": null,
"e": 25842,
"s": 25768,
"text": "Now create a pseudo-element after using CSS and rotate it by using 60deg."
},
{
"code": null,
"e": 25922,
"s": 25842,
"text": "Also create another pseudo-element before by using CSS and rotate it by -60deg."
},
{
"code": null,
"e": 25984,
"s": 25922,
"text": "Example 1: This example draws a curve edge hexagon using CSS."
},
{
"code": "<!DOCTYPE html><html> <head> <title> Draw a Curved Edge Hexagon using CSS </title> <style> .hexagon { top: 30vh; left: 40%; position: absolute; margin: 0 auto; background-color: dodgerblue; border-radius: 10px; width: 100px; height: 63px; box-sizing: border-box; transition: all 1s; border: 0.4vh solid transparent; } /* Creating pseudo-class */ .hexagon:before, .hexagon:after { content: \"\"; border: inherit; position: absolute; top: -0.5vh; left: -0.5vh; background-color: dodgerblue; border-radius: inherit; height: 100%; width: 100%; } /* Align them in such a way that they form a hexagon */ .hexagon:before { transform: rotate(60deg); } .hexagon:after { transform: rotate(-60deg); } </style></head> <body style=\"text-align: center;\"> <h1 style=\"color:forestgreen;\"> Geeks For Geeks </h1> <!-- Hexagon Division --> <div class=\"hexagon\" id=\"hexagon\"> </div></body> </html>",
"e": 27270,
"s": 25984,
"text": null
},
{
"code": null,
"e": 27278,
"s": 27270,
"text": "Output:"
},
{
"code": null,
"e": 27351,
"s": 27278,
"text": "Example 2: How to draw a curved edge hexagon using CSS with some effect."
},
{
"code": "<!DOCTYPE html><html> <head> <title> Draw a Curved Edge Hexagon using CSS </title> <style> .hexagon { top: 30vh; left: 40%; position: absolute; margin: 0 auto; /*To Add effect on the background*/ background: linear-gradient(to left, DarkBlue, DodgerBlue); border-radius: 10px; width: 100px; height: 63px; box-sizing: border-box; transition: all 1s; border: 0.4vh solid transparent; border-top-color: dodgerblue; border-bottom-color: dodgerblue; } /*To create pseudo-class */ .hexagon:before, .hexagon:after { content: \"\"; border: inherit; position: absolute; top: -0.5vh; left: -0.5vh; /*To Add effect on the background*/ background: linear-gradient(to left, DarkBlue, DodgerBlue); border-radius: inherit; height: 100%; width: 100%; } /* Align them in such a way that they form a hexagon */ .hexagon:before { transform: rotate(60deg); } .hexagon:after { transform: rotate(-60deg); } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:forestgreen;\"> Geeks For Geeks </h1> <!-- Hexagon Division --> <div class=\"hexagon\" id=\"hexagon\"></div></body> </html>",
"e": 28937,
"s": 27351,
"text": null
},
{
"code": null,
"e": 28945,
"s": 28937,
"text": "Output:"
},
{
"code": null,
"e": 29082,
"s": 28945,
"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": 29091,
"s": 29082,
"text": "CSS-Misc"
},
{
"code": null,
"e": 29095,
"s": 29091,
"text": "CSS"
},
{
"code": null,
"e": 29100,
"s": 29095,
"text": "HTML"
},
{
"code": null,
"e": 29117,
"s": 29100,
"text": "Web Technologies"
},
{
"code": null,
"e": 29144,
"s": 29117,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29149,
"s": 29144,
"text": "HTML"
},
{
"code": null,
"e": 29247,
"s": 29149,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29295,
"s": 29247,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 29350,
"s": 29295,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 29387,
"s": 29350,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 29451,
"s": 29387,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 29490,
"s": 29451,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 29538,
"s": 29490,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 29598,
"s": 29538,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 29651,
"s": 29598,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 29712,
"s": 29651,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Android Motion Layout in Kotlin - GeeksforGeeks
|
07 Aug, 2020
MotionLayout is a special version of ConstraintLayout. It is a layout that helps to manage motion and widget animations in the app. Since it is a special version of ConstraintLayout, it is made as a sub-class of ConstraintLayout. It provides touch control motion to the app by describing how to transition between different layouts. In a nutshell, it is very powerful and can be used to create extensive animations and touch-controlled motions in the app.
MotionLayout, as its name hints at, is, first of all, a layout, letting you position your elements. It’s actually a subclass of ConstraintLayout and builds upon its rich layout capabilities.
MotionLayout was created to bridge the gap between layout transitions and complex motion handling.
Beyond this scope, the other key difference is that MotionLayout is fully declarative that it can be fully described in XML, there is no code is expected.
Below are the various steps to create a motion layout in Kotlin.
Step 1: Start a new Android Studio projectPlease refer to this article to see in detail about how to create a new Android Studio project.
Step 2: Adding MotionLayout class to the Project
This is a necessary step since without this, our app will cease to run. Since MotionLayout is a subclass of ConstraintLayout, it is a fairly new addition to the Android family and the chances are pretty high that we don’t have it in our project by default. To add it to our project, we need to add the following dependency to our build.gradle: app:
implementation ‘androidx.constraintlayout:constraintlayout:2.0.0-beta7’
We will need to do a gradle sync following the change we have made. Once it is successful, we can continue to build the rest of the app.
Step 3: Making MotionLayout as the root layout
In this step, we will be designing the activity_main.xml file. We will use MotionLayout as our root XML element and define its attributes such as height and width. It should be noted that a MotionLayout can contain other layouts such as ConstraintLayout, RelativeLayout, FrameLayout nested inside it. It also contains all the views such as TextView and Button that we want in our UI. Let’s look at the code for activity_main.xml for our app.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.motion.widget.MotionLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/motionLayout" android:layout_width="match_parent" android:layout_height="match_parent" app:layoutDescription="@xml/new_xml" tools:context=".MainActivity"> <FrameLayout android:id="@+id/textViewContainer" android:layout_width="match_parent" android:layout_height="match_parent" /> <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/swipeLayout" android:layout_width="match_parent" android:layout_height="0dp" android:background="#185416"/> <TextView android:id="@+id/tvHelloWorld" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Geeks for Geeks!" android:textSize="50sp" app:layout_constraintTop_toTopOf="@id/textViewContainer" app:layout_constraintBottom_toBottomOf="@id/textViewContainer" app:layout_constraintStart_toStartOf="@id/textViewContainer" app:layout_constraintEnd_toEndOf="@id/textViewContainer"/> </androidx.constraintlayout.motion.widget.MotionLayout>
Notice that in the above code, we have an attribute called app:layoutDescription which has the value @xml/new_xml. This actually is the file that contains the description of how our animation is and what it should do. We haven’t made this file yet but will make it in the next step. The code also has a ConstraintLayout which is a part of the animation. It will basically cover the screen when the animation takes place. Next, we have a single TextView which will be displayed on our screen.
Step 4: Making a new xml file
Just like we said, we will now make the new_xml.xml file which was set as the value for app:layoutDescription in our previous code. To do this, we first need to create a new XML resource file. First, we will create a directory in our resource folder and name it xml. For this, click on app -> res(right-click) -> New -> Directory
Now that we have an xml directory, we will create a file named new_xml in it. To do this, click on xml(right-click) -> New -> XML Resource File and name the file new_xml.
Step 5: Adding code to new_xml.xml
Now that we have everything ready, we can define how our animation should be in new_xml.xml. We start by opening a MotionScene XML tag. In this example, we will just make a basic transition animation using the Transition attribute and define when it should occur i.e DragUp, DragDown, DragLeft, etc by setting the OnSwipe element. This is how our code looks:
XML
<?xml version="1.0" encoding="utf-8"?><MotionScene xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:motion="http://schemas.android.com/tools"> <Transition app:constraintSetStart="@+id/start" app:constraintSetEnd="@+id/end" app:duration="100" app:motionInterpolator="linear"> <OnSwipe app:dragDirection="dragUp"/> </Transition> <ConstraintSet android:id="@id/start"> <Constraint android:id="@id/tvHelloWorld"> <CustomAttribute app:attributeName="textColor" app:customColorValue="#175416" /> </Constraint> <Constraint android:id="@id/swipeLayout" app:layout_constraintTop_toBottomOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" /> </ConstraintSet> <ConstraintSet android:id="@id/end"> <Constraint android:id="@id/tvHelloWorld"> <CustomAttribute app:attributeName="textColor" app:customColorValue="@android:color/white" /> </Constraint> <Constraint android:id="@id/swipeLayout" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" /> </ConstraintSet> </MotionScene>
To know what other animations can we apply, check this link : https://developer.android.com/training/constraint-layout/motionlayout#additional_motionlayout_attributes .
Step 6: MainActivity.kt File
Now we have everything we need to make our app work. Just one little thing to note is that we haven’t made any changes so far to our MainActivity.kt file. This is because we are just designing the UI and not the logic of the app. In case someone wants their app to do something, there will definitely be some code in the above files but for this example, this is how our MainActivity.kt looks like:
Kotlin
package com.example.motionlayoutgfg1 import androidx.appcompat.app.AppCompatActivityimport android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) }}
Since in our new_xml.xml file we defined that our animation transition will take place when we swipe up(dragUp), this is what our output looks like when we do so.
android
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
ImageView in Android with Example
How to Build a Weather App in Android?
Android SQLite Database in Kotlin
Suspend Function In Kotlin Coroutines
ScrollView in Android
Kotlin Coroutines on Android
Kotlin extension function
How to Use View Binding in RecyclerView Adapter Class in Android?
|
[
{
"code": null,
"e": 25763,
"s": 25735,
"text": "\n07 Aug, 2020"
},
{
"code": null,
"e": 26219,
"s": 25763,
"text": "MotionLayout is a special version of ConstraintLayout. It is a layout that helps to manage motion and widget animations in the app. Since it is a special version of ConstraintLayout, it is made as a sub-class of ConstraintLayout. It provides touch control motion to the app by describing how to transition between different layouts. In a nutshell, it is very powerful and can be used to create extensive animations and touch-controlled motions in the app."
},
{
"code": null,
"e": 26410,
"s": 26219,
"text": "MotionLayout, as its name hints at, is, first of all, a layout, letting you position your elements. It’s actually a subclass of ConstraintLayout and builds upon its rich layout capabilities."
},
{
"code": null,
"e": 26510,
"s": 26410,
"text": "MotionLayout was created to bridge the gap between layout transitions and complex motion handling. "
},
{
"code": null,
"e": 26665,
"s": 26510,
"text": "Beyond this scope, the other key difference is that MotionLayout is fully declarative that it can be fully described in XML, there is no code is expected."
},
{
"code": null,
"e": 26730,
"s": 26665,
"text": "Below are the various steps to create a motion layout in Kotlin."
},
{
"code": null,
"e": 26868,
"s": 26730,
"text": "Step 1: Start a new Android Studio projectPlease refer to this article to see in detail about how to create a new Android Studio project."
},
{
"code": null,
"e": 26917,
"s": 26868,
"text": "Step 2: Adding MotionLayout class to the Project"
},
{
"code": null,
"e": 27266,
"s": 26917,
"text": "This is a necessary step since without this, our app will cease to run. Since MotionLayout is a subclass of ConstraintLayout, it is a fairly new addition to the Android family and the chances are pretty high that we don’t have it in our project by default. To add it to our project, we need to add the following dependency to our build.gradle: app:"
},
{
"code": null,
"e": 27338,
"s": 27266,
"text": "implementation ‘androidx.constraintlayout:constraintlayout:2.0.0-beta7’"
},
{
"code": null,
"e": 27475,
"s": 27338,
"text": "We will need to do a gradle sync following the change we have made. Once it is successful, we can continue to build the rest of the app."
},
{
"code": null,
"e": 27522,
"s": 27475,
"text": "Step 3: Making MotionLayout as the root layout"
},
{
"code": null,
"e": 27964,
"s": 27522,
"text": "In this step, we will be designing the activity_main.xml file. We will use MotionLayout as our root XML element and define its attributes such as height and width. It should be noted that a MotionLayout can contain other layouts such as ConstraintLayout, RelativeLayout, FrameLayout nested inside it. It also contains all the views such as TextView and Button that we want in our UI. Let’s look at the code for activity_main.xml for our app."
},
{
"code": null,
"e": 27968,
"s": 27964,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.motion.widget.MotionLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/motionLayout\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" app:layoutDescription=\"@xml/new_xml\" tools:context=\".MainActivity\"> <FrameLayout android:id=\"@+id/textViewContainer\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /> <androidx.constraintlayout.widget.ConstraintLayout android:id=\"@+id/swipeLayout\" android:layout_width=\"match_parent\" android:layout_height=\"0dp\" android:background=\"#185416\"/> <TextView android:id=\"@+id/tvHelloWorld\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Geeks for Geeks!\" android:textSize=\"50sp\" app:layout_constraintTop_toTopOf=\"@id/textViewContainer\" app:layout_constraintBottom_toBottomOf=\"@id/textViewContainer\" app:layout_constraintStart_toStartOf=\"@id/textViewContainer\" app:layout_constraintEnd_toEndOf=\"@id/textViewContainer\"/> </androidx.constraintlayout.motion.widget.MotionLayout>",
"e": 29309,
"s": 27968,
"text": null
},
{
"code": null,
"e": 29801,
"s": 29309,
"text": "Notice that in the above code, we have an attribute called app:layoutDescription which has the value @xml/new_xml. This actually is the file that contains the description of how our animation is and what it should do. We haven’t made this file yet but will make it in the next step. The code also has a ConstraintLayout which is a part of the animation. It will basically cover the screen when the animation takes place. Next, we have a single TextView which will be displayed on our screen."
},
{
"code": null,
"e": 29831,
"s": 29801,
"text": "Step 4: Making a new xml file"
},
{
"code": null,
"e": 30161,
"s": 29831,
"text": "Just like we said, we will now make the new_xml.xml file which was set as the value for app:layoutDescription in our previous code. To do this, we first need to create a new XML resource file. First, we will create a directory in our resource folder and name it xml. For this, click on app -> res(right-click) -> New -> Directory"
},
{
"code": null,
"e": 30334,
"s": 30161,
"text": "Now that we have an xml directory, we will create a file named new_xml in it. To do this, click on xml(right-click) -> New -> XML Resource File and name the file new_xml. "
},
{
"code": null,
"e": 30369,
"s": 30334,
"text": "Step 5: Adding code to new_xml.xml"
},
{
"code": null,
"e": 30728,
"s": 30369,
"text": "Now that we have everything ready, we can define how our animation should be in new_xml.xml. We start by opening a MotionScene XML tag. In this example, we will just make a basic transition animation using the Transition attribute and define when it should occur i.e DragUp, DragDown, DragLeft, etc by setting the OnSwipe element. This is how our code looks:"
},
{
"code": null,
"e": 30732,
"s": 30728,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><MotionScene xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:motion=\"http://schemas.android.com/tools\"> <Transition app:constraintSetStart=\"@+id/start\" app:constraintSetEnd=\"@+id/end\" app:duration=\"100\" app:motionInterpolator=\"linear\"> <OnSwipe app:dragDirection=\"dragUp\"/> </Transition> <ConstraintSet android:id=\"@id/start\"> <Constraint android:id=\"@id/tvHelloWorld\"> <CustomAttribute app:attributeName=\"textColor\" app:customColorValue=\"#175416\" /> </Constraint> <Constraint android:id=\"@id/swipeLayout\" app:layout_constraintTop_toBottomOf=\"parent\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" /> </ConstraintSet> <ConstraintSet android:id=\"@id/end\"> <Constraint android:id=\"@id/tvHelloWorld\"> <CustomAttribute app:attributeName=\"textColor\" app:customColorValue=\"@android:color/white\" /> </Constraint> <Constraint android:id=\"@id/swipeLayout\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" /> </ConstraintSet> </MotionScene>",
"e": 32333,
"s": 30732,
"text": null
},
{
"code": null,
"e": 32503,
"s": 32333,
"text": "To know what other animations can we apply, check this link : https://developer.android.com/training/constraint-layout/motionlayout#additional_motionlayout_attributes . "
},
{
"code": null,
"e": 32532,
"s": 32503,
"text": "Step 6: MainActivity.kt File"
},
{
"code": null,
"e": 32931,
"s": 32532,
"text": "Now we have everything we need to make our app work. Just one little thing to note is that we haven’t made any changes so far to our MainActivity.kt file. This is because we are just designing the UI and not the logic of the app. In case someone wants their app to do something, there will definitely be some code in the above files but for this example, this is how our MainActivity.kt looks like:"
},
{
"code": null,
"e": 32938,
"s": 32931,
"text": "Kotlin"
},
{
"code": "package com.example.motionlayoutgfg1 import androidx.appcompat.app.AppCompatActivityimport android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) }}",
"e": 33255,
"s": 32938,
"text": null
},
{
"code": null,
"e": 33419,
"s": 33255,
"text": "Since in our new_xml.xml file we defined that our animation transition will take place when we swipe up(dragUp), this is what our output looks like when we do so."
},
{
"code": null,
"e": 33427,
"s": 33419,
"text": "android"
},
{
"code": null,
"e": 33434,
"s": 33427,
"text": "Kotlin"
},
{
"code": null,
"e": 33532,
"s": 33434,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33574,
"s": 33532,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 33614,
"s": 33574,
"text": "How to Get Current Location in Android?"
},
{
"code": null,
"e": 33648,
"s": 33614,
"text": "ImageView in Android with Example"
},
{
"code": null,
"e": 33687,
"s": 33648,
"text": "How to Build a Weather App in Android?"
},
{
"code": null,
"e": 33721,
"s": 33687,
"text": "Android SQLite Database in Kotlin"
},
{
"code": null,
"e": 33759,
"s": 33721,
"text": "Suspend Function In Kotlin Coroutines"
},
{
"code": null,
"e": 33781,
"s": 33759,
"text": "ScrollView in Android"
},
{
"code": null,
"e": 33810,
"s": 33781,
"text": "Kotlin Coroutines on Android"
},
{
"code": null,
"e": 33836,
"s": 33810,
"text": "Kotlin extension function"
}
] |
How to get return text from PHP file with ajax ? - GeeksforGeeks
|
06 Dec, 2021
In this article, we will see how to get return the text from the PHP file with ajax. Ajax is an acronym for Asynchronous JavaScript and XML is a series of web development techniques that build asynchronous web applications using many web technologies on the client-side. Without reloading the web page, AJAX enables you to send and receive information asynchronously.
Approach: When the button gets clicked, we have initialized the XMLHttpRequest object, which is responsible for making AJAX calls. Then, we have to check if the readyState value is 4, which means the request is completed, and we have got a response from the server.
Next, we have checked if the status code equals 200, which means the request was successful. Finally, we fetch the response which is stored in the responseText property of the XMLHttpRequest object. After setting up the listener, we initiate the request by calling the open method of the XMLHttpRequest object. Then call the send method of the XMLHttpRequest object, which actually sends the request to the server. When the server responds, you can see the text displaying the response from the PHP file.
Example: This example describes returning the text from PHP with AJAX.
HTML
<!DOCTYPE html><html> <body> <button type="button" id="fetchBtn">Click Me!</button> <p id="txt"></p> <script> let fetchBtn = document.getElementById('fetchBtn'); fetchBtn.addEventListener('click', buttonClickHandler); function buttonClickHandler() { // Instantiate an xhr object var xhr = new XMLHttpRequest(); // What to do when response is ready xhr.onreadystatechange = () => { if(xhr.readyState === 4) { if(xhr.status === 200) { document.getElementById("txt").innerHTML = xhr.responseText; } else { console.log('Error Code: ' + xhr.status); console.log('Error Message: ' + xhr.statusText); } } } xhr.open('GET', 'data.php'); // Send the request xhr.send(); } </script></body> </html>
PHP code: The following is the code for the “data.php” file used in the above HTML code.
data.php
<html><body> <?php echo '<h1>Welcome to GfG</h1>'; ?> </body></html>
Output:
bhaskargeeksforgeeks
PHP-Questions
Picked
Technical Scripter 2020
HTML
JavaScript
PHP
PHP Programs
Technical Scripter
Web Technologies
HTML
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
|
[
{
"code": null,
"e": 26373,
"s": 26345,
"text": "\n06 Dec, 2021"
},
{
"code": null,
"e": 26741,
"s": 26373,
"text": "In this article, we will see how to get return the text from the PHP file with ajax. Ajax is an acronym for Asynchronous JavaScript and XML is a series of web development techniques that build asynchronous web applications using many web technologies on the client-side. Without reloading the web page, AJAX enables you to send and receive information asynchronously."
},
{
"code": null,
"e": 27007,
"s": 26741,
"text": "Approach: When the button gets clicked, we have initialized the XMLHttpRequest object, which is responsible for making AJAX calls. Then, we have to check if the readyState value is 4, which means the request is completed, and we have got a response from the server."
},
{
"code": null,
"e": 27512,
"s": 27007,
"text": "Next, we have checked if the status code equals 200, which means the request was successful. Finally, we fetch the response which is stored in the responseText property of the XMLHttpRequest object. After setting up the listener, we initiate the request by calling the open method of the XMLHttpRequest object. Then call the send method of the XMLHttpRequest object, which actually sends the request to the server. When the server responds, you can see the text displaying the response from the PHP file."
},
{
"code": null,
"e": 27583,
"s": 27512,
"text": "Example: This example describes returning the text from PHP with AJAX."
},
{
"code": null,
"e": 27588,
"s": 27583,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <button type=\"button\" id=\"fetchBtn\">Click Me!</button> <p id=\"txt\"></p> <script> let fetchBtn = document.getElementById('fetchBtn'); fetchBtn.addEventListener('click', buttonClickHandler); function buttonClickHandler() { // Instantiate an xhr object var xhr = new XMLHttpRequest(); // What to do when response is ready xhr.onreadystatechange = () => { if(xhr.readyState === 4) { if(xhr.status === 200) { document.getElementById(\"txt\").innerHTML = xhr.responseText; } else { console.log('Error Code: ' + xhr.status); console.log('Error Message: ' + xhr.statusText); } } } xhr.open('GET', 'data.php'); // Send the request xhr.send(); } </script></body> </html>",
"e": 28538,
"s": 27588,
"text": null
},
{
"code": null,
"e": 28627,
"s": 28538,
"text": "PHP code: The following is the code for the “data.php” file used in the above HTML code."
},
{
"code": null,
"e": 28636,
"s": 28627,
"text": "data.php"
},
{
"code": "<html><body> <?php echo '<h1>Welcome to GfG</h1>'; ?> </body></html>",
"e": 28708,
"s": 28636,
"text": null
},
{
"code": null,
"e": 28716,
"s": 28708,
"text": "Output:"
},
{
"code": null,
"e": 28737,
"s": 28716,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 28751,
"s": 28737,
"text": "PHP-Questions"
},
{
"code": null,
"e": 28758,
"s": 28751,
"text": "Picked"
},
{
"code": null,
"e": 28782,
"s": 28758,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28787,
"s": 28782,
"text": "HTML"
},
{
"code": null,
"e": 28798,
"s": 28787,
"text": "JavaScript"
},
{
"code": null,
"e": 28802,
"s": 28798,
"text": "PHP"
},
{
"code": null,
"e": 28815,
"s": 28802,
"text": "PHP Programs"
},
{
"code": null,
"e": 28834,
"s": 28815,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28851,
"s": 28834,
"text": "Web Technologies"
},
{
"code": null,
"e": 28856,
"s": 28851,
"text": "HTML"
},
{
"code": null,
"e": 28860,
"s": 28856,
"text": "PHP"
},
{
"code": null,
"e": 28958,
"s": 28860,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28982,
"s": 28958,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 29023,
"s": 28982,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 29060,
"s": 29023,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29089,
"s": 29060,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29109,
"s": 29089,
"text": "Angular File Upload"
},
{
"code": null,
"e": 29149,
"s": 29109,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29194,
"s": 29149,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29255,
"s": 29194,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29327,
"s": 29255,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Modify given string such that odd and even indices is lexicographically largest and smallest - GeeksforGeeks
|
29 Sep, 2021
Given a string S consisting of N lowercase alphabets, the task is to modify the given string by replacing all the characters with characters other than the current character such that the suffix string formed from odd and even indices is lexicographically largest and smallest respectively among all possible modifications of the string S.
Examples:
Input: S = “giad”Output: azbzExplanation:Modify the given string S to “azbz”.Now the suffixes starting at odd indices {zbz, z} are lexicographically largest among all possible replacements of characters.And all the suffixes starting at even indices {azbz, bz} are lexicographically smallest among all possible replacements of characters.
Input: S = “ewdwnk”Output: azazaz
Approach: The given problem can be solved by using the Greedy Approach. The idea is to replace all the odd indices characters with the character ‘z’ and if the character ‘z’ is present then replace it with ‘y’. Similarly, replace all the even indices characters with the character ‘a’ and if the character ‘a’ is present then replace it with ‘b’. After the above modifications, print the string S as the resultant string formed.
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 modify the given string// satisfying the given criteriastring performOperation(string S, int N){ // Traverse the string S for (int i = 0; i < N; i++) { // If i is even if (i % 2 == 0) { // If the S[i] is 'a', then // change S[i] to 'b' if (S[i] == 'a') { S[i] = 'b'; } // Otherwise, change S[i] // to 'a' else { S[i] = 'a'; } } else { // If S[i] is 'z', then // change S[i] to 'y' if (S[i] == 'z') { S[i] = 'y'; } // Otherwise, change S[i] // to 'z' else { S[i] = 'z'; } } } // Return the result return S;} // Driver Codeint main(){ string S = "giad"; int N = S.size(); cout << performOperation(S, N); return 0;}
// Java program for the above approachimport java.util.*;class GFG{ // Function to modify the given String// satisfying the given criteriastatic String performOperation(char[] S, int N){ // Traverse the String S for (int i = 0; i < N; i++) { // If i is even if (i % 2 == 0) { // If the S[i] is 'a', then // change S[i] to 'b' if (S[i] == 'a') { S[i] = 'b'; } // Otherwise, change S[i] // to 'a' else { S[i] = 'a'; } } else { // If S[i] is 'z', then // change S[i] to 'y' if (S[i] == 'z') { S[i] = 'y'; } // Otherwise, change S[i] // to 'z' else { S[i] = 'z'; } } } // Return the result return String.valueOf(S);} // Driver Codepublic static void main(String[] args){ String S = "giad"; int N = S.length(); System.out.print(performOperation(S.toCharArray(), N));}} // This code is contributed by shikhasingrajput
# python program for the above approach # Function to modify the given string# satisfying the given criteriadef performOperation(S, N): # Traverse the string S # we cannot directly change string # because it is immutable # so change of list of char S = list(S) for i in range(0, N): # If i is even if (i % 2 == 0): # If the S[i] is 'a', then # change S[i] to 'b' if (S[i] == 'a'): S[i] = 'b' # Otherwise, change S[i] # to 'a' else: S[i] = 'a' else: # If S[i] is 'z', then # change S[i] to 'y' if (S[i] == 'z'): S[i] = 'y' # Otherwise, change S[i] # to 'z' else: S[i] = 'z' # Return the result # join the list of char return "".join(S) # Driver Codeif __name__ == "__main__": S = "giad" N = len(S) print(performOperation(S, N)) # This code is contributed by rakeshsahni
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to modify the given string// satisfying the given criteriastatic string performOperation(string S, int N){ // Traverse the string S for (int i = 0; i < N; i++) { // If i is even if (i % 2 == 0) { // If the S[i] is 'a', then // change S[i] to 'b' if (S[i] == 'a') { S = S.Substring(0, i) + 'b' + S.Substring(i + 1); } // Otherwise, change S[i] // to 'a' else { S = S.Substring(0, i) + 'a' + S.Substring(i + 1); } } else { // If S[i] is 'z', then // change S[i] to 'y' if (S[i] == 'z') { S = S.Substring(0, i) + 'y' + S.Substring(i + 1); } // Otherwise, change S[i] // to 'z' else { S = S.Substring(0, i) + 'z' + S.Substring(i + 1); } } } // Return the result return S;} // Driver Codepublic static void Main(){ string S = "giad"; int N = S.Length; Console.Write(performOperation(S, N));}} // This code is contributed by ipg2016107.
<script> // JavaScript program for the above approach// Function to modify the given string// satisfying the given criteriafunction performOperation(S, N){ // Traverse the string S for (var i = 0; i < N; i++) { // If i is even if (i % 2 == 0) { // If the S[i] is 'a', then // change S[i] to 'b' if (S.charAt(i) == 'a') { S[i] = 'b'; } // Otherwise, change S[i] // to 'a' else { S[i]= 'a'; } } else { // If S[i] is 'z', then // change S[i] to 'y' if (S.charAt(i) == 'z') { S.charAt(i) = 'y'; } // Otherwise, change S[i] // to 'z' else { S[i] = 'z'; } } } // Return the result return S;} // Driver Code var S = "giad"; var N = S.length; document.write(performOperation(S, N)); // This code is contributed by shivanisinghss2110</script>
azbz
Time Complexity: O(N)Auxiliary Space: O(1)
rakeshsahni
shivanisinghss2110
ipg2016107
shikhasingrajput
lexicographic-ordering
Greedy
Mathematical
Strings
Strings
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Optimal Page Replacement Algorithm
Program for Best Fit algorithm in Memory Management
Program for First Fit algorithm in Memory Management
Bin Packing Problem (Minimize number of used Bins)
Max Flow Problem Introduction
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
C++ Data Types
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
|
[
{
"code": null,
"e": 26537,
"s": 26509,
"text": "\n29 Sep, 2021"
},
{
"code": null,
"e": 26877,
"s": 26537,
"text": "Given a string S consisting of N lowercase alphabets, the task is to modify the given string by replacing all the characters with characters other than the current character such that the suffix string formed from odd and even indices is lexicographically largest and smallest respectively among all possible modifications of the string S."
},
{
"code": null,
"e": 26887,
"s": 26877,
"text": "Examples:"
},
{
"code": null,
"e": 27227,
"s": 26887,
"text": "Input: S = “giad”Output: azbzExplanation:Modify the given string S to “azbz”.Now the suffixes starting at odd indices {zbz, z} are lexicographically largest among all possible replacements of characters.And all the suffixes starting at even indices {azbz, bz} are lexicographically smallest among all possible replacements of characters."
},
{
"code": null,
"e": 27261,
"s": 27227,
"text": "Input: S = “ewdwnk”Output: azazaz"
},
{
"code": null,
"e": 27690,
"s": 27261,
"text": "Approach: The given problem can be solved by using the Greedy Approach. The idea is to replace all the odd indices characters with the character ‘z’ and if the character ‘z’ is present then replace it with ‘y’. Similarly, replace all the even indices characters with the character ‘a’ and if the character ‘a’ is present then replace it with ‘b’. After the above modifications, print the string S as the resultant string formed."
},
{
"code": null,
"e": 27741,
"s": 27690,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27745,
"s": 27741,
"text": "C++"
},
{
"code": null,
"e": 27750,
"s": 27745,
"text": "Java"
},
{
"code": null,
"e": 27758,
"s": 27750,
"text": "Python3"
},
{
"code": null,
"e": 27761,
"s": 27758,
"text": "C#"
},
{
"code": null,
"e": 27772,
"s": 27761,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to modify the given string// satisfying the given criteriastring performOperation(string S, int N){ // Traverse the string S for (int i = 0; i < N; i++) { // If i is even if (i % 2 == 0) { // If the S[i] is 'a', then // change S[i] to 'b' if (S[i] == 'a') { S[i] = 'b'; } // Otherwise, change S[i] // to 'a' else { S[i] = 'a'; } } else { // If S[i] is 'z', then // change S[i] to 'y' if (S[i] == 'z') { S[i] = 'y'; } // Otherwise, change S[i] // to 'z' else { S[i] = 'z'; } } } // Return the result return S;} // Driver Codeint main(){ string S = \"giad\"; int N = S.size(); cout << performOperation(S, N); return 0;}",
"e": 28790,
"s": 27772,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to modify the given String// satisfying the given criteriastatic String performOperation(char[] S, int N){ // Traverse the String S for (int i = 0; i < N; i++) { // If i is even if (i % 2 == 0) { // If the S[i] is 'a', then // change S[i] to 'b' if (S[i] == 'a') { S[i] = 'b'; } // Otherwise, change S[i] // to 'a' else { S[i] = 'a'; } } else { // If S[i] is 'z', then // change S[i] to 'y' if (S[i] == 'z') { S[i] = 'y'; } // Otherwise, change S[i] // to 'z' else { S[i] = 'z'; } } } // Return the result return String.valueOf(S);} // Driver Codepublic static void main(String[] args){ String S = \"giad\"; int N = S.length(); System.out.print(performOperation(S.toCharArray(), N));}} // This code is contributed by shikhasingrajput",
"e": 29908,
"s": 28790,
"text": null
},
{
"code": "# python program for the above approach # Function to modify the given string# satisfying the given criteriadef performOperation(S, N): # Traverse the string S # we cannot directly change string # because it is immutable # so change of list of char S = list(S) for i in range(0, N): # If i is even if (i % 2 == 0): # If the S[i] is 'a', then # change S[i] to 'b' if (S[i] == 'a'): S[i] = 'b' # Otherwise, change S[i] # to 'a' else: S[i] = 'a' else: # If S[i] is 'z', then # change S[i] to 'y' if (S[i] == 'z'): S[i] = 'y' # Otherwise, change S[i] # to 'z' else: S[i] = 'z' # Return the result # join the list of char return \"\".join(S) # Driver Codeif __name__ == \"__main__\": S = \"giad\" N = len(S) print(performOperation(S, N)) # This code is contributed by rakeshsahni",
"e": 31016,
"s": 29908,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to modify the given string// satisfying the given criteriastatic string performOperation(string S, int N){ // Traverse the string S for (int i = 0; i < N; i++) { // If i is even if (i % 2 == 0) { // If the S[i] is 'a', then // change S[i] to 'b' if (S[i] == 'a') { S = S.Substring(0, i) + 'b' + S.Substring(i + 1); } // Otherwise, change S[i] // to 'a' else { S = S.Substring(0, i) + 'a' + S.Substring(i + 1); } } else { // If S[i] is 'z', then // change S[i] to 'y' if (S[i] == 'z') { S = S.Substring(0, i) + 'y' + S.Substring(i + 1); } // Otherwise, change S[i] // to 'z' else { S = S.Substring(0, i) + 'z' + S.Substring(i + 1); } } } // Return the result return S;} // Driver Codepublic static void Main(){ string S = \"giad\"; int N = S.Length; Console.Write(performOperation(S, N));}} // This code is contributed by ipg2016107.",
"e": 32256,
"s": 31016,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach// Function to modify the given string// satisfying the given criteriafunction performOperation(S, N){ // Traverse the string S for (var i = 0; i < N; i++) { // If i is even if (i % 2 == 0) { // If the S[i] is 'a', then // change S[i] to 'b' if (S.charAt(i) == 'a') { S[i] = 'b'; } // Otherwise, change S[i] // to 'a' else { S[i]= 'a'; } } else { // If S[i] is 'z', then // change S[i] to 'y' if (S.charAt(i) == 'z') { S.charAt(i) = 'y'; } // Otherwise, change S[i] // to 'z' else { S[i] = 'z'; } } } // Return the result return S;} // Driver Code var S = \"giad\"; var N = S.length; document.write(performOperation(S, N)); // This code is contributed by shivanisinghss2110</script>",
"e": 33298,
"s": 32256,
"text": null
},
{
"code": null,
"e": 33303,
"s": 33298,
"text": "azbz"
},
{
"code": null,
"e": 33348,
"s": 33305,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 33360,
"s": 33348,
"text": "rakeshsahni"
},
{
"code": null,
"e": 33379,
"s": 33360,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 33390,
"s": 33379,
"text": "ipg2016107"
},
{
"code": null,
"e": 33407,
"s": 33390,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 33430,
"s": 33407,
"text": "lexicographic-ordering"
},
{
"code": null,
"e": 33437,
"s": 33430,
"text": "Greedy"
},
{
"code": null,
"e": 33450,
"s": 33437,
"text": "Mathematical"
},
{
"code": null,
"e": 33458,
"s": 33450,
"text": "Strings"
},
{
"code": null,
"e": 33466,
"s": 33458,
"text": "Strings"
},
{
"code": null,
"e": 33473,
"s": 33466,
"text": "Greedy"
},
{
"code": null,
"e": 33486,
"s": 33473,
"text": "Mathematical"
},
{
"code": null,
"e": 33584,
"s": 33486,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33619,
"s": 33584,
"text": "Optimal Page Replacement Algorithm"
},
{
"code": null,
"e": 33671,
"s": 33619,
"text": "Program for Best Fit algorithm in Memory Management"
},
{
"code": null,
"e": 33724,
"s": 33671,
"text": "Program for First Fit algorithm in Memory Management"
},
{
"code": null,
"e": 33775,
"s": 33724,
"text": "Bin Packing Problem (Minimize number of used Bins)"
},
{
"code": null,
"e": 33805,
"s": 33775,
"text": "Max Flow Problem Introduction"
},
{
"code": null,
"e": 33835,
"s": 33805,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 33878,
"s": 33835,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 33893,
"s": 33878,
"text": "C++ Data Types"
},
{
"code": null,
"e": 33917,
"s": 33893,
"text": "Merge two sorted arrays"
}
] |
Python | Numpy matrix.reshape() - GeeksforGeeks
|
18 Apr, 2019
With the help of Numpy matrix.reshape() method, we are able to reshape the shape of the given matrix. Remember all elements should be covered after reshaping the given matrix.
Syntax : matrix.reshape(shape)
Return: new reshapped matrix
Example #1 :In the given example we are able to reshape the given matrix by using matrix.reshape() method.
# import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[64, 1; 12, 3]') # applying matrix.reshape() methodgeeks = gfg.reshape((1, 4)) print(geeks)
[[64 1 12 3]]
Example #2 :
# import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1, 2; 4, 5; 7, 8]') # applying matrix.reshape() methodgeeks = gfg.reshape((2, 3)) print(geeks)
[[1 2 4]
[5 7 8]]
Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
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": 26153,
"s": 26125,
"text": "\n18 Apr, 2019"
},
{
"code": null,
"e": 26329,
"s": 26153,
"text": "With the help of Numpy matrix.reshape() method, we are able to reshape the shape of the given matrix. Remember all elements should be covered after reshaping the given matrix."
},
{
"code": null,
"e": 26360,
"s": 26329,
"text": "Syntax : matrix.reshape(shape)"
},
{
"code": null,
"e": 26389,
"s": 26360,
"text": "Return: new reshapped matrix"
},
{
"code": null,
"e": 26496,
"s": 26389,
"text": "Example #1 :In the given example we are able to reshape the given matrix by using matrix.reshape() method."
},
{
"code": "# import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[64, 1; 12, 3]') # applying matrix.reshape() methodgeeks = gfg.reshape((1, 4)) print(geeks)",
"e": 26711,
"s": 26496,
"text": null
},
{
"code": null,
"e": 26728,
"s": 26711,
"text": "[[64 1 12 3]]\n"
},
{
"code": null,
"e": 26741,
"s": 26728,
"text": "Example #2 :"
},
{
"code": "# import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1, 2; 4, 5; 7, 8]') # applying matrix.reshape() methodgeeks = gfg.reshape((2, 3)) print(geeks)",
"e": 26962,
"s": 26741,
"text": null
},
{
"code": null,
"e": 26982,
"s": 26962,
"text": "[[1 2 4]\n [5 7 8]]\n"
},
{
"code": null,
"e": 27011,
"s": 26982,
"text": "Python numpy-Matrix Function"
},
{
"code": null,
"e": 27024,
"s": 27011,
"text": "Python-numpy"
},
{
"code": null,
"e": 27031,
"s": 27024,
"text": "Python"
},
{
"code": null,
"e": 27129,
"s": 27031,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27147,
"s": 27129,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27182,
"s": 27147,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27214,
"s": 27182,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27236,
"s": 27214,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27278,
"s": 27236,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27308,
"s": 27278,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27334,
"s": 27308,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27363,
"s": 27334,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27407,
"s": 27363,
"text": "Reading and Writing to text files in Python"
}
] |
Python Slicing | Reverse an array in groups of given size - GeeksforGeeks
|
11 May, 2020
Given an array, reverse every sub-array formed by consecutive k elements.
Examples:
Input:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
k = 3
Output:
[3, 2, 1, 6, 5, 4, 9, 8, 7]
Input:
arr = [1, 2, 3, 4, 5, 6, 7, 8]
k = 5
Output:
[5, 4, 3, 2, 1, 8, 7, 6]
Input:
arr = [1, 2, 3, 4, 5, 6]
k = 1
Output:
[1, 2, 3, 4, 5, 6]
Input:
arr = [1, 2, 3, 4, 5, 6, 7, 8]
k = 10
Output:
[8, 7, 6, 5, 4, 3, 2, 1]
We have existing solution for this problem please refer Reverse an array in groups of given size link. We can solve this problem quickly in Python using list slicing and reversed() function.Below example will give you better understanding of approach.
Example:
# function to Reverse an array in groups of given size def reverseGroup(input,k): # set starting index at 0 start = 0 # run a while loop len(input)/k times # because there will be len(input)/k number # of groups of size k result = [] while (start<len(input)): # if length of group is less than k # that means we are left with only last # group reverse remaining elements if len(input[start:])<k: result = result + list(reversed(input[start:])) break # select current group of size of k # reverse it and concatenate result = result + list(reversed(input[start:start + k])) start = start + k print(result) # Driver programif __name__ == "__main__": input = [1, 2, 3, 4, 5, 6, 7, 8] k = 5 reverseGroup(input,k)
[5, 4, 3, 2, 1, 8, 7, 6]
Using Direct Function
# function to Reverse an array in groups of given size def reverseGroup(a, k): # take an empty list res = [] # iterate over the list with increment of # k times in each iteration for i in range(0, len(a), k): # reverse the list in each iteration over # span of k elements using extend res.extend((a[i:i + k])[::-1]) print(res) # Driver programif __name__ == "__main__": input = [1, 2, 3, 4, 5, 6, 7, 8] k = 5 reverseGroup(input, k)
[5, 4, 3, 2, 1, 8, 7, 6]
nikhilk26
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
Convert integer to string in Python
How To Convert Python Dictionary To JSON?
sum() function in Python
|
[
{
"code": null,
"e": 25511,
"s": 25483,
"text": "\n11 May, 2020"
},
{
"code": null,
"e": 25585,
"s": 25511,
"text": "Given an array, reverse every sub-array formed by consecutive k elements."
},
{
"code": null,
"e": 25595,
"s": 25585,
"text": "Examples:"
},
{
"code": null,
"e": 25914,
"s": 25595,
"text": "Input: \narr = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nk = 3\nOutput: \n[3, 2, 1, 6, 5, 4, 9, 8, 7]\n\nInput: \narr = [1, 2, 3, 4, 5, 6, 7, 8]\nk = 5\nOutput: \n[5, 4, 3, 2, 1, 8, 7, 6]\n\nInput: \narr = [1, 2, 3, 4, 5, 6]\nk = 1\nOutput: \n[1, 2, 3, 4, 5, 6]\n\nInput: \narr = [1, 2, 3, 4, 5, 6, 7, 8]\nk = 10\nOutput: \n[8, 7, 6, 5, 4, 3, 2, 1]\n"
},
{
"code": null,
"e": 26166,
"s": 25914,
"text": "We have existing solution for this problem please refer Reverse an array in groups of given size link. We can solve this problem quickly in Python using list slicing and reversed() function.Below example will give you better understanding of approach."
},
{
"code": null,
"e": 26175,
"s": 26166,
"text": "Example:"
},
{
"code": "# function to Reverse an array in groups of given size def reverseGroup(input,k): # set starting index at 0 start = 0 # run a while loop len(input)/k times # because there will be len(input)/k number # of groups of size k result = [] while (start<len(input)): # if length of group is less than k # that means we are left with only last # group reverse remaining elements if len(input[start:])<k: result = result + list(reversed(input[start:])) break # select current group of size of k # reverse it and concatenate result = result + list(reversed(input[start:start + k])) start = start + k print(result) # Driver programif __name__ == \"__main__\": input = [1, 2, 3, 4, 5, 6, 7, 8] k = 5 reverseGroup(input,k)",
"e": 27041,
"s": 26175,
"text": null
},
{
"code": null,
"e": 27067,
"s": 27041,
"text": "[5, 4, 3, 2, 1, 8, 7, 6]\n"
},
{
"code": null,
"e": 27089,
"s": 27067,
"text": "Using Direct Function"
},
{
"code": "# function to Reverse an array in groups of given size def reverseGroup(a, k): # take an empty list res = [] # iterate over the list with increment of # k times in each iteration for i in range(0, len(a), k): # reverse the list in each iteration over # span of k elements using extend res.extend((a[i:i + k])[::-1]) print(res) # Driver programif __name__ == \"__main__\": input = [1, 2, 3, 4, 5, 6, 7, 8] k = 5 reverseGroup(input, k)",
"e": 27577,
"s": 27089,
"text": null
},
{
"code": null,
"e": 27603,
"s": 27577,
"text": "[5, 4, 3, 2, 1, 8, 7, 6]\n"
},
{
"code": null,
"e": 27613,
"s": 27603,
"text": "nikhilk26"
},
{
"code": null,
"e": 27634,
"s": 27613,
"text": "Python list-programs"
},
{
"code": null,
"e": 27646,
"s": 27634,
"text": "python-list"
},
{
"code": null,
"e": 27653,
"s": 27646,
"text": "Python"
},
{
"code": null,
"e": 27665,
"s": 27653,
"text": "python-list"
},
{
"code": null,
"e": 27763,
"s": 27665,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27795,
"s": 27763,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27817,
"s": 27795,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27859,
"s": 27817,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27885,
"s": 27859,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27914,
"s": 27885,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27951,
"s": 27914,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27993,
"s": 27951,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28029,
"s": 27993,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 28071,
"s": 28029,
"text": "How To Convert Python Dictionary To JSON?"
}
] |
How to zoom in on a point using scale and translate ? - GeeksforGeeks
|
27 Feb, 2020
You are given a zoom in to particular image by using scale and translate method. In this zooming process, an image should be zoom in from the center of the image. That image has some width and height in case of rectangular shape and has proper dimensions according to the shape of the image. In zoom in process an image get bigger in size as per requirement. In an image viewer this zoom in process is very important. To get this process you can use scale() and translate() method.
The scale() method scales the current drawing into a smaller or larger size. If you scale a canvas, all future drawings will also be scaled. The position will also be scaled. If you scale(2, 2) drawing will be positioned twice as far from the left and top of the canvas as you specify. The translate() method remaps the (0, 0) position as the canvas. If you have an image and scale it by a factor of 2, the bottom-right point will double in both x and y direction as (0, 0) is the top-left of the image. If you like to zoom the image of the center then a solution is as follows:
Translate the image.
Scale the image by x and y factors.
Translate the image back.
Below example illustrate the above approach:Example:
<!DOCTYPE html><html> <head> <title> Zooming process using scale and trsnslate </title> <style> #canvas { border: 2px solid black; } h1{ color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <p>Scroll your mouse inside the canvas</p> <canvas id="canvas" width="600" height="200"></canvas> </center> <script> var zoomIntensity = 0.1; var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); var width = 600; var height = 200; var scale = 1; var orgnx = 0; var orgny = 0; var visibleWidth = width; var visibleHeight = height; function draw() { context.fillStyle = "white"; context.fillRect(orgnx, orgny, 800 / scale, 800 / scale); context.fillStyle = "green"; context.fillRect(250,50,100,100); } setInterval(draw, 800 / 60); // Scroll effect function canvas.onwheel = function(event) { event.preventDefault(); var x = event.clientX - canvas.offsetLeft; var y = event.clientY - canvas.offsetTop; var scroll = event.deltaY < 0 ? 1 : -2; var zoom = Math.exp(scroll * zoomIntensity); context.translate(orgnx, orgny); orgnx -= x / (scale * zoom) - x / scale; orgny -= y / (scale * zoom) - y / scale; context.scale(zoom, zoom); context.translate(-orgnx, -orgny); // Updating scale and visisble width and height scale *= zoom; visibleWidth = width / scale; visibleHeight = height / scale; } </script></body> </html>
Output :
CSS-Misc
HTML-Misc
JavaScript-Misc
Picked
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to apply style to parent if it has child with CSS?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Design a web page using HTML and CSS
How to set space between the flexbox ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
|
[
{
"code": null,
"e": 26695,
"s": 26667,
"text": "\n27 Feb, 2020"
},
{
"code": null,
"e": 27177,
"s": 26695,
"text": "You are given a zoom in to particular image by using scale and translate method. In this zooming process, an image should be zoom in from the center of the image. That image has some width and height in case of rectangular shape and has proper dimensions according to the shape of the image. In zoom in process an image get bigger in size as per requirement. In an image viewer this zoom in process is very important. To get this process you can use scale() and translate() method."
},
{
"code": null,
"e": 27756,
"s": 27177,
"text": "The scale() method scales the current drawing into a smaller or larger size. If you scale a canvas, all future drawings will also be scaled. The position will also be scaled. If you scale(2, 2) drawing will be positioned twice as far from the left and top of the canvas as you specify. The translate() method remaps the (0, 0) position as the canvas. If you have an image and scale it by a factor of 2, the bottom-right point will double in both x and y direction as (0, 0) is the top-left of the image. If you like to zoom the image of the center then a solution is as follows:"
},
{
"code": null,
"e": 27777,
"s": 27756,
"text": "Translate the image."
},
{
"code": null,
"e": 27813,
"s": 27777,
"text": "Scale the image by x and y factors."
},
{
"code": null,
"e": 27839,
"s": 27813,
"text": "Translate the image back."
},
{
"code": null,
"e": 27892,
"s": 27839,
"text": "Below example illustrate the above approach:Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Zooming process using scale and trsnslate </title> <style> #canvas { border: 2px solid black; } h1{ color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <p>Scroll your mouse inside the canvas</p> <canvas id=\"canvas\" width=\"600\" height=\"200\"></canvas> </center> <script> var zoomIntensity = 0.1; var canvas = document.getElementById(\"canvas\"); var context = canvas.getContext(\"2d\"); var width = 600; var height = 200; var scale = 1; var orgnx = 0; var orgny = 0; var visibleWidth = width; var visibleHeight = height; function draw() { context.fillStyle = \"white\"; context.fillRect(orgnx, orgny, 800 / scale, 800 / scale); context.fillStyle = \"green\"; context.fillRect(250,50,100,100); } setInterval(draw, 800 / 60); // Scroll effect function canvas.onwheel = function(event) { event.preventDefault(); var x = event.clientX - canvas.offsetLeft; var y = event.clientY - canvas.offsetTop; var scroll = event.deltaY < 0 ? 1 : -2; var zoom = Math.exp(scroll * zoomIntensity); context.translate(orgnx, orgny); orgnx -= x / (scale * zoom) - x / scale; orgny -= y / (scale * zoom) - y / scale; context.scale(zoom, zoom); context.translate(-orgnx, -orgny); // Updating scale and visisble width and height scale *= zoom; visibleWidth = width / scale; visibleHeight = height / scale; } </script></body> </html>",
"e": 29688,
"s": 27892,
"text": null
},
{
"code": null,
"e": 29697,
"s": 29688,
"text": "Output :"
},
{
"code": null,
"e": 29706,
"s": 29697,
"text": "CSS-Misc"
},
{
"code": null,
"e": 29716,
"s": 29706,
"text": "HTML-Misc"
},
{
"code": null,
"e": 29732,
"s": 29716,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 29739,
"s": 29732,
"text": "Picked"
},
{
"code": null,
"e": 29743,
"s": 29739,
"text": "CSS"
},
{
"code": null,
"e": 29748,
"s": 29743,
"text": "HTML"
},
{
"code": null,
"e": 29759,
"s": 29748,
"text": "JavaScript"
},
{
"code": null,
"e": 29776,
"s": 29759,
"text": "Web Technologies"
},
{
"code": null,
"e": 29803,
"s": 29776,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29808,
"s": 29803,
"text": "HTML"
},
{
"code": null,
"e": 29906,
"s": 29808,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29961,
"s": 29906,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 29998,
"s": 29961,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 30062,
"s": 29998,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 30099,
"s": 30062,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 30138,
"s": 30099,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 30198,
"s": 30138,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 30251,
"s": 30198,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 30312,
"s": 30251,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 30336,
"s": 30312,
"text": "REST API (Introduction)"
}
] |
What are the features of ReactJS ? - GeeksforGeeks
|
22 Oct, 2021
React is a JavaScript Library created by Facebook for creating dynamic and interactive applications and building better UI/UX design for web and mobile applications. React is an open-source and component-based front-end library. React is responsible for the UI design. React makes code easier to debug by dividing them into components.
JSX (JavaScript Syntax Extension)
Virtual DOM
One-way data binding
Performance
Extensions
Conditional statements
Components
Simplicity
Let’s understand each of them in detail.
1. JSX(JavaScript Syntax Extension): JSX is a combination of HTML and JavaScript. You can embed JavaScript objects inside the HTML elements. JSX is not supported by the browsers, as a result Babel compiler transcompile the code into JavaScript code. JSX makes codes easy and understandable. It is easy to learn if you know HTML and JavaScript.
const name="GeekforGeeks";
const ele = <h1>Welcome to {name}</h1>;
2. Virtual DOM: DOM stands for Document Object Model. It is the most important part of the web as it divides into modules and executes the code. Usually, JavaScript Frameworks updates the whole DOM at once, which makes the web application slow. But react uses virtual DOM which is an exact copy of real DOM. Whenever there is a modification in the web application, the whole virtual DOM is updated first and finds the difference between real DOM and Virtual DOM. Once it finds the difference, then DOM updates only the part that has changed recently and everything remains the same.
In the above-shown figure, when the whole virtual DOM has updated there is a change in the child components. So, now DOM finds the difference and updates only the changed part.
3. One-way Data Binding: One-way data binding, the name itself says that it is a one-direction flow. The data in react flows only in one direction i.e. the data is transferred from top to bottom i.e. from parent components to child components. The properties(props) in the child component cannot return the data to its parent component but it can have communication with the parent components to modify the states according to the provided inputs. This is the working process of one-way data binding. This keeps everything modular and fast.
One-way Data Binding
As shown in the above diagram, data can flow only from top to bottom.
4. Performance: As we discussed earlier, react uses virtual DOM and updates only the modified parts. So , this makes the DOM to run faster. DOM executes in memory so we can create separate components which makes the DOM run faster.
5. Extension: React has many extensions that we can use to create full-fledged UI applications. It supports mobile app development and provides server-side rendering. React is extended with Flux, Redux, React Native, etc. which helps us to create good-looking UI.
6. Conditional Statements: JSX allows us to write conditional statements. The data in the browser is displayed according to the conditions provided inside the JSX.
Syntax:
const age = 12;
if (age >= 10)
{
<p> Greater than { age } </p>;
}
else
{
<p> { age } </p>;
}
7. Components: React.js divides the web page into multiple components as it is component-based. Each component is a part of the UI design which has its own logic and design as shown in the below image. So the component logic which is written in JavaScript makes it easy and run faster and can be reusable.
Multiple components
8. Simplicity: React.js is a component-based which makes the code reusable and React.js uses JSX which is a combination of HTML and JavaScript. This makes code easy to understand and easy to debug and has less code.
Let’s see how react.js works by creating an application.
Follow the below steps to create a react application:
Step 1: Create a react application by using the following command:
npx create-react-app foldername
Step 2: Change your directory to the newly created folder.
cd foldername
Project Structure: A project structure is created as shown below:
Step 3: Now create a new file as PassMessage.js in src folder and add the following code.
Javascript
import React from 'react'import App from './App'; function PassMessage() { return ( <div> <h1 style = { { textAlign: 'center', color: 'green' } }> Congratulations!!!You passed the test. </h1> </div> )} export default PassMessage
Step 4: Now create another file as FailMessage.js in src folder and add the following code.
Javascript
import React from 'react'import App from './App' function FailMessage() { return ( <div > <h1 style = { { textAlign: 'center', color: 'green' } }> You failed the test.Better luck next time..!! </h1> </div> )} export default FailMessage
Step 5: Now add the following code in App.js.
Javascript
import PassMessage from './PassMessage';import FailMessage from './FailMessage'; function App(props) { const isPass = props.isPass; if (isPass) { return <PassMessage/> ; } return <FailMessage/> ;}; export default App;
Step 6: Add the below code in index.js.
Javascript
import React from 'react';import ReactDOM from 'react-dom';import App from './App';import FailMessage from './FailMessage';import PassMessage from './PassMessage'; ReactDOM.render( <App isPass = { true }/>, document.getElementById('root'));
Step to run the application: Open the terminal and type the following command.
npm start
If you give the value of isPass={true} in index.js, then it will give the following output:
If the value of isPass={false} in index.js, then the following output is displayed.
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to pass data from one component to other component in ReactJS ?
ReactJS useNavigate() Hook
ReactJS defaultProps
How to set background images in ReactJS ?
Re-rendering Components in ReactJS
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 25967,
"s": 25939,
"text": "\n22 Oct, 2021"
},
{
"code": null,
"e": 26305,
"s": 25967,
"text": " React is a JavaScript Library created by Facebook for creating dynamic and interactive applications and building better UI/UX design for web and mobile applications. React is an open-source and component-based front-end library. React is responsible for the UI design. React makes code easier to debug by dividing them into components. "
},
{
"code": null,
"e": 26339,
"s": 26305,
"text": "JSX (JavaScript Syntax Extension)"
},
{
"code": null,
"e": 26351,
"s": 26339,
"text": "Virtual DOM"
},
{
"code": null,
"e": 26372,
"s": 26351,
"text": "One-way data binding"
},
{
"code": null,
"e": 26384,
"s": 26372,
"text": "Performance"
},
{
"code": null,
"e": 26395,
"s": 26384,
"text": "Extensions"
},
{
"code": null,
"e": 26418,
"s": 26395,
"text": "Conditional statements"
},
{
"code": null,
"e": 26429,
"s": 26418,
"text": "Components"
},
{
"code": null,
"e": 26440,
"s": 26429,
"text": "Simplicity"
},
{
"code": null,
"e": 26482,
"s": 26440,
"text": "Let’s understand each of them in detail. "
},
{
"code": null,
"e": 26827,
"s": 26482,
"text": "1. JSX(JavaScript Syntax Extension): JSX is a combination of HTML and JavaScript. You can embed JavaScript objects inside the HTML elements. JSX is not supported by the browsers, as a result Babel compiler transcompile the code into JavaScript code. JSX makes codes easy and understandable. It is easy to learn if you know HTML and JavaScript."
},
{
"code": null,
"e": 26894,
"s": 26827,
"text": "const name=\"GeekforGeeks\";\nconst ele = <h1>Welcome to {name}</h1>;"
},
{
"code": null,
"e": 27478,
"s": 26894,
"text": "2. Virtual DOM: DOM stands for Document Object Model. It is the most important part of the web as it divides into modules and executes the code. Usually, JavaScript Frameworks updates the whole DOM at once, which makes the web application slow. But react uses virtual DOM which is an exact copy of real DOM. Whenever there is a modification in the web application, the whole virtual DOM is updated first and finds the difference between real DOM and Virtual DOM. Once it finds the difference, then DOM updates only the part that has changed recently and everything remains the same. "
},
{
"code": null,
"e": 27656,
"s": 27478,
"text": " In the above-shown figure, when the whole virtual DOM has updated there is a change in the child components. So, now DOM finds the difference and updates only the changed part."
},
{
"code": null,
"e": 28197,
"s": 27656,
"text": "3. One-way Data Binding: One-way data binding, the name itself says that it is a one-direction flow. The data in react flows only in one direction i.e. the data is transferred from top to bottom i.e. from parent components to child components. The properties(props) in the child component cannot return the data to its parent component but it can have communication with the parent components to modify the states according to the provided inputs. This is the working process of one-way data binding. This keeps everything modular and fast."
},
{
"code": null,
"e": 28218,
"s": 28197,
"text": "One-way Data Binding"
},
{
"code": null,
"e": 28288,
"s": 28218,
"text": "As shown in the above diagram, data can flow only from top to bottom."
},
{
"code": null,
"e": 28520,
"s": 28288,
"text": "4. Performance: As we discussed earlier, react uses virtual DOM and updates only the modified parts. So , this makes the DOM to run faster. DOM executes in memory so we can create separate components which makes the DOM run faster."
},
{
"code": null,
"e": 28784,
"s": 28520,
"text": "5. Extension: React has many extensions that we can use to create full-fledged UI applications. It supports mobile app development and provides server-side rendering. React is extended with Flux, Redux, React Native, etc. which helps us to create good-looking UI."
},
{
"code": null,
"e": 28948,
"s": 28784,
"text": "6. Conditional Statements: JSX allows us to write conditional statements. The data in the browser is displayed according to the conditions provided inside the JSX."
},
{
"code": null,
"e": 28956,
"s": 28948,
"text": "Syntax:"
},
{
"code": null,
"e": 29061,
"s": 28956,
"text": "const age = 12;\nif (age >= 10)\n{ \n <p> Greater than { age } </p>;\n} \nelse \n{ \n <p> { age } </p>;\n}"
},
{
"code": null,
"e": 29367,
"s": 29061,
"text": "7. Components: React.js divides the web page into multiple components as it is component-based. Each component is a part of the UI design which has its own logic and design as shown in the below image. So the component logic which is written in JavaScript makes it easy and run faster and can be reusable."
},
{
"code": null,
"e": 29387,
"s": 29367,
"text": "Multiple components"
},
{
"code": null,
"e": 29603,
"s": 29387,
"text": "8. Simplicity: React.js is a component-based which makes the code reusable and React.js uses JSX which is a combination of HTML and JavaScript. This makes code easy to understand and easy to debug and has less code."
},
{
"code": null,
"e": 29660,
"s": 29603,
"text": "Let’s see how react.js works by creating an application."
},
{
"code": null,
"e": 29714,
"s": 29660,
"text": "Follow the below steps to create a react application:"
},
{
"code": null,
"e": 29781,
"s": 29714,
"text": "Step 1: Create a react application by using the following command:"
},
{
"code": null,
"e": 29813,
"s": 29781,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 29872,
"s": 29813,
"text": "Step 2: Change your directory to the newly created folder."
},
{
"code": null,
"e": 29886,
"s": 29872,
"text": "cd foldername"
},
{
"code": null,
"e": 29952,
"s": 29886,
"text": "Project Structure: A project structure is created as shown below:"
},
{
"code": null,
"e": 30043,
"s": 29952,
"text": "Step 3: Now create a new file as PassMessage.js in src folder and add the following code."
},
{
"code": null,
"e": 30054,
"s": 30043,
"text": "Javascript"
},
{
"code": "import React from 'react'import App from './App'; function PassMessage() { return ( <div> <h1 style = { { textAlign: 'center', color: 'green' } }> Congratulations!!!You passed the test. </h1> </div> )} export default PassMessage",
"e": 30387,
"s": 30054,
"text": null
},
{
"code": null,
"e": 30479,
"s": 30387,
"text": "Step 4: Now create another file as FailMessage.js in src folder and add the following code."
},
{
"code": null,
"e": 30490,
"s": 30479,
"text": "Javascript"
},
{
"code": "import React from 'react'import App from './App' function FailMessage() { return ( <div > <h1 style = { { textAlign: 'center', color: 'green' } }> You failed the test.Better luck next time..!! </h1> </div> )} export default FailMessage",
"e": 30796,
"s": 30490,
"text": null
},
{
"code": null,
"e": 30851,
"s": 30805,
"text": "Step 5: Now add the following code in App.js."
},
{
"code": null,
"e": 30862,
"s": 30851,
"text": "Javascript"
},
{
"code": "import PassMessage from './PassMessage';import FailMessage from './FailMessage'; function App(props) { const isPass = props.isPass; if (isPass) { return <PassMessage/> ; } return <FailMessage/> ;}; export default App;",
"e": 31115,
"s": 30862,
"text": null
},
{
"code": null,
"e": 31155,
"s": 31115,
"text": "Step 6: Add the below code in index.js."
},
{
"code": null,
"e": 31166,
"s": 31155,
"text": "Javascript"
},
{
"code": "import React from 'react';import ReactDOM from 'react-dom';import App from './App';import FailMessage from './FailMessage';import PassMessage from './PassMessage'; ReactDOM.render( <App isPass = { true }/>, document.getElementById('root'));",
"e": 31424,
"s": 31166,
"text": null
},
{
"code": null,
"e": 31503,
"s": 31424,
"text": "Step to run the application: Open the terminal and type the following command."
},
{
"code": null,
"e": 31513,
"s": 31503,
"text": "npm start"
},
{
"code": null,
"e": 31605,
"s": 31513,
"text": "If you give the value of isPass={true} in index.js, then it will give the following output:"
},
{
"code": null,
"e": 31689,
"s": 31605,
"text": "If the value of isPass={false} in index.js, then the following output is displayed."
},
{
"code": null,
"e": 31696,
"s": 31689,
"text": "Picked"
},
{
"code": null,
"e": 31712,
"s": 31696,
"text": "React-Questions"
},
{
"code": null,
"e": 31720,
"s": 31712,
"text": "ReactJS"
},
{
"code": null,
"e": 31737,
"s": 31720,
"text": "Web Technologies"
},
{
"code": null,
"e": 31835,
"s": 31737,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31903,
"s": 31835,
"text": "How to pass data from one component to other component in ReactJS ?"
},
{
"code": null,
"e": 31930,
"s": 31903,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 31951,
"s": 31930,
"text": "ReactJS defaultProps"
},
{
"code": null,
"e": 31993,
"s": 31951,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 32028,
"s": 31993,
"text": "Re-rendering Components in ReactJS"
},
{
"code": null,
"e": 32068,
"s": 32028,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32113,
"s": 32068,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32163,
"s": 32113,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 32224,
"s": 32163,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
Vulscan - Vulnerability Scanning with Nmap in Kali Linux - GeeksforGeeks
|
07 Oct, 2021
Vulscan is a free and open-source tool available on GitHub. Vulscan uses nmap as the main scanner to scan the IP addresses and domains, the easiest and useful tool for reconnaissance of network. Vulscan interface is very similar to Metasploit 1 and Metasploit 2 which makes it easy to use. This tool provides a command-line interface that you can run on the Kali Linux terminal in order to scan hosts and domains. This tool can be used to get information about our target(domain) which can be a website or an IP address or a domain. The interactive console provides a number of helpful features, such as command completion and contextual help. Vulscan is a web reconnaissance tool that uses NSE script. Vulscan has NSE scripts that give additional features to nmap to detect and find vulnerabilities and further which can be used to perform exploitation. Nse scripts have many modules such as network discovery and backdoor detection. It has so many modules such as database interaction, built-in convenience functions, interactive help, and command completion. Vulscan provides a powerful environment in which open source web-based reconnaissance can be conducted and you can gather all information about the target.
Step 1: Use the following command to install the tool in your kali Linux operating system.
git clone https://github.com/scipag/vulscan scipag_vulscan
ln -s `pwd`/scipag_vulscan /usr/share/nmap/scripts/vulscan
Step 2: Now use the following command to move into the directory of the tool. Use the second command to list out the contents of the tool
cd scipag_vulscan
ls
The tool has been downloaded and installed successfully now we will see an example to use the tool.
nmap -sV --script=vulscan/vulscan.nse <domain>
This tool automates the nmap vulnerability scanner using NSE scripts.
sweetyty
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
Docker - COPY Instruction
mv command in Linux with examples
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Thread functions in C/C++
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
|
[
{
"code": null,
"e": 25651,
"s": 25623,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 26870,
"s": 25651,
"text": "Vulscan is a free and open-source tool available on GitHub. Vulscan uses nmap as the main scanner to scan the IP addresses and domains, the easiest and useful tool for reconnaissance of network. Vulscan interface is very similar to Metasploit 1 and Metasploit 2 which makes it easy to use. This tool provides a command-line interface that you can run on the Kali Linux terminal in order to scan hosts and domains. This tool can be used to get information about our target(domain) which can be a website or an IP address or a domain. The interactive console provides a number of helpful features, such as command completion and contextual help. Vulscan is a web reconnaissance tool that uses NSE script. Vulscan has NSE scripts that give additional features to nmap to detect and find vulnerabilities and further which can be used to perform exploitation. Nse scripts have many modules such as network discovery and backdoor detection. It has so many modules such as database interaction, built-in convenience functions, interactive help, and command completion. Vulscan provides a powerful environment in which open source web-based reconnaissance can be conducted and you can gather all information about the target."
},
{
"code": null,
"e": 26961,
"s": 26870,
"text": "Step 1: Use the following command to install the tool in your kali Linux operating system."
},
{
"code": null,
"e": 27083,
"s": 26961,
"text": "git clone https://github.com/scipag/vulscan scipag_vulscan\nln -s `pwd`/scipag_vulscan /usr/share/nmap/scripts/vulscan "
},
{
"code": null,
"e": 27221,
"s": 27083,
"text": "Step 2: Now use the following command to move into the directory of the tool. Use the second command to list out the contents of the tool"
},
{
"code": null,
"e": 27242,
"s": 27221,
"text": "cd scipag_vulscan\nls"
},
{
"code": null,
"e": 27342,
"s": 27242,
"text": "The tool has been downloaded and installed successfully now we will see an example to use the tool."
},
{
"code": null,
"e": 27389,
"s": 27342,
"text": "nmap -sV --script=vulscan/vulscan.nse <domain>"
},
{
"code": null,
"e": 27459,
"s": 27389,
"text": "This tool automates the nmap vulnerability scanner using NSE scripts."
},
{
"code": null,
"e": 27468,
"s": 27459,
"text": "sweetyty"
},
{
"code": null,
"e": 27479,
"s": 27468,
"text": "Kali-Linux"
},
{
"code": null,
"e": 27491,
"s": 27479,
"text": "Linux-Tools"
},
{
"code": null,
"e": 27502,
"s": 27491,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27600,
"s": 27502,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27635,
"s": 27600,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 27661,
"s": 27635,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 27695,
"s": 27661,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 27724,
"s": 27695,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 27761,
"s": 27724,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 27798,
"s": 27761,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 27824,
"s": 27798,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 27866,
"s": 27824,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 27902,
"s": 27866,
"text": "uniq Command in LINUX with examples"
}
] |
GATE | GATE CS 2011 | Question 65 - GeeksforGeeks
|
30 Sep, 2021
Consider an instruction pipeline with four stages (S1, S2, S3 and S4) each with combinational circuit only. The pipeline registers are required between each stage and at the end of the last stage. Delays for the stages and for the pipeline registers are as given in the figure:
What is the approximate speed up of the pipeline in steady state under ideal conditions when compared to the corresponding non-pipeline implementation?(A) 4.0(B) 2.5(C) 1.1(D) 3.0Answer: (B)Explanation:
Pipeline registers overhead is not counted in normal
time execution
So the total count will be
5+6+11+8= 30 [without pipeline]
Now, for pipeline, each stage will be of 11 n-sec (+ 1 n-sec for overhead).
and, in steady state output is produced after every pipeline cycle. Here,
in this case 11 n-sec. After adding 1n-sec overhead, We will get 12 n-sec
of constant output producing cycle.
dividing 30/12 we get 2.5
YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersPrevious Year Questions Pipelining | COA | GeeksforGeeks GATE | Harshit NigamWatch 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:0025:57 / 57:56•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=i9nHxd-NCdg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2011
GATE-GATE CS 2011
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
|
[
{
"code": null,
"e": 25647,
"s": 25619,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 25925,
"s": 25647,
"text": "Consider an instruction pipeline with four stages (S1, S2, S3 and S4) each with combinational circuit only. The pipeline registers are required between each stage and at the end of the last stage. Delays for the stages and for the pipeline registers are as given in the figure:"
},
{
"code": null,
"e": 26128,
"s": 25925,
"text": "What is the approximate speed up of the pipeline in steady state under ideal conditions when compared to the corresponding non-pipeline implementation?(A) 4.0(B) 2.5(C) 1.1(D) 3.0Answer: (B)Explanation:"
},
{
"code": null,
"e": 26547,
"s": 26128,
"text": "Pipeline registers overhead is not counted in normal \ntime execution\n\nSo the total count will be\n\n5+6+11+8= 30 [without pipeline]\n\nNow, for pipeline, each stage will be of 11 n-sec (+ 1 n-sec for overhead).\nand, in steady state output is produced after every pipeline cycle. Here,\nin this case 11 n-sec. After adding 1n-sec overhead, We will get 12 n-sec\nof constant output producing cycle.\n\ndividing 30/12 we get 2.5 "
},
{
"code": null,
"e": 27453,
"s": 26547,
"text": "YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersPrevious Year Questions Pipelining | COA | GeeksforGeeks GATE | Harshit NigamWatch 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:0025:57 / 57:56•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=i9nHxd-NCdg\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question"
},
{
"code": null,
"e": 27466,
"s": 27453,
"text": "GATE-CS-2011"
},
{
"code": null,
"e": 27484,
"s": 27466,
"text": "GATE-GATE CS 2011"
},
{
"code": null,
"e": 27489,
"s": 27484,
"text": "GATE"
},
{
"code": null,
"e": 27587,
"s": 27489,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27621,
"s": 27587,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 27655,
"s": 27621,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 27689,
"s": 27655,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 27722,
"s": 27689,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 27758,
"s": 27722,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 27792,
"s": 27758,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 27828,
"s": 27792,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 27862,
"s": 27828,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 27896,
"s": 27862,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
Controlled Access Protocols in Computer Network - GeeksforGeeks
|
19 Oct, 2021
In controlled access, the stations seek information from one another to find which station has the right to send. It allows only one node to send at a time, to avoid collision of messages on shared medium.The three controlled-access methods are:
ReservationPollingToken Passing
Reservation
Polling
Token Passing
In the reservation method, a station needs to make a reservation before sending data.
The time line has two kinds of periods:Reservation interval of fixed time lengthData transmission period of variable frames.
Reservation interval of fixed time lengthData transmission period of variable frames.
Reservation interval of fixed time length
Data transmission period of variable frames.
If there are M stations, the reservation interval is divided into M slots, and each station has one slot.
Suppose if station 1 has a frame to send, it transmits 1 bit during the slot 1. No other station is allowed to transmit during this slot.
In general, i th station may announce that it has a frame to send by inserting a 1 bit into i th slot. After all N slots have been checked, each station knows which stations wish to transmit.
The stations which have reserved their slots transfer their frames in that order.
After data transmission period, next reservation interval begins.
Since everyone agrees on who goes next, there will never be any collisions.
The following figure shows a situation with five stations and a five-slot reservation frame. In the first interval, only stations 1, 3, and 4 have made reservations. In the second interval, only station 1 has made a reservation.
Polling process is similar to the roll-call performed in class. Just like the teacher, a controller sends a message to each node in turn.
In this, one acts as a primary station(controller) and the others are secondary stations. All data exchanges must be made through the controller.
The message sent by the controller contains the address of the node being selected for granting access.
Although all nodes receive the message but the addressed one responds to it and sends data, if any. If there is no data, usually a “poll reject”(NAK) message is sent back.
Problems include high overhead of the polling messages and high dependence on the reliability of the controller.
EfficiencyLet Tpoll be the time for polling and Tt be the time required for transmission of data. Then,
Efficiency = Tt/(Tt + Tpoll)
In token passing scheme, the stations are connected logically to each other in form of ring and access of stations is governed by tokens.
A token is a special bit pattern or a small message, which circulate from one station to the next in some predefined order.
In Token ring, token is passed from one station to another adjacent station in the ring whereas incase of Token bus, each stationuses the bus to send the token to the next station in some predefined order.
In both cases, token represents permission to send. If a station has a frame queued for transmission when it receives the token, it can send that frame before it passes the token to the next station. If it has no queued frame, it passes the token simply.
After sending a frame, each station must wait for all N stations (including itself) to send the token to their neighbors and the other N – 1 stations to send a frame, if they have one.
There exists problems like duplication of token or token is lost or insertion of new station, removal of a station, which need be tackled for correct and reliable operation of this scheme.
PerformancePerformance of token ring can be concluded by 2 parameters:-
Delay, which is a measure of time between when a packet is ready and when it is delivered. So, the average time (delay) required to send a token to the next station = a/N.Throughput, which is a measure of the successful traffic.
Delay, which is a measure of time between when a packet is ready and when it is delivered. So, the average time (delay) required to send a token to the next station = a/N.
Throughput, which is a measure of the successful traffic.
Throughput, S = 1/(1 + a/N) for a<1
and
S = 1/{a(1 + 1/N)} for a>1.
where N = number of stations
a = Tp/Tt
(Tp = propagation delay and Tt = transmission delay)
23620uday2021
Computer Networks
GATE CS
Technical Scripter
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between IPv4 and IPv6
Socket Programming in Python
Caesar Cipher in Cryptography
UDP Server-Client implementation in C
Socket Programming in Java
ACID Properties in DBMS
Types of Operating Systems
Normal Forms in DBMS
Page Replacement Algorithms in Operating Systems
Cache Memory in Computer Organization
|
[
{
"code": null,
"e": 37837,
"s": 37809,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 38083,
"s": 37837,
"text": "In controlled access, the stations seek information from one another to find which station has the right to send. It allows only one node to send at a time, to avoid collision of messages on shared medium.The three controlled-access methods are:"
},
{
"code": null,
"e": 38115,
"s": 38083,
"text": "ReservationPollingToken Passing"
},
{
"code": null,
"e": 38127,
"s": 38115,
"text": "Reservation"
},
{
"code": null,
"e": 38135,
"s": 38127,
"text": "Polling"
},
{
"code": null,
"e": 38149,
"s": 38135,
"text": "Token Passing"
},
{
"code": null,
"e": 38235,
"s": 38149,
"text": "In the reservation method, a station needs to make a reservation before sending data."
},
{
"code": null,
"e": 38360,
"s": 38235,
"text": "The time line has two kinds of periods:Reservation interval of fixed time lengthData transmission period of variable frames."
},
{
"code": null,
"e": 38446,
"s": 38360,
"text": "Reservation interval of fixed time lengthData transmission period of variable frames."
},
{
"code": null,
"e": 38488,
"s": 38446,
"text": "Reservation interval of fixed time length"
},
{
"code": null,
"e": 38533,
"s": 38488,
"text": "Data transmission period of variable frames."
},
{
"code": null,
"e": 38639,
"s": 38533,
"text": "If there are M stations, the reservation interval is divided into M slots, and each station has one slot."
},
{
"code": null,
"e": 38777,
"s": 38639,
"text": "Suppose if station 1 has a frame to send, it transmits 1 bit during the slot 1. No other station is allowed to transmit during this slot."
},
{
"code": null,
"e": 38969,
"s": 38777,
"text": "In general, i th station may announce that it has a frame to send by inserting a 1 bit into i th slot. After all N slots have been checked, each station knows which stations wish to transmit."
},
{
"code": null,
"e": 39051,
"s": 38969,
"text": "The stations which have reserved their slots transfer their frames in that order."
},
{
"code": null,
"e": 39117,
"s": 39051,
"text": "After data transmission period, next reservation interval begins."
},
{
"code": null,
"e": 39193,
"s": 39117,
"text": "Since everyone agrees on who goes next, there will never be any collisions."
},
{
"code": null,
"e": 39422,
"s": 39193,
"text": "The following figure shows a situation with five stations and a five-slot reservation frame. In the first interval, only stations 1, 3, and 4 have made reservations. In the second interval, only station 1 has made a reservation."
},
{
"code": null,
"e": 39560,
"s": 39422,
"text": "Polling process is similar to the roll-call performed in class. Just like the teacher, a controller sends a message to each node in turn."
},
{
"code": null,
"e": 39706,
"s": 39560,
"text": "In this, one acts as a primary station(controller) and the others are secondary stations. All data exchanges must be made through the controller."
},
{
"code": null,
"e": 39810,
"s": 39706,
"text": "The message sent by the controller contains the address of the node being selected for granting access."
},
{
"code": null,
"e": 39982,
"s": 39810,
"text": "Although all nodes receive the message but the addressed one responds to it and sends data, if any. If there is no data, usually a “poll reject”(NAK) message is sent back."
},
{
"code": null,
"e": 40095,
"s": 39982,
"text": "Problems include high overhead of the polling messages and high dependence on the reliability of the controller."
},
{
"code": null,
"e": 40199,
"s": 40095,
"text": "EfficiencyLet Tpoll be the time for polling and Tt be the time required for transmission of data. Then,"
},
{
"code": null,
"e": 40229,
"s": 40199,
"text": " Efficiency = Tt/(Tt + Tpoll)"
},
{
"code": null,
"e": 40367,
"s": 40229,
"text": "In token passing scheme, the stations are connected logically to each other in form of ring and access of stations is governed by tokens."
},
{
"code": null,
"e": 40491,
"s": 40367,
"text": "A token is a special bit pattern or a small message, which circulate from one station to the next in some predefined order."
},
{
"code": null,
"e": 40697,
"s": 40491,
"text": "In Token ring, token is passed from one station to another adjacent station in the ring whereas incase of Token bus, each stationuses the bus to send the token to the next station in some predefined order."
},
{
"code": null,
"e": 40952,
"s": 40697,
"text": "In both cases, token represents permission to send. If a station has a frame queued for transmission when it receives the token, it can send that frame before it passes the token to the next station. If it has no queued frame, it passes the token simply."
},
{
"code": null,
"e": 41137,
"s": 40952,
"text": "After sending a frame, each station must wait for all N stations (including itself) to send the token to their neighbors and the other N – 1 stations to send a frame, if they have one."
},
{
"code": null,
"e": 41326,
"s": 41137,
"text": "There exists problems like duplication of token or token is lost or insertion of new station, removal of a station, which need be tackled for correct and reliable operation of this scheme."
},
{
"code": null,
"e": 41398,
"s": 41326,
"text": "PerformancePerformance of token ring can be concluded by 2 parameters:-"
},
{
"code": null,
"e": 41627,
"s": 41398,
"text": "Delay, which is a measure of time between when a packet is ready and when it is delivered. So, the average time (delay) required to send a token to the next station = a/N.Throughput, which is a measure of the successful traffic."
},
{
"code": null,
"e": 41799,
"s": 41627,
"text": "Delay, which is a measure of time between when a packet is ready and when it is delivered. So, the average time (delay) required to send a token to the next station = a/N."
},
{
"code": null,
"e": 41857,
"s": 41799,
"text": "Throughput, which is a measure of the successful traffic."
},
{
"code": null,
"e": 41895,
"s": 41857,
"text": " Throughput, S = 1/(1 + a/N) for a<1 "
},
{
"code": null,
"e": 41899,
"s": 41895,
"text": "and"
},
{
"code": null,
"e": 42054,
"s": 41899,
"text": " S = 1/{a(1 + 1/N)} for a>1. \n where N = number of stations\n a = Tp/Tt \n(Tp = propagation delay and Tt = transmission delay)\n"
},
{
"code": null,
"e": 42068,
"s": 42054,
"text": "23620uday2021"
},
{
"code": null,
"e": 42086,
"s": 42068,
"text": "Computer Networks"
},
{
"code": null,
"e": 42094,
"s": 42086,
"text": "GATE CS"
},
{
"code": null,
"e": 42113,
"s": 42094,
"text": "Technical Scripter"
},
{
"code": null,
"e": 42131,
"s": 42113,
"text": "Computer Networks"
},
{
"code": null,
"e": 42229,
"s": 42131,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42263,
"s": 42229,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 42292,
"s": 42263,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 42322,
"s": 42292,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 42360,
"s": 42322,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 42387,
"s": 42360,
"text": "Socket Programming in Java"
},
{
"code": null,
"e": 42411,
"s": 42387,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 42438,
"s": 42411,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 42459,
"s": 42438,
"text": "Normal Forms in DBMS"
},
{
"code": null,
"e": 42508,
"s": 42459,
"text": "Page Replacement Algorithms in Operating Systems"
}
] |
numpy.random.shuffle() in python - GeeksforGeeks
|
18 Aug, 2020
With the help of numpy.random.shuffle() method, we can get the random positioning of different integer values in the numpy array or we can say that all the values in an array will be shuffled randomly.
Syntax : numpy.random.shuffle(x)
Return : Return the reshuffled numpy array.
Example #1 :
In this example we can see that by using numpy.random.shuffle() method, we are able to do the reshuffling of values in the numpy array or change the positions of values in an array.
Python3
# import numpyimport numpy as npimport matplotlib.pyplot as plt gfg = np.arange(10)# Using shuffle() methodnp.random.shuffle(gfg) print(gfg)
Output :
[7 1 5 0 8 4 3 9 6 2]
Example #2 :
Python3
# import numpyimport numpy as npimport matplotlib.pyplot as plt gfg = np.arange(16).reshape((4, 4))# Using shuffle() methodnp.random.shuffle(gfg) print(gfg)
Output :
[[ 4 5 6 7]
[ 0 1 2 3]
[ 8 9 10 11]
[12 13 14 15]]
Python numpy-Random
Python-numpy
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
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n18 Aug, 2020"
},
{
"code": null,
"e": 25739,
"s": 25537,
"text": "With the help of numpy.random.shuffle() method, we can get the random positioning of different integer values in the numpy array or we can say that all the values in an array will be shuffled randomly."
},
{
"code": null,
"e": 25772,
"s": 25739,
"text": "Syntax : numpy.random.shuffle(x)"
},
{
"code": null,
"e": 25816,
"s": 25772,
"text": "Return : Return the reshuffled numpy array."
},
{
"code": null,
"e": 25829,
"s": 25816,
"text": "Example #1 :"
},
{
"code": null,
"e": 26011,
"s": 25829,
"text": "In this example we can see that by using numpy.random.shuffle() method, we are able to do the reshuffling of values in the numpy array or change the positions of values in an array."
},
{
"code": null,
"e": 26019,
"s": 26011,
"text": "Python3"
},
{
"code": "# import numpyimport numpy as npimport matplotlib.pyplot as plt gfg = np.arange(10)# Using shuffle() methodnp.random.shuffle(gfg) print(gfg)",
"e": 26162,
"s": 26019,
"text": null
},
{
"code": null,
"e": 26171,
"s": 26162,
"text": "Output :"
},
{
"code": null,
"e": 26193,
"s": 26171,
"text": "[7 1 5 0 8 4 3 9 6 2]"
},
{
"code": null,
"e": 26206,
"s": 26193,
"text": "Example #2 :"
},
{
"code": null,
"e": 26214,
"s": 26206,
"text": "Python3"
},
{
"code": "# import numpyimport numpy as npimport matplotlib.pyplot as plt gfg = np.arange(16).reshape((4, 4))# Using shuffle() methodnp.random.shuffle(gfg) print(gfg)",
"e": 26373,
"s": 26214,
"text": null
},
{
"code": null,
"e": 26382,
"s": 26373,
"text": "Output :"
},
{
"code": null,
"e": 26397,
"s": 26382,
"text": "[[ 4 5 6 7]"
},
{
"code": null,
"e": 26411,
"s": 26397,
"text": "[ 0 1 2 3]"
},
{
"code": null,
"e": 26425,
"s": 26411,
"text": "[ 8 9 10 11]"
},
{
"code": null,
"e": 26440,
"s": 26425,
"text": "[12 13 14 15]]"
},
{
"code": null,
"e": 26460,
"s": 26440,
"text": "Python numpy-Random"
},
{
"code": null,
"e": 26473,
"s": 26460,
"text": "Python-numpy"
},
{
"code": null,
"e": 26480,
"s": 26473,
"text": "Python"
},
{
"code": null,
"e": 26578,
"s": 26480,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26610,
"s": 26578,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26652,
"s": 26610,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26694,
"s": 26652,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26750,
"s": 26694,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26777,
"s": 26750,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26816,
"s": 26777,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26847,
"s": 26816,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26876,
"s": 26847,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 26898,
"s": 26876,
"text": "Defaultdict in Python"
}
] |
How to install NumPy package in Julia? - GeeksforGeeks
|
17 May, 2020
Julia is a very new and fast high-level programming language and has the power to compete with python. Like python, Julia is also compatible to do machine learning and data analysis part. In this tutorial, we will learn about how to install NumPy and use it in our Julia environment.
Before we begin with the installation of Julia, it is good to check if it might be already installed on your system. To check if your device is preinstalled with Julia or not, just go to the Command line(search for cmd in the Run dialog( + R)).Now run the following command:
julia
If Julia is not installed, please follow the steps on How to Install Julia on Windows?
Follow these steps to make use of libraries like NumPy in Julia:
Step 1: Use the Using Pkg command to install the external packages in Julia.
using Pkg
Step 2: Add the PyCall package to install the required python modules in julia and to do so use the command given below:
Pkg.add("PyCall")
Step 3: In this step, we have to use the PyCall package and for that use the following command:
using PyCall
Step 4: And Here we go, this is the final statement which we use to complete the setup for numpy.
np = pyimport("numpy")
Python-numpy
How To
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Align Text in HTML?
How to filter object array based on attributes?
Java Tutorial
How to Install FFmpeg on Windows?
How to Install Anaconda on Windows?
Vectors in Julia
Printing Output on Screen in Julia
String concatenation in Julia
Getting rounded value of a number in Julia - round() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
|
[
{
"code": null,
"e": 26159,
"s": 26131,
"text": "\n17 May, 2020"
},
{
"code": null,
"e": 26443,
"s": 26159,
"text": "Julia is a very new and fast high-level programming language and has the power to compete with python. Like python, Julia is also compatible to do machine learning and data analysis part. In this tutorial, we will learn about how to install NumPy and use it in our Julia environment."
},
{
"code": null,
"e": 26718,
"s": 26443,
"text": "Before we begin with the installation of Julia, it is good to check if it might be already installed on your system. To check if your device is preinstalled with Julia or not, just go to the Command line(search for cmd in the Run dialog( + R)).Now run the following command:"
},
{
"code": null,
"e": 26724,
"s": 26718,
"text": "julia"
},
{
"code": null,
"e": 26811,
"s": 26724,
"text": "If Julia is not installed, please follow the steps on How to Install Julia on Windows?"
},
{
"code": null,
"e": 26876,
"s": 26811,
"text": "Follow these steps to make use of libraries like NumPy in Julia:"
},
{
"code": null,
"e": 26953,
"s": 26876,
"text": "Step 1: Use the Using Pkg command to install the external packages in Julia."
},
{
"code": null,
"e": 26963,
"s": 26953,
"text": "using Pkg"
},
{
"code": null,
"e": 27084,
"s": 26963,
"text": "Step 2: Add the PyCall package to install the required python modules in julia and to do so use the command given below:"
},
{
"code": null,
"e": 27102,
"s": 27084,
"text": "Pkg.add(\"PyCall\")"
},
{
"code": null,
"e": 27198,
"s": 27102,
"text": "Step 3: In this step, we have to use the PyCall package and for that use the following command:"
},
{
"code": null,
"e": 27211,
"s": 27198,
"text": "using PyCall"
},
{
"code": null,
"e": 27309,
"s": 27211,
"text": "Step 4: And Here we go, this is the final statement which we use to complete the setup for numpy."
},
{
"code": null,
"e": 27332,
"s": 27309,
"text": "np = pyimport(\"numpy\")"
},
{
"code": null,
"e": 27345,
"s": 27332,
"text": "Python-numpy"
},
{
"code": null,
"e": 27352,
"s": 27345,
"text": "How To"
},
{
"code": null,
"e": 27358,
"s": 27352,
"text": "Julia"
},
{
"code": null,
"e": 27456,
"s": 27358,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27483,
"s": 27456,
"text": "How to Align Text in HTML?"
},
{
"code": null,
"e": 27531,
"s": 27483,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 27545,
"s": 27531,
"text": "Java Tutorial"
},
{
"code": null,
"e": 27579,
"s": 27545,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 27615,
"s": 27579,
"text": "How to Install Anaconda on Windows?"
},
{
"code": null,
"e": 27632,
"s": 27615,
"text": "Vectors in Julia"
},
{
"code": null,
"e": 27667,
"s": 27632,
"text": "Printing Output on Screen in Julia"
},
{
"code": null,
"e": 27697,
"s": 27667,
"text": "String concatenation in Julia"
},
{
"code": null,
"e": 27757,
"s": 27697,
"text": "Getting rounded value of a number in Julia - round() Method"
}
] |
stack emplace() in C++ STL - GeeksforGeeks
|
27 May, 2021
Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new element is added at one end and (top) an element is removed from that end only.
This function is used to insert a new element into the stack container, the new element is added on top of the stack. Syntax :
stackname.emplace(value)
Parameters :
The element to be inserted into the stack
is passed as the parameter.
Result :
The parameter is added to the stack
at the top position.
Examples:
Input : mystack{1, 2, 3, 4, 5};
mystack.emplace(6);
Output : mystack = 6, 5, 4, 3, 2, 1
Input : mystack{};
mystack.emplace(4);
Output : mystack = 4
Note: In stack container, the elements are printed in reverse order because the top is printed first then moving on to other elements.
Errors and Exceptions 1. It has a strong exception guarantee, therefore, no changes are made if an exception is thrown. 2. Parameter should be of same type as that of the container, otherwise an error is thrown.
CPP
// CPP program to illustrate// Implementation of emplace() function#include <iostream>#include <stack>using namespace std; int main() { stack<int> mystack; mystack.emplace(1); mystack.emplace(2); mystack.emplace(3); mystack.emplace(4); mystack.emplace(5); mystack.emplace(6); // stack becomes 1, 2, 3, 4, 5, 6 // printing the stack cout << "mystack = "; while (!mystack.empty()) { cout << mystack.top() << " "; mystack.pop(); } return 0;}
Output:
6 5 4 3 2 1
Time Complexity : O(1)Difference between stack::emplace() and stack::push() function. While push() function inserts a copy of the value or the parameter passed to the function into the container at the top, the emplace() function constructs a new element as the value of the parameter and then adds it to the top of the container. Application : Given a number of integers, add them to the stack using emplace() and find the size of the stack without using size function.
Input : 5, 13, 0, 9, 4
Output: 5
Algorithm 1. Insert the given elements to the stack container using emplace() one by one. 2. Keep popping the elements of stack until it becomes empty, and increment the counter variable. 3. Print the counter variable.
CPP
// CPP program to illustrate// Application of emplace() function#include <iostream>#include <stack>using namespace std; int main() { int c = 0; // Empty stack stack<int> mystack; mystack.emplace(5); mystack.emplace(13); mystack.emplace(0); mystack.emplace(9); mystack.emplace(4); // stack becomes 5, 13, 0, 9, 4 // Counting number of elements in queue while (!mystack.empty()) { mystack.pop(); c++; } cout << c;}
Output:
5
divyanshu1150
cpp-stack
cpp-stack-functions
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Inline Functions in C++
Queue in C++ Standard Template Library (STL)
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
|
[
{
"code": null,
"e": 25367,
"s": 25339,
"text": "\n27 May, 2021"
},
{
"code": null,
"e": 25546,
"s": 25367,
"text": "Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new element is added at one end and (top) an element is removed from that end only. "
},
{
"code": null,
"e": 25675,
"s": 25546,
"text": "This function is used to insert a new element into the stack container, the new element is added on top of the stack. Syntax : "
},
{
"code": null,
"e": 25850,
"s": 25675,
"text": "stackname.emplace(value)\nParameters :\nThe element to be inserted into the stack\nis passed as the parameter.\nResult :\nThe parameter is added to the stack \nat the top position."
},
{
"code": null,
"e": 25862,
"s": 25850,
"text": "Examples: "
},
{
"code": null,
"e": 26031,
"s": 25862,
"text": "Input : mystack{1, 2, 3, 4, 5};\n mystack.emplace(6);\nOutput : mystack = 6, 5, 4, 3, 2, 1\n\nInput : mystack{};\n mystack.emplace(4);\nOutput : mystack = 4"
},
{
"code": null,
"e": 26168,
"s": 26033,
"text": "Note: In stack container, the elements are printed in reverse order because the top is printed first then moving on to other elements."
},
{
"code": null,
"e": 26381,
"s": 26168,
"text": "Errors and Exceptions 1. It has a strong exception guarantee, therefore, no changes are made if an exception is thrown. 2. Parameter should be of same type as that of the container, otherwise an error is thrown. "
},
{
"code": null,
"e": 26385,
"s": 26381,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// Implementation of emplace() function#include <iostream>#include <stack>using namespace std; int main() { stack<int> mystack; mystack.emplace(1); mystack.emplace(2); mystack.emplace(3); mystack.emplace(4); mystack.emplace(5); mystack.emplace(6); // stack becomes 1, 2, 3, 4, 5, 6 // printing the stack cout << \"mystack = \"; while (!mystack.empty()) { cout << mystack.top() << \" \"; mystack.pop(); } return 0;}",
"e": 26844,
"s": 26385,
"text": null
},
{
"code": null,
"e": 26854,
"s": 26844,
"text": "Output: "
},
{
"code": null,
"e": 26866,
"s": 26854,
"text": "6 5 4 3 2 1"
},
{
"code": null,
"e": 27338,
"s": 26866,
"text": "Time Complexity : O(1)Difference between stack::emplace() and stack::push() function. While push() function inserts a copy of the value or the parameter passed to the function into the container at the top, the emplace() function constructs a new element as the value of the parameter and then adds it to the top of the container. Application : Given a number of integers, add them to the stack using emplace() and find the size of the stack without using size function. "
},
{
"code": null,
"e": 27371,
"s": 27338,
"text": "Input : 5, 13, 0, 9, 4\nOutput: 5"
},
{
"code": null,
"e": 27591,
"s": 27371,
"text": "Algorithm 1. Insert the given elements to the stack container using emplace() one by one. 2. Keep popping the elements of stack until it becomes empty, and increment the counter variable. 3. Print the counter variable. "
},
{
"code": null,
"e": 27595,
"s": 27591,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// Application of emplace() function#include <iostream>#include <stack>using namespace std; int main() { int c = 0; // Empty stack stack<int> mystack; mystack.emplace(5); mystack.emplace(13); mystack.emplace(0); mystack.emplace(9); mystack.emplace(4); // stack becomes 5, 13, 0, 9, 4 // Counting number of elements in queue while (!mystack.empty()) { mystack.pop(); c++; } cout << c;}",
"e": 28028,
"s": 27595,
"text": null
},
{
"code": null,
"e": 28038,
"s": 28028,
"text": "Output: "
},
{
"code": null,
"e": 28040,
"s": 28038,
"text": "5"
},
{
"code": null,
"e": 28056,
"s": 28042,
"text": "divyanshu1150"
},
{
"code": null,
"e": 28066,
"s": 28056,
"text": "cpp-stack"
},
{
"code": null,
"e": 28086,
"s": 28066,
"text": "cpp-stack-functions"
},
{
"code": null,
"e": 28090,
"s": 28086,
"text": "STL"
},
{
"code": null,
"e": 28094,
"s": 28090,
"text": "C++"
},
{
"code": null,
"e": 28098,
"s": 28094,
"text": "STL"
},
{
"code": null,
"e": 28102,
"s": 28098,
"text": "CPP"
},
{
"code": null,
"e": 28200,
"s": 28102,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28228,
"s": 28200,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 28248,
"s": 28228,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 28281,
"s": 28248,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 28305,
"s": 28281,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 28330,
"s": 28305,
"text": "std::string class in C++"
},
{
"code": null,
"e": 28374,
"s": 28330,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 28398,
"s": 28374,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 28443,
"s": 28398,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 28496,
"s": 28443,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
}
] |
Dart – Loops
|
01 Feb, 2021
Looping statement in Dart or any other programming language is used to repeat a certain set of commands until certain conditions are not completed. There are different ways to do so. They are:
for loop
for... in loop
for each loop
while loop
do-while loop
For loop in Dart is similar to that in Java and also the flow of execution is the same as that in Java.Syntax:
for(initialization; condition; test expression){
// Body of the loop
}
Control flow goes as:
initializationConditionBody of loopTest expression
initialization
Condition
Body of loop
Test expression
The first is executed only once i.e in the beginning while the other three are executed until the condition turns out to be false.Example:
Dart
// Printing GeeksForGeeks 5 timesvoid main(){ for (int i = 0; i < 5; i++) { print('GeeksForGeeks'); }}
Output:
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
For...in loop in Dart takes an expression or object as an iterator. It is similar to that in Java and its flow of execution is also the same as that in Java.
Syntax:
for (var in expression) {
// Body of loop
}
Example:
Dart
void main(){ var GeeksForGeeks = [ 1, 2, 3, 4, 5 ]; for (int i in GeeksForGeeks) { print(i); }}
Output:
1
2
3
4
5
The for-each loop iterates over all elements in some container/collectible and passes the elements to some specific function.
Syntax:
collection.foreach(void f(value))
Parameters:
f( value): It is used to make a call to the f function for each element in the collection.
Dart
void main() { var GeeksForGeeks = [1,2,3,4,5]; GeeksForGeeks.forEach((var num)=> print(num));}
Output:
1
2
3
4
5
The body of the loop will run until and unless the condition is true.
Syntax:
while(condition){
text expression;
// Body of loop
}
Example:
Dart
void main(){ var GeeksForGeeks = 4; int i = 1; while (i <= GeeksForGeeks) { print('Hello Geek'); i++; }}
Output:
Hello Geek
Hello Geek
Hello Geek
Hello Geek
The body of the loop will be executed first and then the condition is tested.
Syntax:
do{
text expression;
// Body of loop
}while(condition);
Example:
Dart
void main(){ var GeeksForGeeks = 4; int i = 1; do { print('Hello Geek'); i++; } while (i <= GeeksForGeeks);}
Output:
Hello Geek
Hello Geek
Hello Geek
Hello Geek
vermaaayush68
Dart Loops
Dart
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": 223,
"s": 28,
"text": "Looping statement in Dart or any other programming language is used to repeat a certain set of commands until certain conditions are not completed. There are different ways to do so. They are: "
},
{
"code": null,
"e": 232,
"s": 223,
"text": "for loop"
},
{
"code": null,
"e": 247,
"s": 232,
"text": "for... in loop"
},
{
"code": null,
"e": 261,
"s": 247,
"text": "for each loop"
},
{
"code": null,
"e": 272,
"s": 261,
"text": "while loop"
},
{
"code": null,
"e": 286,
"s": 272,
"text": "do-while loop"
},
{
"code": null,
"e": 398,
"s": 286,
"text": "For loop in Dart is similar to that in Java and also the flow of execution is the same as that in Java.Syntax: "
},
{
"code": null,
"e": 474,
"s": 398,
"text": " for(initialization; condition; test expression){\n // Body of the loop\n}"
},
{
"code": null,
"e": 497,
"s": 474,
"text": "Control flow goes as: "
},
{
"code": null,
"e": 548,
"s": 497,
"text": "initializationConditionBody of loopTest expression"
},
{
"code": null,
"e": 563,
"s": 548,
"text": "initialization"
},
{
"code": null,
"e": 573,
"s": 563,
"text": "Condition"
},
{
"code": null,
"e": 586,
"s": 573,
"text": "Body of loop"
},
{
"code": null,
"e": 602,
"s": 586,
"text": "Test expression"
},
{
"code": null,
"e": 743,
"s": 602,
"text": "The first is executed only once i.e in the beginning while the other three are executed until the condition turns out to be false.Example: "
},
{
"code": null,
"e": 748,
"s": 743,
"text": "Dart"
},
{
"code": "// Printing GeeksForGeeks 5 timesvoid main(){ for (int i = 0; i < 5; i++) { print('GeeksForGeeks'); }}",
"e": 864,
"s": 748,
"text": null
},
{
"code": null,
"e": 874,
"s": 864,
"text": "Output: "
},
{
"code": null,
"e": 944,
"s": 874,
"text": "GeeksForGeeks\nGeeksForGeeks\nGeeksForGeeks\nGeeksForGeeks\nGeeksForGeeks"
},
{
"code": null,
"e": 1105,
"s": 946,
"text": "For...in loop in Dart takes an expression or object as an iterator. It is similar to that in Java and its flow of execution is also the same as that in Java. "
},
{
"code": null,
"e": 1114,
"s": 1105,
"text": "Syntax: "
},
{
"code": null,
"e": 1162,
"s": 1114,
"text": " for (var in expression) {\n // Body of loop\n}"
},
{
"code": null,
"e": 1173,
"s": 1162,
"text": "Example: "
},
{
"code": null,
"e": 1178,
"s": 1173,
"text": "Dart"
},
{
"code": "void main(){ var GeeksForGeeks = [ 1, 2, 3, 4, 5 ]; for (int i in GeeksForGeeks) { print(i); }}",
"e": 1290,
"s": 1178,
"text": null
},
{
"code": null,
"e": 1300,
"s": 1290,
"text": "Output: "
},
{
"code": null,
"e": 1310,
"s": 1300,
"text": "1\n2\n3\n4\n5"
},
{
"code": null,
"e": 1436,
"s": 1310,
"text": "The for-each loop iterates over all elements in some container/collectible and passes the elements to some specific function."
},
{
"code": null,
"e": 1444,
"s": 1436,
"text": "Syntax:"
},
{
"code": null,
"e": 1479,
"s": 1444,
"text": " collection.foreach(void f(value))"
},
{
"code": null,
"e": 1491,
"s": 1479,
"text": "Parameters:"
},
{
"code": null,
"e": 1582,
"s": 1491,
"text": "f( value): It is used to make a call to the f function for each element in the collection."
},
{
"code": null,
"e": 1587,
"s": 1582,
"text": "Dart"
},
{
"code": "void main() { var GeeksForGeeks = [1,2,3,4,5]; GeeksForGeeks.forEach((var num)=> print(num));}",
"e": 1684,
"s": 1587,
"text": null
},
{
"code": null,
"e": 1692,
"s": 1684,
"text": "Output:"
},
{
"code": null,
"e": 1702,
"s": 1692,
"text": "1\n2\n3\n4\n5"
},
{
"code": null,
"e": 1773,
"s": 1702,
"text": "The body of the loop will run until and unless the condition is true. "
},
{
"code": null,
"e": 1782,
"s": 1773,
"text": "Syntax: "
},
{
"code": null,
"e": 1844,
"s": 1782,
"text": " while(condition){\n text expression;\n // Body of loop\n}"
},
{
"code": null,
"e": 1855,
"s": 1844,
"text": "Example: "
},
{
"code": null,
"e": 1860,
"s": 1855,
"text": "Dart"
},
{
"code": "void main(){ var GeeksForGeeks = 4; int i = 1; while (i <= GeeksForGeeks) { print('Hello Geek'); i++; }}",
"e": 1991,
"s": 1860,
"text": null
},
{
"code": null,
"e": 2001,
"s": 1991,
"text": "Output: "
},
{
"code": null,
"e": 2045,
"s": 2001,
"text": "Hello Geek\nHello Geek\nHello Geek\nHello Geek"
},
{
"code": null,
"e": 2126,
"s": 2047,
"text": "The body of the loop will be executed first and then the condition is tested. "
},
{
"code": null,
"e": 2135,
"s": 2126,
"text": "Syntax: "
},
{
"code": null,
"e": 2200,
"s": 2135,
"text": " do{\n text expression;\n // Body of loop\n}while(condition);"
},
{
"code": null,
"e": 2211,
"s": 2200,
"text": "Example: "
},
{
"code": null,
"e": 2216,
"s": 2211,
"text": "Dart"
},
{
"code": "void main(){ var GeeksForGeeks = 4; int i = 1; do { print('Hello Geek'); i++; } while (i <= GeeksForGeeks);}",
"e": 2351,
"s": 2216,
"text": null
},
{
"code": null,
"e": 2361,
"s": 2351,
"text": "Output: "
},
{
"code": null,
"e": 2405,
"s": 2361,
"text": "Hello Geek\nHello Geek\nHello Geek\nHello Geek"
},
{
"code": null,
"e": 2421,
"s": 2407,
"text": "vermaaayush68"
},
{
"code": null,
"e": 2432,
"s": 2421,
"text": "Dart Loops"
},
{
"code": null,
"e": 2437,
"s": 2432,
"text": "Dart"
}
] |
How to convert IEnumerable to List and List back to IEnumerable in C#?
|
IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated.
This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.
List class represents the list of objects which can be accessed by index. It comes under the System.Collection.Generic namespace.
List class can be used to create a collection of different types like integers, strings etc. List class also provides the methods to search, sort, and manipulate lists.
static void Main(string[] args) {
List list = new List();
IEnumerable enumerable = Enumerable.Range(1, 5);
foreach (var item in enumerable) {
list.Add(item);
}
foreach (var item in list) {
Console.WriteLine(item);
}
Console.ReadLine();
}
1
2
3
4
5
convert List to IEnumerable
static void Main(string[] args) {
List list = new List();
IEnumerable enumerable = Enumerable.Range(1, 5);
foreach (var item in enumerable) {
list.Add(item);
}
foreach (var item in list) {
Console.WriteLine(item);
}
IEnumerable enumerableAfterConversion= list.AsEnumerable();
foreach (var item in enumerableAfterConversion) {
Console.WriteLine(item);
}
Console.ReadLine();
}
1
2
3
4
5
1
2
3
4
5
|
[
{
"code": null,
"e": 1376,
"s": 1187,
"text": "IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated."
},
{
"code": null,
"e": 1495,
"s": 1376,
"text": "This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement."
},
{
"code": null,
"e": 1625,
"s": 1495,
"text": "List class represents the list of objects which can be accessed by index. It comes under the System.Collection.Generic namespace."
},
{
"code": null,
"e": 1794,
"s": 1625,
"text": "List class can be used to create a collection of different types like integers, strings etc. List class also provides the methods to search, sort, and manipulate lists."
},
{
"code": null,
"e": 2066,
"s": 1794,
"text": "static void Main(string[] args) {\n List list = new List();\n IEnumerable enumerable = Enumerable.Range(1, 5);\n\n foreach (var item in enumerable) {\n list.Add(item);\n }\n foreach (var item in list) {\n Console.WriteLine(item);\n }\n Console.ReadLine();\n}"
},
{
"code": null,
"e": 2076,
"s": 2066,
"text": "1\n2\n3\n4\n5"
},
{
"code": null,
"e": 2104,
"s": 2076,
"text": "convert List to IEnumerable"
},
{
"code": null,
"e": 2528,
"s": 2104,
"text": "static void Main(string[] args) {\n List list = new List();\n IEnumerable enumerable = Enumerable.Range(1, 5);\n\n foreach (var item in enumerable) {\n list.Add(item);\n }\n foreach (var item in list) {\n Console.WriteLine(item);\n }\n IEnumerable enumerableAfterConversion= list.AsEnumerable();\n foreach (var item in enumerableAfterConversion) {\n Console.WriteLine(item);\n }\n Console.ReadLine();\n}"
},
{
"code": null,
"e": 2548,
"s": 2528,
"text": "1\n2\n3\n4\n5\n1\n2\n3\n4\n5"
}
] |
MySQL | Grant / Revoke Privileges
|
03 Mar, 2018
Granting Privileges
We have already learned about how to create user in MySQL using MySQL | create user statement. But using the Create User Statement only creates a new user but does not grant any privileges to the user account.Therefore to grant privileges to a user account, the GRANT statement is used.
Syntax:
GRANT privileges_names ON object TO user;
Parameters Used:
privileges_name: These are the access rights or privileges granted to the user.
object:It is the name of the database object to which permissions are being granted. In the case of granting privileges on a table, this would be the table name.
user:It is the name of the user to whom the privileges would be granted.
Privileges:The privileges that can be granted to the users are listed below along with description:
Let us now learn about different ways of granting privileges to the users:
Granting SELECT Privilege to a User in a Table: To grant Select Privilege to a table named “users” where User Name is Amit, the following GRANT statement should be executed.GRANT SELECT ON Users TO'Amit'@'localhost;Granting more than one Privilege to a User in a Table: To grant multiple Privileges to a user named “Amit” in a table “users”, the following GRANT statement should be executed.GRANT SELECT, INSERT, DELETE, UPDATE ON Users TO 'Amit'@'localhost;Granting All the Privilege to a User in a Table: To Grant all the privileges to a user named “Amit” in a table “users”, the following Grant statement should be executed.GRANT ALL ON Users TO 'Amit'@'localhost;Granting a Privilege to all Users in a Table: To Grant a specific privilege to all the users in a table “users”, the following Grant statement should be executed.GRANT SELECT ON Users TO '*'@'localhost;In the above example the “*” symbol is used to grant select permission to all the users of the table “users”.Granting Privileges on Functions/Procedures: While using functions and procedures, the Grant statement can be used to grant users the ability to execute the functions and procedures in MySQL.Granting Execute Privilege: Execute privilege gives the ability to execute a function or procedure.Syntax:GRANT EXECUTE ON [ PROCEDURE | FUNCTION ] object TO user; Different ways of granting EXECUTE Privileges:Granting EXECUTE privileges on a function in MySQL.: If there is a function named “CalculateSalary” and you want to grant EXECUTE access to the user named Amit, then the following GRANT statement should be executed.GRANT EXECUTE ON FUNCTION Calculatesalary TO 'Amit'@localhost';Granting EXECUTE privileges to all Users on a function in MySQL.: If there is a function named “CalculateSalary” and you want to grant EXECUTE access to all the users, then the following GRANT statement should be executed.GRANT EXECUTE ON FUNCTION Calculatesalary TO '*'@localhost'; Granting EXECUTE privilege to a Users on a procedure in MySQL.: If there is a procedure named “DBMSProcedure” and you want to grant EXECUTE access to the user named Amit, then the following GRANT statement should be executed.GRANT EXECUTE ON PROCEDURE DBMSProcedure TO 'Amit'@localhost'; Granting EXECUTE privileges to all Users on a procedure in MySQL.: If there is a procedure called “DBMSProcedure” and you want to grant EXECUTE access to all the users, then the following GRANT statement should be executed.GRANT EXECUTE ON PROCEDURE DBMSProcedure TO '*'@localhost';
Granting SELECT Privilege to a User in a Table: To grant Select Privilege to a table named “users” where User Name is Amit, the following GRANT statement should be executed.GRANT SELECT ON Users TO'Amit'@'localhost;
GRANT SELECT ON Users TO'Amit'@'localhost;
Granting more than one Privilege to a User in a Table: To grant multiple Privileges to a user named “Amit” in a table “users”, the following GRANT statement should be executed.GRANT SELECT, INSERT, DELETE, UPDATE ON Users TO 'Amit'@'localhost;
GRANT SELECT, INSERT, DELETE, UPDATE ON Users TO 'Amit'@'localhost;
Granting All the Privilege to a User in a Table: To Grant all the privileges to a user named “Amit” in a table “users”, the following Grant statement should be executed.GRANT ALL ON Users TO 'Amit'@'localhost;
GRANT ALL ON Users TO 'Amit'@'localhost;
Granting a Privilege to all Users in a Table: To Grant a specific privilege to all the users in a table “users”, the following Grant statement should be executed.GRANT SELECT ON Users TO '*'@'localhost;In the above example the “*” symbol is used to grant select permission to all the users of the table “users”.
GRANT SELECT ON Users TO '*'@'localhost;
In the above example the “*” symbol is used to grant select permission to all the users of the table “users”.
Granting Privileges on Functions/Procedures: While using functions and procedures, the Grant statement can be used to grant users the ability to execute the functions and procedures in MySQL.Granting Execute Privilege: Execute privilege gives the ability to execute a function or procedure.Syntax:GRANT EXECUTE ON [ PROCEDURE | FUNCTION ] object TO user; Different ways of granting EXECUTE Privileges:Granting EXECUTE privileges on a function in MySQL.: If there is a function named “CalculateSalary” and you want to grant EXECUTE access to the user named Amit, then the following GRANT statement should be executed.GRANT EXECUTE ON FUNCTION Calculatesalary TO 'Amit'@localhost';Granting EXECUTE privileges to all Users on a function in MySQL.: If there is a function named “CalculateSalary” and you want to grant EXECUTE access to all the users, then the following GRANT statement should be executed.GRANT EXECUTE ON FUNCTION Calculatesalary TO '*'@localhost'; Granting EXECUTE privilege to a Users on a procedure in MySQL.: If there is a procedure named “DBMSProcedure” and you want to grant EXECUTE access to the user named Amit, then the following GRANT statement should be executed.GRANT EXECUTE ON PROCEDURE DBMSProcedure TO 'Amit'@localhost'; Granting EXECUTE privileges to all Users on a procedure in MySQL.: If there is a procedure called “DBMSProcedure” and you want to grant EXECUTE access to all the users, then the following GRANT statement should be executed.GRANT EXECUTE ON PROCEDURE DBMSProcedure TO '*'@localhost';
Granting Execute Privilege: Execute privilege gives the ability to execute a function or procedure.
Syntax:
GRANT EXECUTE ON [ PROCEDURE | FUNCTION ] object TO user;
Different ways of granting EXECUTE Privileges:
Granting EXECUTE privileges on a function in MySQL.: If there is a function named “CalculateSalary” and you want to grant EXECUTE access to the user named Amit, then the following GRANT statement should be executed.GRANT EXECUTE ON FUNCTION Calculatesalary TO 'Amit'@localhost';
GRANT EXECUTE ON FUNCTION Calculatesalary TO 'Amit'@localhost';
Granting EXECUTE privileges to all Users on a function in MySQL.: If there is a function named “CalculateSalary” and you want to grant EXECUTE access to all the users, then the following GRANT statement should be executed.GRANT EXECUTE ON FUNCTION Calculatesalary TO '*'@localhost';
GRANT EXECUTE ON FUNCTION Calculatesalary TO '*'@localhost';
Granting EXECUTE privilege to a Users on a procedure in MySQL.: If there is a procedure named “DBMSProcedure” and you want to grant EXECUTE access to the user named Amit, then the following GRANT statement should be executed.GRANT EXECUTE ON PROCEDURE DBMSProcedure TO 'Amit'@localhost';
GRANT EXECUTE ON PROCEDURE DBMSProcedure TO 'Amit'@localhost';
Granting EXECUTE privileges to all Users on a procedure in MySQL.: If there is a procedure called “DBMSProcedure” and you want to grant EXECUTE access to all the users, then the following GRANT statement should be executed.GRANT EXECUTE ON PROCEDURE DBMSProcedure TO '*'@localhost';
GRANT EXECUTE ON PROCEDURE DBMSProcedure TO '*'@localhost';
Checking the Privileges Granted to a User: To see the privileges granted to a user in a table, the SHOW GRANTS statement is used. To check the privileges granted to a user named “Amit” and host as “localhost”, the following SHOW GRANTS statement will be executed:
SHOW GRANTS FOR 'Amit'@localhost';
Output :
GRANTS FOR Amit@localhost
GRANT USAGE ON *.* TO `SUPER`@localhost`
Revoking Privileges from a Table
The Revoke statement is used to revoke some or all of the privileges which have been granted to a user in the past.
Syntax:
REVOKE privileges ON object FROM user;
Parameters Used:
object:It is the name of the database object from which permissions are being revoked. In the case of revoking privileges from a table, this would be the table name.
user:It is the name of the user from whom the privileges are being revoked.
PrivilegesPrivileges can be of the following values:
Different ways of revoking privileges from a user:
Revoking SELECT Privilege to a User in a Table: To revoke Select Privilege to a table named “users” where User Name is Amit, the following revoke statement should be executed.REVOKE SELECT ON users TO 'Amit'@localhost'; Revoking more than Privilege to a User in a Table: To revoke multiple Privileges to a user named “Amit” in a table “users”, the following revoke statement should be executed.REVOKE SELECT, INSERT, DELETE, UPDATE ON Users TO 'Amit'@'localhost; Revoking All the Privilege to a User in a Table: To revoke all the privileges to a user named “Amit” in a table “users”, the following revoke statement should be executed.REVOKE ALL ON Users TO 'Amit'@'localhost; Revoking a Privilege to all Users in a Table: To Revoke a specific privilege to all the users in a table “users”, the following revoke statement should be executed.REVOKE SELECT ON Users TO '*'@'localhost; Revoking Privileges on Functions/Procedures: While using functions and procedures, the revoke statement can be used to revoke the privileges from users which have been EXECUTE privileges in the past.Syntax:REVOKE EXECUTE ON [ PROCEDURE | FUNCTION ] object FROM user; Revoking EXECUTE privileges on a function in MySQL.: If there is a function called “CalculateSalary” and you want to revoke EXECUTE access to the user named Amit, then the following revoke statement should be executed.REVOKE EXECUTE ON FUNCTION Calculatesalary TO 'Amit'@localhost'; Revoking EXECUTE privileges to all Users on a function in MySQL.: If there is a function called “CalculateSalary” and you want to revoke EXECUTE access to all the users, then the following revoke statement should be executed.REVOKE EXECUTE ON FUNCTION Calculatesalary TO '*'@localhost'; Revoking EXECUTE privilege to a Users on a procedure in MySQL.: If there is a procedure called “DBMSProcedure” and you want to revoke EXECUTE access to the user named Amit, then the following revoke statement should be executed.REVOKE EXECUTE ON PROCEDURE DBMSProcedure TO 'Amit'@localhost'; Revoking EXECUTE privileges to all Users on a procedure in MySQL.: If there is a procedure called “DBMSProcedure” and you want to revoke EXECUTE access to all the users, then the following revoke statement should be executed.REVOKE EXECUTE ON PROCEDURE DBMSProcedure TO '*'@localhost';
Revoking SELECT Privilege to a User in a Table: To revoke Select Privilege to a table named “users” where User Name is Amit, the following revoke statement should be executed.REVOKE SELECT ON users TO 'Amit'@localhost';
REVOKE SELECT ON users TO 'Amit'@localhost';
Revoking more than Privilege to a User in a Table: To revoke multiple Privileges to a user named “Amit” in a table “users”, the following revoke statement should be executed.REVOKE SELECT, INSERT, DELETE, UPDATE ON Users TO 'Amit'@'localhost;
REVOKE SELECT, INSERT, DELETE, UPDATE ON Users TO 'Amit'@'localhost;
Revoking All the Privilege to a User in a Table: To revoke all the privileges to a user named “Amit” in a table “users”, the following revoke statement should be executed.REVOKE ALL ON Users TO 'Amit'@'localhost;
Revoking All the Privilege to a User in a Table: To revoke all the privileges to a user named “Amit” in a table “users”, the following revoke statement should be executed.
REVOKE ALL ON Users TO 'Amit'@'localhost;
Revoking a Privilege to all Users in a Table: To Revoke a specific privilege to all the users in a table “users”, the following revoke statement should be executed.REVOKE SELECT ON Users TO '*'@'localhost;
REVOKE SELECT ON Users TO '*'@'localhost;
Revoking Privileges on Functions/Procedures: While using functions and procedures, the revoke statement can be used to revoke the privileges from users which have been EXECUTE privileges in the past.Syntax:REVOKE EXECUTE ON [ PROCEDURE | FUNCTION ] object FROM user; Revoking EXECUTE privileges on a function in MySQL.: If there is a function called “CalculateSalary” and you want to revoke EXECUTE access to the user named Amit, then the following revoke statement should be executed.REVOKE EXECUTE ON FUNCTION Calculatesalary TO 'Amit'@localhost'; Revoking EXECUTE privileges to all Users on a function in MySQL.: If there is a function called “CalculateSalary” and you want to revoke EXECUTE access to all the users, then the following revoke statement should be executed.REVOKE EXECUTE ON FUNCTION Calculatesalary TO '*'@localhost'; Revoking EXECUTE privilege to a Users on a procedure in MySQL.: If there is a procedure called “DBMSProcedure” and you want to revoke EXECUTE access to the user named Amit, then the following revoke statement should be executed.REVOKE EXECUTE ON PROCEDURE DBMSProcedure TO 'Amit'@localhost'; Revoking EXECUTE privileges to all Users on a procedure in MySQL.: If there is a procedure called “DBMSProcedure” and you want to revoke EXECUTE access to all the users, then the following revoke statement should be executed.REVOKE EXECUTE ON PROCEDURE DBMSProcedure TO '*'@localhost';
Syntax:
REVOKE EXECUTE ON [ PROCEDURE | FUNCTION ] object FROM user;
Revoking EXECUTE privileges on a function in MySQL.: If there is a function called “CalculateSalary” and you want to revoke EXECUTE access to the user named Amit, then the following revoke statement should be executed.REVOKE EXECUTE ON FUNCTION Calculatesalary TO 'Amit'@localhost';
REVOKE EXECUTE ON FUNCTION Calculatesalary TO 'Amit'@localhost';
Revoking EXECUTE privileges to all Users on a function in MySQL.: If there is a function called “CalculateSalary” and you want to revoke EXECUTE access to all the users, then the following revoke statement should be executed.REVOKE EXECUTE ON FUNCTION Calculatesalary TO '*'@localhost';
REVOKE EXECUTE ON FUNCTION Calculatesalary TO '*'@localhost';
Revoking EXECUTE privilege to a Users on a procedure in MySQL.: If there is a procedure called “DBMSProcedure” and you want to revoke EXECUTE access to the user named Amit, then the following revoke statement should be executed.REVOKE EXECUTE ON PROCEDURE DBMSProcedure TO 'Amit'@localhost';
REVOKE EXECUTE ON PROCEDURE DBMSProcedure TO 'Amit'@localhost';
Revoking EXECUTE privileges to all Users on a procedure in MySQL.: If there is a procedure called “DBMSProcedure” and you want to revoke EXECUTE access to all the users, then the following revoke statement should be executed.REVOKE EXECUTE ON PROCEDURE DBMSProcedure TO '*'@localhost';
REVOKE EXECUTE ON PROCEDURE DBMSProcedure TO '*'@localhost';
mysql
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Difference between Clustered and Non-clustered index
Introduction of B-Tree
SQL Interview Questions
Data Preprocessing in Data Mining
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
CTE in SQL
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Mar, 2018"
},
{
"code": null,
"e": 74,
"s": 54,
"text": "Granting Privileges"
},
{
"code": null,
"e": 361,
"s": 74,
"text": "We have already learned about how to create user in MySQL using MySQL | create user statement. But using the Create User Statement only creates a new user but does not grant any privileges to the user account.Therefore to grant privileges to a user account, the GRANT statement is used."
},
{
"code": null,
"e": 369,
"s": 361,
"text": "Syntax:"
},
{
"code": null,
"e": 411,
"s": 369,
"text": "GRANT privileges_names ON object TO user;"
},
{
"code": null,
"e": 428,
"s": 411,
"text": "Parameters Used:"
},
{
"code": null,
"e": 508,
"s": 428,
"text": "privileges_name: These are the access rights or privileges granted to the user."
},
{
"code": null,
"e": 670,
"s": 508,
"text": "object:It is the name of the database object to which permissions are being granted. In the case of granting privileges on a table, this would be the table name."
},
{
"code": null,
"e": 743,
"s": 670,
"text": "user:It is the name of the user to whom the privileges would be granted."
},
{
"code": null,
"e": 843,
"s": 743,
"text": "Privileges:The privileges that can be granted to the users are listed below along with description:"
},
{
"code": null,
"e": 918,
"s": 843,
"text": "Let us now learn about different ways of granting privileges to the users:"
},
{
"code": null,
"e": 3431,
"s": 918,
"text": "Granting SELECT Privilege to a User in a Table: To grant Select Privilege to a table named “users” where User Name is Amit, the following GRANT statement should be executed.GRANT SELECT ON Users TO'Amit'@'localhost;Granting more than one Privilege to a User in a Table: To grant multiple Privileges to a user named “Amit” in a table “users”, the following GRANT statement should be executed.GRANT SELECT, INSERT, DELETE, UPDATE ON Users TO 'Amit'@'localhost;Granting All the Privilege to a User in a Table: To Grant all the privileges to a user named “Amit” in a table “users”, the following Grant statement should be executed.GRANT ALL ON Users TO 'Amit'@'localhost;Granting a Privilege to all Users in a Table: To Grant a specific privilege to all the users in a table “users”, the following Grant statement should be executed.GRANT SELECT ON Users TO '*'@'localhost;In the above example the “*” symbol is used to grant select permission to all the users of the table “users”.Granting Privileges on Functions/Procedures: While using functions and procedures, the Grant statement can be used to grant users the ability to execute the functions and procedures in MySQL.Granting Execute Privilege: Execute privilege gives the ability to execute a function or procedure.Syntax:GRANT EXECUTE ON [ PROCEDURE | FUNCTION ] object TO user; Different ways of granting EXECUTE Privileges:Granting EXECUTE privileges on a function in MySQL.: If there is a function named “CalculateSalary” and you want to grant EXECUTE access to the user named Amit, then the following GRANT statement should be executed.GRANT EXECUTE ON FUNCTION Calculatesalary TO 'Amit'@localhost';Granting EXECUTE privileges to all Users on a function in MySQL.: If there is a function named “CalculateSalary” and you want to grant EXECUTE access to all the users, then the following GRANT statement should be executed.GRANT EXECUTE ON FUNCTION Calculatesalary TO '*'@localhost'; Granting EXECUTE privilege to a Users on a procedure in MySQL.: If there is a procedure named “DBMSProcedure” and you want to grant EXECUTE access to the user named Amit, then the following GRANT statement should be executed.GRANT EXECUTE ON PROCEDURE DBMSProcedure TO 'Amit'@localhost'; Granting EXECUTE privileges to all Users on a procedure in MySQL.: If there is a procedure called “DBMSProcedure” and you want to grant EXECUTE access to all the users, then the following GRANT statement should be executed.GRANT EXECUTE ON PROCEDURE DBMSProcedure TO '*'@localhost'; "
},
{
"code": null,
"e": 3647,
"s": 3431,
"text": "Granting SELECT Privilege to a User in a Table: To grant Select Privilege to a table named “users” where User Name is Amit, the following GRANT statement should be executed.GRANT SELECT ON Users TO'Amit'@'localhost;"
},
{
"code": null,
"e": 3690,
"s": 3647,
"text": "GRANT SELECT ON Users TO'Amit'@'localhost;"
},
{
"code": null,
"e": 3934,
"s": 3690,
"text": "Granting more than one Privilege to a User in a Table: To grant multiple Privileges to a user named “Amit” in a table “users”, the following GRANT statement should be executed.GRANT SELECT, INSERT, DELETE, UPDATE ON Users TO 'Amit'@'localhost;"
},
{
"code": null,
"e": 4002,
"s": 3934,
"text": "GRANT SELECT, INSERT, DELETE, UPDATE ON Users TO 'Amit'@'localhost;"
},
{
"code": null,
"e": 4212,
"s": 4002,
"text": "Granting All the Privilege to a User in a Table: To Grant all the privileges to a user named “Amit” in a table “users”, the following Grant statement should be executed.GRANT ALL ON Users TO 'Amit'@'localhost;"
},
{
"code": null,
"e": 4253,
"s": 4212,
"text": "GRANT ALL ON Users TO 'Amit'@'localhost;"
},
{
"code": null,
"e": 4566,
"s": 4253,
"text": "Granting a Privilege to all Users in a Table: To Grant a specific privilege to all the users in a table “users”, the following Grant statement should be executed.GRANT SELECT ON Users TO '*'@'localhost;In the above example the “*” symbol is used to grant select permission to all the users of the table “users”."
},
{
"code": null,
"e": 4608,
"s": 4566,
"text": "GRANT SELECT ON Users TO '*'@'localhost;"
},
{
"code": null,
"e": 4718,
"s": 4608,
"text": "In the above example the “*” symbol is used to grant select permission to all the users of the table “users”."
},
{
"code": null,
"e": 6252,
"s": 4718,
"text": "Granting Privileges on Functions/Procedures: While using functions and procedures, the Grant statement can be used to grant users the ability to execute the functions and procedures in MySQL.Granting Execute Privilege: Execute privilege gives the ability to execute a function or procedure.Syntax:GRANT EXECUTE ON [ PROCEDURE | FUNCTION ] object TO user; Different ways of granting EXECUTE Privileges:Granting EXECUTE privileges on a function in MySQL.: If there is a function named “CalculateSalary” and you want to grant EXECUTE access to the user named Amit, then the following GRANT statement should be executed.GRANT EXECUTE ON FUNCTION Calculatesalary TO 'Amit'@localhost';Granting EXECUTE privileges to all Users on a function in MySQL.: If there is a function named “CalculateSalary” and you want to grant EXECUTE access to all the users, then the following GRANT statement should be executed.GRANT EXECUTE ON FUNCTION Calculatesalary TO '*'@localhost'; Granting EXECUTE privilege to a Users on a procedure in MySQL.: If there is a procedure named “DBMSProcedure” and you want to grant EXECUTE access to the user named Amit, then the following GRANT statement should be executed.GRANT EXECUTE ON PROCEDURE DBMSProcedure TO 'Amit'@localhost'; Granting EXECUTE privileges to all Users on a procedure in MySQL.: If there is a procedure called “DBMSProcedure” and you want to grant EXECUTE access to all the users, then the following GRANT statement should be executed.GRANT EXECUTE ON PROCEDURE DBMSProcedure TO '*'@localhost'; "
},
{
"code": null,
"e": 6352,
"s": 6252,
"text": "Granting Execute Privilege: Execute privilege gives the ability to execute a function or procedure."
},
{
"code": null,
"e": 6360,
"s": 6352,
"text": "Syntax:"
},
{
"code": null,
"e": 6419,
"s": 6360,
"text": "GRANT EXECUTE ON [ PROCEDURE | FUNCTION ] object TO user; "
},
{
"code": null,
"e": 6466,
"s": 6419,
"text": "Different ways of granting EXECUTE Privileges:"
},
{
"code": null,
"e": 6745,
"s": 6466,
"text": "Granting EXECUTE privileges on a function in MySQL.: If there is a function named “CalculateSalary” and you want to grant EXECUTE access to the user named Amit, then the following GRANT statement should be executed.GRANT EXECUTE ON FUNCTION Calculatesalary TO 'Amit'@localhost';"
},
{
"code": null,
"e": 6809,
"s": 6745,
"text": "GRANT EXECUTE ON FUNCTION Calculatesalary TO 'Amit'@localhost';"
},
{
"code": null,
"e": 7093,
"s": 6809,
"text": "Granting EXECUTE privileges to all Users on a function in MySQL.: If there is a function named “CalculateSalary” and you want to grant EXECUTE access to all the users, then the following GRANT statement should be executed.GRANT EXECUTE ON FUNCTION Calculatesalary TO '*'@localhost'; "
},
{
"code": null,
"e": 7155,
"s": 7093,
"text": "GRANT EXECUTE ON FUNCTION Calculatesalary TO '*'@localhost'; "
},
{
"code": null,
"e": 7444,
"s": 7155,
"text": "Granting EXECUTE privilege to a Users on a procedure in MySQL.: If there is a procedure named “DBMSProcedure” and you want to grant EXECUTE access to the user named Amit, then the following GRANT statement should be executed.GRANT EXECUTE ON PROCEDURE DBMSProcedure TO 'Amit'@localhost'; "
},
{
"code": null,
"e": 7508,
"s": 7444,
"text": "GRANT EXECUTE ON PROCEDURE DBMSProcedure TO 'Amit'@localhost'; "
},
{
"code": null,
"e": 7792,
"s": 7508,
"text": "Granting EXECUTE privileges to all Users on a procedure in MySQL.: If there is a procedure called “DBMSProcedure” and you want to grant EXECUTE access to all the users, then the following GRANT statement should be executed.GRANT EXECUTE ON PROCEDURE DBMSProcedure TO '*'@localhost'; "
},
{
"code": null,
"e": 7853,
"s": 7792,
"text": "GRANT EXECUTE ON PROCEDURE DBMSProcedure TO '*'@localhost'; "
},
{
"code": null,
"e": 8117,
"s": 7853,
"text": "Checking the Privileges Granted to a User: To see the privileges granted to a user in a table, the SHOW GRANTS statement is used. To check the privileges granted to a user named “Amit” and host as “localhost”, the following SHOW GRANTS statement will be executed:"
},
{
"code": null,
"e": 8154,
"s": 8117,
"text": "SHOW GRANTS FOR 'Amit'@localhost'; "
},
{
"code": null,
"e": 8163,
"s": 8154,
"text": "Output :"
},
{
"code": null,
"e": 8235,
"s": 8163,
"text": "GRANTS FOR Amit@localhost \n\nGRANT USAGE ON *.* TO `SUPER`@localhost` \n"
},
{
"code": null,
"e": 8268,
"s": 8235,
"text": "Revoking Privileges from a Table"
},
{
"code": null,
"e": 8384,
"s": 8268,
"text": "The Revoke statement is used to revoke some or all of the privileges which have been granted to a user in the past."
},
{
"code": null,
"e": 8392,
"s": 8384,
"text": "Syntax:"
},
{
"code": null,
"e": 8432,
"s": 8392,
"text": "REVOKE privileges ON object FROM user;\n"
},
{
"code": null,
"e": 8449,
"s": 8432,
"text": "Parameters Used:"
},
{
"code": null,
"e": 8615,
"s": 8449,
"text": "object:It is the name of the database object from which permissions are being revoked. In the case of revoking privileges from a table, this would be the table name."
},
{
"code": null,
"e": 8691,
"s": 8615,
"text": "user:It is the name of the user from whom the privileges are being revoked."
},
{
"code": null,
"e": 8744,
"s": 8691,
"text": "PrivilegesPrivileges can be of the following values:"
},
{
"code": null,
"e": 8795,
"s": 8744,
"text": "Different ways of revoking privileges from a user:"
},
{
"code": null,
"e": 11095,
"s": 8795,
"text": "Revoking SELECT Privilege to a User in a Table: To revoke Select Privilege to a table named “users” where User Name is Amit, the following revoke statement should be executed.REVOKE SELECT ON users TO 'Amit'@localhost'; Revoking more than Privilege to a User in a Table: To revoke multiple Privileges to a user named “Amit” in a table “users”, the following revoke statement should be executed.REVOKE SELECT, INSERT, DELETE, UPDATE ON Users TO 'Amit'@'localhost; Revoking All the Privilege to a User in a Table: To revoke all the privileges to a user named “Amit” in a table “users”, the following revoke statement should be executed.REVOKE ALL ON Users TO 'Amit'@'localhost; Revoking a Privilege to all Users in a Table: To Revoke a specific privilege to all the users in a table “users”, the following revoke statement should be executed.REVOKE SELECT ON Users TO '*'@'localhost; Revoking Privileges on Functions/Procedures: While using functions and procedures, the revoke statement can be used to revoke the privileges from users which have been EXECUTE privileges in the past.Syntax:REVOKE EXECUTE ON [ PROCEDURE | FUNCTION ] object FROM user; Revoking EXECUTE privileges on a function in MySQL.: If there is a function called “CalculateSalary” and you want to revoke EXECUTE access to the user named Amit, then the following revoke statement should be executed.REVOKE EXECUTE ON FUNCTION Calculatesalary TO 'Amit'@localhost'; Revoking EXECUTE privileges to all Users on a function in MySQL.: If there is a function called “CalculateSalary” and you want to revoke EXECUTE access to all the users, then the following revoke statement should be executed.REVOKE EXECUTE ON FUNCTION Calculatesalary TO '*'@localhost'; Revoking EXECUTE privilege to a Users on a procedure in MySQL.: If there is a procedure called “DBMSProcedure” and you want to revoke EXECUTE access to the user named Amit, then the following revoke statement should be executed.REVOKE EXECUTE ON PROCEDURE DBMSProcedure TO 'Amit'@localhost'; Revoking EXECUTE privileges to all Users on a procedure in MySQL.: If there is a procedure called “DBMSProcedure” and you want to revoke EXECUTE access to all the users, then the following revoke statement should be executed.REVOKE EXECUTE ON PROCEDURE DBMSProcedure TO '*'@localhost'; "
},
{
"code": null,
"e": 11317,
"s": 11095,
"text": "Revoking SELECT Privilege to a User in a Table: To revoke Select Privilege to a table named “users” where User Name is Amit, the following revoke statement should be executed.REVOKE SELECT ON users TO 'Amit'@localhost'; "
},
{
"code": null,
"e": 11364,
"s": 11317,
"text": "REVOKE SELECT ON users TO 'Amit'@localhost'; "
},
{
"code": null,
"e": 11608,
"s": 11364,
"text": "Revoking more than Privilege to a User in a Table: To revoke multiple Privileges to a user named “Amit” in a table “users”, the following revoke statement should be executed.REVOKE SELECT, INSERT, DELETE, UPDATE ON Users TO 'Amit'@'localhost; "
},
{
"code": null,
"e": 11678,
"s": 11608,
"text": "REVOKE SELECT, INSERT, DELETE, UPDATE ON Users TO 'Amit'@'localhost; "
},
{
"code": null,
"e": 11892,
"s": 11678,
"text": "Revoking All the Privilege to a User in a Table: To revoke all the privileges to a user named “Amit” in a table “users”, the following revoke statement should be executed.REVOKE ALL ON Users TO 'Amit'@'localhost; "
},
{
"code": null,
"e": 12064,
"s": 11892,
"text": "Revoking All the Privilege to a User in a Table: To revoke all the privileges to a user named “Amit” in a table “users”, the following revoke statement should be executed."
},
{
"code": null,
"e": 12107,
"s": 12064,
"text": "REVOKE ALL ON Users TO 'Amit'@'localhost; "
},
{
"code": null,
"e": 12315,
"s": 12107,
"text": "Revoking a Privilege to all Users in a Table: To Revoke a specific privilege to all the users in a table “users”, the following revoke statement should be executed.REVOKE SELECT ON Users TO '*'@'localhost; "
},
{
"code": null,
"e": 12359,
"s": 12315,
"text": "REVOKE SELECT ON Users TO '*'@'localhost; "
},
{
"code": null,
"e": 13775,
"s": 12359,
"text": "Revoking Privileges on Functions/Procedures: While using functions and procedures, the revoke statement can be used to revoke the privileges from users which have been EXECUTE privileges in the past.Syntax:REVOKE EXECUTE ON [ PROCEDURE | FUNCTION ] object FROM user; Revoking EXECUTE privileges on a function in MySQL.: If there is a function called “CalculateSalary” and you want to revoke EXECUTE access to the user named Amit, then the following revoke statement should be executed.REVOKE EXECUTE ON FUNCTION Calculatesalary TO 'Amit'@localhost'; Revoking EXECUTE privileges to all Users on a function in MySQL.: If there is a function called “CalculateSalary” and you want to revoke EXECUTE access to all the users, then the following revoke statement should be executed.REVOKE EXECUTE ON FUNCTION Calculatesalary TO '*'@localhost'; Revoking EXECUTE privilege to a Users on a procedure in MySQL.: If there is a procedure called “DBMSProcedure” and you want to revoke EXECUTE access to the user named Amit, then the following revoke statement should be executed.REVOKE EXECUTE ON PROCEDURE DBMSProcedure TO 'Amit'@localhost'; Revoking EXECUTE privileges to all Users on a procedure in MySQL.: If there is a procedure called “DBMSProcedure” and you want to revoke EXECUTE access to all the users, then the following revoke statement should be executed.REVOKE EXECUTE ON PROCEDURE DBMSProcedure TO '*'@localhost'; "
},
{
"code": null,
"e": 13783,
"s": 13775,
"text": "Syntax:"
},
{
"code": null,
"e": 13845,
"s": 13783,
"text": "REVOKE EXECUTE ON [ PROCEDURE | FUNCTION ] object FROM user; "
},
{
"code": null,
"e": 14129,
"s": 13845,
"text": "Revoking EXECUTE privileges on a function in MySQL.: If there is a function called “CalculateSalary” and you want to revoke EXECUTE access to the user named Amit, then the following revoke statement should be executed.REVOKE EXECUTE ON FUNCTION Calculatesalary TO 'Amit'@localhost'; "
},
{
"code": null,
"e": 14195,
"s": 14129,
"text": "REVOKE EXECUTE ON FUNCTION Calculatesalary TO 'Amit'@localhost'; "
},
{
"code": null,
"e": 14483,
"s": 14195,
"text": "Revoking EXECUTE privileges to all Users on a function in MySQL.: If there is a function called “CalculateSalary” and you want to revoke EXECUTE access to all the users, then the following revoke statement should be executed.REVOKE EXECUTE ON FUNCTION Calculatesalary TO '*'@localhost'; "
},
{
"code": null,
"e": 14546,
"s": 14483,
"text": "REVOKE EXECUTE ON FUNCTION Calculatesalary TO '*'@localhost'; "
},
{
"code": null,
"e": 14839,
"s": 14546,
"text": "Revoking EXECUTE privilege to a Users on a procedure in MySQL.: If there is a procedure called “DBMSProcedure” and you want to revoke EXECUTE access to the user named Amit, then the following revoke statement should be executed.REVOKE EXECUTE ON PROCEDURE DBMSProcedure TO 'Amit'@localhost'; "
},
{
"code": null,
"e": 14904,
"s": 14839,
"text": "REVOKE EXECUTE ON PROCEDURE DBMSProcedure TO 'Amit'@localhost'; "
},
{
"code": null,
"e": 15191,
"s": 14904,
"text": "Revoking EXECUTE privileges to all Users on a procedure in MySQL.: If there is a procedure called “DBMSProcedure” and you want to revoke EXECUTE access to all the users, then the following revoke statement should be executed.REVOKE EXECUTE ON PROCEDURE DBMSProcedure TO '*'@localhost'; "
},
{
"code": null,
"e": 15253,
"s": 15191,
"text": "REVOKE EXECUTE ON PROCEDURE DBMSProcedure TO '*'@localhost'; "
},
{
"code": null,
"e": 15259,
"s": 15253,
"text": "mysql"
},
{
"code": null,
"e": 15264,
"s": 15259,
"text": "DBMS"
},
{
"code": null,
"e": 15268,
"s": 15264,
"text": "SQL"
},
{
"code": null,
"e": 15273,
"s": 15268,
"text": "DBMS"
},
{
"code": null,
"e": 15277,
"s": 15273,
"text": "SQL"
},
{
"code": null,
"e": 15375,
"s": 15277,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15386,
"s": 15375,
"text": "CTE in SQL"
},
{
"code": null,
"e": 15439,
"s": 15386,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 15462,
"s": 15439,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 15486,
"s": 15462,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 15520,
"s": 15486,
"text": "Data Preprocessing in Data Mining"
},
{
"code": null,
"e": 15562,
"s": 15520,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 15606,
"s": 15562,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 15617,
"s": 15606,
"text": "CTE in SQL"
},
{
"code": null,
"e": 15638,
"s": 15617,
"text": "SQL | ALTER (RENAME)"
}
] |
Render a HTML Template as Response – Django Views
|
11 Nov, 2019
A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response. This article revolves around how to render an HTML page from Django using views. Django has always been known for its app structure and ability to manage applications easily. Let’s dive in to see how to render a template file through a Django view.
Illustration of How to render a HTML Template in a view using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
After you have a project and an app, open views.py and let’s start creating a view called geeks_view which is used print “Hello world” through a template file. A django view is a python function which accept an argument called request and returns an response.Enter following code into views.py of app
from django.shortcuts import render # Create your views here.def geeks_view(request): # render function takes argument - request # and return HTML as response return render(request, "home.html")
but this code won’t work until into define a proper mapping of URL. Mapping means you need to tell Django what a user enters in the browser to render your particular view. For example www.geeksforgeeks.org tells django to execute its home page view. So let’s modify urls.py to start our view.Include your app’s urls into main urls by adding following code to geeksforgeeks > urls.py
"""geeksforgeeks URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com / en / 2.2 / topics / http / urls / Examples:Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name ='home')Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name ='home')Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))"""from django.contrib import adminfrom django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include("geeks.urls")),]
Now lets create a path to our view from geeks > urls.py
from django.contrib import adminfrom django.urls import path # importing views from views..pyfrom .views import geeks_view urlpatterns = [ path('', geeks_view ),]
Done. Now go to check if our template gets rendered or not. visit here – http://localhost:8000/
It is giving an error that you don’t have a template home.html. So let’s create our template now, in geeks folder create a folder called templates and create a file home.html into it. Now let’s check again – http://localhost:8000/.
This way you can render any template file using the same procedure –
1. Create a view in views.py
2. Create a template file which is to be rendered and link it to the view.
3. Create a URL to map to that view.
We used this error because during your process of learning on how to create a project using django? you may encounter a lot of errors, there you dont need to hyper, just take a long breath and simply google the error you will have solution to everything.
Django-models
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
Python | os.path.join() method
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n11 Nov, 2019"
},
{
"code": null,
"e": 419,
"s": 53,
"text": "A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response. This article revolves around how to render an HTML page from Django using views. Django has always been known for its app structure and ability to manage applications easily. Let’s dive in to see how to render a template file through a Django view."
},
{
"code": null,
"e": 559,
"s": 419,
"text": "Illustration of How to render a HTML Template in a view using an Example. Consider a project named geeksforgeeks having an app named geeks."
},
{
"code": null,
"e": 646,
"s": 559,
"text": "Refer to the following articles to check how to create a project and an app in Django."
},
{
"code": null,
"e": 697,
"s": 646,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 730,
"s": 697,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 1031,
"s": 730,
"text": "After you have a project and an app, open views.py and let’s start creating a view called geeks_view which is used print “Hello world” through a template file. A django view is a python function which accept an argument called request and returns an response.Enter following code into views.py of app"
},
{
"code": "from django.shortcuts import render # Create your views here.def geeks_view(request): # render function takes argument - request # and return HTML as response return render(request, \"home.html\")",
"e": 1243,
"s": 1031,
"text": null
},
{
"code": null,
"e": 1626,
"s": 1243,
"text": "but this code won’t work until into define a proper mapping of URL. Mapping means you need to tell Django what a user enters in the browser to render your particular view. For example www.geeksforgeeks.org tells django to execute its home page view. So let’s modify urls.py to start our view.Include your app’s urls into main urls by adding following code to geeksforgeeks > urls.py"
},
{
"code": "\"\"\"geeksforgeeks URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com / en / 2.2 / topics / http / urls / Examples:Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name ='home')Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name ='home')Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\"\"\"from django.contrib import adminfrom django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include(\"geeks.urls\")),]",
"e": 2424,
"s": 1626,
"text": null
},
{
"code": null,
"e": 2480,
"s": 2424,
"text": "Now lets create a path to our view from geeks > urls.py"
},
{
"code": "from django.contrib import adminfrom django.urls import path # importing views from views..pyfrom .views import geeks_view urlpatterns = [ path('', geeks_view ),]",
"e": 2648,
"s": 2480,
"text": null
},
{
"code": null,
"e": 2744,
"s": 2648,
"text": "Done. Now go to check if our template gets rendered or not. visit here – http://localhost:8000/"
},
{
"code": null,
"e": 2976,
"s": 2744,
"text": "It is giving an error that you don’t have a template home.html. So let’s create our template now, in geeks folder create a folder called templates and create a file home.html into it. Now let’s check again – http://localhost:8000/."
},
{
"code": null,
"e": 3045,
"s": 2976,
"text": "This way you can render any template file using the same procedure –"
},
{
"code": null,
"e": 3186,
"s": 3045,
"text": "1. Create a view in views.py\n2. Create a template file which is to be rendered and link it to the view.\n3. Create a URL to map to that view."
},
{
"code": null,
"e": 3441,
"s": 3186,
"text": "We used this error because during your process of learning on how to create a project using django? you may encounter a lot of errors, there you dont need to hyper, just take a long breath and simply google the error you will have solution to everything."
},
{
"code": null,
"e": 3455,
"s": 3441,
"text": "Django-models"
},
{
"code": null,
"e": 3469,
"s": 3455,
"text": "Python Django"
},
{
"code": null,
"e": 3476,
"s": 3469,
"text": "Python"
},
{
"code": null,
"e": 3574,
"s": 3476,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3592,
"s": 3574,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3634,
"s": 3592,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3656,
"s": 3634,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3682,
"s": 3656,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3714,
"s": 3682,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3743,
"s": 3714,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3770,
"s": 3743,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3806,
"s": 3770,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 3827,
"s": 3806,
"text": "Python OOPs Concepts"
}
] |
Machine Learning - GeeksforGeeks
|
02 Jun, 2022
Machine Learning is the field of study that gives computers the capability to learn without being explicitly programmed. ML is one of the most exciting technologies that one would have ever come across. As it is evident from the name, it gives the computer that makes it more similar to humans: The ability to learn. Machine learning is actively being used today, perhaps in many more places than one would expect.
Machine Learning is an essential skill for any aspiring data analyst and data scientist, and also for those who wish to transform a massive amount of raw data into trends and predictions. Learn this skill today with Machine Learning Foundation – Self Paced Course , designed and curated by industry experts having years of expertise in ML and industry-based projects.
Introduction
Data and it’s Processing
Supervised Learning
Unsupervised Learning
Reinforcement Learning
Dimensionality Reduction
Natural Language Processing
Neural Networks
ML – Deployment
ML – Applications
Miscellaneous
Introduction :
Getting Started with Machine LearningAn Introduction to Machine LearningWhat is Machine Learning ?Introduction to Data in Machine LearningDemystifying Machine LearningML – ApplicationsBest Python libraries for Machine LearningArtificial Intelligence | An IntroductionMachine Learning and Artificial IntelligenceDifference between Machine learning and Artificial IntelligenceAgents in Artificial Intelligence10 Basic Machine Learning Interview Questions
Getting Started with Machine Learning
An Introduction to Machine Learning
What is Machine Learning ?
Introduction to Data in Machine Learning
Demystifying Machine Learning
ML – Applications
Best Python libraries for Machine Learning
Artificial Intelligence | An Introduction
Machine Learning and Artificial Intelligence
Difference between Machine learning and Artificial Intelligence
Agents in Artificial Intelligence
10 Basic Machine Learning Interview Questions
Data and It’s Processing:
Introduction to Data in Machine LearningUnderstanding Data ProcessingPython | Create Test DataSets using SklearnPython | Generate test datasets for Machine learningPython | Data Preprocessing in PythonData CleaningFeature Scaling – Part 1Feature Scaling – Part 2Python | Label Encoding of datasetsPython | One Hot Encoding of datasetsHandling Imbalanced Data with SMOTE and Near Miss Algorithm in PythonDummy variable trap in Regression Models
Introduction to Data in Machine Learning
Understanding Data Processing
Python | Create Test DataSets using Sklearn
Python | Generate test datasets for Machine learning
Python | Data Preprocessing in Python
Data Cleaning
Feature Scaling – Part 1
Feature Scaling – Part 2
Python | Label Encoding of datasets
Python | One Hot Encoding of datasets
Handling Imbalanced Data with SMOTE and Near Miss Algorithm in Python
Dummy variable trap in Regression Models
Supervised learning :
Getting started with ClassificationBasic Concept of ClassificationTypes of Regression TechniquesClassification vs RegressionML | Types of Learning – Supervised LearningMulticlass classification using scikit-learnGradient Descent :Gradient Descent algorithm and its variantsStochastic Gradient Descent (SGD)Mini-Batch Gradient Descent with PythonOptimization techniques for Gradient DescentIntroduction to Momentum-based Gradient OptimizerLinear Regression :Introduction to Linear RegressionGradient Descent in Linear RegressionMathematical explanation for Linear Regression workingNormal Equation in Linear RegressionLinear Regression (Python Implementation)Simple Linear-Regression using RUnivariate Linear Regression in PythonMultiple Linear Regression using PythonMultiple Linear Regression using RLocally weighted Linear RegressionGeneralized Linear ModelsPython | Linear Regression using sklearnLinear Regression Using TensorflowA Practical approach to Simple Linear Regression using RLinear Regression using PyTorchPyspark | Linear regression using Apache MLlibML | Boston Housing Kaggle Challenge with Linear RegressionPython | Implementation of Polynomial RegressionSoftmax Regression using TensorFlowLogistic Regression :Understanding Logistic RegressionWhy Logistic Regression in Classification ?Logistic Regression using PythonCost function in Logistic RegressionLogistic Regression using TensorflowNaive Bayes ClassifiersSupport Vector:Support Vector Machines(SVMs) in PythonSVM Hyperparameter Tuning using GridSearchCVSupport Vector Machines(SVMs) in RUsing SVM to perform classification on a non-linear datasetDecision Tree:Decision TreeDecision Tree Regression using sklearnDecision Tree Introduction with exampleDecision tree implementation using PythonDecision Tree in Software EngineeringRandom Forest:Random Forest Regression in PythonEnsemble ClassifierVoting Classifier using SklearnBagging classifier
Getting started with Classification
Basic Concept of Classification
Types of Regression Techniques
Classification vs Regression
ML | Types of Learning – Supervised Learning
Multiclass classification using scikit-learn
Gradient Descent :Gradient Descent algorithm and its variantsStochastic Gradient Descent (SGD)Mini-Batch Gradient Descent with PythonOptimization techniques for Gradient DescentIntroduction to Momentum-based Gradient Optimizer
Gradient Descent algorithm and its variants
Stochastic Gradient Descent (SGD)
Mini-Batch Gradient Descent with Python
Optimization techniques for Gradient Descent
Introduction to Momentum-based Gradient Optimizer
Linear Regression :Introduction to Linear RegressionGradient Descent in Linear RegressionMathematical explanation for Linear Regression workingNormal Equation in Linear RegressionLinear Regression (Python Implementation)Simple Linear-Regression using RUnivariate Linear Regression in PythonMultiple Linear Regression using PythonMultiple Linear Regression using RLocally weighted Linear RegressionGeneralized Linear ModelsPython | Linear Regression using sklearnLinear Regression Using TensorflowA Practical approach to Simple Linear Regression using RLinear Regression using PyTorchPyspark | Linear regression using Apache MLlibML | Boston Housing Kaggle Challenge with Linear Regression
Introduction to Linear Regression
Gradient Descent in Linear Regression
Mathematical explanation for Linear Regression working
Normal Equation in Linear Regression
Linear Regression (Python Implementation)
Simple Linear-Regression using R
Univariate Linear Regression in Python
Multiple Linear Regression using Python
Multiple Linear Regression using R
Locally weighted Linear Regression
Generalized Linear Models
Python | Linear Regression using sklearn
Linear Regression Using Tensorflow
A Practical approach to Simple Linear Regression using R
Linear Regression using PyTorch
Pyspark | Linear regression using Apache MLlib
ML | Boston Housing Kaggle Challenge with Linear Regression
Python | Implementation of Polynomial Regression
Softmax Regression using TensorFlow
Logistic Regression :Understanding Logistic RegressionWhy Logistic Regression in Classification ?Logistic Regression using PythonCost function in Logistic RegressionLogistic Regression using Tensorflow
Understanding Logistic Regression
Why Logistic Regression in Classification ?
Logistic Regression using Python
Cost function in Logistic Regression
Logistic Regression using Tensorflow
Naive Bayes Classifiers
Support Vector:Support Vector Machines(SVMs) in PythonSVM Hyperparameter Tuning using GridSearchCVSupport Vector Machines(SVMs) in RUsing SVM to perform classification on a non-linear dataset
Support Vector Machines(SVMs) in Python
SVM Hyperparameter Tuning using GridSearchCV
Support Vector Machines(SVMs) in R
Using SVM to perform classification on a non-linear dataset
Decision Tree:Decision TreeDecision Tree Regression using sklearnDecision Tree Introduction with exampleDecision tree implementation using PythonDecision Tree in Software Engineering
Decision Tree
Decision Tree Regression using sklearn
Decision Tree Introduction with example
Decision tree implementation using Python
Decision Tree in Software Engineering
Random Forest:Random Forest Regression in PythonEnsemble ClassifierVoting Classifier using SklearnBagging classifier
Random Forest Regression in Python
Ensemble Classifier
Voting Classifier using Sklearn
Bagging classifier
Unsupervised learning :
ML | Types of Learning – Unsupervised LearningSupervised and Unsupervised learningClustering in Machine LearningDifferent Types of Clustering AlgorithmK means Clustering – IntroductionElbow Method for optimal value of k in KMeansRandom Initialization Trap in K-MeansML | K-means++ AlgorithmAnalysis of test data using K-Means Clustering in PythonMini Batch K-means clustering algorithmMean-Shift ClusteringDBSCAN – Density based clusteringImplementing DBSCAN algorithm using SklearnFuzzy ClusteringSpectral ClusteringOPTICS ClusteringOPTICS Clustering Implementing using SklearnHierarchical clustering (Agglomerative and Divisive clustering)Implementing Agglomerative Clustering using SklearnGaussian Mixture Model
ML | Types of Learning – Unsupervised Learning
Supervised and Unsupervised learning
Clustering in Machine Learning
Different Types of Clustering Algorithm
K means Clustering – Introduction
Elbow Method for optimal value of k in KMeans
Random Initialization Trap in K-Means
ML | K-means++ Algorithm
Analysis of test data using K-Means Clustering in Python
Mini Batch K-means clustering algorithm
Mean-Shift Clustering
DBSCAN – Density based clustering
Implementing DBSCAN algorithm using Sklearn
Fuzzy Clustering
Spectral Clustering
OPTICS Clustering
OPTICS Clustering Implementing using Sklearn
Hierarchical clustering (Agglomerative and Divisive clustering)
Implementing Agglomerative Clustering using Sklearn
Gaussian Mixture Model
Reinforcement Learning:
Reinforcement learningReinforcement Learning Algorithm : Python Implementation using Q-learningIntroduction to Thompson SamplingGenetic Algorithm for Reinforcement LearningSARSA Reinforcement LearningQ-Learning in Python
Reinforcement learning
Reinforcement Learning Algorithm : Python Implementation using Q-learning
Introduction to Thompson Sampling
Genetic Algorithm for Reinforcement Learning
SARSA Reinforcement Learning
Q-Learning in Python
Dimensionality Reduction :
Introduction to Dimensionality ReductionIntroduction to Kernel PCAPrincipal Component Analysis(PCA)Principal Component Analysis with PythonLow-Rank ApproximationsOverview of Linear Discriminant Analysis (LDA)Mathematical Explanation of Linear Discriminant Analysis (LDA)Generalized Discriminant Analysis (GDA)Independent Component AnalysisFeature MappingExtra Tree Classifier for Feature SelectionChi-Square Test for Feature Selection – Mathematical ExplanationML | T-distributed Stochastic Neighbor Embedding (t-SNE) AlgorithmPython | How and where to apply Feature Scaling?Parameters for Feature SelectionUnderfitting and Overfitting in Machine Learning
Introduction to Dimensionality Reduction
Introduction to Kernel PCA
Principal Component Analysis(PCA)
Principal Component Analysis with Python
Low-Rank Approximations
Overview of Linear Discriminant Analysis (LDA)
Mathematical Explanation of Linear Discriminant Analysis (LDA)
Generalized Discriminant Analysis (GDA)
Independent Component Analysis
Feature Mapping
Extra Tree Classifier for Feature Selection
Chi-Square Test for Feature Selection – Mathematical Explanation
ML | T-distributed Stochastic Neighbor Embedding (t-SNE) Algorithm
Python | How and where to apply Feature Scaling?
Parameters for Feature Selection
Underfitting and Overfitting in Machine Learning
Natural Language Processing :
Introduction to Natural Language ProcessingText Preprocessing in Python | Set – 1Text Preprocessing in Python | Set 2Removing stop words with NLTK in PythonTokenize text using NLTK in pythonHow tokenizing text, sentence, words worksIntroduction to StemmingStemming words with NLTKLemmatization with NLTKLemmatization with TextBlobHow to get synonyms/antonyms from NLTK WordNet in Python?
Introduction to Natural Language Processing
Text Preprocessing in Python | Set – 1
Text Preprocessing in Python | Set 2
Removing stop words with NLTK in Python
Tokenize text using NLTK in python
How tokenizing text, sentence, words works
Introduction to Stemming
Stemming words with NLTK
Lemmatization with NLTK
Lemmatization with TextBlob
How to get synonyms/antonyms from NLTK WordNet in Python?
Neural Networks :
Introduction to Artificial Neutral Networks | Set 1Introduction to Artificial Neural Network | Set 2Introduction to ANN (Artificial Neural Networks) | Set 3 (Hybrid Systems)Introduction to ANN | Set 4 (Network Architectures)Activation functionsImplementing Artificial Neural Network training process in PythonA single neuron neural network in PythonConvolutional Neural NetworksIntroduction to Convolution Neural NetworkIntroduction to Pooling LayerIntroduction to PaddingTypes of padding in convolution layerApplying Convolutional Neural Network on mnist datasetRecurrent Neural NetworksIntroduction to Recurrent Neural NetworkRecurrent Neural Networks Explanationseq2seq modelIntroduction to Long Short Term MemoryLong Short Term Memory Networks ExplanationGated Recurrent Unit Networks(GAN)Text Generation using Gated Recurrent Unit NetworksGANs – Generative Adversarial NetworkIntroduction to Generative Adversarial NetworkGenerative Adversarial Networks (GANs)Use Cases of Generative Adversarial NetworksBuilding a Generative Adversarial Network using KerasModal Collapse in GANsIntroduction to Deep Q-LearningImplementing Deep Q-Learning using Tensorflow
Introduction to Artificial Neutral Networks | Set 1
Introduction to Artificial Neural Network | Set 2
Introduction to ANN (Artificial Neural Networks) | Set 3 (Hybrid Systems)
Introduction to ANN | Set 4 (Network Architectures)
Activation functions
Implementing Artificial Neural Network training process in Python
A single neuron neural network in Python
Convolutional Neural NetworksIntroduction to Convolution Neural NetworkIntroduction to Pooling LayerIntroduction to PaddingTypes of padding in convolution layerApplying Convolutional Neural Network on mnist dataset
Introduction to Convolution Neural Network
Introduction to Pooling Layer
Introduction to Padding
Types of padding in convolution layer
Applying Convolutional Neural Network on mnist dataset
Recurrent Neural NetworksIntroduction to Recurrent Neural NetworkRecurrent Neural Networks Explanationseq2seq modelIntroduction to Long Short Term MemoryLong Short Term Memory Networks ExplanationGated Recurrent Unit Networks(GAN)Text Generation using Gated Recurrent Unit Networks
Introduction to Recurrent Neural Network
Recurrent Neural Networks Explanation
seq2seq model
Introduction to Long Short Term Memory
Long Short Term Memory Networks Explanation
Gated Recurrent Unit Networks(GAN)
Text Generation using Gated Recurrent Unit Networks
GANs – Generative Adversarial NetworkIntroduction to Generative Adversarial NetworkGenerative Adversarial Networks (GANs)Use Cases of Generative Adversarial NetworksBuilding a Generative Adversarial Network using KerasModal Collapse in GANs
Introduction to Generative Adversarial Network
Generative Adversarial Networks (GANs)
Use Cases of Generative Adversarial Networks
Building a Generative Adversarial Network using Keras
Modal Collapse in GANs
Introduction to Deep Q-Learning
Implementing Deep Q-Learning using Tensorflow
ML – Deployment :
Deploy your Machine Learning web app (Streamlit) on HerokuDeploy a Machine Learning Model using Streamlit LibraryDeploy Machine Learning Model using FlaskPython – Create UIs for prototyping Machine Learning model with GradioHow to Prepare Data Before Deploying a Machine Learning Model?https://www.geeksforgeeks.org/deploying-ml-models-as-api-using-fastapi/?ref=rpDeploying Scrapy spider on ScrapingHub
Deploy your Machine Learning web app (Streamlit) on Heroku
Deploy a Machine Learning Model using Streamlit Library
Deploy Machine Learning Model using Flask
Python – Create UIs for prototyping Machine Learning model with Gradio
How to Prepare Data Before Deploying a Machine Learning Model?
https://www.geeksforgeeks.org/deploying-ml-models-as-api-using-fastapi/?ref=rp
Deploying Scrapy spider on ScrapingHub
ML – Applications :
Rainfall prediction using Linear regressionIdentifying handwritten digits using Logistic Regression in PyTorchKaggle Breast Cancer Wisconsin Diagnosis using Logistic RegressionPython | Implementation of Movie Recommender SystemSupport Vector Machine to recognize facial features in C++Decision Trees – Fake (Counterfeit) Coin Puzzle (12 Coin Puzzle)Credit Card Fraud DetectionNLP analysis of Restaurant reviewsApplying Multinomial Naive Bayes to NLP ProblemsImage compression using K-means clusteringDeep learning | Image Caption Generation using the Avengers EndGames CharactersHow Does Google Use Machine Learning?How Does NASA Use Machine Learning?5 Mind-Blowing Ways Facebook Uses Machine LearningTargeted Advertising using Machine LearningHow Machine Learning Is Used by Famous Companies?
Rainfall prediction using Linear regression
Identifying handwritten digits using Logistic Regression in PyTorch
Kaggle Breast Cancer Wisconsin Diagnosis using Logistic Regression
Python | Implementation of Movie Recommender System
Support Vector Machine to recognize facial features in C++
Decision Trees – Fake (Counterfeit) Coin Puzzle (12 Coin Puzzle)
Credit Card Fraud Detection
NLP analysis of Restaurant reviews
Applying Multinomial Naive Bayes to NLP Problems
Image compression using K-means clustering
Deep learning | Image Caption Generation using the Avengers EndGames Characters
How Does Google Use Machine Learning?
How Does NASA Use Machine Learning?
5 Mind-Blowing Ways Facebook Uses Machine Learning
Targeted Advertising using Machine Learning
How Machine Learning Is Used by Famous Companies?
Misc :
Pattern Recognition | IntroductionCalculate Efficiency Of Binary ClassifierLogistic Regression v/s Decision Tree ClassificationR vs Python in DatascienceExplanation of Fundamental Functions involved in A3C algorithmDifferential Privacy and Deep LearningArtificial intelligence vs Machine Learning vs Deep LearningIntroduction to Multi-Task Learning(MTL) for Deep LearningTop 10 Algorithms every Machine Learning Engineer should knowAzure Virtual Machine for Machine Learning30 minutes to machine learningWhat is AutoML in Machine Learning?Confusion Matrix in Machine Learning
Pattern Recognition | Introduction
Calculate Efficiency Of Binary Classifier
Logistic Regression v/s Decision Tree Classification
R vs Python in Datascience
Explanation of Fundamental Functions involved in A3C algorithm
Differential Privacy and Deep Learning
Artificial intelligence vs Machine Learning vs Deep Learning
Introduction to Multi-Task Learning(MTL) for Deep Learning
Top 10 Algorithms every Machine Learning Engineer should know
Azure Virtual Machine for Machine Learning
30 minutes to machine learning
What is AutoML in Machine Learning?
Confusion Matrix in Machine Learning
Machines are learning, so why do you wish to get left behind? Strengthen your ML and AI foundations today and become future ready. This self-paced course will help you learn advanced concepts like- Regression, Classification, Data Dimensionality and much more. Also included- Projects that will help you get hands-on experience. So wait no more, and strengthen your Machine Learning Foundations.
Every organisation now relies on data before making any important decisions regarding their future. So, it is safe to say that Data is really the king now. So why do you want to get left behind? This LIVE course will introduce the learner to advanced concepts like: Linear Regression, Naive Bayes & KNN, Numpy, Pandas, Matlab & much more. You will also get to work on real-life projects through the course. So wait no more, Become a Data Science Expert now.
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
|
[
{
"code": null,
"e": 29498,
"s": 29470,
"text": "\n02 Jun, 2022"
},
{
"code": null,
"e": 29914,
"s": 29498,
"text": " Machine Learning is the field of study that gives computers the capability to learn without being explicitly programmed. ML is one of the most exciting technologies that one would have ever come across. As it is evident from the name, it gives the computer that makes it more similar to humans: The ability to learn. Machine learning is actively being used today, perhaps in many more places than one would expect."
},
{
"code": null,
"e": 30282,
"s": 29914,
"text": "Machine Learning is an essential skill for any aspiring data analyst and data scientist, and also for those who wish to transform a massive amount of raw data into trends and predictions. Learn this skill today with Machine Learning Foundation – Self Paced Course , designed and curated by industry experts having years of expertise in ML and industry-based projects."
},
{
"code": null,
"e": 30295,
"s": 30282,
"text": "Introduction"
},
{
"code": null,
"e": 30320,
"s": 30295,
"text": "Data and it’s Processing"
},
{
"code": null,
"e": 30340,
"s": 30320,
"text": "Supervised Learning"
},
{
"code": null,
"e": 30362,
"s": 30340,
"text": "Unsupervised Learning"
},
{
"code": null,
"e": 30385,
"s": 30362,
"text": "Reinforcement Learning"
},
{
"code": null,
"e": 30410,
"s": 30385,
"text": "Dimensionality Reduction"
},
{
"code": null,
"e": 30438,
"s": 30410,
"text": "Natural Language Processing"
},
{
"code": null,
"e": 30454,
"s": 30438,
"text": "Neural Networks"
},
{
"code": null,
"e": 30470,
"s": 30454,
"text": "ML – Deployment"
},
{
"code": null,
"e": 30488,
"s": 30470,
"text": "ML – Applications"
},
{
"code": null,
"e": 30502,
"s": 30488,
"text": "Miscellaneous"
},
{
"code": null,
"e": 30519,
"s": 30504,
"text": "Introduction :"
},
{
"code": null,
"e": 30972,
"s": 30519,
"text": "Getting Started with Machine LearningAn Introduction to Machine LearningWhat is Machine Learning ?Introduction to Data in Machine LearningDemystifying Machine LearningML – ApplicationsBest Python libraries for Machine LearningArtificial Intelligence | An IntroductionMachine Learning and Artificial IntelligenceDifference between Machine learning and Artificial IntelligenceAgents in Artificial Intelligence10 Basic Machine Learning Interview Questions"
},
{
"code": null,
"e": 31010,
"s": 30972,
"text": "Getting Started with Machine Learning"
},
{
"code": null,
"e": 31046,
"s": 31010,
"text": "An Introduction to Machine Learning"
},
{
"code": null,
"e": 31073,
"s": 31046,
"text": "What is Machine Learning ?"
},
{
"code": null,
"e": 31114,
"s": 31073,
"text": "Introduction to Data in Machine Learning"
},
{
"code": null,
"e": 31144,
"s": 31114,
"text": "Demystifying Machine Learning"
},
{
"code": null,
"e": 31162,
"s": 31144,
"text": "ML – Applications"
},
{
"code": null,
"e": 31205,
"s": 31162,
"text": "Best Python libraries for Machine Learning"
},
{
"code": null,
"e": 31247,
"s": 31205,
"text": "Artificial Intelligence | An Introduction"
},
{
"code": null,
"e": 31292,
"s": 31247,
"text": "Machine Learning and Artificial Intelligence"
},
{
"code": null,
"e": 31356,
"s": 31292,
"text": "Difference between Machine learning and Artificial Intelligence"
},
{
"code": null,
"e": 31390,
"s": 31356,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 31436,
"s": 31390,
"text": "10 Basic Machine Learning Interview Questions"
},
{
"code": null,
"e": 31462,
"s": 31436,
"text": "Data and It’s Processing:"
},
{
"code": null,
"e": 31906,
"s": 31462,
"text": "Introduction to Data in Machine LearningUnderstanding Data ProcessingPython | Create Test DataSets using SklearnPython | Generate test datasets for Machine learningPython | Data Preprocessing in PythonData CleaningFeature Scaling – Part 1Feature Scaling – Part 2Python | Label Encoding of datasetsPython | One Hot Encoding of datasetsHandling Imbalanced Data with SMOTE and Near Miss Algorithm in PythonDummy variable trap in Regression Models"
},
{
"code": null,
"e": 31947,
"s": 31906,
"text": "Introduction to Data in Machine Learning"
},
{
"code": null,
"e": 31977,
"s": 31947,
"text": "Understanding Data Processing"
},
{
"code": null,
"e": 32021,
"s": 31977,
"text": "Python | Create Test DataSets using Sklearn"
},
{
"code": null,
"e": 32074,
"s": 32021,
"text": "Python | Generate test datasets for Machine learning"
},
{
"code": null,
"e": 32112,
"s": 32074,
"text": "Python | Data Preprocessing in Python"
},
{
"code": null,
"e": 32126,
"s": 32112,
"text": "Data Cleaning"
},
{
"code": null,
"e": 32151,
"s": 32126,
"text": "Feature Scaling – Part 1"
},
{
"code": null,
"e": 32176,
"s": 32151,
"text": "Feature Scaling – Part 2"
},
{
"code": null,
"e": 32212,
"s": 32176,
"text": "Python | Label Encoding of datasets"
},
{
"code": null,
"e": 32250,
"s": 32212,
"text": "Python | One Hot Encoding of datasets"
},
{
"code": null,
"e": 32320,
"s": 32250,
"text": "Handling Imbalanced Data with SMOTE and Near Miss Algorithm in Python"
},
{
"code": null,
"e": 32361,
"s": 32320,
"text": "Dummy variable trap in Regression Models"
},
{
"code": null,
"e": 32383,
"s": 32361,
"text": "Supervised learning :"
},
{
"code": null,
"e": 34306,
"s": 32383,
"text": "Getting started with ClassificationBasic Concept of ClassificationTypes of Regression TechniquesClassification vs RegressionML | Types of Learning – Supervised LearningMulticlass classification using scikit-learnGradient Descent :Gradient Descent algorithm and its variantsStochastic Gradient Descent (SGD)Mini-Batch Gradient Descent with PythonOptimization techniques for Gradient DescentIntroduction to Momentum-based Gradient OptimizerLinear Regression :Introduction to Linear RegressionGradient Descent in Linear RegressionMathematical explanation for Linear Regression workingNormal Equation in Linear RegressionLinear Regression (Python Implementation)Simple Linear-Regression using RUnivariate Linear Regression in PythonMultiple Linear Regression using PythonMultiple Linear Regression using RLocally weighted Linear RegressionGeneralized Linear ModelsPython | Linear Regression using sklearnLinear Regression Using TensorflowA Practical approach to Simple Linear Regression using RLinear Regression using PyTorchPyspark | Linear regression using Apache MLlibML | Boston Housing Kaggle Challenge with Linear RegressionPython | Implementation of Polynomial RegressionSoftmax Regression using TensorFlowLogistic Regression :Understanding Logistic RegressionWhy Logistic Regression in Classification ?Logistic Regression using PythonCost function in Logistic RegressionLogistic Regression using TensorflowNaive Bayes ClassifiersSupport Vector:Support Vector Machines(SVMs) in PythonSVM Hyperparameter Tuning using GridSearchCVSupport Vector Machines(SVMs) in RUsing SVM to perform classification on a non-linear datasetDecision Tree:Decision TreeDecision Tree Regression using sklearnDecision Tree Introduction with exampleDecision tree implementation using PythonDecision Tree in Software EngineeringRandom Forest:Random Forest Regression in PythonEnsemble ClassifierVoting Classifier using SklearnBagging classifier"
},
{
"code": null,
"e": 34342,
"s": 34306,
"text": "Getting started with Classification"
},
{
"code": null,
"e": 34374,
"s": 34342,
"text": "Basic Concept of Classification"
},
{
"code": null,
"e": 34405,
"s": 34374,
"text": "Types of Regression Techniques"
},
{
"code": null,
"e": 34434,
"s": 34405,
"text": "Classification vs Regression"
},
{
"code": null,
"e": 34479,
"s": 34434,
"text": "ML | Types of Learning – Supervised Learning"
},
{
"code": null,
"e": 34524,
"s": 34479,
"text": "Multiclass classification using scikit-learn"
},
{
"code": null,
"e": 34751,
"s": 34524,
"text": "Gradient Descent :Gradient Descent algorithm and its variantsStochastic Gradient Descent (SGD)Mini-Batch Gradient Descent with PythonOptimization techniques for Gradient DescentIntroduction to Momentum-based Gradient Optimizer"
},
{
"code": null,
"e": 34795,
"s": 34751,
"text": "Gradient Descent algorithm and its variants"
},
{
"code": null,
"e": 34829,
"s": 34795,
"text": "Stochastic Gradient Descent (SGD)"
},
{
"code": null,
"e": 34869,
"s": 34829,
"text": "Mini-Batch Gradient Descent with Python"
},
{
"code": null,
"e": 34914,
"s": 34869,
"text": "Optimization techniques for Gradient Descent"
},
{
"code": null,
"e": 34964,
"s": 34914,
"text": "Introduction to Momentum-based Gradient Optimizer"
},
{
"code": null,
"e": 35653,
"s": 34964,
"text": "Linear Regression :Introduction to Linear RegressionGradient Descent in Linear RegressionMathematical explanation for Linear Regression workingNormal Equation in Linear RegressionLinear Regression (Python Implementation)Simple Linear-Regression using RUnivariate Linear Regression in PythonMultiple Linear Regression using PythonMultiple Linear Regression using RLocally weighted Linear RegressionGeneralized Linear ModelsPython | Linear Regression using sklearnLinear Regression Using TensorflowA Practical approach to Simple Linear Regression using RLinear Regression using PyTorchPyspark | Linear regression using Apache MLlibML | Boston Housing Kaggle Challenge with Linear Regression"
},
{
"code": null,
"e": 35687,
"s": 35653,
"text": "Introduction to Linear Regression"
},
{
"code": null,
"e": 35725,
"s": 35687,
"text": "Gradient Descent in Linear Regression"
},
{
"code": null,
"e": 35780,
"s": 35725,
"text": "Mathematical explanation for Linear Regression working"
},
{
"code": null,
"e": 35817,
"s": 35780,
"text": "Normal Equation in Linear Regression"
},
{
"code": null,
"e": 35859,
"s": 35817,
"text": "Linear Regression (Python Implementation)"
},
{
"code": null,
"e": 35892,
"s": 35859,
"text": "Simple Linear-Regression using R"
},
{
"code": null,
"e": 35931,
"s": 35892,
"text": "Univariate Linear Regression in Python"
},
{
"code": null,
"e": 35971,
"s": 35931,
"text": "Multiple Linear Regression using Python"
},
{
"code": null,
"e": 36006,
"s": 35971,
"text": "Multiple Linear Regression using R"
},
{
"code": null,
"e": 36041,
"s": 36006,
"text": "Locally weighted Linear Regression"
},
{
"code": null,
"e": 36067,
"s": 36041,
"text": "Generalized Linear Models"
},
{
"code": null,
"e": 36108,
"s": 36067,
"text": "Python | Linear Regression using sklearn"
},
{
"code": null,
"e": 36143,
"s": 36108,
"text": "Linear Regression Using Tensorflow"
},
{
"code": null,
"e": 36200,
"s": 36143,
"text": "A Practical approach to Simple Linear Regression using R"
},
{
"code": null,
"e": 36232,
"s": 36200,
"text": "Linear Regression using PyTorch"
},
{
"code": null,
"e": 36279,
"s": 36232,
"text": "Pyspark | Linear regression using Apache MLlib"
},
{
"code": null,
"e": 36339,
"s": 36279,
"text": "ML | Boston Housing Kaggle Challenge with Linear Regression"
},
{
"code": null,
"e": 36388,
"s": 36339,
"text": "Python | Implementation of Polynomial Regression"
},
{
"code": null,
"e": 36424,
"s": 36388,
"text": "Softmax Regression using TensorFlow"
},
{
"code": null,
"e": 36626,
"s": 36424,
"text": "Logistic Regression :Understanding Logistic RegressionWhy Logistic Regression in Classification ?Logistic Regression using PythonCost function in Logistic RegressionLogistic Regression using Tensorflow"
},
{
"code": null,
"e": 36660,
"s": 36626,
"text": "Understanding Logistic Regression"
},
{
"code": null,
"e": 36704,
"s": 36660,
"text": "Why Logistic Regression in Classification ?"
},
{
"code": null,
"e": 36737,
"s": 36704,
"text": "Logistic Regression using Python"
},
{
"code": null,
"e": 36774,
"s": 36737,
"text": "Cost function in Logistic Regression"
},
{
"code": null,
"e": 36811,
"s": 36774,
"text": "Logistic Regression using Tensorflow"
},
{
"code": null,
"e": 36835,
"s": 36811,
"text": "Naive Bayes Classifiers"
},
{
"code": null,
"e": 37027,
"s": 36835,
"text": "Support Vector:Support Vector Machines(SVMs) in PythonSVM Hyperparameter Tuning using GridSearchCVSupport Vector Machines(SVMs) in RUsing SVM to perform classification on a non-linear dataset"
},
{
"code": null,
"e": 37067,
"s": 37027,
"text": "Support Vector Machines(SVMs) in Python"
},
{
"code": null,
"e": 37112,
"s": 37067,
"text": "SVM Hyperparameter Tuning using GridSearchCV"
},
{
"code": null,
"e": 37147,
"s": 37112,
"text": "Support Vector Machines(SVMs) in R"
},
{
"code": null,
"e": 37207,
"s": 37147,
"text": "Using SVM to perform classification on a non-linear dataset"
},
{
"code": null,
"e": 37390,
"s": 37207,
"text": "Decision Tree:Decision TreeDecision Tree Regression using sklearnDecision Tree Introduction with exampleDecision tree implementation using PythonDecision Tree in Software Engineering"
},
{
"code": null,
"e": 37404,
"s": 37390,
"text": "Decision Tree"
},
{
"code": null,
"e": 37443,
"s": 37404,
"text": "Decision Tree Regression using sklearn"
},
{
"code": null,
"e": 37483,
"s": 37443,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 37525,
"s": 37483,
"text": "Decision tree implementation using Python"
},
{
"code": null,
"e": 37563,
"s": 37525,
"text": "Decision Tree in Software Engineering"
},
{
"code": null,
"e": 37680,
"s": 37563,
"text": "Random Forest:Random Forest Regression in PythonEnsemble ClassifierVoting Classifier using SklearnBagging classifier"
},
{
"code": null,
"e": 37715,
"s": 37680,
"text": "Random Forest Regression in Python"
},
{
"code": null,
"e": 37735,
"s": 37715,
"text": "Ensemble Classifier"
},
{
"code": null,
"e": 37767,
"s": 37735,
"text": "Voting Classifier using Sklearn"
},
{
"code": null,
"e": 37786,
"s": 37767,
"text": "Bagging classifier"
},
{
"code": null,
"e": 37810,
"s": 37786,
"text": "Unsupervised learning :"
},
{
"code": null,
"e": 38525,
"s": 37810,
"text": "ML | Types of Learning – Unsupervised LearningSupervised and Unsupervised learningClustering in Machine LearningDifferent Types of Clustering AlgorithmK means Clustering – IntroductionElbow Method for optimal value of k in KMeansRandom Initialization Trap in K-MeansML | K-means++ AlgorithmAnalysis of test data using K-Means Clustering in PythonMini Batch K-means clustering algorithmMean-Shift ClusteringDBSCAN – Density based clusteringImplementing DBSCAN algorithm using SklearnFuzzy ClusteringSpectral ClusteringOPTICS ClusteringOPTICS Clustering Implementing using SklearnHierarchical clustering (Agglomerative and Divisive clustering)Implementing Agglomerative Clustering using SklearnGaussian Mixture Model"
},
{
"code": null,
"e": 38572,
"s": 38525,
"text": "ML | Types of Learning – Unsupervised Learning"
},
{
"code": null,
"e": 38609,
"s": 38572,
"text": "Supervised and Unsupervised learning"
},
{
"code": null,
"e": 38640,
"s": 38609,
"text": "Clustering in Machine Learning"
},
{
"code": null,
"e": 38680,
"s": 38640,
"text": "Different Types of Clustering Algorithm"
},
{
"code": null,
"e": 38714,
"s": 38680,
"text": "K means Clustering – Introduction"
},
{
"code": null,
"e": 38760,
"s": 38714,
"text": "Elbow Method for optimal value of k in KMeans"
},
{
"code": null,
"e": 38798,
"s": 38760,
"text": "Random Initialization Trap in K-Means"
},
{
"code": null,
"e": 38823,
"s": 38798,
"text": "ML | K-means++ Algorithm"
},
{
"code": null,
"e": 38880,
"s": 38823,
"text": "Analysis of test data using K-Means Clustering in Python"
},
{
"code": null,
"e": 38920,
"s": 38880,
"text": "Mini Batch K-means clustering algorithm"
},
{
"code": null,
"e": 38942,
"s": 38920,
"text": "Mean-Shift Clustering"
},
{
"code": null,
"e": 38976,
"s": 38942,
"text": "DBSCAN – Density based clustering"
},
{
"code": null,
"e": 39020,
"s": 38976,
"text": "Implementing DBSCAN algorithm using Sklearn"
},
{
"code": null,
"e": 39037,
"s": 39020,
"text": "Fuzzy Clustering"
},
{
"code": null,
"e": 39057,
"s": 39037,
"text": "Spectral Clustering"
},
{
"code": null,
"e": 39075,
"s": 39057,
"text": "OPTICS Clustering"
},
{
"code": null,
"e": 39120,
"s": 39075,
"text": "OPTICS Clustering Implementing using Sklearn"
},
{
"code": null,
"e": 39184,
"s": 39120,
"text": "Hierarchical clustering (Agglomerative and Divisive clustering)"
},
{
"code": null,
"e": 39236,
"s": 39184,
"text": "Implementing Agglomerative Clustering using Sklearn"
},
{
"code": null,
"e": 39259,
"s": 39236,
"text": "Gaussian Mixture Model"
},
{
"code": null,
"e": 39283,
"s": 39259,
"text": "Reinforcement Learning:"
},
{
"code": null,
"e": 39504,
"s": 39283,
"text": "Reinforcement learningReinforcement Learning Algorithm : Python Implementation using Q-learningIntroduction to Thompson SamplingGenetic Algorithm for Reinforcement LearningSARSA Reinforcement LearningQ-Learning in Python"
},
{
"code": null,
"e": 39527,
"s": 39504,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 39601,
"s": 39527,
"text": "Reinforcement Learning Algorithm : Python Implementation using Q-learning"
},
{
"code": null,
"e": 39635,
"s": 39601,
"text": "Introduction to Thompson Sampling"
},
{
"code": null,
"e": 39680,
"s": 39635,
"text": "Genetic Algorithm for Reinforcement Learning"
},
{
"code": null,
"e": 39709,
"s": 39680,
"text": "SARSA Reinforcement Learning"
},
{
"code": null,
"e": 39730,
"s": 39709,
"text": "Q-Learning in Python"
},
{
"code": null,
"e": 39757,
"s": 39730,
"text": "Dimensionality Reduction :"
},
{
"code": null,
"e": 40413,
"s": 39757,
"text": "Introduction to Dimensionality ReductionIntroduction to Kernel PCAPrincipal Component Analysis(PCA)Principal Component Analysis with PythonLow-Rank ApproximationsOverview of Linear Discriminant Analysis (LDA)Mathematical Explanation of Linear Discriminant Analysis (LDA)Generalized Discriminant Analysis (GDA)Independent Component AnalysisFeature MappingExtra Tree Classifier for Feature SelectionChi-Square Test for Feature Selection – Mathematical ExplanationML | T-distributed Stochastic Neighbor Embedding (t-SNE) AlgorithmPython | How and where to apply Feature Scaling?Parameters for Feature SelectionUnderfitting and Overfitting in Machine Learning"
},
{
"code": null,
"e": 40454,
"s": 40413,
"text": "Introduction to Dimensionality Reduction"
},
{
"code": null,
"e": 40481,
"s": 40454,
"text": "Introduction to Kernel PCA"
},
{
"code": null,
"e": 40515,
"s": 40481,
"text": "Principal Component Analysis(PCA)"
},
{
"code": null,
"e": 40556,
"s": 40515,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 40580,
"s": 40556,
"text": "Low-Rank Approximations"
},
{
"code": null,
"e": 40627,
"s": 40580,
"text": "Overview of Linear Discriminant Analysis (LDA)"
},
{
"code": null,
"e": 40690,
"s": 40627,
"text": "Mathematical Explanation of Linear Discriminant Analysis (LDA)"
},
{
"code": null,
"e": 40730,
"s": 40690,
"text": "Generalized Discriminant Analysis (GDA)"
},
{
"code": null,
"e": 40761,
"s": 40730,
"text": "Independent Component Analysis"
},
{
"code": null,
"e": 40777,
"s": 40761,
"text": "Feature Mapping"
},
{
"code": null,
"e": 40821,
"s": 40777,
"text": "Extra Tree Classifier for Feature Selection"
},
{
"code": null,
"e": 40886,
"s": 40821,
"text": "Chi-Square Test for Feature Selection – Mathematical Explanation"
},
{
"code": null,
"e": 40953,
"s": 40886,
"text": "ML | T-distributed Stochastic Neighbor Embedding (t-SNE) Algorithm"
},
{
"code": null,
"e": 41002,
"s": 40953,
"text": "Python | How and where to apply Feature Scaling?"
},
{
"code": null,
"e": 41035,
"s": 41002,
"text": "Parameters for Feature Selection"
},
{
"code": null,
"e": 41084,
"s": 41035,
"text": "Underfitting and Overfitting in Machine Learning"
},
{
"code": null,
"e": 41114,
"s": 41084,
"text": "Natural Language Processing :"
},
{
"code": null,
"e": 41502,
"s": 41114,
"text": "Introduction to Natural Language ProcessingText Preprocessing in Python | Set – 1Text Preprocessing in Python | Set 2Removing stop words with NLTK in PythonTokenize text using NLTK in pythonHow tokenizing text, sentence, words worksIntroduction to StemmingStemming words with NLTKLemmatization with NLTKLemmatization with TextBlobHow to get synonyms/antonyms from NLTK WordNet in Python?"
},
{
"code": null,
"e": 41546,
"s": 41502,
"text": "Introduction to Natural Language Processing"
},
{
"code": null,
"e": 41585,
"s": 41546,
"text": "Text Preprocessing in Python | Set – 1"
},
{
"code": null,
"e": 41622,
"s": 41585,
"text": "Text Preprocessing in Python | Set 2"
},
{
"code": null,
"e": 41662,
"s": 41622,
"text": "Removing stop words with NLTK in Python"
},
{
"code": null,
"e": 41697,
"s": 41662,
"text": "Tokenize text using NLTK in python"
},
{
"code": null,
"e": 41740,
"s": 41697,
"text": "How tokenizing text, sentence, words works"
},
{
"code": null,
"e": 41765,
"s": 41740,
"text": "Introduction to Stemming"
},
{
"code": null,
"e": 41790,
"s": 41765,
"text": "Stemming words with NLTK"
},
{
"code": null,
"e": 41814,
"s": 41790,
"text": "Lemmatization with NLTK"
},
{
"code": null,
"e": 41842,
"s": 41814,
"text": "Lemmatization with TextBlob"
},
{
"code": null,
"e": 41900,
"s": 41842,
"text": "How to get synonyms/antonyms from NLTK WordNet in Python?"
},
{
"code": null,
"e": 41918,
"s": 41900,
"text": "Neural Networks :"
},
{
"code": null,
"e": 43079,
"s": 41918,
"text": "Introduction to Artificial Neutral Networks | Set 1Introduction to Artificial Neural Network | Set 2Introduction to ANN (Artificial Neural Networks) | Set 3 (Hybrid Systems)Introduction to ANN | Set 4 (Network Architectures)Activation functionsImplementing Artificial Neural Network training process in PythonA single neuron neural network in PythonConvolutional Neural NetworksIntroduction to Convolution Neural NetworkIntroduction to Pooling LayerIntroduction to PaddingTypes of padding in convolution layerApplying Convolutional Neural Network on mnist datasetRecurrent Neural NetworksIntroduction to Recurrent Neural NetworkRecurrent Neural Networks Explanationseq2seq modelIntroduction to Long Short Term MemoryLong Short Term Memory Networks ExplanationGated Recurrent Unit Networks(GAN)Text Generation using Gated Recurrent Unit NetworksGANs – Generative Adversarial NetworkIntroduction to Generative Adversarial NetworkGenerative Adversarial Networks (GANs)Use Cases of Generative Adversarial NetworksBuilding a Generative Adversarial Network using KerasModal Collapse in GANsIntroduction to Deep Q-LearningImplementing Deep Q-Learning using Tensorflow"
},
{
"code": null,
"e": 43131,
"s": 43079,
"text": "Introduction to Artificial Neutral Networks | Set 1"
},
{
"code": null,
"e": 43181,
"s": 43131,
"text": "Introduction to Artificial Neural Network | Set 2"
},
{
"code": null,
"e": 43255,
"s": 43181,
"text": "Introduction to ANN (Artificial Neural Networks) | Set 3 (Hybrid Systems)"
},
{
"code": null,
"e": 43307,
"s": 43255,
"text": "Introduction to ANN | Set 4 (Network Architectures)"
},
{
"code": null,
"e": 43328,
"s": 43307,
"text": "Activation functions"
},
{
"code": null,
"e": 43394,
"s": 43328,
"text": "Implementing Artificial Neural Network training process in Python"
},
{
"code": null,
"e": 43435,
"s": 43394,
"text": "A single neuron neural network in Python"
},
{
"code": null,
"e": 43650,
"s": 43435,
"text": "Convolutional Neural NetworksIntroduction to Convolution Neural NetworkIntroduction to Pooling LayerIntroduction to PaddingTypes of padding in convolution layerApplying Convolutional Neural Network on mnist dataset"
},
{
"code": null,
"e": 43693,
"s": 43650,
"text": "Introduction to Convolution Neural Network"
},
{
"code": null,
"e": 43723,
"s": 43693,
"text": "Introduction to Pooling Layer"
},
{
"code": null,
"e": 43747,
"s": 43723,
"text": "Introduction to Padding"
},
{
"code": null,
"e": 43785,
"s": 43747,
"text": "Types of padding in convolution layer"
},
{
"code": null,
"e": 43840,
"s": 43785,
"text": "Applying Convolutional Neural Network on mnist dataset"
},
{
"code": null,
"e": 44122,
"s": 43840,
"text": "Recurrent Neural NetworksIntroduction to Recurrent Neural NetworkRecurrent Neural Networks Explanationseq2seq modelIntroduction to Long Short Term MemoryLong Short Term Memory Networks ExplanationGated Recurrent Unit Networks(GAN)Text Generation using Gated Recurrent Unit Networks"
},
{
"code": null,
"e": 44163,
"s": 44122,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 44201,
"s": 44163,
"text": "Recurrent Neural Networks Explanation"
},
{
"code": null,
"e": 44215,
"s": 44201,
"text": "seq2seq model"
},
{
"code": null,
"e": 44254,
"s": 44215,
"text": "Introduction to Long Short Term Memory"
},
{
"code": null,
"e": 44298,
"s": 44254,
"text": "Long Short Term Memory Networks Explanation"
},
{
"code": null,
"e": 44333,
"s": 44298,
"text": "Gated Recurrent Unit Networks(GAN)"
},
{
"code": null,
"e": 44385,
"s": 44333,
"text": "Text Generation using Gated Recurrent Unit Networks"
},
{
"code": null,
"e": 44626,
"s": 44385,
"text": "GANs – Generative Adversarial NetworkIntroduction to Generative Adversarial NetworkGenerative Adversarial Networks (GANs)Use Cases of Generative Adversarial NetworksBuilding a Generative Adversarial Network using KerasModal Collapse in GANs"
},
{
"code": null,
"e": 44673,
"s": 44626,
"text": "Introduction to Generative Adversarial Network"
},
{
"code": null,
"e": 44712,
"s": 44673,
"text": "Generative Adversarial Networks (GANs)"
},
{
"code": null,
"e": 44757,
"s": 44712,
"text": "Use Cases of Generative Adversarial Networks"
},
{
"code": null,
"e": 44811,
"s": 44757,
"text": "Building a Generative Adversarial Network using Keras"
},
{
"code": null,
"e": 44834,
"s": 44811,
"text": "Modal Collapse in GANs"
},
{
"code": null,
"e": 44866,
"s": 44834,
"text": "Introduction to Deep Q-Learning"
},
{
"code": null,
"e": 44912,
"s": 44866,
"text": "Implementing Deep Q-Learning using Tensorflow"
},
{
"code": null,
"e": 44930,
"s": 44912,
"text": "ML – Deployment :"
},
{
"code": null,
"e": 45333,
"s": 44930,
"text": "Deploy your Machine Learning web app (Streamlit) on HerokuDeploy a Machine Learning Model using Streamlit LibraryDeploy Machine Learning Model using FlaskPython – Create UIs for prototyping Machine Learning model with GradioHow to Prepare Data Before Deploying a Machine Learning Model?https://www.geeksforgeeks.org/deploying-ml-models-as-api-using-fastapi/?ref=rpDeploying Scrapy spider on ScrapingHub"
},
{
"code": null,
"e": 45392,
"s": 45333,
"text": "Deploy your Machine Learning web app (Streamlit) on Heroku"
},
{
"code": null,
"e": 45448,
"s": 45392,
"text": "Deploy a Machine Learning Model using Streamlit Library"
},
{
"code": null,
"e": 45490,
"s": 45448,
"text": "Deploy Machine Learning Model using Flask"
},
{
"code": null,
"e": 45561,
"s": 45490,
"text": "Python – Create UIs for prototyping Machine Learning model with Gradio"
},
{
"code": null,
"e": 45624,
"s": 45561,
"text": "How to Prepare Data Before Deploying a Machine Learning Model?"
},
{
"code": null,
"e": 45703,
"s": 45624,
"text": "https://www.geeksforgeeks.org/deploying-ml-models-as-api-using-fastapi/?ref=rp"
},
{
"code": null,
"e": 45742,
"s": 45703,
"text": "Deploying Scrapy spider on ScrapingHub"
},
{
"code": null,
"e": 45762,
"s": 45742,
"text": "ML – Applications :"
},
{
"code": null,
"e": 46556,
"s": 45762,
"text": "Rainfall prediction using Linear regressionIdentifying handwritten digits using Logistic Regression in PyTorchKaggle Breast Cancer Wisconsin Diagnosis using Logistic RegressionPython | Implementation of Movie Recommender SystemSupport Vector Machine to recognize facial features in C++Decision Trees – Fake (Counterfeit) Coin Puzzle (12 Coin Puzzle)Credit Card Fraud DetectionNLP analysis of Restaurant reviewsApplying Multinomial Naive Bayes to NLP ProblemsImage compression using K-means clusteringDeep learning | Image Caption Generation using the Avengers EndGames CharactersHow Does Google Use Machine Learning?How Does NASA Use Machine Learning?5 Mind-Blowing Ways Facebook Uses Machine LearningTargeted Advertising using Machine LearningHow Machine Learning Is Used by Famous Companies?"
},
{
"code": null,
"e": 46600,
"s": 46556,
"text": "Rainfall prediction using Linear regression"
},
{
"code": null,
"e": 46668,
"s": 46600,
"text": "Identifying handwritten digits using Logistic Regression in PyTorch"
},
{
"code": null,
"e": 46735,
"s": 46668,
"text": "Kaggle Breast Cancer Wisconsin Diagnosis using Logistic Regression"
},
{
"code": null,
"e": 46787,
"s": 46735,
"text": "Python | Implementation of Movie Recommender System"
},
{
"code": null,
"e": 46846,
"s": 46787,
"text": "Support Vector Machine to recognize facial features in C++"
},
{
"code": null,
"e": 46911,
"s": 46846,
"text": "Decision Trees – Fake (Counterfeit) Coin Puzzle (12 Coin Puzzle)"
},
{
"code": null,
"e": 46939,
"s": 46911,
"text": "Credit Card Fraud Detection"
},
{
"code": null,
"e": 46974,
"s": 46939,
"text": "NLP analysis of Restaurant reviews"
},
{
"code": null,
"e": 47023,
"s": 46974,
"text": "Applying Multinomial Naive Bayes to NLP Problems"
},
{
"code": null,
"e": 47066,
"s": 47023,
"text": "Image compression using K-means clustering"
},
{
"code": null,
"e": 47146,
"s": 47066,
"text": "Deep learning | Image Caption Generation using the Avengers EndGames Characters"
},
{
"code": null,
"e": 47184,
"s": 47146,
"text": "How Does Google Use Machine Learning?"
},
{
"code": null,
"e": 47220,
"s": 47184,
"text": "How Does NASA Use Machine Learning?"
},
{
"code": null,
"e": 47271,
"s": 47220,
"text": "5 Mind-Blowing Ways Facebook Uses Machine Learning"
},
{
"code": null,
"e": 47315,
"s": 47271,
"text": "Targeted Advertising using Machine Learning"
},
{
"code": null,
"e": 47365,
"s": 47315,
"text": "How Machine Learning Is Used by Famous Companies?"
},
{
"code": null,
"e": 47372,
"s": 47365,
"text": "Misc :"
},
{
"code": null,
"e": 47948,
"s": 47372,
"text": "Pattern Recognition | IntroductionCalculate Efficiency Of Binary ClassifierLogistic Regression v/s Decision Tree ClassificationR vs Python in DatascienceExplanation of Fundamental Functions involved in A3C algorithmDifferential Privacy and Deep LearningArtificial intelligence vs Machine Learning vs Deep LearningIntroduction to Multi-Task Learning(MTL) for Deep LearningTop 10 Algorithms every Machine Learning Engineer should knowAzure Virtual Machine for Machine Learning30 minutes to machine learningWhat is AutoML in Machine Learning?Confusion Matrix in Machine Learning"
},
{
"code": null,
"e": 47983,
"s": 47948,
"text": "Pattern Recognition | Introduction"
},
{
"code": null,
"e": 48025,
"s": 47983,
"text": "Calculate Efficiency Of Binary Classifier"
},
{
"code": null,
"e": 48078,
"s": 48025,
"text": "Logistic Regression v/s Decision Tree Classification"
},
{
"code": null,
"e": 48105,
"s": 48078,
"text": "R vs Python in Datascience"
},
{
"code": null,
"e": 48168,
"s": 48105,
"text": "Explanation of Fundamental Functions involved in A3C algorithm"
},
{
"code": null,
"e": 48207,
"s": 48168,
"text": "Differential Privacy and Deep Learning"
},
{
"code": null,
"e": 48268,
"s": 48207,
"text": "Artificial intelligence vs Machine Learning vs Deep Learning"
},
{
"code": null,
"e": 48327,
"s": 48268,
"text": "Introduction to Multi-Task Learning(MTL) for Deep Learning"
},
{
"code": null,
"e": 48389,
"s": 48327,
"text": "Top 10 Algorithms every Machine Learning Engineer should know"
},
{
"code": null,
"e": 48432,
"s": 48389,
"text": "Azure Virtual Machine for Machine Learning"
},
{
"code": null,
"e": 48463,
"s": 48432,
"text": "30 minutes to machine learning"
},
{
"code": null,
"e": 48499,
"s": 48463,
"text": "What is AutoML in Machine Learning?"
},
{
"code": null,
"e": 48536,
"s": 48499,
"text": "Confusion Matrix in Machine Learning"
},
{
"code": null,
"e": 48932,
"s": 48536,
"text": "Machines are learning, so why do you wish to get left behind? Strengthen your ML and AI foundations today and become future ready. This self-paced course will help you learn advanced concepts like- Regression, Classification, Data Dimensionality and much more. Also included- Projects that will help you get hands-on experience. So wait no more, and strengthen your Machine Learning Foundations."
},
{
"code": null,
"e": 49390,
"s": 48932,
"text": "Every organisation now relies on data before making any important decisions regarding their future. So, it is safe to say that Data is really the king now. So why do you want to get left behind? This LIVE course will introduce the learner to advanced concepts like: Linear Regression, Naive Bayes & KNN, Numpy, Pandas, Matlab & much more. You will also get to work on real-life projects through the course. So wait no more, Become a Data Science Expert now."
}
] |
Python | Pandas DatetimeIndex.day_name()
|
29 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas DatetimeIndex.day_name() function return the day names of the DateTimeIndex with specified locale. The default locale is None in which case the names are returned in English language.
Syntax: DatetimeIndex.day_name(locale=None)
Parameters :locale : locale determining the language in which to return the day name
Return : Index of day names
Example #1: Use DatetimeIndex.day_name() function to return the names of the day for each entry in the DatetimeIndex object. Return the names of the days in French locale
# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'Q' represents quarterly frequency didx = pd.DatetimeIndex(start ='2018-11-15 09:45:10', freq ='Q', periods = 5) # Print the DatetimeIndexprint(didx)
Output :
Now we want to return the names of the days in French locale.
# return the names of the days in Frenchdidx.day_name(locale ='French')
Output :As we can see in the output, the function has returned an Index object containing the names of the days in French.
Let’s return the name of the days in English
# return the names of the days in Englishdidx.day_name(locale ='English')
Output : Example #2: Use DatetimeIndex.day_name() function to return the names of the day for each entry in the DatetimeIndex object. Return the names of the day in German locale
# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'M' represents monthly frequency didx = pd.DatetimeIndex(start ='2015-03-02', freq ='M', periods = 5) # Print the DatetimeIndexprint(didx)
Output :
Now we want to return the names of the days in German locale.
# return the names of the days in Germandidx.day_name(locale ='German')
Output :As we can see in the output, the function has returned an Index object containing the names of the day in German locale.
Python pandas-datetimeIndex
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Dec, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 433,
"s": 242,
"text": "Pandas DatetimeIndex.day_name() function return the day names of the DateTimeIndex with specified locale. The default locale is None in which case the names are returned in English language."
},
{
"code": null,
"e": 477,
"s": 433,
"text": "Syntax: DatetimeIndex.day_name(locale=None)"
},
{
"code": null,
"e": 562,
"s": 477,
"text": "Parameters :locale : locale determining the language in which to return the day name"
},
{
"code": null,
"e": 590,
"s": 562,
"text": "Return : Index of day names"
},
{
"code": null,
"e": 761,
"s": 590,
"text": "Example #1: Use DatetimeIndex.day_name() function to return the names of the day for each entry in the DatetimeIndex object. Return the names of the days in French locale"
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'Q' represents quarterly frequency didx = pd.DatetimeIndex(start ='2018-11-15 09:45:10', freq ='Q', periods = 5) # Print the DatetimeIndexprint(didx)",
"e": 990,
"s": 761,
"text": null
},
{
"code": null,
"e": 999,
"s": 990,
"text": "Output :"
},
{
"code": null,
"e": 1061,
"s": 999,
"text": "Now we want to return the names of the days in French locale."
},
{
"code": "# return the names of the days in Frenchdidx.day_name(locale ='French')",
"e": 1133,
"s": 1061,
"text": null
},
{
"code": null,
"e": 1256,
"s": 1133,
"text": "Output :As we can see in the output, the function has returned an Index object containing the names of the days in French."
},
{
"code": null,
"e": 1301,
"s": 1256,
"text": "Let’s return the name of the days in English"
},
{
"code": "# return the names of the days in Englishdidx.day_name(locale ='English')",
"e": 1375,
"s": 1301,
"text": null
},
{
"code": null,
"e": 1554,
"s": 1375,
"text": "Output : Example #2: Use DatetimeIndex.day_name() function to return the names of the day for each entry in the DatetimeIndex object. Return the names of the day in German locale"
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'M' represents monthly frequency didx = pd.DatetimeIndex(start ='2015-03-02', freq ='M', periods = 5) # Print the DatetimeIndexprint(didx)",
"e": 1772,
"s": 1554,
"text": null
},
{
"code": null,
"e": 1781,
"s": 1772,
"text": "Output :"
},
{
"code": null,
"e": 1843,
"s": 1781,
"text": "Now we want to return the names of the days in German locale."
},
{
"code": "# return the names of the days in Germandidx.day_name(locale ='German')",
"e": 1915,
"s": 1843,
"text": null
},
{
"code": null,
"e": 2044,
"s": 1915,
"text": "Output :As we can see in the output, the function has returned an Index object containing the names of the day in German locale."
},
{
"code": null,
"e": 2072,
"s": 2044,
"text": "Python pandas-datetimeIndex"
},
{
"code": null,
"e": 2086,
"s": 2072,
"text": "Python-pandas"
},
{
"code": null,
"e": 2093,
"s": 2086,
"text": "Python"
},
{
"code": null,
"e": 2191,
"s": 2093,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2209,
"s": 2191,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2251,
"s": 2209,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2273,
"s": 2251,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2308,
"s": 2273,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2334,
"s": 2308,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2366,
"s": 2334,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2395,
"s": 2366,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2422,
"s": 2395,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2452,
"s": 2422,
"text": "Iterate over a list in Python"
}
] |
Java Program to Find Common Elements Between Two Arrays
|
08 Mar, 2021
Given two arrays and our task is to find their common elements. Examples:
Input: Array1 = ["Article", "for", "Geeks", "for", "Geeks"],
Array2 = ["Article", "Geeks", "Geeks"]
Output: [Article,Geeks]
Input: Array1 = ["a", "b", "c", "d", "e", "f"],
Array2 = ["b", "d", "e", "h", "g", "c"]
Output: [b, c, d, e]
Approach:
Get the two java Arrays.Iterate through each and every element of the arrays one by one and check whether they are common in both.Add each common element in the set for unique entries.
Get the two java Arrays.
Iterate through each and every element of the arrays one by one and check whether they are common in both.
Add each common element in the set for unique entries.
Java
// Java Program to find common elements// in two Arrays// Using iterative method import java.io.*;import java.util.*; class GFG { private static void FindCommonElemet(String[] arr1, String[] arr2) { Set<String> set = new HashSet<>(); for (int i = 0; i < arr1.length; i++) { for (int j = 0; j < arr2.length; j++) { if (arr1[i] == arr2[j]) { // add common elements set.add(arr1[i]); break; } } } for (String i : set) { System.out.print(i + " "); } } // main method public static void main(String[] args) { // create Array 1 String[] arr1 = { "Article", "in", "Geeks", "for", "Geeks" }; // create Array 2 String[] arr2 = { "Geeks", "for", "Geeks" }; // print Array 1 System.out.println("Array 1: " + Arrays.toString(arr1)); // print Array 2 System.out.println("Array 2: " + Arrays.toString(arr2)); System.out.print("Common Elements: "); // Find the common elements FindCommonElemet(arr1, arr2); }}
Array 1: [Article, in, Geeks, for, Geeks]
Array 2: [Geeks, for, Geeks]
Common Elements: Geeks for
Time Complexity: O(n^2)
By using the retainAll() method of the HashSet we can find the common elements between two arrays.
Syntax:
// This method keeps only the common elements
// of both Collection in Collection1.
Collections1.retainAll(Collections2)
Approach :
Get the two Arrays.Create two hashsets and add elements from arrays tp those sets.Find the common elements in both the sets using Collection.retainAll() method. This method keeps only the common elements of both Collection in Collection1.Set 1 now contains the common elements only.
Get the two Arrays.
Create two hashsets and add elements from arrays tp those sets.
Find the common elements in both the sets using Collection.retainAll() method. This method keeps only the common elements of both Collection in Collection1.
Set 1 now contains the common elements only.
Below is the implementation of the above approach:
Java
// Java Program to find common elements// in two Arrays using hashsets// and retainAll() methodimport java.io.*;import java.util.*; class GFG { // function to create hashsets // from arrays and find // their common element public static void FindCommonElements(int[] arr1, int[] arr2) { // create hashsets Set<Integer> set1 = new HashSet<>(); Set<Integer> set2 = new HashSet<>(); // Adding elements from array1 for (int i : arr1) { set1.add(i); } // Adding elements from array2 for (int i : arr2) { set2.add(i); } // use retainAll() method to // find common elements set1.retainAll(set2); System.out.println("Common elements- " + set1); } // main method public static void main(String[] args) { // create Array 1 int[] arr1 = { 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 }; // create Array 2 int[] arr2 = { 100, 9, 64, 7, 36, 5, 16, 3, 4, 1 }; // print Array 1 System.out.println("Array 1: " + Arrays.toString(arr1)); // print Array 2 System.out.println("Array 2: " + Arrays.toString(arr2)); FindCommonElements(arr1, arr2); }}
Array 1: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Array 2: [100, 9, 64, 7, 36, 5, 16, 3, 4, 1]
Common elements- [16, 64, 1, 4, 36, 100, 9]
Time Complexity: O(n) Using HashSet:
Approach:
1. Add all elements of first array into a hashset.
2. Iterate the second array and check whether element present in hashset using contains method. If contains == true, add the element to result in array.
Below is the implementation of the above approach:
Java
// Java program for the above approachimport java.io.*;import java.util.Arrays;import java.util.HashSet;import java.util.Set; class Test { private static void findCommonElements(int[] arr1, int[] arr2) { // Check if length of arr1 is greater than 0 // and length of arr2 is greater than 0 if (arr1.length > 0 && arr2.length > 0) { Set<Integer> firstSet = new HashSet<Integer>(); for (int i = 0; i < arr1.length; i++) { firstSet.add(arr1[i]); } // Iterate the elements of the arr2 for (int j = 0; j < arr2.length; j++) { if (firstSet.contains(arr2[j])) { System.out.println(arr2[j]); } } } } // Driver Code public static void main(String[] args) { int[] arr1 = new int[] { 1, 2, 3, 4, 5, 6, 7 }; int[] arr2 = new int[] { 1, 3, 4, 5, 6, 9, 8 }; // Function Call findCommonElements(arr1, arr2); }}
1
3
4
5
6
Time Complexity: O(n)
jeevajmanivel
Java-Array-Programs
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Mar, 2021"
},
{
"code": null,
"e": 102,
"s": 28,
"text": "Given two arrays and our task is to find their common elements. Examples:"
},
{
"code": null,
"e": 356,
"s": 102,
"text": "Input: Array1 = [\"Article\", \"for\", \"Geeks\", \"for\", \"Geeks\"], \n Array2 = [\"Article\", \"Geeks\", \"Geeks\"]\nOutput: [Article,Geeks]\n\nInput: Array1 = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"], \n Array2 = [\"b\", \"d\", \"e\", \"h\", \"g\", \"c\"]\nOutput: [b, c, d, e]"
},
{
"code": null,
"e": 367,
"s": 356,
"text": "Approach: "
},
{
"code": null,
"e": 552,
"s": 367,
"text": "Get the two java Arrays.Iterate through each and every element of the arrays one by one and check whether they are common in both.Add each common element in the set for unique entries."
},
{
"code": null,
"e": 577,
"s": 552,
"text": "Get the two java Arrays."
},
{
"code": null,
"e": 684,
"s": 577,
"text": "Iterate through each and every element of the arrays one by one and check whether they are common in both."
},
{
"code": null,
"e": 739,
"s": 684,
"text": "Add each common element in the set for unique entries."
},
{
"code": null,
"e": 744,
"s": 739,
"text": "Java"
},
{
"code": "// Java Program to find common elements// in two Arrays// Using iterative method import java.io.*;import java.util.*; class GFG { private static void FindCommonElemet(String[] arr1, String[] arr2) { Set<String> set = new HashSet<>(); for (int i = 0; i < arr1.length; i++) { for (int j = 0; j < arr2.length; j++) { if (arr1[i] == arr2[j]) { // add common elements set.add(arr1[i]); break; } } } for (String i : set) { System.out.print(i + \" \"); } } // main method public static void main(String[] args) { // create Array 1 String[] arr1 = { \"Article\", \"in\", \"Geeks\", \"for\", \"Geeks\" }; // create Array 2 String[] arr2 = { \"Geeks\", \"for\", \"Geeks\" }; // print Array 1 System.out.println(\"Array 1: \" + Arrays.toString(arr1)); // print Array 2 System.out.println(\"Array 2: \" + Arrays.toString(arr2)); System.out.print(\"Common Elements: \"); // Find the common elements FindCommonElemet(arr1, arr2); }}",
"e": 2003,
"s": 744,
"text": null
},
{
"code": null,
"e": 2102,
"s": 2003,
"text": "Array 1: [Article, in, Geeks, for, Geeks]\nArray 2: [Geeks, for, Geeks]\nCommon Elements: Geeks for "
},
{
"code": null,
"e": 2126,
"s": 2102,
"text": "Time Complexity: O(n^2)"
},
{
"code": null,
"e": 2225,
"s": 2126,
"text": "By using the retainAll() method of the HashSet we can find the common elements between two arrays."
},
{
"code": null,
"e": 2234,
"s": 2225,
"text": "Syntax: "
},
{
"code": null,
"e": 2356,
"s": 2234,
"text": "// This method keeps only the common elements\n// of both Collection in Collection1.\n\nCollections1.retainAll(Collections2)"
},
{
"code": null,
"e": 2368,
"s": 2356,
"text": "Approach : "
},
{
"code": null,
"e": 2651,
"s": 2368,
"text": "Get the two Arrays.Create two hashsets and add elements from arrays tp those sets.Find the common elements in both the sets using Collection.retainAll() method. This method keeps only the common elements of both Collection in Collection1.Set 1 now contains the common elements only."
},
{
"code": null,
"e": 2671,
"s": 2651,
"text": "Get the two Arrays."
},
{
"code": null,
"e": 2735,
"s": 2671,
"text": "Create two hashsets and add elements from arrays tp those sets."
},
{
"code": null,
"e": 2892,
"s": 2735,
"text": "Find the common elements in both the sets using Collection.retainAll() method. This method keeps only the common elements of both Collection in Collection1."
},
{
"code": null,
"e": 2937,
"s": 2892,
"text": "Set 1 now contains the common elements only."
},
{
"code": null,
"e": 2988,
"s": 2937,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2993,
"s": 2988,
"text": "Java"
},
{
"code": "// Java Program to find common elements// in two Arrays using hashsets// and retainAll() methodimport java.io.*;import java.util.*; class GFG { // function to create hashsets // from arrays and find // their common element public static void FindCommonElements(int[] arr1, int[] arr2) { // create hashsets Set<Integer> set1 = new HashSet<>(); Set<Integer> set2 = new HashSet<>(); // Adding elements from array1 for (int i : arr1) { set1.add(i); } // Adding elements from array2 for (int i : arr2) { set2.add(i); } // use retainAll() method to // find common elements set1.retainAll(set2); System.out.println(\"Common elements- \" + set1); } // main method public static void main(String[] args) { // create Array 1 int[] arr1 = { 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 }; // create Array 2 int[] arr2 = { 100, 9, 64, 7, 36, 5, 16, 3, 4, 1 }; // print Array 1 System.out.println(\"Array 1: \" + Arrays.toString(arr1)); // print Array 2 System.out.println(\"Array 2: \" + Arrays.toString(arr2)); FindCommonElements(arr1, arr2); }}",
"e": 4331,
"s": 2993,
"text": null
},
{
"code": null,
"e": 4469,
"s": 4331,
"text": "Array 1: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]\nArray 2: [100, 9, 64, 7, 36, 5, 16, 3, 4, 1]\nCommon elements- [16, 64, 1, 4, 36, 100, 9]\n"
},
{
"code": null,
"e": 4636,
"s": 4469,
"text": "Time Complexity: O(n) Using HashSet:"
},
{
"code": null,
"e": 4646,
"s": 4636,
"text": "Approach:"
},
{
"code": null,
"e": 4697,
"s": 4646,
"text": "1. Add all elements of first array into a hashset."
},
{
"code": null,
"e": 4850,
"s": 4697,
"text": "2. Iterate the second array and check whether element present in hashset using contains method. If contains == true, add the element to result in array."
},
{
"code": null,
"e": 4901,
"s": 4850,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 4906,
"s": 4901,
"text": "Java"
},
{
"code": "// Java program for the above approachimport java.io.*;import java.util.Arrays;import java.util.HashSet;import java.util.Set; class Test { private static void findCommonElements(int[] arr1, int[] arr2) { // Check if length of arr1 is greater than 0 // and length of arr2 is greater than 0 if (arr1.length > 0 && arr2.length > 0) { Set<Integer> firstSet = new HashSet<Integer>(); for (int i = 0; i < arr1.length; i++) { firstSet.add(arr1[i]); } // Iterate the elements of the arr2 for (int j = 0; j < arr2.length; j++) { if (firstSet.contains(arr2[j])) { System.out.println(arr2[j]); } } } } // Driver Code public static void main(String[] args) { int[] arr1 = new int[] { 1, 2, 3, 4, 5, 6, 7 }; int[] arr2 = new int[] { 1, 3, 4, 5, 6, 9, 8 }; // Function Call findCommonElements(arr1, arr2); }}",
"e": 5981,
"s": 4906,
"text": null
},
{
"code": null,
"e": 5992,
"s": 5981,
"text": "1\n3\n4\n5\n6\n"
},
{
"code": null,
"e": 6014,
"s": 5992,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 6028,
"s": 6014,
"text": "jeevajmanivel"
},
{
"code": null,
"e": 6048,
"s": 6028,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 6053,
"s": 6048,
"text": "Java"
},
{
"code": null,
"e": 6067,
"s": 6053,
"text": "Java Programs"
},
{
"code": null,
"e": 6072,
"s": 6067,
"text": "Java"
}
] |
Scope of Variables in C#
|
19 Jan, 2019
The part of the program where a particular variable is accessible is termed as the Scope of that variable. A variable can be defined in a class, method, loop etc. In C/C++, all identifiers are lexically (or statically) scoped, i.e.scope of a variable can be determined at compile time and independent of the function call stack. But the C# programs are organized in the form of classes.
So C# scope rules of variables can be divided into three categories as follows:
Class Level Scope
Method Level Scope
Block Level Scope
Declaring the variables in a class but outside any method can be directly accessed anywhere in the class.
These variables are also termed as the fields or class members.
Class level scoped variable can be accessed by the non-static methods of the class in which it is declared.
Access modifier of class level variables doesn’t affect their scope within a class.
Member variables can also be accessed outside the class by using the access modifiers.
Example:
// C# program to illustrate the// Class Level Scope of variablesusing System; // declaring a Classclass GFG { // from here class level scope starts // this is a class level variable // having class level scope int a = 10; // declaring a method public void display() { // accessing class level variable Console.WriteLine(a); } // here method ends } // here class level scope ends
Variables that are declared inside a method have method level scope. These are not accessible outside the method.
However, these variables can be accessed by the nested code blocks inside a method.
These variables are termed as the local variables.
There will be a compile-time error if these variables are declared twice with the same name in the same scope.
These variables don’t exist after method’s execution is over.
Example:
// C# program to illustrate the// Method Level Scope of variablesusing System; // declaring a Classclass GFG { // from here class level scope starts // declaring a method public void display() { // from here method level scope starts // this variable has // method level scope int m = 47; // accessing method level variable Console.WriteLine(m); } // here method level scope ends // declaring a method public void display1() { // from here method level scope starts // it will give compile time error as // you are trying to access the local // variable of method display() Console.WriteLine(m); } // here method level scope ends } // here class level scope ends
These variables are generally declared inside the for, while statement etc.
These variables are also termed as the loop variables or statements variable as they have limited their scope up to the body of the statement in which it declared.
Generally, a loop inside a method has three level of nested code blocks(i.e. class level, method level, loop level).
The variable which is declared outside the loop is also accessible within the nested loops. It means a class level variable will be accessible to the methods and all loops. Method level variable will be accessible to loop and method inside that method.
A variable which is declared inside a loop body will not be visible to the outside of loop body.
Example:
// C# code to illustrate the Block// Level scope of variablesusing System; // declaring a Classclass GFG { // from here class level scope starts // declaring a method public void display() { // from here method level scope starts // this variable has // method level scope int i = 0; for (i = 0; i < 4; i++) { // accessing method level variable Console.WriteLine(i); } // here j is block level variable // it is only accessible inside // this for loop for (int j = 0; j < 5; j++) { // accessing block level variable Console.WriteLine(j); } // this will give error as block level // variable can't be accessed outside // the block Console.WriteLine(j); } // here method level scope ends } // here class level scope ends
CSharp-Basics
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Multiple inheritance using interfaces
Introduction to .NET Framework
Differences Between .NET Core and .NET Framework
C# | Delegates
C# | Method Overriding
C# | String.IndexOf( ) Method | Set - 1
C# | Replace() Method
C# | Arrays
Extension Method in C#
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Jan, 2019"
},
{
"code": null,
"e": 439,
"s": 52,
"text": "The part of the program where a particular variable is accessible is termed as the Scope of that variable. A variable can be defined in a class, method, loop etc. In C/C++, all identifiers are lexically (or statically) scoped, i.e.scope of a variable can be determined at compile time and independent of the function call stack. But the C# programs are organized in the form of classes."
},
{
"code": null,
"e": 519,
"s": 439,
"text": "So C# scope rules of variables can be divided into three categories as follows:"
},
{
"code": null,
"e": 537,
"s": 519,
"text": "Class Level Scope"
},
{
"code": null,
"e": 556,
"s": 537,
"text": "Method Level Scope"
},
{
"code": null,
"e": 574,
"s": 556,
"text": "Block Level Scope"
},
{
"code": null,
"e": 680,
"s": 574,
"text": "Declaring the variables in a class but outside any method can be directly accessed anywhere in the class."
},
{
"code": null,
"e": 744,
"s": 680,
"text": "These variables are also termed as the fields or class members."
},
{
"code": null,
"e": 852,
"s": 744,
"text": "Class level scoped variable can be accessed by the non-static methods of the class in which it is declared."
},
{
"code": null,
"e": 936,
"s": 852,
"text": "Access modifier of class level variables doesn’t affect their scope within a class."
},
{
"code": null,
"e": 1023,
"s": 936,
"text": "Member variables can also be accessed outside the class by using the access modifiers."
},
{
"code": null,
"e": 1032,
"s": 1023,
"text": "Example:"
},
{
"code": "// C# program to illustrate the// Class Level Scope of variablesusing System; // declaring a Classclass GFG { // from here class level scope starts // this is a class level variable // having class level scope int a = 10; // declaring a method public void display() { // accessing class level variable Console.WriteLine(a); } // here method ends } // here class level scope ends",
"e": 1454,
"s": 1032,
"text": null
},
{
"code": null,
"e": 1568,
"s": 1454,
"text": "Variables that are declared inside a method have method level scope. These are not accessible outside the method."
},
{
"code": null,
"e": 1652,
"s": 1568,
"text": "However, these variables can be accessed by the nested code blocks inside a method."
},
{
"code": null,
"e": 1703,
"s": 1652,
"text": "These variables are termed as the local variables."
},
{
"code": null,
"e": 1814,
"s": 1703,
"text": "There will be a compile-time error if these variables are declared twice with the same name in the same scope."
},
{
"code": null,
"e": 1876,
"s": 1814,
"text": "These variables don’t exist after method’s execution is over."
},
{
"code": null,
"e": 1885,
"s": 1876,
"text": "Example:"
},
{
"code": "// C# program to illustrate the// Method Level Scope of variablesusing System; // declaring a Classclass GFG { // from here class level scope starts // declaring a method public void display() { // from here method level scope starts // this variable has // method level scope int m = 47; // accessing method level variable Console.WriteLine(m); } // here method level scope ends // declaring a method public void display1() { // from here method level scope starts // it will give compile time error as // you are trying to access the local // variable of method display() Console.WriteLine(m); } // here method level scope ends } // here class level scope ends",
"e": 2655,
"s": 1885,
"text": null
},
{
"code": null,
"e": 2731,
"s": 2655,
"text": "These variables are generally declared inside the for, while statement etc."
},
{
"code": null,
"e": 2895,
"s": 2731,
"text": "These variables are also termed as the loop variables or statements variable as they have limited their scope up to the body of the statement in which it declared."
},
{
"code": null,
"e": 3012,
"s": 2895,
"text": "Generally, a loop inside a method has three level of nested code blocks(i.e. class level, method level, loop level)."
},
{
"code": null,
"e": 3265,
"s": 3012,
"text": "The variable which is declared outside the loop is also accessible within the nested loops. It means a class level variable will be accessible to the methods and all loops. Method level variable will be accessible to loop and method inside that method."
},
{
"code": null,
"e": 3362,
"s": 3265,
"text": "A variable which is declared inside a loop body will not be visible to the outside of loop body."
},
{
"code": null,
"e": 3371,
"s": 3362,
"text": "Example:"
},
{
"code": "// C# code to illustrate the Block// Level scope of variablesusing System; // declaring a Classclass GFG { // from here class level scope starts // declaring a method public void display() { // from here method level scope starts // this variable has // method level scope int i = 0; for (i = 0; i < 4; i++) { // accessing method level variable Console.WriteLine(i); } // here j is block level variable // it is only accessible inside // this for loop for (int j = 0; j < 5; j++) { // accessing block level variable Console.WriteLine(j); } // this will give error as block level // variable can't be accessed outside // the block Console.WriteLine(j); } // here method level scope ends } // here class level scope ends",
"e": 4263,
"s": 3371,
"text": null
},
{
"code": null,
"e": 4277,
"s": 4263,
"text": "CSharp-Basics"
},
{
"code": null,
"e": 4280,
"s": 4277,
"text": "C#"
},
{
"code": null,
"e": 4378,
"s": 4280,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4406,
"s": 4378,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 4449,
"s": 4406,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 4480,
"s": 4449,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 4529,
"s": 4480,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 4544,
"s": 4529,
"text": "C# | Delegates"
},
{
"code": null,
"e": 4567,
"s": 4544,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 4607,
"s": 4567,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 4629,
"s": 4607,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 4641,
"s": 4629,
"text": "C# | Arrays"
}
] |
Inverse Fourier transform in MATLAB
|
30 May, 2021
Inverse Fourier Transform helps to return from Frequency domain function X(ω) to Time Domain x(t). In this article, we will see how to find Inverse Fourier Transform in MATLAB.
The mathematical expression for Inverse Fourier transform is:
In MATLAB, ifourier command returns the Inverse Fourier transform of given function. Input can be provided to ifourier function using 3 different syntax.
ifourier(X): In this method, X is the frequency domain function whereas by default independent variable is w (If X does not contain w, then ifourier uses the function symvar) and the transformation variable is x.
ifourier(X,transvar): Here, X is the frequency domain function whereas transvar is the transformation variable instead of x.
ifourier(X,indepvar,transvar): In this syntax, X is the frequency domain function whereas indepvar is the independent variable and transvar is the transformation variable instead of w and x respectively.
Example:
Find the Inverse Fourier Transform of
Matlab
% MATLAB code specify the variable% w and t as symbolic onessyms w t % define Frequency domain function X(w)X=exp(-w^2/4); % ifourier command to transform into% time domain function x(t)% using 1st syntax, where by default % independent variable = w% and transformation variable is x .x1 = ifourier(X); % using 2nd syntax, where transformation variable = tx2 = ifourier(X,t); % using 3rd syntax, where independent variable % = w (as there is no other% variable in function) and transformation % variable = t x3 = ifourier(X,w,t); % Display the output valuedisp('1. Inverse Fourier Transform of exp(-w^2/4) using ifourier(X) :')disp(x1); disp('2. Inverse Fourier Transform of exp(-w^2/4) using ifourier(X,t) :')disp(x2); disp('3. Inverse Fourier Transform of exp(-w^2/4) using ifourier(X,w,t) :')disp(x3);
Output:
Example:
Find the Inverse Fourier Transform of
Matlab
% MATLAB code to specify the variable %% a w and t as symbolic ones %syms a w t % define Frequency domain function X(w)X=exp(-w^2-a^2); % ifourier command to transform into% time domain function x(t)% using 1st syntax, where by default% independent variable = w% and transformation variable is x .x1=ifourier(X); % using 2nd syntax, where transformation % variable = tx2=ifourier(X,t); % using 3rd syntax, where independent % variable = w (as there is no other% variable in function) and transformation % variable = t x3=ifourier(X,w,t); % Display the output valuedisp('1. Inverse Fourier Transform of exp(-w^2-a^2) using ifourier(X) :')disp(x1); disp('2. Inverse Fourier Transform of exp(-w^2-a^2) using ifourier(X,t) :')disp(x2); disp('3. Inverse Fourier Transform of exp(-w^2-a^2) using ifourier(X,w,t) :')disp(x3);
Output:
MATLAB-Maths
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?
How to Solve Histogram Equalization Numerical Problem in MATLAB?
Adaptive Histogram Equalization in Image Processing Using MATLAB
MRI Image Segmentation in MATLAB
How to detect duplicate values and its indices within an array in MATLAB?
Double Integral in MATLAB
Classes and Object in MATLAB
How to Normalize a Histogram in MATLAB?
How to remove space in a string in MATLAB?
Forward and Inverse Fourier Transform of an Image in MATLAB
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 May, 2021"
},
{
"code": null,
"e": 231,
"s": 54,
"text": "Inverse Fourier Transform helps to return from Frequency domain function X(ω) to Time Domain x(t). In this article, we will see how to find Inverse Fourier Transform in MATLAB."
},
{
"code": null,
"e": 293,
"s": 231,
"text": "The mathematical expression for Inverse Fourier transform is:"
},
{
"code": null,
"e": 449,
"s": 295,
"text": "In MATLAB, ifourier command returns the Inverse Fourier transform of given function. Input can be provided to ifourier function using 3 different syntax."
},
{
"code": null,
"e": 662,
"s": 449,
"text": "ifourier(X): In this method, X is the frequency domain function whereas by default independent variable is w (If X does not contain w, then ifourier uses the function symvar) and the transformation variable is x."
},
{
"code": null,
"e": 787,
"s": 662,
"text": "ifourier(X,transvar): Here, X is the frequency domain function whereas transvar is the transformation variable instead of x."
},
{
"code": null,
"e": 991,
"s": 787,
"text": "ifourier(X,indepvar,transvar): In this syntax, X is the frequency domain function whereas indepvar is the independent variable and transvar is the transformation variable instead of w and x respectively."
},
{
"code": null,
"e": 1000,
"s": 991,
"text": "Example:"
},
{
"code": null,
"e": 1040,
"s": 1000,
"text": " Find the Inverse Fourier Transform of "
},
{
"code": null,
"e": 1047,
"s": 1040,
"text": "Matlab"
},
{
"code": "% MATLAB code specify the variable% w and t as symbolic onessyms w t % define Frequency domain function X(w)X=exp(-w^2/4); % ifourier command to transform into% time domain function x(t)% using 1st syntax, where by default % independent variable = w% and transformation variable is x .x1 = ifourier(X); % using 2nd syntax, where transformation variable = tx2 = ifourier(X,t); % using 3rd syntax, where independent variable % = w (as there is no other% variable in function) and transformation % variable = t x3 = ifourier(X,w,t); % Display the output valuedisp('1. Inverse Fourier Transform of exp(-w^2/4) using ifourier(X) :')disp(x1); disp('2. Inverse Fourier Transform of exp(-w^2/4) using ifourier(X,t) :')disp(x2); disp('3. Inverse Fourier Transform of exp(-w^2/4) using ifourier(X,w,t) :')disp(x3);",
"e": 1859,
"s": 1047,
"text": null
},
{
"code": null,
"e": 1867,
"s": 1859,
"text": "Output:"
},
{
"code": null,
"e": 1876,
"s": 1867,
"text": "Example:"
},
{
"code": null,
"e": 1916,
"s": 1876,
"text": " Find the Inverse Fourier Transform of "
},
{
"code": null,
"e": 1923,
"s": 1916,
"text": "Matlab"
},
{
"code": "% MATLAB code to specify the variable %% a w and t as symbolic ones %syms a w t % define Frequency domain function X(w)X=exp(-w^2-a^2); % ifourier command to transform into% time domain function x(t)% using 1st syntax, where by default% independent variable = w% and transformation variable is x .x1=ifourier(X); % using 2nd syntax, where transformation % variable = tx2=ifourier(X,t); % using 3rd syntax, where independent % variable = w (as there is no other% variable in function) and transformation % variable = t x3=ifourier(X,w,t); % Display the output valuedisp('1. Inverse Fourier Transform of exp(-w^2-a^2) using ifourier(X) :')disp(x1); disp('2. Inverse Fourier Transform of exp(-w^2-a^2) using ifourier(X,t) :')disp(x2); disp('3. Inverse Fourier Transform of exp(-w^2-a^2) using ifourier(X,w,t) :')disp(x3);",
"e": 2749,
"s": 1923,
"text": null
},
{
"code": null,
"e": 2757,
"s": 2749,
"text": "Output:"
},
{
"code": null,
"e": 2770,
"s": 2757,
"text": "MATLAB-Maths"
},
{
"code": null,
"e": 2777,
"s": 2770,
"text": "Picked"
},
{
"code": null,
"e": 2784,
"s": 2777,
"text": "MATLAB"
},
{
"code": null,
"e": 2882,
"s": 2784,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2961,
"s": 2882,
"text": "How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?"
},
{
"code": null,
"e": 3026,
"s": 2961,
"text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?"
},
{
"code": null,
"e": 3091,
"s": 3026,
"text": "Adaptive Histogram Equalization in Image Processing Using MATLAB"
},
{
"code": null,
"e": 3124,
"s": 3091,
"text": "MRI Image Segmentation in MATLAB"
},
{
"code": null,
"e": 3198,
"s": 3124,
"text": "How to detect duplicate values and its indices within an array in MATLAB?"
},
{
"code": null,
"e": 3224,
"s": 3198,
"text": "Double Integral in MATLAB"
},
{
"code": null,
"e": 3253,
"s": 3224,
"text": "Classes and Object in MATLAB"
},
{
"code": null,
"e": 3293,
"s": 3253,
"text": "How to Normalize a Histogram in MATLAB?"
},
{
"code": null,
"e": 3336,
"s": 3293,
"text": "How to remove space in a string in MATLAB?"
}
] |
Modulus function in C++ STL
|
14 Sep, 2018
Modulus function is used to return the value of the modulus between its two arguments. It works same as modulus operator works.
template struct modulus : binary_function
{
T operator() (const T& x, const T& y) const
{
return x%y;
}
};
Member types:
Type of first argument
Type of second argument
Type of result returned by member operator
Note: We must include library ‘functional’ and ‘algorithm’ to use modulus and transform.
Bewlo programs illustrate the working of modulus function:
// C++ program to implement modulus function#include <algorithm> // transform#include <functional> // modulus, bind2nd#include <iostream> // coutusing namespace std; int main(){ // defining the array int array[] = { 8, 6, 3, 4, 1 }; int remainders[5]; // transform function that helps to apply // modulus between the arguments transform(array, array + 5, remainders, bind2nd(modulus<int>(), 2)); for (int i = 0; i < 5; i++) // printing the results while checking // whether no. is even or odd cout << array[i] << " is a " << (remainders[i] == 0 ? "even" : "odd") << endl; return 0;}
8 is a even
6 is a even
3 is a odd
4 is a even
1 is a odd
// C++ program to implement modulus function#include <algorithm> // transform#include <functional> // modulus, bind2nd#include <iostream> // cout#include <iterator>#include <vector>using namespace std; int main(){ // Create a std::vector with elements // {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} vector<int> v; for (int i = 0; i < 10; ++i) v.push_back(i); // Perform a modulus of two on every element transform(v.begin(), v.end(), v.begin(), bind2nd(modulus<int>(), 2)); // Display the vector copy(v.begin(), v.end(), ostream_iterator<int>(cout, " ")); cout << endl; return 0;}
0 1 0 1 0 1 0 1 0 1
CPP-Functions
cpp-template
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
std::find in C++
List in C++ Standard Template Library (STL)
Inline Functions in C++
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Sep, 2018"
},
{
"code": null,
"e": 156,
"s": 28,
"text": "Modulus function is used to return the value of the modulus between its two arguments. It works same as modulus operator works."
},
{
"code": null,
"e": 277,
"s": 156,
"text": "template struct modulus : binary_function \n{\n T operator() (const T& x, const T& y) const \n {\n return x%y;\n }\n};\n"
},
{
"code": null,
"e": 291,
"s": 277,
"text": "Member types:"
},
{
"code": null,
"e": 314,
"s": 291,
"text": "Type of first argument"
},
{
"code": null,
"e": 338,
"s": 314,
"text": "Type of second argument"
},
{
"code": null,
"e": 381,
"s": 338,
"text": "Type of result returned by member operator"
},
{
"code": null,
"e": 470,
"s": 381,
"text": "Note: We must include library ‘functional’ and ‘algorithm’ to use modulus and transform."
},
{
"code": null,
"e": 529,
"s": 470,
"text": "Bewlo programs illustrate the working of modulus function:"
},
{
"code": "// C++ program to implement modulus function#include <algorithm> // transform#include <functional> // modulus, bind2nd#include <iostream> // coutusing namespace std; int main(){ // defining the array int array[] = { 8, 6, 3, 4, 1 }; int remainders[5]; // transform function that helps to apply // modulus between the arguments transform(array, array + 5, remainders, bind2nd(modulus<int>(), 2)); for (int i = 0; i < 5; i++) // printing the results while checking // whether no. is even or odd cout << array[i] << \" is a \" << (remainders[i] == 0 ? \"even\" : \"odd\") << endl; return 0;}",
"e": 1203,
"s": 529,
"text": null
},
{
"code": null,
"e": 1262,
"s": 1203,
"text": "8 is a even\n6 is a even\n3 is a odd\n4 is a even\n1 is a odd\n"
},
{
"code": "// C++ program to implement modulus function#include <algorithm> // transform#include <functional> // modulus, bind2nd#include <iostream> // cout#include <iterator>#include <vector>using namespace std; int main(){ // Create a std::vector with elements // {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} vector<int> v; for (int i = 0; i < 10; ++i) v.push_back(i); // Perform a modulus of two on every element transform(v.begin(), v.end(), v.begin(), bind2nd(modulus<int>(), 2)); // Display the vector copy(v.begin(), v.end(), ostream_iterator<int>(cout, \" \")); cout << endl; return 0;}",
"e": 1897,
"s": 1262,
"text": null
},
{
"code": null,
"e": 1918,
"s": 1897,
"text": "0 1 0 1 0 1 0 1 0 1\n"
},
{
"code": null,
"e": 1932,
"s": 1918,
"text": "CPP-Functions"
},
{
"code": null,
"e": 1945,
"s": 1932,
"text": "cpp-template"
},
{
"code": null,
"e": 1949,
"s": 1945,
"text": "STL"
},
{
"code": null,
"e": 1953,
"s": 1949,
"text": "C++"
},
{
"code": null,
"e": 1957,
"s": 1953,
"text": "STL"
},
{
"code": null,
"e": 1961,
"s": 1957,
"text": "CPP"
},
{
"code": null,
"e": 2059,
"s": 1961,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2083,
"s": 2059,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 2103,
"s": 2083,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 2136,
"s": 2103,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 2180,
"s": 2136,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2205,
"s": 2180,
"text": "std::string class in C++"
},
{
"code": null,
"e": 2250,
"s": 2205,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2298,
"s": 2250,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 2315,
"s": 2298,
"text": "std::find in C++"
},
{
"code": null,
"e": 2359,
"s": 2315,
"text": "List in C++ Standard Template Library (STL)"
}
] |
Service Locator Pattern
|
06 Mar, 2018
The service locator pattern is a design pattern used in software development to encapsulate the processes involved in obtaining a service with a strong abstraction layer. This pattern uses a central registry known as the “service locator” which on request returns the information necessary to perform a certain task.The ServiceLocator is responsible for returning instances of services when they are requested for by the service consumers or the service clients.
UML Diagram Service Locator Pattern
Design components
Service Locator : The Service Locator abstracts the API lookup services, vendor dependencies, lookup complexities, and business object creation, and provides a simple interface to clients. This reduces the client’s complexity. In addition, the same client or other clients can reuse the Service Locator.
InitialContext : The InitialContext object is the start point in the lookup and creation process. Service providers provide the context object, which varies depending on the type of business object provided by the Service Locator’s lookup and creation service.
ServiceFactory : The ServiceFactory object represents an object that provides life cycle management for the BusinessService objects. The ServiceFactory object for enterprise beans is an EJBHome object.
BusinessService : The BusinessService is a role that is fulfilled by the service the client is seeking to access. The BusinessService object is created or looked up or removed by the ServiceFactory. The BusinessService object in the context of an EJB application is an enterprise bean.
Suppose classes with dependencies on services whose concrete types are specified at compile time.
In the above diagram, ClassA has compile time dependencies on ServiceA and ServiceB.But this situation has drawbacks.
If we want to replace or update the dependencies we must change the classes source code and recompile the solution.
The concrete implementation of the dependencies must be available at compile time.
By using the Service Locator pattern :
In simple words, Service Locator pattern does not describe how to instantiate the services. It describes a way to register services and locate them.
Let’s see an example of Service Locator Pattern.
// Java program to// illustrate Service Design Service// Locator Pattern import java.util.ArrayList;import java.util.List; // Service interface// for getting name and// Executing it. interface Service { public String getName(); public void execute();} // Service one implementing Locatorclass ServiceOne implements Service { public void execute() { System.out.println("Executing ServiceOne"); } @Override public String getName() { return "ServiceOne"; }} // Service two implementing Locatorclass ServiceTwo implements Service { public void execute() { System.out.println("Executing ServiceTwo"); } @Override public String getName() { return "ServiceTwo"; }} // Checking the context// for ServiceOne and ServiceTwoclass InitialContext { public Object lookup(String name) { if (name.equalsIgnoreCase("ServiceOne")) { System.out.println("Creating a new ServiceOne object"); return new ServiceOne(); } else if (name.equalsIgnoreCase("ServiceTwo")) { System.out.println("Creating a new ServiceTwo object"); return new ServiceTwo(); } return null; }} class Cache { private List<Service> services; public Cache() { services = new ArrayList<Service>(); } public Service getService(String serviceName) { for (Service service : services) { if (service.getName().equalsIgnoreCase(serviceName)) { System.out.println("Returning cached " + serviceName + " object"); return service; } } return null; } public void addService(Service newService) { boolean exists = false; for (Service service : services) { if (service.getName().equalsIgnoreCase(newService.getName())) { exists = true; } } if (!exists) { services.add(newService); } }} // Locator classclass ServiceLocator { private static Cache cache; static { cache = new Cache(); } public static Service getService(String name) { Service service = cache.getService(name); if (service != null) { return service; } InitialContext context = new InitialContext(); Service ServiceOne = (Service)context.lookup(name); cache.addService(ServiceOne); return ServiceOne; }} // Driver classclass ServiceLocatorPatternDemo { public static void main(String[] args) { Service service = ServiceLocator.getService("ServiceOne"); service.execute(); service = ServiceLocator.getService("ServiceTwo"); service.execute(); service = ServiceLocator.getService("ServiceOne"); service.execute(); service = ServiceLocator.getService("ServiceTwo"); service.execute(); }}
Output:
Creating a new ServiceOne object
Executing ServiceOne
Creating a new ServiceTwo object
Executing ServiceTwo
Returning cached ServiceOne object
Executing ServiceOne
Returning cached ServiceTwo object
Executing ServiceTwo
Advantages :
Applications can optimize themselves at run-time by selectively adding and removing items from the service locator.
Large sections of a library or application can be completely separated. The only link between them becomes the registry.
Disadvantages :
The registry makes the code more difficult to maintain (opposed to using Dependency injection), because it becomes unclear when you would be introducing a breaking change.
The registry hides the class dependencies causing run-time errors instead of compile-time errors when dependencies are missing.
Strategies
The following strategies are used to implement service Locator Pattern :
EJB Service Locator Strategy : This strategy uses EJBHome object for enterprise bean components and this EJBHome is cached in the ServiceLocator for future use when the client needs the home object again.
JMS Queue Service Locator Strategy : This strategy is applicable to point to point messaging requirements. The following the strategies under JMS Queue Service Locator Strategy.
JMS Queue Service Locator Strategy
JMS Topic Service Locator Strategy
Type Checked Service Locator Strategy : This strategy has trade-offs. It reduces the flexibility of lookup, which is in the Services Property Locator strategy, but add the type checking of passing in a constant to the ServiceLocator.getHome() method.
Design Pattern
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Mar, 2018"
},
{
"code": null,
"e": 517,
"s": 54,
"text": "The service locator pattern is a design pattern used in software development to encapsulate the processes involved in obtaining a service with a strong abstraction layer. This pattern uses a central registry known as the “service locator” which on request returns the information necessary to perform a certain task.The ServiceLocator is responsible for returning instances of services when they are requested for by the service consumers or the service clients."
},
{
"code": null,
"e": 553,
"s": 517,
"text": "UML Diagram Service Locator Pattern"
},
{
"code": null,
"e": 571,
"s": 553,
"text": "Design components"
},
{
"code": null,
"e": 875,
"s": 571,
"text": "Service Locator : The Service Locator abstracts the API lookup services, vendor dependencies, lookup complexities, and business object creation, and provides a simple interface to clients. This reduces the client’s complexity. In addition, the same client or other clients can reuse the Service Locator."
},
{
"code": null,
"e": 1136,
"s": 875,
"text": "InitialContext : The InitialContext object is the start point in the lookup and creation process. Service providers provide the context object, which varies depending on the type of business object provided by the Service Locator’s lookup and creation service."
},
{
"code": null,
"e": 1338,
"s": 1136,
"text": "ServiceFactory : The ServiceFactory object represents an object that provides life cycle management for the BusinessService objects. The ServiceFactory object for enterprise beans is an EJBHome object."
},
{
"code": null,
"e": 1624,
"s": 1338,
"text": "BusinessService : The BusinessService is a role that is fulfilled by the service the client is seeking to access. The BusinessService object is created or looked up or removed by the ServiceFactory. The BusinessService object in the context of an EJB application is an enterprise bean."
},
{
"code": null,
"e": 1722,
"s": 1624,
"text": "Suppose classes with dependencies on services whose concrete types are specified at compile time."
},
{
"code": null,
"e": 1840,
"s": 1722,
"text": "In the above diagram, ClassA has compile time dependencies on ServiceA and ServiceB.But this situation has drawbacks."
},
{
"code": null,
"e": 1956,
"s": 1840,
"text": "If we want to replace or update the dependencies we must change the classes source code and recompile the solution."
},
{
"code": null,
"e": 2039,
"s": 1956,
"text": "The concrete implementation of the dependencies must be available at compile time."
},
{
"code": null,
"e": 2078,
"s": 2039,
"text": "By using the Service Locator pattern :"
},
{
"code": null,
"e": 2227,
"s": 2078,
"text": "In simple words, Service Locator pattern does not describe how to instantiate the services. It describes a way to register services and locate them."
},
{
"code": null,
"e": 2276,
"s": 2227,
"text": "Let’s see an example of Service Locator Pattern."
},
{
"code": "// Java program to// illustrate Service Design Service// Locator Pattern import java.util.ArrayList;import java.util.List; // Service interface// for getting name and// Executing it. interface Service { public String getName(); public void execute();} // Service one implementing Locatorclass ServiceOne implements Service { public void execute() { System.out.println(\"Executing ServiceOne\"); } @Override public String getName() { return \"ServiceOne\"; }} // Service two implementing Locatorclass ServiceTwo implements Service { public void execute() { System.out.println(\"Executing ServiceTwo\"); } @Override public String getName() { return \"ServiceTwo\"; }} // Checking the context// for ServiceOne and ServiceTwoclass InitialContext { public Object lookup(String name) { if (name.equalsIgnoreCase(\"ServiceOne\")) { System.out.println(\"Creating a new ServiceOne object\"); return new ServiceOne(); } else if (name.equalsIgnoreCase(\"ServiceTwo\")) { System.out.println(\"Creating a new ServiceTwo object\"); return new ServiceTwo(); } return null; }} class Cache { private List<Service> services; public Cache() { services = new ArrayList<Service>(); } public Service getService(String serviceName) { for (Service service : services) { if (service.getName().equalsIgnoreCase(serviceName)) { System.out.println(\"Returning cached \" + serviceName + \" object\"); return service; } } return null; } public void addService(Service newService) { boolean exists = false; for (Service service : services) { if (service.getName().equalsIgnoreCase(newService.getName())) { exists = true; } } if (!exists) { services.add(newService); } }} // Locator classclass ServiceLocator { private static Cache cache; static { cache = new Cache(); } public static Service getService(String name) { Service service = cache.getService(name); if (service != null) { return service; } InitialContext context = new InitialContext(); Service ServiceOne = (Service)context.lookup(name); cache.addService(ServiceOne); return ServiceOne; }} // Driver classclass ServiceLocatorPatternDemo { public static void main(String[] args) { Service service = ServiceLocator.getService(\"ServiceOne\"); service.execute(); service = ServiceLocator.getService(\"ServiceTwo\"); service.execute(); service = ServiceLocator.getService(\"ServiceOne\"); service.execute(); service = ServiceLocator.getService(\"ServiceTwo\"); service.execute(); }}",
"e": 5235,
"s": 2276,
"text": null
},
{
"code": null,
"e": 5243,
"s": 5235,
"text": "Output:"
},
{
"code": null,
"e": 5464,
"s": 5243,
"text": "Creating a new ServiceOne object\nExecuting ServiceOne\nCreating a new ServiceTwo object\nExecuting ServiceTwo\nReturning cached ServiceOne object\nExecuting ServiceOne\nReturning cached ServiceTwo object\nExecuting ServiceTwo\n"
},
{
"code": null,
"e": 5477,
"s": 5464,
"text": "Advantages :"
},
{
"code": null,
"e": 5593,
"s": 5477,
"text": "Applications can optimize themselves at run-time by selectively adding and removing items from the service locator."
},
{
"code": null,
"e": 5714,
"s": 5593,
"text": "Large sections of a library or application can be completely separated. The only link between them becomes the registry."
},
{
"code": null,
"e": 5730,
"s": 5714,
"text": "Disadvantages :"
},
{
"code": null,
"e": 5902,
"s": 5730,
"text": "The registry makes the code more difficult to maintain (opposed to using Dependency injection), because it becomes unclear when you would be introducing a breaking change."
},
{
"code": null,
"e": 6030,
"s": 5902,
"text": "The registry hides the class dependencies causing run-time errors instead of compile-time errors when dependencies are missing."
},
{
"code": null,
"e": 6041,
"s": 6030,
"text": "Strategies"
},
{
"code": null,
"e": 6114,
"s": 6041,
"text": "The following strategies are used to implement service Locator Pattern :"
},
{
"code": null,
"e": 6319,
"s": 6114,
"text": "EJB Service Locator Strategy : This strategy uses EJBHome object for enterprise bean components and this EJBHome is cached in the ServiceLocator for future use when the client needs the home object again."
},
{
"code": null,
"e": 6497,
"s": 6319,
"text": "JMS Queue Service Locator Strategy : This strategy is applicable to point to point messaging requirements. The following the strategies under JMS Queue Service Locator Strategy."
},
{
"code": null,
"e": 6532,
"s": 6497,
"text": "JMS Queue Service Locator Strategy"
},
{
"code": null,
"e": 6567,
"s": 6532,
"text": "JMS Topic Service Locator Strategy"
},
{
"code": null,
"e": 6818,
"s": 6567,
"text": "Type Checked Service Locator Strategy : This strategy has trade-offs. It reduces the flexibility of lookup, which is in the Services Property Locator strategy, but add the type checking of passing in a constant to the ServiceLocator.getHome() method."
},
{
"code": null,
"e": 6833,
"s": 6818,
"text": "Design Pattern"
}
] |
Python: Call Parent class method
|
23 Jan, 2020
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made.
Example:
# Python program to demonstrate# classes class cls: # Constructor def __init__(self, fname, mname, lname): self.firstname = fname self.middlename = mname self.lastname = lname # class Function def print(self): print(self.firstname, self.middlename, self.lastname) # Use the Parent class to create an object# and then execute the print method:x = cls("Geeks", "for", "Geeks")x.print()
Output:
Geeks for Geeks
To understand about the concept of parent class, you have to know about Inheritance in Python. In simpler terms, inheritance is the concept by which one class (commonly known as child class or sub class) inherits the properties from another class (commonly known as Parent class or super class).
But have you ever wondered about calling the functions defined inside the parent class with the help of child class? Well this can done using Python. You just have to create an object of the child class and call the function of the parent class using dot(.) operator.
Example:
# Python code to demonstrate # parent call method class Parent: # create a parent class method def show(self): print("Inside Parent class") # create a child classclass Child(Parent): # Create a child class method def display(self): print("Inside Child class") # Driver's codeobj = Child()obj.display() # Calling Parent classobj.show()
Output
Inside Child class
Inside Parent class
Method overriding is an ability of any object-oriented programming language that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes.
Parent class methods can also be called within the overridden methods. This can generally be achieved by two ways.
Using Classname: Parent’s class methods can be called by using the Parent classname.method inside the overridden method.Example:# Python program to demonstrate# calling the parent's class method# inside the overridden method class Parent(): def show(self): print("Inside Parent") class Child(Parent): def show(self): # Calling the parent's class # method Parent.show(self) print("Inside Child") # Driver's codeobj = Child()obj.show()Output:Inside Parent
Inside Child
Example:
# Python program to demonstrate# calling the parent's class method# inside the overridden method class Parent(): def show(self): print("Inside Parent") class Child(Parent): def show(self): # Calling the parent's class # method Parent.show(self) print("Inside Child") # Driver's codeobj = Child()obj.show()
Output:
Inside Parent
Inside Child
Using Super(): Python super() function provides us the facility to refer to the parent class explicitly. It is basically useful where we have to call superclass functions. It returns the proxy object that allows us to refer parent class by ‘super’.Example 1:# Python program to demonstrate# calling the parent's class method# inside the overridden method using# super() class Parent(): def show(self): print("Inside Parent") class Child(Parent): def show(self): # Calling the parent's class # method super().show() print("Inside Child") # Driver's codeobj = Child()obj.show()Output:Inside Parent
Inside Child
Example 2:# Program to define the use of super() # function in multiple inheritance class GFG1: def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG1)') def sub_GFG(self, b): print('Printing from class GFG1:', b) # class GFG2 inherits the GFG1 class GFG2(GFG1): def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG2)') super().__init__() def sub_GFG(self, b): print('Printing from class GFG2:', b) super().sub_GFG(b + 1) # class GFG3 inherits the GFG1 ang GFG2 both class GFG3(GFG2): def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG3)') super().__init__() def sub_GFG(self, b): print('Printing from class GFG3:', b) super().sub_GFG(b + 1) # main function if __name__ == '__main__': # created the object gfg gfg = GFG3() # calling the function sub_GFG3() from class GHG3 # which inherits both GFG1 and GFG2 classes gfg.sub_GFG(10)Output:HEY !!!!!! GfG I am initialised(Class GEG3)
HEY !!!!!! GfG I am initialised(Class GEG2)
HEY !!!!!! GfG I am initialised(Class GEG1)
Printing from class GFG3: 10
Printing from class GFG2: 11
Printing from class GFG1: 12
Example 1:
# Python program to demonstrate# calling the parent's class method# inside the overridden method using# super() class Parent(): def show(self): print("Inside Parent") class Child(Parent): def show(self): # Calling the parent's class # method super().show() print("Inside Child") # Driver's codeobj = Child()obj.show()
Output:
Inside Parent
Inside Child
Example 2:
# Program to define the use of super() # function in multiple inheritance class GFG1: def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG1)') def sub_GFG(self, b): print('Printing from class GFG1:', b) # class GFG2 inherits the GFG1 class GFG2(GFG1): def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG2)') super().__init__() def sub_GFG(self, b): print('Printing from class GFG2:', b) super().sub_GFG(b + 1) # class GFG3 inherits the GFG1 ang GFG2 both class GFG3(GFG2): def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG3)') super().__init__() def sub_GFG(self, b): print('Printing from class GFG3:', b) super().sub_GFG(b + 1) # main function if __name__ == '__main__': # created the object gfg gfg = GFG3() # calling the function sub_GFG3() from class GHG3 # which inherits both GFG1 and GFG2 classes gfg.sub_GFG(10)
Output:
HEY !!!!!! GfG I am initialised(Class GEG3)
HEY !!!!!! GfG I am initialised(Class GEG2)
HEY !!!!!! GfG I am initialised(Class GEG1)
Printing from class GFG3: 10
Printing from class GFG2: 11
Printing from class GFG1: 12
python-oop-concepts
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n23 Jan, 2020"
},
{
"code": null,
"e": 302,
"s": 53,
"text": "A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made."
},
{
"code": null,
"e": 311,
"s": 302,
"text": "Example:"
},
{
"code": "# Python program to demonstrate# classes class cls: # Constructor def __init__(self, fname, mname, lname): self.firstname = fname self.middlename = mname self.lastname = lname # class Function def print(self): print(self.firstname, self.middlename, self.lastname) # Use the Parent class to create an object# and then execute the print method:x = cls(\"Geeks\", \"for\", \"Geeks\")x.print()",
"e": 751,
"s": 311,
"text": null
},
{
"code": null,
"e": 759,
"s": 751,
"text": "Output:"
},
{
"code": null,
"e": 776,
"s": 759,
"text": "Geeks for Geeks\n"
},
{
"code": null,
"e": 1072,
"s": 776,
"text": "To understand about the concept of parent class, you have to know about Inheritance in Python. In simpler terms, inheritance is the concept by which one class (commonly known as child class or sub class) inherits the properties from another class (commonly known as Parent class or super class)."
},
{
"code": null,
"e": 1340,
"s": 1072,
"text": "But have you ever wondered about calling the functions defined inside the parent class with the help of child class? Well this can done using Python. You just have to create an object of the child class and call the function of the parent class using dot(.) operator."
},
{
"code": null,
"e": 1349,
"s": 1340,
"text": "Example:"
},
{
"code": "# Python code to demonstrate # parent call method class Parent: # create a parent class method def show(self): print(\"Inside Parent class\") # create a child classclass Child(Parent): # Create a child class method def display(self): print(\"Inside Child class\") # Driver's codeobj = Child()obj.display() # Calling Parent classobj.show()",
"e": 1723,
"s": 1349,
"text": null
},
{
"code": null,
"e": 1730,
"s": 1723,
"text": "Output"
},
{
"code": null,
"e": 1770,
"s": 1730,
"text": "Inside Child class\nInside Parent class\n"
},
{
"code": null,
"e": 2005,
"s": 1770,
"text": "Method overriding is an ability of any object-oriented programming language that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes."
},
{
"code": null,
"e": 2120,
"s": 2005,
"text": "Parent class methods can also be called within the overridden methods. This can generally be achieved by two ways."
},
{
"code": null,
"e": 2672,
"s": 2120,
"text": "Using Classname: Parent’s class methods can be called by using the Parent classname.method inside the overridden method.Example:# Python program to demonstrate# calling the parent's class method# inside the overridden method class Parent(): def show(self): print(\"Inside Parent\") class Child(Parent): def show(self): # Calling the parent's class # method Parent.show(self) print(\"Inside Child\") # Driver's codeobj = Child()obj.show()Output:Inside Parent\nInside Child\n"
},
{
"code": null,
"e": 2681,
"s": 2672,
"text": "Example:"
},
{
"code": "# Python program to demonstrate# calling the parent's class method# inside the overridden method class Parent(): def show(self): print(\"Inside Parent\") class Child(Parent): def show(self): # Calling the parent's class # method Parent.show(self) print(\"Inside Child\") # Driver's codeobj = Child()obj.show()",
"e": 3071,
"s": 2681,
"text": null
},
{
"code": null,
"e": 3079,
"s": 3071,
"text": "Output:"
},
{
"code": null,
"e": 3107,
"s": 3079,
"text": "Inside Parent\nInside Child\n"
},
{
"code": null,
"e": 5068,
"s": 3107,
"text": "Using Super(): Python super() function provides us the facility to refer to the parent class explicitly. It is basically useful where we have to call superclass functions. It returns the proxy object that allows us to refer parent class by ‘super’.Example 1:# Python program to demonstrate# calling the parent's class method# inside the overridden method using# super() class Parent(): def show(self): print(\"Inside Parent\") class Child(Parent): def show(self): # Calling the parent's class # method super().show() print(\"Inside Child\") # Driver's codeobj = Child()obj.show()Output:Inside Parent\nInside Child\nExample 2:# Program to define the use of super() # function in multiple inheritance class GFG1: def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG1)') def sub_GFG(self, b): print('Printing from class GFG1:', b) # class GFG2 inherits the GFG1 class GFG2(GFG1): def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG2)') super().__init__() def sub_GFG(self, b): print('Printing from class GFG2:', b) super().sub_GFG(b + 1) # class GFG3 inherits the GFG1 ang GFG2 both class GFG3(GFG2): def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG3)') super().__init__() def sub_GFG(self, b): print('Printing from class GFG3:', b) super().sub_GFG(b + 1) # main function if __name__ == '__main__': # created the object gfg gfg = GFG3() # calling the function sub_GFG3() from class GHG3 # which inherits both GFG1 and GFG2 classes gfg.sub_GFG(10)Output:HEY !!!!!! GfG I am initialised(Class GEG3)\nHEY !!!!!! GfG I am initialised(Class GEG2)\nHEY !!!!!! GfG I am initialised(Class GEG1)\nPrinting from class GFG3: 10\nPrinting from class GFG2: 11\nPrinting from class GFG1: 12\n"
},
{
"code": null,
"e": 5079,
"s": 5068,
"text": "Example 1:"
},
{
"code": "# Python program to demonstrate# calling the parent's class method# inside the overridden method using# super() class Parent(): def show(self): print(\"Inside Parent\") class Child(Parent): def show(self): # Calling the parent's class # method super().show() print(\"Inside Child\") # Driver's codeobj = Child()obj.show()",
"e": 5481,
"s": 5079,
"text": null
},
{
"code": null,
"e": 5489,
"s": 5481,
"text": "Output:"
},
{
"code": null,
"e": 5517,
"s": 5489,
"text": "Inside Parent\nInside Child\n"
},
{
"code": null,
"e": 5528,
"s": 5517,
"text": "Example 2:"
},
{
"code": "# Program to define the use of super() # function in multiple inheritance class GFG1: def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG1)') def sub_GFG(self, b): print('Printing from class GFG1:', b) # class GFG2 inherits the GFG1 class GFG2(GFG1): def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG2)') super().__init__() def sub_GFG(self, b): print('Printing from class GFG2:', b) super().sub_GFG(b + 1) # class GFG3 inherits the GFG1 ang GFG2 both class GFG3(GFG2): def __init__(self): print('HEY !!!!!! GfG I am initialised(Class GEG3)') super().__init__() def sub_GFG(self, b): print('Printing from class GFG3:', b) super().sub_GFG(b + 1) # main function if __name__ == '__main__': # created the object gfg gfg = GFG3() # calling the function sub_GFG3() from class GHG3 # which inherits both GFG1 and GFG2 classes gfg.sub_GFG(10)",
"e": 6560,
"s": 5528,
"text": null
},
{
"code": null,
"e": 6568,
"s": 6560,
"text": "Output:"
},
{
"code": null,
"e": 6788,
"s": 6568,
"text": "HEY !!!!!! GfG I am initialised(Class GEG3)\nHEY !!!!!! GfG I am initialised(Class GEG2)\nHEY !!!!!! GfG I am initialised(Class GEG1)\nPrinting from class GFG3: 10\nPrinting from class GFG2: 11\nPrinting from class GFG1: 12\n"
},
{
"code": null,
"e": 6808,
"s": 6788,
"text": "python-oop-concepts"
},
{
"code": null,
"e": 6815,
"s": 6808,
"text": "Python"
},
{
"code": null,
"e": 6913,
"s": 6815,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6931,
"s": 6913,
"text": "Python Dictionary"
},
{
"code": null,
"e": 6973,
"s": 6931,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 6995,
"s": 6973,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 7030,
"s": 6995,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 7056,
"s": 7030,
"text": "Python String | replace()"
},
{
"code": null,
"e": 7088,
"s": 7056,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 7117,
"s": 7088,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 7144,
"s": 7117,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 7165,
"s": 7144,
"text": "Python OOPs Concepts"
}
] |
Short-circuit evaluation in Programming
|
22 Jun, 2021
Short-Circuit Evaluation: Short-circuiting is a programming concept by which the compiler skips the execution or evaluation of some sub-expressions in a logical expression. The compiler stops evaluating the further sub-expressions as soon as the value of the expression is determined. Below is an example of the same:
C++
if (a == b || c == d || e == f) { // do_something}
Explanation: In the above expression, If the expression a == b is true, then c == d and e == f are never evaluated at all because the expression’s result has already been determined. Similarly, if the logical AND (&&) operator instead of logical OR (||) and the expression a == b is false, the compiler will skip evaluating other sub-expressions.
Example 1:
C++
// C program to illustrate the concept// of short circuiting#include <stdio.h> // Driver Codeint main(){ int x = 1; if (x || ++x) { printf("%d", x); } return 0;}
1
Explanation: In the above C program, inside the if statement, the value of the first sub-expression i.e., x is 1(which means true in boolean), so the value of the second sub-expression does not affect the value of the expression and hence the compiler skips checking it. So the value of x is not incremented.
Example 2:
C
// C program to illustrate the concept// of short circuiting#include <stdio.h> // Driver Codeint main(){ int a = 10; int b = -1; // Here b == -1 is not evaluated as // a != 10 is false if (a != 10 && b == -1) { printf("I won't be printed!\n"); } else { printf("Hello, else block is printed"); } return 0;}
Hello, else block is printed
Explanation: The above program prints the output of the else block because the first condition is false which is sufficient to determine the expression’s value, so the second condition is not evaluated.
Example 3: Below is the C program to calculate the square root to demonstrate the concept of short-circuit evaluation:
C
// C program to illustrate the concept// of short circuiting#include <math.h>#include <stdio.h> // Function to calculate the square rootint calculate_sqrt(int i){ printf("Sqrt of %d: %.2f\n", i, sqrt(i)); return i;} // Driver Codeint main(){ int a = 15; // Here since a is 10, calculate_sqrt // function will be called if (a >= 10 && calculate_sqrt(a)) { printf("I will be printed!\n"); } return 0;}
Sqrt of 15: 3.87
I will be printed!
Explanation: In the above program if the number is less than 10 then the square root is not performed. Due to this the error are getting avoided for the negative number as well.
Applications: The concept of short-circuiting can be helpful in many scenarios. Some of them are listed below:
Avoiding unexpected behavior: It can be used to avoid unexpected behavior due to the second argument. For Example: consider the below code snippet:
C
// C program to illustrate the concept// of short circuiting#include <stdio.h> // Driver Codeint main(){ float nr = 5, dr = 0; dr&& printf("a/b = %.2f", nr / dr);}
Explanation: As the expression (nr/dr) gives runtime errors but due to adding the expression dr && with the operation, the error avoided as the value of dr is 0 which excludes the computation of (nr/dr).
Avoiding Expensive Computation: It can be helpful in avoiding expensive computations which are required to be executed only under specific conditions. Below is the code snippet to illustrate the same:
C
int a = 0; // myfunc(b) will not be calledif (a != 0 && myfunc(b)) { // do_something();}
Examples: In the above example, if it is required to do an expensive operation using the myfunc() for the value 0, then the expensive operation for the non-zero values can be avoided by using this concept. This can also be used in file handling to avoid the expensive task of getting a file ready every time if the file is already in a ready state as
isFileReady() || getFileReady()
Advantages Of Short-Circuit Evaluation:
It can be helpful in avoiding computationally expensive tasks under certain circumstances.
It provides a check for the first argument without which the second argument may result in a runtime error.
Disadvantages Of Short-Circuit Evaluation:
It can cause unexpected behavior if not used properly. For any function in the code snippet that does some kind of allocation of system resources/memory allocation, we may get unexpected behavior.
Code execution becomes less efficient with short-circuited execution paths because in some compilers the new checks for short-circuits are extra execution cycles in themselves.
C Basics
C Language
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
Operators in C / C++
Exception Handling in C++
What is the purpose of a function prototype?
TCP Server-Client implementation in C
Strings in C
Arrow operator -> in C/C++ with Examples
Basics of File Handling in C
Header files in C/C++ and its uses
UDP Server-Client implementation in C
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 370,
"s": 52,
"text": "Short-Circuit Evaluation: Short-circuiting is a programming concept by which the compiler skips the execution or evaluation of some sub-expressions in a logical expression. The compiler stops evaluating the further sub-expressions as soon as the value of the expression is determined. Below is an example of the same:"
},
{
"code": null,
"e": 374,
"s": 370,
"text": "C++"
},
{
"code": "if (a == b || c == d || e == f) { // do_something}",
"e": 428,
"s": 374,
"text": null
},
{
"code": null,
"e": 775,
"s": 428,
"text": "Explanation: In the above expression, If the expression a == b is true, then c == d and e == f are never evaluated at all because the expression’s result has already been determined. Similarly, if the logical AND (&&) operator instead of logical OR (||) and the expression a == b is false, the compiler will skip evaluating other sub-expressions."
},
{
"code": null,
"e": 786,
"s": 775,
"text": "Example 1:"
},
{
"code": null,
"e": 790,
"s": 786,
"text": "C++"
},
{
"code": "// C program to illustrate the concept// of short circuiting#include <stdio.h> // Driver Codeint main(){ int x = 1; if (x || ++x) { printf(\"%d\", x); } return 0;}",
"e": 976,
"s": 790,
"text": null
},
{
"code": null,
"e": 978,
"s": 976,
"text": "1"
},
{
"code": null,
"e": 1287,
"s": 978,
"text": "Explanation: In the above C program, inside the if statement, the value of the first sub-expression i.e., x is 1(which means true in boolean), so the value of the second sub-expression does not affect the value of the expression and hence the compiler skips checking it. So the value of x is not incremented."
},
{
"code": null,
"e": 1298,
"s": 1287,
"text": "Example 2:"
},
{
"code": null,
"e": 1300,
"s": 1298,
"text": "C"
},
{
"code": "// C program to illustrate the concept// of short circuiting#include <stdio.h> // Driver Codeint main(){ int a = 10; int b = -1; // Here b == -1 is not evaluated as // a != 10 is false if (a != 10 && b == -1) { printf(\"I won't be printed!\\n\"); } else { printf(\"Hello, else block is printed\"); } return 0;}",
"e": 1652,
"s": 1300,
"text": null
},
{
"code": null,
"e": 1681,
"s": 1652,
"text": "Hello, else block is printed"
},
{
"code": null,
"e": 1884,
"s": 1681,
"text": "Explanation: The above program prints the output of the else block because the first condition is false which is sufficient to determine the expression’s value, so the second condition is not evaluated."
},
{
"code": null,
"e": 2003,
"s": 1884,
"text": "Example 3: Below is the C program to calculate the square root to demonstrate the concept of short-circuit evaluation:"
},
{
"code": null,
"e": 2005,
"s": 2003,
"text": "C"
},
{
"code": "// C program to illustrate the concept// of short circuiting#include <math.h>#include <stdio.h> // Function to calculate the square rootint calculate_sqrt(int i){ printf(\"Sqrt of %d: %.2f\\n\", i, sqrt(i)); return i;} // Driver Codeint main(){ int a = 15; // Here since a is 10, calculate_sqrt // function will be called if (a >= 10 && calculate_sqrt(a)) { printf(\"I will be printed!\\n\"); } return 0;}",
"e": 2455,
"s": 2005,
"text": null
},
{
"code": null,
"e": 2491,
"s": 2455,
"text": "Sqrt of 15: 3.87\nI will be printed!"
},
{
"code": null,
"e": 2669,
"s": 2491,
"text": "Explanation: In the above program if the number is less than 10 then the square root is not performed. Due to this the error are getting avoided for the negative number as well."
},
{
"code": null,
"e": 2780,
"s": 2669,
"text": "Applications: The concept of short-circuiting can be helpful in many scenarios. Some of them are listed below:"
},
{
"code": null,
"e": 2928,
"s": 2780,
"text": "Avoiding unexpected behavior: It can be used to avoid unexpected behavior due to the second argument. For Example: consider the below code snippet:"
},
{
"code": null,
"e": 2930,
"s": 2928,
"text": "C"
},
{
"code": "// C program to illustrate the concept// of short circuiting#include <stdio.h> // Driver Codeint main(){ float nr = 5, dr = 0; dr&& printf(\"a/b = %.2f\", nr / dr);}",
"e": 3101,
"s": 2930,
"text": null
},
{
"code": null,
"e": 3307,
"s": 3103,
"text": "Explanation: As the expression (nr/dr) gives runtime errors but due to adding the expression dr && with the operation, the error avoided as the value of dr is 0 which excludes the computation of (nr/dr)."
},
{
"code": null,
"e": 3508,
"s": 3307,
"text": "Avoiding Expensive Computation: It can be helpful in avoiding expensive computations which are required to be executed only under specific conditions. Below is the code snippet to illustrate the same:"
},
{
"code": null,
"e": 3510,
"s": 3508,
"text": "C"
},
{
"code": "int a = 0; // myfunc(b) will not be calledif (a != 0 && myfunc(b)) { // do_something();}",
"e": 3603,
"s": 3510,
"text": null
},
{
"code": null,
"e": 3954,
"s": 3603,
"text": "Examples: In the above example, if it is required to do an expensive operation using the myfunc() for the value 0, then the expensive operation for the non-zero values can be avoided by using this concept. This can also be used in file handling to avoid the expensive task of getting a file ready every time if the file is already in a ready state as"
},
{
"code": null,
"e": 3987,
"s": 3954,
"text": "isFileReady() || getFileReady() "
},
{
"code": null,
"e": 4027,
"s": 3987,
"text": "Advantages Of Short-Circuit Evaluation:"
},
{
"code": null,
"e": 4118,
"s": 4027,
"text": "It can be helpful in avoiding computationally expensive tasks under certain circumstances."
},
{
"code": null,
"e": 4226,
"s": 4118,
"text": "It provides a check for the first argument without which the second argument may result in a runtime error."
},
{
"code": null,
"e": 4269,
"s": 4226,
"text": "Disadvantages Of Short-Circuit Evaluation:"
},
{
"code": null,
"e": 4466,
"s": 4269,
"text": "It can cause unexpected behavior if not used properly. For any function in the code snippet that does some kind of allocation of system resources/memory allocation, we may get unexpected behavior."
},
{
"code": null,
"e": 4643,
"s": 4466,
"text": "Code execution becomes less efficient with short-circuited execution paths because in some compilers the new checks for short-circuits are extra execution cycles in themselves."
},
{
"code": null,
"e": 4652,
"s": 4643,
"text": "C Basics"
},
{
"code": null,
"e": 4663,
"s": 4652,
"text": "C Language"
},
{
"code": null,
"e": 4674,
"s": 4663,
"text": "C Programs"
},
{
"code": null,
"e": 4772,
"s": 4674,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4820,
"s": 4772,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 4841,
"s": 4820,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 4867,
"s": 4841,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 4912,
"s": 4867,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 4950,
"s": 4912,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 4963,
"s": 4950,
"text": "Strings in C"
},
{
"code": null,
"e": 5004,
"s": 4963,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 5033,
"s": 5004,
"text": "Basics of File Handling in C"
},
{
"code": null,
"e": 5068,
"s": 5033,
"text": "Header files in C/C++ and its uses"
}
] |
numpy.ceil() in Python
|
04 Dec, 2020
The numpy.ceil() is a mathematical function that returns the ceil of the elements of array. The ceil of the scalar x is the smallest integer i, such that i >= x
Syntax : numpy.ceil(x[, out]) = ufunc ‘ceil’)Parameters :a : [array_like] Input array
Return : The ceil of each element with float data-type.
Code #1 : Working
# Python program explaining# ceil() functionimport numpy as np in_array = [.5, 1.5, 2.5, 3.5, 4.5, 10.1]print ("Input array : \n", in_array) ceiloff_values = np.ceil(in_array)print ("\nRounded values : \n", ceiloff_values) in_array = [.53, 1.54, .71]print ("\nInput array : \n", in_array) ceiloff_values = np.ceil(in_array)print ("\nRounded values : \n", ceiloff_values) in_array = [.5538, 1.33354, .71445]print ("\nInput array : \n", in_array) ceiloff_values = np.ceil(in_array)print ("\nRounded values : \n", ceiloff_values)
Output :
Input array :
[0.5, 1.5, 2.5, 3.5, 4.5, 10.1]
Rounded values :
[ 1. 2. 3. 4. 5. 11.]
Input array :
[0.53, 1.54, 0.71]
Rounded values :
[ 1. 2. 1.]
Input array :
[0.5538, 1.33354, 0.71445]
Rounded values :
[ 1. 2. 1.]
Code #2 : Working
# Python program explaining# ceil() functionimport numpy as np in_array = [1.67, 4.5, 7, 9, 12]print ("Input array : \n", in_array) ceiloff_values = np.ceil(in_array)print ("\nRounded values : \n", ceiloff_values) in_array = [133.000, 344.54, 437.56, 44.9, 1.2]print ("\nInput array : \n", in_array) ceiloff_values = np.ceil(in_array)print ("\nRounded values upto 2: \n", ceiloff_values)
Output :
Input array :
[1.67, 4.5, 7, 9, 12]
Rounded values :
[ 2. 5. 7. 9. 12.]
Input array :
[133.0, 344.54, 437.56, 44.9, 1.2]
Rounded values upto 2:
[ 133. 345. 438. 45. 2.]
References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.ceil.html#numpy.ceil.
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n04 Dec, 2020"
},
{
"code": null,
"e": 214,
"s": 53,
"text": "The numpy.ceil() is a mathematical function that returns the ceil of the elements of array. The ceil of the scalar x is the smallest integer i, such that i >= x"
},
{
"code": null,
"e": 300,
"s": 214,
"text": "Syntax : numpy.ceil(x[, out]) = ufunc ‘ceil’)Parameters :a : [array_like] Input array"
},
{
"code": null,
"e": 356,
"s": 300,
"text": "Return : The ceil of each element with float data-type."
},
{
"code": null,
"e": 375,
"s": 356,
"text": " Code #1 : Working"
},
{
"code": "# Python program explaining# ceil() functionimport numpy as np in_array = [.5, 1.5, 2.5, 3.5, 4.5, 10.1]print (\"Input array : \\n\", in_array) ceiloff_values = np.ceil(in_array)print (\"\\nRounded values : \\n\", ceiloff_values) in_array = [.53, 1.54, .71]print (\"\\nInput array : \\n\", in_array) ceiloff_values = np.ceil(in_array)print (\"\\nRounded values : \\n\", ceiloff_values) in_array = [.5538, 1.33354, .71445]print (\"\\nInput array : \\n\", in_array) ceiloff_values = np.ceil(in_array)print (\"\\nRounded values : \\n\", ceiloff_values)",
"e": 910,
"s": 375,
"text": null
},
{
"code": null,
"e": 919,
"s": 910,
"text": "Output :"
},
{
"code": null,
"e": 1168,
"s": 919,
"text": "Input array : \n [0.5, 1.5, 2.5, 3.5, 4.5, 10.1]\n\nRounded values : \n [ 1. 2. 3. 4. 5. 11.]\n\nInput array : \n [0.53, 1.54, 0.71]\n\nRounded values : \n [ 1. 2. 1.]\n\nInput array : \n [0.5538, 1.33354, 0.71445]\n\nRounded values : \n [ 1. 2. 1.]\n"
},
{
"code": null,
"e": 1188,
"s": 1170,
"text": "Code #2 : Working"
},
{
"code": "# Python program explaining# ceil() functionimport numpy as np in_array = [1.67, 4.5, 7, 9, 12]print (\"Input array : \\n\", in_array) ceiloff_values = np.ceil(in_array)print (\"\\nRounded values : \\n\", ceiloff_values) in_array = [133.000, 344.54, 437.56, 44.9, 1.2]print (\"\\nInput array : \\n\", in_array) ceiloff_values = np.ceil(in_array)print (\"\\nRounded values upto 2: \\n\", ceiloff_values)",
"e": 1582,
"s": 1188,
"text": null
},
{
"code": null,
"e": 1591,
"s": 1582,
"text": "Output :"
},
{
"code": null,
"e": 1786,
"s": 1591,
"text": "Input array : \n [1.67, 4.5, 7, 9, 12]\n\nRounded values : \n [ 2. 5. 7. 9. 12.]\n\nInput array : \n [133.0, 344.54, 437.56, 44.9, 1.2]\n\nRounded values upto 2: \n [ 133. 345. 438. 45. 2.]"
},
{
"code": null,
"e": 1885,
"s": 1786,
"text": " References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.ceil.html#numpy.ceil."
},
{
"code": null,
"e": 1920,
"s": 1885,
"text": "Python numpy-Mathematical Function"
},
{
"code": null,
"e": 1933,
"s": 1920,
"text": "Python-numpy"
},
{
"code": null,
"e": 1940,
"s": 1933,
"text": "Python"
}
] |
DATEDIFF() Function in MySQL
|
25 Nov, 2020
DATEDIFF() function in MySQL is used to return the number of days between two specified date values.
Syntax:
DATEDIFF(date1, date2)
Parameter: This function accepts two parameters as given below:
date1: First specified date
date2: Second specified date
Returns :
It returns the number of days between two specified date values.
Example 1 :
Getting the number of days between two specified date values where the date is specified in the format of YYYY-MM-DD. Here the date1 is greater than date2, so the return value is positive.
SELECT DATEDIFF("2020-11-20", "2020-11-1");
Output :
19
Example 2:
Getting the number of days between two specified date values where the date is specified in the format of YYYY-MM-DD. Here the date1 is less than date2, so the return value is negative.
SELECT DATEDIFF("2020-11-12", "2020-11-19");
Output:
-7
Example 3:
Getting the number of days between two specified date values where the date is specified in the format of YYYY-MM-DD HH-MM-SS.
SELECT DATEDIFF("2020-11-20 09:34:21", "2020-11-17 09:34:21");
Output:
3
Example 4:
Getting the number of days between two specified date values where the date is specified in the format of YYYY-MM-DD HH-MM-SS. Here time value does not matter as date1 and date2 are taken the same but time is different still the output is zero (0).
SELECT DATEDIFF("2020-11-20 09:34:21", "2020-11-20 08:11:23");
Output:
0
mysql
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 Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Window functions in SQL
MySQL | Group_CONCAT() Function
SQL | GROUP BY
Difference between DDL and DML in DBMS
Difference between DELETE and TRUNCATE
SQL Correlated Subqueries
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Nov, 2020"
},
{
"code": null,
"e": 130,
"s": 28,
"text": "DATEDIFF() function in MySQL is used to return the number of days between two specified date values. "
},
{
"code": null,
"e": 138,
"s": 130,
"text": "Syntax:"
},
{
"code": null,
"e": 163,
"s": 138,
"text": "DATEDIFF(date1, date2)\n\n"
},
{
"code": null,
"e": 227,
"s": 163,
"text": "Parameter: This function accepts two parameters as given below:"
},
{
"code": null,
"e": 255,
"s": 227,
"text": "date1: First specified date"
},
{
"code": null,
"e": 284,
"s": 255,
"text": "date2: Second specified date"
},
{
"code": null,
"e": 294,
"s": 284,
"text": "Returns :"
},
{
"code": null,
"e": 359,
"s": 294,
"text": "It returns the number of days between two specified date values."
},
{
"code": null,
"e": 371,
"s": 359,
"text": "Example 1 :"
},
{
"code": null,
"e": 560,
"s": 371,
"text": "Getting the number of days between two specified date values where the date is specified in the format of YYYY-MM-DD. Here the date1 is greater than date2, so the return value is positive."
},
{
"code": null,
"e": 608,
"s": 560,
"text": "SELECT DATEDIFF(\"2020-11-20\", \"2020-11-1\"); \n\n"
},
{
"code": null,
"e": 617,
"s": 608,
"text": "Output :"
},
{
"code": null,
"e": 622,
"s": 617,
"text": "19\n\n"
},
{
"code": null,
"e": 633,
"s": 622,
"text": "Example 2:"
},
{
"code": null,
"e": 819,
"s": 633,
"text": "Getting the number of days between two specified date values where the date is specified in the format of YYYY-MM-DD. Here the date1 is less than date2, so the return value is negative."
},
{
"code": null,
"e": 868,
"s": 819,
"text": "SELECT DATEDIFF(\"2020-11-12\", \"2020-11-19\"); \n\n"
},
{
"code": null,
"e": 876,
"s": 868,
"text": "Output:"
},
{
"code": null,
"e": 881,
"s": 876,
"text": "-7\n\n"
},
{
"code": null,
"e": 892,
"s": 881,
"text": "Example 3:"
},
{
"code": null,
"e": 1020,
"s": 892,
"text": "Getting the number of days between two specified date values where the date is specified in the format of YYYY-MM-DD HH-MM-SS. "
},
{
"code": null,
"e": 1087,
"s": 1020,
"text": "SELECT DATEDIFF(\"2020-11-20 09:34:21\", \"2020-11-17 09:34:21\"); \n\n"
},
{
"code": null,
"e": 1095,
"s": 1087,
"text": "Output:"
},
{
"code": null,
"e": 1099,
"s": 1095,
"text": "3\n\n"
},
{
"code": null,
"e": 1110,
"s": 1099,
"text": "Example 4:"
},
{
"code": null,
"e": 1359,
"s": 1110,
"text": "Getting the number of days between two specified date values where the date is specified in the format of YYYY-MM-DD HH-MM-SS. Here time value does not matter as date1 and date2 are taken the same but time is different still the output is zero (0)."
},
{
"code": null,
"e": 1426,
"s": 1359,
"text": "SELECT DATEDIFF(\"2020-11-20 09:34:21\", \"2020-11-20 08:11:23\"); \n\n"
},
{
"code": null,
"e": 1434,
"s": 1426,
"text": "Output:"
},
{
"code": null,
"e": 1438,
"s": 1434,
"text": "0\n\n"
},
{
"code": null,
"e": 1444,
"s": 1438,
"text": "mysql"
},
{
"code": null,
"e": 1448,
"s": 1444,
"text": "SQL"
},
{
"code": null,
"e": 1452,
"s": 1448,
"text": "SQL"
},
{
"code": null,
"e": 1550,
"s": 1452,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1616,
"s": 1550,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 1640,
"s": 1616,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 1652,
"s": 1640,
"text": "SQL | Views"
},
{
"code": null,
"e": 1697,
"s": 1652,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 1721,
"s": 1697,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 1753,
"s": 1721,
"text": "MySQL | Group_CONCAT() Function"
},
{
"code": null,
"e": 1768,
"s": 1753,
"text": "SQL | GROUP BY"
},
{
"code": null,
"e": 1807,
"s": 1768,
"text": "Difference between DDL and DML in DBMS"
},
{
"code": null,
"e": 1846,
"s": 1807,
"text": "Difference between DELETE and TRUNCATE"
}
] |
Find first set bit | Practice | GeeksforGeeks
|
Given an integer an N. The task is to return the position of first set bit found from the right side in the binary representation of the number.
Note: If there is no set bit in the integer N, then return 0 from the function.
Example 1:
Input: N = 18
Output: 2
Explanation: Binary representation of
18 is 010010,the first set bit from the
right side is at position 2.
Example 2:
Input: N = 12
Output: 3
Explanation: Binary representation
of 12 is 1100, the first set bit
from the right side is at position 3.
Your Task:
The task is to complete the function getFirstSetBit() that takes an integer n as a parameter and returns the position of first set bit.
Expected Time Complexity: O(log N).
Expected Auxiliary Space: O(1).
Constraints:
0 <= N <= 108
+1
proudtobe72719 hours ago
unsigned int getFirstSetBit(int n)
{
unsigned int c=0;
while(n)
{
++c;
if(n%2==1) break;
n=n/2;
}
return c;
}
0
kiran1931 day ago
unsigned int getFirstSetBit(int n) { for(int i=0;i<=log2(n);i++) if((1<<i)&n)return i+1; return 0; }
0
kailashkolluru6 days ago
unsigned int getFirstSetBit(int n)
{
// Your code here
if(n%2 == 1) return 1;
if(n ==0) return 0;
int pos=0;
while(n%2 == 0){
n >>= 1;
pos +=1;
}
pos +=1;
return pos;
}
0
rahuljamui70841 week ago
unsigned int getFirstSetBit(int n){
return log2(n&-n)+1;
}
0
kaalthesuraj1 week ago
Easy 3 lines :
unsigned int getFirstSetBit(int n)
{
bitset<32> bits(n);
for(int i=0;i<32;i++) if(bits[i]==1) return i+1;
return 0;
}
0
amandeep278031 week ago
class Solution
{
public:
//Function to find position of first set bit in the given number.
unsigned int getFirstSetBit(int n)
{
if(n==0)
return 0;
unsigned int setbit = 0;
for(unsigned int i=0;i<32;i++)
{
unsigned int mask = 1<<i;
if((mask&n)!=0)
{
setbit = i;
break;
}
}
return setbit+1;
}
};
0
ss7181 week ago
class Solution
{
//Function to find position of first set bit in the given number.
public static int getFirstSetBit(int n){
// Your code here
if (n == 0) {
return 0;
}
// n - 1 has the rightmost set bit reversed and the //0's after it converted to 1.
int p = n & (~(n - 1));
int pow = (int)(Math.log(p)/ Math.log(2)) + 1;
return pow;
}
}
0
arobindosuklabaidya1 week ago
Simple C++ Solution
unsigned int getFirstSetBit(int n) { int pos=0; if(n==0){ return 0; } for(int i=0;i<32;i++){ if((n&(1<<i))!=0){ pos=i; break; } } return pos+1; }
0
manmittiwade1241 week ago
class Solution{ public: //Function to find position of first set bit in the given number. unsigned int getFirstSetBit(int n) { return ffs(n); } // //Your code here };
0
pranavkumar123842 weeks ago
// java solution//User function Template for Java
class Solution{ //Function to find position of first set bit in the given number. public static int getFirstSetBit(int n){ // Your code here if(n==0) return 0; int pos=0; while(n>0 &&(n&1)==0){ n=n>>1; pos++; } return ++pos; }}
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": 465,
"s": 238,
"text": "Given an integer an N. The task is to return the position of first set bit found from the right side in the binary representation of the number.\nNote: If there is no set bit in the integer N, then return 0 from the function. "
},
{
"code": null,
"e": 476,
"s": 465,
"text": "Example 1:"
},
{
"code": null,
"e": 609,
"s": 476,
"text": "Input: N = 18\nOutput: 2\nExplanation: Binary representation of \n18 is 010010,the first set bit from the \nright side is at position 2."
},
{
"code": null,
"e": 620,
"s": 609,
"text": "Example 2:"
},
{
"code": null,
"e": 755,
"s": 620,
"text": "Input: N = 12 \nOutput: 3 \nExplanation: Binary representation \nof 12 is 1100, the first set bit \nfrom the right side is at position 3."
},
{
"code": null,
"e": 902,
"s": 755,
"text": "Your Task:\nThe task is to complete the function getFirstSetBit() that takes an integer n as a parameter and returns the position of first set bit."
},
{
"code": null,
"e": 970,
"s": 902,
"text": "Expected Time Complexity: O(log N).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 997,
"s": 970,
"text": "Constraints:\n0 <= N <= 108"
},
{
"code": null,
"e": 1000,
"s": 997,
"text": "+1"
},
{
"code": null,
"e": 1025,
"s": 1000,
"text": "proudtobe72719 hours ago"
},
{
"code": null,
"e": 1209,
"s": 1025,
"text": "unsigned int getFirstSetBit(int n)\n {\n unsigned int c=0;\n while(n)\n {\n ++c;\n if(n%2==1)\tbreak;\n n=n/2;\n }\n return c;\n }"
},
{
"code": null,
"e": 1211,
"s": 1209,
"text": "0"
},
{
"code": null,
"e": 1229,
"s": 1211,
"text": "kiran1931 day ago"
},
{
"code": null,
"e": 1356,
"s": 1229,
"text": "unsigned int getFirstSetBit(int n) { for(int i=0;i<=log2(n);i++) if((1<<i)&n)return i+1; return 0; }"
},
{
"code": null,
"e": 1358,
"s": 1356,
"text": "0"
},
{
"code": null,
"e": 1383,
"s": 1358,
"text": "kailashkolluru6 days ago"
},
{
"code": null,
"e": 1652,
"s": 1383,
"text": " unsigned int getFirstSetBit(int n)\n {\n // Your code here\n if(n%2 == 1) return 1;\n if(n ==0) return 0;\n int pos=0;\n while(n%2 == 0){\n n >>= 1;\n pos +=1;\n }\n pos +=1;\n return pos;\n }"
},
{
"code": null,
"e": 1654,
"s": 1652,
"text": "0"
},
{
"code": null,
"e": 1679,
"s": 1654,
"text": "rahuljamui70841 week ago"
},
{
"code": null,
"e": 1751,
"s": 1679,
"text": " unsigned int getFirstSetBit(int n){\n return log2(n&-n)+1;\n }"
},
{
"code": null,
"e": 1753,
"s": 1751,
"text": "0"
},
{
"code": null,
"e": 1776,
"s": 1753,
"text": "kaalthesuraj1 week ago"
},
{
"code": null,
"e": 1792,
"s": 1776,
"text": "Easy 3 lines : "
},
{
"code": null,
"e": 1948,
"s": 1792,
"text": " unsigned int getFirstSetBit(int n)\n {\n bitset<32> bits(n);\n for(int i=0;i<32;i++) if(bits[i]==1) return i+1;\n return 0;\n }"
},
{
"code": null,
"e": 1950,
"s": 1948,
"text": "0"
},
{
"code": null,
"e": 1974,
"s": 1950,
"text": "amandeep278031 week ago"
},
{
"code": null,
"e": 2428,
"s": 1974,
"text": "class Solution\n{\n public:\n //Function to find position of first set bit in the given number.\n unsigned int getFirstSetBit(int n)\n {\n if(n==0)\n return 0;\n unsigned int setbit = 0;\n for(unsigned int i=0;i<32;i++)\n {\n unsigned int mask = 1<<i;\n if((mask&n)!=0)\n {\n setbit = i;\n break;\n }\n }\n return setbit+1;\n }\n};"
},
{
"code": null,
"e": 2430,
"s": 2428,
"text": "0"
},
{
"code": null,
"e": 2446,
"s": 2430,
"text": "ss7181 week ago"
},
{
"code": null,
"e": 2893,
"s": 2446,
"text": "class Solution\n{\n //Function to find position of first set bit in the given number.\n public static int getFirstSetBit(int n){\n \n // Your code here\n if (n == 0) {\n return 0;\n }\n // n - 1 has the rightmost set bit reversed and the //0's after it converted to 1.\n int p = n & (~(n - 1));\n int pow = (int)(Math.log(p)/ Math.log(2)) + 1;\n return pow;\n \n }\n}"
},
{
"code": null,
"e": 2895,
"s": 2893,
"text": "0"
},
{
"code": null,
"e": 2925,
"s": 2895,
"text": "arobindosuklabaidya1 week ago"
},
{
"code": null,
"e": 2945,
"s": 2925,
"text": "Simple C++ Solution"
},
{
"code": null,
"e": 3192,
"s": 2945,
"text": " unsigned int getFirstSetBit(int n) { int pos=0; if(n==0){ return 0; } for(int i=0;i<32;i++){ if((n&(1<<i))!=0){ pos=i; break; } } return pos+1; }"
},
{
"code": null,
"e": 3194,
"s": 3192,
"text": "0"
},
{
"code": null,
"e": 3220,
"s": 3194,
"text": "manmittiwade1241 week ago"
},
{
"code": null,
"e": 3438,
"s": 3220,
"text": "class Solution{ public: //Function to find position of first set bit in the given number. unsigned int getFirstSetBit(int n) { return ffs(n); } // //Your code here };"
},
{
"code": null,
"e": 3440,
"s": 3438,
"text": "0"
},
{
"code": null,
"e": 3468,
"s": 3440,
"text": "pranavkumar123842 weeks ago"
},
{
"code": null,
"e": 3518,
"s": 3468,
"text": "// java solution//User function Template for Java"
},
{
"code": null,
"e": 3821,
"s": 3518,
"text": "class Solution{ //Function to find position of first set bit in the given number. public static int getFirstSetBit(int n){ // Your code here if(n==0) return 0; int pos=0; while(n>0 &&(n&1)==0){ n=n>>1; pos++; } return ++pos; }}"
},
{
"code": null,
"e": 3967,
"s": 3821,
"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": 4003,
"s": 3967,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4013,
"s": 4003,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4023,
"s": 4013,
"text": "\nContest\n"
},
{
"code": null,
"e": 4086,
"s": 4023,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4271,
"s": 4086,
"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": 4555,
"s": 4271,
"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": 4701,
"s": 4555,
"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": 4778,
"s": 4701,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 4819,
"s": 4778,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 4847,
"s": 4819,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 4918,
"s": 4847,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 5105,
"s": 4918,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
Python | Replace negative value with zero in numpy array
|
17 Oct, 2019
Given numpy array, the task is to replace negative value with zero in numpy array. Let’s see a few examples of this problem.
Method #1: Naive Method
# Python code to demonstrate# to replace negative value with 0import numpy as np ini_array1 = np.array([1, 2, -3, 4, -5, -6]) # printing initial arraysprint("initial array", ini_array1) # code to replace all negative value with 0ini_array1[ini_array1<0] = 0 # printing resultprint("New resulting array: ", ini_array1)
initial array [ 1 2 -3 4 -5 -6]
New resulting array: [1 2 0 4 0 0]
Method #2: Using np.where
# Python code to demonstrate# to replace negative values with 0import numpy as np ini_array1 = np.array([1, 2, -3, 4, -5, -6]) # printing initial arraysprint("initial array", ini_array1) # code to replace all negative value with 0result = np.where(ini_array1<0, 0, ini_array1) # printing resultprint("New resulting array: ", result)
initial array [ 1 2 -3 4 -5 -6]
New resulting array: [1 2 0 4 0 0]
Method #3: Using np.clip
# Python code to demonstrate# to replace negative values with 0import numpy as np # supposing maxx value array can holdmaxx = 1000 ini_array1 = np.array([1, 2, -3, 4, -5, -6]) # printing initial arraysprint("initial array", ini_array1) # code to replace all negative value with 0result = np.clip(ini_array1, 0, 1000) # printing resultprint("New resulting array: ", result)
initial array [ 1 2 -3 4 -5 -6]
New resulting array: [1 2 0 4 0 0]
Method #4: Comparing the given array with an array of zeros and write in the maximum value from the two arrays as the output.
# Python code to demonstrate# to replace negative values with 0import numpy as np ini_array1 = np.array([1, 2, -3, 4, -5, -6]) # printing initial arraysprint("initial array", ini_array1) # Creating a array of 0zero_array = np.zeros(ini_array1.shape, dtype=ini_array1.dtype)print("Zero array", zero_array) # code to replace all negative value with 0ini_array2 = np.maximum(ini_array1, zero_array) # printing resultprint("New resulting array: ", ini_array2)
initial array [ 1 2 -3 4 -5 -6]
Zero array [0 0 0 0 0 0]
New resulting array: [1 2 0 4 0 0]
nikhilaggarwal3
Python numpy-program
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Oct, 2019"
},
{
"code": null,
"e": 153,
"s": 28,
"text": "Given numpy array, the task is to replace negative value with zero in numpy array. Let’s see a few examples of this problem."
},
{
"code": null,
"e": 177,
"s": 153,
"text": "Method #1: Naive Method"
},
{
"code": "# Python code to demonstrate# to replace negative value with 0import numpy as np ini_array1 = np.array([1, 2, -3, 4, -5, -6]) # printing initial arraysprint(\"initial array\", ini_array1) # code to replace all negative value with 0ini_array1[ini_array1<0] = 0 # printing resultprint(\"New resulting array: \", ini_array1)",
"e": 499,
"s": 177,
"text": null
},
{
"code": null,
"e": 570,
"s": 499,
"text": "initial array [ 1 2 -3 4 -5 -6]\nNew resulting array: [1 2 0 4 0 0]\n"
},
{
"code": null,
"e": 597,
"s": 570,
"text": " Method #2: Using np.where"
},
{
"code": "# Python code to demonstrate# to replace negative values with 0import numpy as np ini_array1 = np.array([1, 2, -3, 4, -5, -6]) # printing initial arraysprint(\"initial array\", ini_array1) # code to replace all negative value with 0result = np.where(ini_array1<0, 0, ini_array1) # printing resultprint(\"New resulting array: \", result)",
"e": 934,
"s": 597,
"text": null
},
{
"code": null,
"e": 1005,
"s": 934,
"text": "initial array [ 1 2 -3 4 -5 -6]\nNew resulting array: [1 2 0 4 0 0]\n"
},
{
"code": null,
"e": 1031,
"s": 1005,
"text": " Method #3: Using np.clip"
},
{
"code": "# Python code to demonstrate# to replace negative values with 0import numpy as np # supposing maxx value array can holdmaxx = 1000 ini_array1 = np.array([1, 2, -3, 4, -5, -6]) # printing initial arraysprint(\"initial array\", ini_array1) # code to replace all negative value with 0result = np.clip(ini_array1, 0, 1000) # printing resultprint(\"New resulting array: \", result)",
"e": 1409,
"s": 1031,
"text": null
},
{
"code": null,
"e": 1480,
"s": 1409,
"text": "initial array [ 1 2 -3 4 -5 -6]\nNew resulting array: [1 2 0 4 0 0]\n"
},
{
"code": null,
"e": 1607,
"s": 1480,
"text": " Method #4: Comparing the given array with an array of zeros and write in the maximum value from the two arrays as the output."
},
{
"code": "# Python code to demonstrate# to replace negative values with 0import numpy as np ini_array1 = np.array([1, 2, -3, 4, -5, -6]) # printing initial arraysprint(\"initial array\", ini_array1) # Creating a array of 0zero_array = np.zeros(ini_array1.shape, dtype=ini_array1.dtype)print(\"Zero array\", zero_array) # code to replace all negative value with 0ini_array2 = np.maximum(ini_array1, zero_array) # printing resultprint(\"New resulting array: \", ini_array2)",
"e": 2071,
"s": 1607,
"text": null
},
{
"code": null,
"e": 2167,
"s": 2071,
"text": "initial array [ 1 2 -3 4 -5 -6]\nZero array [0 0 0 0 0 0]\nNew resulting array: [1 2 0 4 0 0]\n"
},
{
"code": null,
"e": 2183,
"s": 2167,
"text": "nikhilaggarwal3"
},
{
"code": null,
"e": 2204,
"s": 2183,
"text": "Python numpy-program"
},
{
"code": null,
"e": 2217,
"s": 2204,
"text": "Python-numpy"
},
{
"code": null,
"e": 2224,
"s": 2217,
"text": "Python"
}
] |
Overview of Packages in Oracle
|
Packages are SQL procedures, functions, variables, statements etc. that are grouped into a single unit. Many different applications can share the contents of a package, as it is stored in the database.
The following are the parts of a package in Oracle −
The package specifications contains information about all the procedures, functions, variables, constants etc. stored inside it. It has the declaration of all the components but not the code.
All the objects that are in the specification are known as public objects. If there is any object that is not available in the specification but is coded in the body, then it is known as a private object.
Syntax of Package specification is −
CREATE [OR REPLACE] PACKAGE name_of_package
IS | AS
[declaration_of_variable ...]
[declaration_of_constant ...]
[declaration_of_exception ...]
[cursor_specification ...]
[PROCEDURE [Schema..] name_of_procedure
[ (parameter {IN,OUT,IN OUT} datatype [,parameter]) ]
]
[FUNCTION [Schema..] name_of_function
[ (parameter {IN,OUT,IN OUT} datatype [,parameter]) ]
RETURN return_datatype
]
END [name_of_package];
The package body contains the code for all the public objects that were declared in the package specification as well as the private objects.
The package body can be created by using the CREATE PACKAGE BODY STATEMENT.
Syntax of Package body is −
CREATE [OR REPLACE] PACKAGE BODY name_of_package
IS | AS
[declaration_of_private_variable ...]
[declaration_of_private_constant ...]
BEGIN
[initialization_statement]
[PROCEDURE [Schema..] name_of_procedure
[ (parameter [,parameter]) ]
IS | AS
declaration_of_variables;
declaration_of_constants;
BEGIN
statement(s);
EXCEPTION
WHEN ...
END
]
[FUNCTION [Schema..] name_of_function
[ (parameter [,parameter]) ]
RETURN return_datatype
IS | AS
declaration_of_variables;
declaration_of_constants;
BEGIN
statement(s);
EXCEPTION
WHEN ...
END
]
[EXCEPTION
WHEN built-in_exception_name1 THEN
User defined statement (action) will be taken;
]
END;
Let us first create a table named STUDENTS −
CREATE TABLE STUDENTS(
ID INT NOT NULL,
NAME VARCHAR (25) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (30),
FEES DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Table Created
We will now insert the values −
INSERT INTO STUDENTS(ID,NAME,AGE,ADDRESS,FEES)
VALUES (1, Tom, 22,'Ohio', 17000 );
INSERT INTO STUDENTS(ID,NAME,AGE,ADDRESS,FEES)
VALUES (2, Jack, 20, 'Washington', 25000 );
INSERT INTO STUDENTS(ID,NAME,AGE,ADDRESS,FEES)
VALUES (3, Amy, 25, 'Boston', 30000 );
INSERT INTO STUDENTS(ID,NAME,AGE,ADDRESS,FEES)
VALUES (4, Anne, 18, 'Texas', 27000 );
Let us now assign the above values to PL/SQL variables:
DECLARE
s_id students.id%type := 2;
s_name students.name%type;
s_addr students.address%type;
s_fees students.fees%type;
BEGIN
SELECT name, fees INTO s_name, s_fees
FROM students
WHERE id = s_id;
dbms_output.put_line
(‘Student ' ||s_name || ' from ' || s_addr || ' pays ' || s_fees);
END;
/
Now the output would be:
Student Jack from Washington pays 25000
PL/SQL procedure completed successfully
Now let’s create a package:
CREATE OR REPLACE PACKAGE BODY stu_fees AS
PROCEDURE find_fees(s_id students.id%TYPE) IS
s_fees students.fees%TYPE;
BEGIN
SELECT fees INTO s_fees
FROM students
WHERE id = s_id;
dbms_output.put_line('Fees = '|| s_fees);
END find_sal;
END stu_fees;
On executing the above code, the following result would be visible:
Package body created.
The following are the uses of Packages:
The package objects can be shared by all the running subprograms. They remain for the whole session and allow data access without needing to store the data in the database.
The packages are a prime example of modularity. They store all types of objects such as procedures, functions, variables, statements into a neat package. This makes the information easy to understand and easily readable.
The packages are divided into Package specification and definition. This means that the type declaration for the packages can be done at leisure and the code can be written in the definition as and when required.
The first time any subprogram requires the package, it is loaded completely into the memory. For the next times, the package is already available for the other subprograms.
The details for the object declarations is available in the package specification while the implementation details are hidden in the package definition.This makes the package easier to handle and use.
|
[
{
"code": null,
"e": 1389,
"s": 1187,
"text": "Packages are SQL procedures, functions, variables, statements etc. that are grouped into a single unit. Many different applications can share the contents of a package, as it is stored in the database."
},
{
"code": null,
"e": 1442,
"s": 1389,
"text": "The following are the parts of a package in Oracle −"
},
{
"code": null,
"e": 1634,
"s": 1442,
"text": "The package specifications contains information about all the procedures, functions, variables, constants etc. stored inside it. It has the declaration of all the components but not the code."
},
{
"code": null,
"e": 1839,
"s": 1634,
"text": "All the objects that are in the specification are known as public objects. If there is any object that is not available in the specification but is coded in the body, then it is known as a private object."
},
{
"code": null,
"e": 1876,
"s": 1839,
"text": "Syntax of Package specification is −"
},
{
"code": null,
"e": 2282,
"s": 1876,
"text": "CREATE [OR REPLACE] PACKAGE name_of_package\nIS | AS\n[declaration_of_variable ...]\n[declaration_of_constant ...]\n[declaration_of_exception ...]\n[cursor_specification ...]\n[PROCEDURE [Schema..] name_of_procedure\n[ (parameter {IN,OUT,IN OUT} datatype [,parameter]) ]\n]\n[FUNCTION [Schema..] name_of_function\n[ (parameter {IN,OUT,IN OUT} datatype [,parameter]) ]\nRETURN return_datatype\n]\nEND [name_of_package];"
},
{
"code": null,
"e": 2424,
"s": 2282,
"text": "The package body contains the code for all the public objects that were declared in the package specification as well as the private objects."
},
{
"code": null,
"e": 2500,
"s": 2424,
"text": "The package body can be created by using the CREATE PACKAGE BODY STATEMENT."
},
{
"code": null,
"e": 2528,
"s": 2500,
"text": "Syntax of Package body is −"
},
{
"code": null,
"e": 3163,
"s": 2528,
"text": "CREATE [OR REPLACE] PACKAGE BODY name_of_package\nIS | AS\n[declaration_of_private_variable ...]\n[declaration_of_private_constant ...]\nBEGIN\n[initialization_statement]\n[PROCEDURE [Schema..] name_of_procedure\n[ (parameter [,parameter]) ]\nIS | AS\ndeclaration_of_variables;\ndeclaration_of_constants;\nBEGIN\nstatement(s);\nEXCEPTION\nWHEN ...\nEND\n]\n[FUNCTION [Schema..] name_of_function\n[ (parameter [,parameter]) ]\nRETURN return_datatype\nIS | AS\ndeclaration_of_variables;\ndeclaration_of_constants;\nBEGIN\nstatement(s);\nEXCEPTION\nWHEN ...\nEND\n]\n[EXCEPTION\nWHEN built-in_exception_name1 THEN\nUser defined statement (action) will be taken;\n]\nEND;"
},
{
"code": null,
"e": 3208,
"s": 3163,
"text": "Let us first create a table named STUDENTS −"
},
{
"code": null,
"e": 3369,
"s": 3208,
"text": "CREATE TABLE STUDENTS(\nID INT NOT NULL,\nNAME VARCHAR (25) NOT NULL,\nAGE INT NOT NULL,\nADDRESS CHAR (30),\nFEES DECIMAL (18, 2),\nPRIMARY KEY (ID)\n);\nTable Created"
},
{
"code": null,
"e": 3401,
"s": 3369,
"text": "We will now insert the values −"
},
{
"code": null,
"e": 3750,
"s": 3401,
"text": "INSERT INTO STUDENTS(ID,NAME,AGE,ADDRESS,FEES)\nVALUES (1, Tom, 22,'Ohio', 17000 );\n\nINSERT INTO STUDENTS(ID,NAME,AGE,ADDRESS,FEES)\nVALUES (2, Jack, 20, 'Washington', 25000 );\n\nINSERT INTO STUDENTS(ID,NAME,AGE,ADDRESS,FEES)\nVALUES (3, Amy, 25, 'Boston', 30000 );\n\nINSERT INTO STUDENTS(ID,NAME,AGE,ADDRESS,FEES)\nVALUES (4, Anne, 18, 'Texas', 27000 );"
},
{
"code": null,
"e": 3806,
"s": 3750,
"text": "Let us now assign the above values to PL/SQL variables:"
},
{
"code": null,
"e": 4096,
"s": 3806,
"text": "DECLARE\ns_id students.id%type := 2;\ns_name students.name%type;\ns_addr students.address%type;\ns_fees students.fees%type;\nBEGIN\nSELECT name, fees INTO s_name, s_fees\nFROM students\nWHERE id = s_id;\ndbms_output.put_line\n(‘Student ' ||s_name || ' from ' || s_addr || ' pays ' || s_fees);\nEND;\n/"
},
{
"code": null,
"e": 4121,
"s": 4096,
"text": "Now the output would be:"
},
{
"code": null,
"e": 4201,
"s": 4121,
"text": "Student Jack from Washington pays 25000\nPL/SQL procedure completed successfully"
},
{
"code": null,
"e": 4229,
"s": 4201,
"text": "Now let’s create a package:"
},
{
"code": null,
"e": 4477,
"s": 4229,
"text": "CREATE OR REPLACE PACKAGE BODY stu_fees AS\n\nPROCEDURE find_fees(s_id students.id%TYPE) IS\ns_fees students.fees%TYPE;\nBEGIN\nSELECT fees INTO s_fees\nFROM students\nWHERE id = s_id;\ndbms_output.put_line('Fees = '|| s_fees);\nEND find_sal;\nEND stu_fees;"
},
{
"code": null,
"e": 4545,
"s": 4477,
"text": "On executing the above code, the following result would be visible:"
},
{
"code": null,
"e": 4567,
"s": 4545,
"text": "Package body created."
},
{
"code": null,
"e": 4607,
"s": 4567,
"text": "The following are the uses of Packages:"
},
{
"code": null,
"e": 4780,
"s": 4607,
"text": "The package objects can be shared by all the running subprograms. They remain for the whole session and allow data access without needing to store the data in the database."
},
{
"code": null,
"e": 5001,
"s": 4780,
"text": "The packages are a prime example of modularity. They store all types of objects such as procedures, functions, variables, statements into a neat package. This makes the information easy to understand and easily readable."
},
{
"code": null,
"e": 5214,
"s": 5001,
"text": "The packages are divided into Package specification and definition. This means that the type declaration for the packages can be done at leisure and the code can be written in the definition as and when required."
},
{
"code": null,
"e": 5387,
"s": 5214,
"text": "The first time any subprogram requires the package, it is loaded completely into the memory. For the next times, the package is already available for the other subprograms."
},
{
"code": null,
"e": 5588,
"s": 5387,
"text": "The details for the object declarations is available in the package specification while the implementation details are hidden in the package definition.This makes the package easier to handle and use."
}
] |
Count maximum non-overlapping subarrays with given sum
|
24 May, 2021
Given an array arr[] consisting of N integers and an integer target, the task is to find the maximum number of non-empty non-overlapping subarrays such that the sum of array elements in each subarray is equal to the target.
Examples:
Input: arr[] = {2, -1, 4, 3, 6, 4, 5, 1}, target = 6Output: 3Explanation: Subarrays {-1, 4, 3}, {6} and {5, 1} have sum equal to target(= 6).
Input: arr[] = {2, 2, 2, 2, 2}, target = 4Output: 2
Approach: To obtain the smallest non-overlapping subarrays with the sum target, the target is to use the Prefix Sum technique. Follow the steps below to solve the problem:
Store all the sums calculated so far in a Map mp with key as the sum of the prefix till that index and value as the ending index of the subarray with that sum.If the prefix-sum till index i, say sum, is equal to target, check if sum – target exists in the Map or not.If sum – target exists in Map and mp[sum – target] = idx, it means that the subarray from [idx + 1, i] has sum equal to target.Now for non-overlapping subarrays, maintain an additional variable availIdx(initially set to -1), and take the subarray from [idx + 1, i] only when mp[sum – target] ≥ availIdx.Whenever such a subarray is found, increment the answer and change the value of availIdx to the current index.Also, for non-overlapping subarrays, it is always beneficial to greedily take subarrays as small as possible. So, for every prefix-sum found, update its index in the Map, even if it already exists.Print the value of count after completing the above steps.
Store all the sums calculated so far in a Map mp with key as the sum of the prefix till that index and value as the ending index of the subarray with that sum.
If the prefix-sum till index i, say sum, is equal to target, check if sum – target exists in the Map or not.
If sum – target exists in Map and mp[sum – target] = idx, it means that the subarray from [idx + 1, i] has sum equal to target.
Now for non-overlapping subarrays, maintain an additional variable availIdx(initially set to -1), and take the subarray from [idx + 1, i] only when mp[sum – target] ≥ availIdx.
Whenever such a subarray is found, increment the answer and change the value of availIdx to the current index.
Also, for non-overlapping subarrays, it is always beneficial to greedily take subarrays as small as possible. So, for every prefix-sum found, update its index in the Map, even if it already exists.
Print the value of count after completing the above steps.
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 count maximum number// of non-overlapping subarrays with// sum equals to the targetint maximumSubarrays(int arr[], int N, int target){ // Stores the final count int ans = 0; // Next subarray should start // from index >= availIdx int availIdx = -1; // Tracks the prefix sum int cur_sum = 0; // Map to store the prefix sum // for respective indices unordered_map<int, int> mp; mp[0] = -1; for (int i = 0; i < N; i++) { cur_sum += arr[i]; // Check if cur_sum - target is // present in the array or not if (mp.find(cur_sum - target) != mp.end() && mp[cur_sum - target] >= availIdx) { ans++; availIdx = i; } // Update the index of // current prefix sum mp[cur_sum] = i; } // Return the count of subarrays return ans;} // Driver Codeint main(){ // Given array arr[] int arr[] = { 2, -1, 4, 3, 6, 4, 5, 1 }; int N = sizeof(arr) / sizeof(arr[0]); // Given sum target int target = 6; // Function Call cout << maximumSubarrays(arr, N, target); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to count maximum number// of non-overlapping subarrays with// sum equals to the targetstatic int maximumSubarrays(int arr[], int N, int target){ // Stores the final count int ans = 0; // Next subarray should start // from index >= availIdx int availIdx = -1; // Tracks the prefix sum int cur_sum = 0; // Map to store the prefix sum // for respective indices HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); mp.put(0, 1); for(int i = 0; i < N; i++) { cur_sum += arr[i]; // Check if cur_sum - target is // present in the array or not if (mp.containsKey(cur_sum - target) && mp.get(cur_sum - target) >= availIdx) { ans++; availIdx = i; } // Update the index of // current prefix sum mp.put(cur_sum, i); } // Return the count of subarrays return ans;} // Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = { 2, -1, 4, 3, 6, 4, 5, 1 }; int N = arr.length; // Given sum target int target = 6; // Function call System.out.print(maximumSubarrays(arr, N, target));}} // This code is contributed by Amit Katiyar
# Python3 program for the above approach # Function to count maximum number# of non-overlapping subarrays with# sum equals to the targetdef maximumSubarrays(arr, N, target): # Stores the final count ans = 0 # Next subarray should start # from index >= availIdx availIdx = -1 # Tracks the prefix sum cur_sum = 0 # Map to store the prefix sum # for respective indices mp = {} mp[0] = -1 for i in range(N): cur_sum += arr[i] # Check if cur_sum - target is # present in the array or not if ((cur_sum - target) in mp and mp[cur_sum - target] >= availIdx): ans += 1 availIdx = i # Update the index of # current prefix sum mp[cur_sum] = i # Return the count of subarrays return ans # Driver Codeif __name__ == '__main__': # Given array arr[] arr = [ 2, -1, 4, 3, 6, 4, 5, 1 ] N = len(arr) # Given sum target target = 6 # Function call print(maximumSubarrays(arr, N, target)) # This code is contributed by mohit kumar 29
// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to count maximum number// of non-overlapping subarrays with// sum equals to the targetstatic int maximumSubarrays(int []arr, int N, int target){ // Stores the readonly count int ans = 0; // Next subarray should start // from index >= availIdx int availIdx = -1; // Tracks the prefix sum int cur_sum = 0; // Map to store the prefix sum // for respective indices Dictionary<int, int> mp = new Dictionary<int, int>(); mp.Add(0, 1); for(int i = 0; i < N; i++) { cur_sum += arr[i]; // Check if cur_sum - target is // present in the array or not if (mp.ContainsKey(cur_sum - target) && mp[cur_sum - target] >= availIdx) { ans++; availIdx = i; } // Update the index of // current prefix sum if(mp.ContainsKey(cur_sum)) mp[cur_sum] = i; else mp.Add(cur_sum, i); } // Return the count of subarrays return ans;} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []arr = {2, -1, 4, 3, 6, 4, 5, 1}; int N = arr.Length; // Given sum target int target = 6; // Function call Console.Write(maximumSubarrays(arr, N, target));}} // This code is contributed by Princi Singh
<script> // JavaScript program for the above approach // Function to count maximum number// of non-overlapping subarrays with// sum equals to the targetfunction maximumSubarrays(arr, N, target){ // Stores the final count var ans = 0; // Next subarray should start // from index >= availIdx var availIdx = -1; // Tracks the prefix sum var cur_sum = 0; // Map to store the prefix sum // for respective indices var mp = new Map(); mp.set(0, 1); for (var i = 0; i < N; i++) { cur_sum += arr[i]; // Check if cur_sum - target is // present in the array or not if (mp.has(cur_sum - target) && mp.get(cur_sum - target) >= availIdx) { ans++; availIdx = i; } // Update the index of // current prefix sum mp.set(cur_sum , i); } // Return the count of subarrays return ans;} // Driver Code // Given array arr[]var arr = [2, -1, 4, 3, 6, 4, 5, 1];var N = arr.length; // Given sum targetvar target = 6; // Function Calldocument.write( maximumSubarrays(arr, N, target)); </script>
3
Time Complexity: O(N)Auxiliary Space: O(N)
mohit kumar 29
amit143katiyar
princi singh
rutvik_56
prefix-sum
subarray
subarray-sum
Arrays
Greedy
Mathematical
prefix-sum
Arrays
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Write a program to print all permutations of a given string
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Huffman Coding | Greedy Algo-3
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 May, 2021"
},
{
"code": null,
"e": 276,
"s": 52,
"text": "Given an array arr[] consisting of N integers and an integer target, the task is to find the maximum number of non-empty non-overlapping subarrays such that the sum of array elements in each subarray is equal to the target."
},
{
"code": null,
"e": 286,
"s": 276,
"text": "Examples:"
},
{
"code": null,
"e": 428,
"s": 286,
"text": "Input: arr[] = {2, -1, 4, 3, 6, 4, 5, 1}, target = 6Output: 3Explanation: Subarrays {-1, 4, 3}, {6} and {5, 1} have sum equal to target(= 6)."
},
{
"code": null,
"e": 481,
"s": 428,
"text": "Input: arr[] = {2, 2, 2, 2, 2}, target = 4Output: 2 "
},
{
"code": null,
"e": 653,
"s": 481,
"text": "Approach: To obtain the smallest non-overlapping subarrays with the sum target, the target is to use the Prefix Sum technique. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 1589,
"s": 653,
"text": "Store all the sums calculated so far in a Map mp with key as the sum of the prefix till that index and value as the ending index of the subarray with that sum.If the prefix-sum till index i, say sum, is equal to target, check if sum – target exists in the Map or not.If sum – target exists in Map and mp[sum – target] = idx, it means that the subarray from [idx + 1, i] has sum equal to target.Now for non-overlapping subarrays, maintain an additional variable availIdx(initially set to -1), and take the subarray from [idx + 1, i] only when mp[sum – target] ≥ availIdx.Whenever such a subarray is found, increment the answer and change the value of availIdx to the current index.Also, for non-overlapping subarrays, it is always beneficial to greedily take subarrays as small as possible. So, for every prefix-sum found, update its index in the Map, even if it already exists.Print the value of count after completing the above steps."
},
{
"code": null,
"e": 1749,
"s": 1589,
"text": "Store all the sums calculated so far in a Map mp with key as the sum of the prefix till that index and value as the ending index of the subarray with that sum."
},
{
"code": null,
"e": 1858,
"s": 1749,
"text": "If the prefix-sum till index i, say sum, is equal to target, check if sum – target exists in the Map or not."
},
{
"code": null,
"e": 1986,
"s": 1858,
"text": "If sum – target exists in Map and mp[sum – target] = idx, it means that the subarray from [idx + 1, i] has sum equal to target."
},
{
"code": null,
"e": 2163,
"s": 1986,
"text": "Now for non-overlapping subarrays, maintain an additional variable availIdx(initially set to -1), and take the subarray from [idx + 1, i] only when mp[sum – target] ≥ availIdx."
},
{
"code": null,
"e": 2274,
"s": 2163,
"text": "Whenever such a subarray is found, increment the answer and change the value of availIdx to the current index."
},
{
"code": null,
"e": 2472,
"s": 2274,
"text": "Also, for non-overlapping subarrays, it is always beneficial to greedily take subarrays as small as possible. So, for every prefix-sum found, update its index in the Map, even if it already exists."
},
{
"code": null,
"e": 2531,
"s": 2472,
"text": "Print the value of count after completing the above steps."
},
{
"code": null,
"e": 2582,
"s": 2531,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2586,
"s": 2582,
"text": "C++"
},
{
"code": null,
"e": 2591,
"s": 2586,
"text": "Java"
},
{
"code": null,
"e": 2599,
"s": 2591,
"text": "Python3"
},
{
"code": null,
"e": 2602,
"s": 2599,
"text": "C#"
},
{
"code": null,
"e": 2613,
"s": 2602,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to count maximum number// of non-overlapping subarrays with// sum equals to the targetint maximumSubarrays(int arr[], int N, int target){ // Stores the final count int ans = 0; // Next subarray should start // from index >= availIdx int availIdx = -1; // Tracks the prefix sum int cur_sum = 0; // Map to store the prefix sum // for respective indices unordered_map<int, int> mp; mp[0] = -1; for (int i = 0; i < N; i++) { cur_sum += arr[i]; // Check if cur_sum - target is // present in the array or not if (mp.find(cur_sum - target) != mp.end() && mp[cur_sum - target] >= availIdx) { ans++; availIdx = i; } // Update the index of // current prefix sum mp[cur_sum] = i; } // Return the count of subarrays return ans;} // Driver Codeint main(){ // Given array arr[] int arr[] = { 2, -1, 4, 3, 6, 4, 5, 1 }; int N = sizeof(arr) / sizeof(arr[0]); // Given sum target int target = 6; // Function Call cout << maximumSubarrays(arr, N, target); return 0;}",
"e": 3926,
"s": 2613,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to count maximum number// of non-overlapping subarrays with// sum equals to the targetstatic int maximumSubarrays(int arr[], int N, int target){ // Stores the final count int ans = 0; // Next subarray should start // from index >= availIdx int availIdx = -1; // Tracks the prefix sum int cur_sum = 0; // Map to store the prefix sum // for respective indices HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); mp.put(0, 1); for(int i = 0; i < N; i++) { cur_sum += arr[i]; // Check if cur_sum - target is // present in the array or not if (mp.containsKey(cur_sum - target) && mp.get(cur_sum - target) >= availIdx) { ans++; availIdx = i; } // Update the index of // current prefix sum mp.put(cur_sum, i); } // Return the count of subarrays return ans;} // Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = { 2, -1, 4, 3, 6, 4, 5, 1 }; int N = arr.length; // Given sum target int target = 6; // Function call System.out.print(maximumSubarrays(arr, N, target));}} // This code is contributed by Amit Katiyar",
"e": 5379,
"s": 3926,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to count maximum number# of non-overlapping subarrays with# sum equals to the targetdef maximumSubarrays(arr, N, target): # Stores the final count ans = 0 # Next subarray should start # from index >= availIdx availIdx = -1 # Tracks the prefix sum cur_sum = 0 # Map to store the prefix sum # for respective indices mp = {} mp[0] = -1 for i in range(N): cur_sum += arr[i] # Check if cur_sum - target is # present in the array or not if ((cur_sum - target) in mp and mp[cur_sum - target] >= availIdx): ans += 1 availIdx = i # Update the index of # current prefix sum mp[cur_sum] = i # Return the count of subarrays return ans # Driver Codeif __name__ == '__main__': # Given array arr[] arr = [ 2, -1, 4, 3, 6, 4, 5, 1 ] N = len(arr) # Given sum target target = 6 # Function call print(maximumSubarrays(arr, N, target)) # This code is contributed by mohit kumar 29",
"e": 6466,
"s": 5379,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to count maximum number// of non-overlapping subarrays with// sum equals to the targetstatic int maximumSubarrays(int []arr, int N, int target){ // Stores the readonly count int ans = 0; // Next subarray should start // from index >= availIdx int availIdx = -1; // Tracks the prefix sum int cur_sum = 0; // Map to store the prefix sum // for respective indices Dictionary<int, int> mp = new Dictionary<int, int>(); mp.Add(0, 1); for(int i = 0; i < N; i++) { cur_sum += arr[i]; // Check if cur_sum - target is // present in the array or not if (mp.ContainsKey(cur_sum - target) && mp[cur_sum - target] >= availIdx) { ans++; availIdx = i; } // Update the index of // current prefix sum if(mp.ContainsKey(cur_sum)) mp[cur_sum] = i; else mp.Add(cur_sum, i); } // Return the count of subarrays return ans;} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []arr = {2, -1, 4, 3, 6, 4, 5, 1}; int N = arr.Length; // Given sum target int target = 6; // Function call Console.Write(maximumSubarrays(arr, N, target));}} // This code is contributed by Princi Singh",
"e": 7872,
"s": 6466,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to count maximum number// of non-overlapping subarrays with// sum equals to the targetfunction maximumSubarrays(arr, N, target){ // Stores the final count var ans = 0; // Next subarray should start // from index >= availIdx var availIdx = -1; // Tracks the prefix sum var cur_sum = 0; // Map to store the prefix sum // for respective indices var mp = new Map(); mp.set(0, 1); for (var i = 0; i < N; i++) { cur_sum += arr[i]; // Check if cur_sum - target is // present in the array or not if (mp.has(cur_sum - target) && mp.get(cur_sum - target) >= availIdx) { ans++; availIdx = i; } // Update the index of // current prefix sum mp.set(cur_sum , i); } // Return the count of subarrays return ans;} // Driver Code // Given array arr[]var arr = [2, -1, 4, 3, 6, 4, 5, 1];var N = arr.length; // Given sum targetvar target = 6; // Function Calldocument.write( maximumSubarrays(arr, N, target)); </script>",
"e": 9036,
"s": 7872,
"text": null
},
{
"code": null,
"e": 9038,
"s": 9036,
"text": "3"
},
{
"code": null,
"e": 9083,
"s": 9040,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 9098,
"s": 9083,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 9113,
"s": 9098,
"text": "amit143katiyar"
},
{
"code": null,
"e": 9126,
"s": 9113,
"text": "princi singh"
},
{
"code": null,
"e": 9136,
"s": 9126,
"text": "rutvik_56"
},
{
"code": null,
"e": 9147,
"s": 9136,
"text": "prefix-sum"
},
{
"code": null,
"e": 9156,
"s": 9147,
"text": "subarray"
},
{
"code": null,
"e": 9169,
"s": 9156,
"text": "subarray-sum"
},
{
"code": null,
"e": 9176,
"s": 9169,
"text": "Arrays"
},
{
"code": null,
"e": 9183,
"s": 9176,
"text": "Greedy"
},
{
"code": null,
"e": 9196,
"s": 9183,
"text": "Mathematical"
},
{
"code": null,
"e": 9207,
"s": 9196,
"text": "prefix-sum"
},
{
"code": null,
"e": 9214,
"s": 9207,
"text": "Arrays"
},
{
"code": null,
"e": 9221,
"s": 9214,
"text": "Greedy"
},
{
"code": null,
"e": 9234,
"s": 9221,
"text": "Mathematical"
},
{
"code": null,
"e": 9332,
"s": 9234,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9400,
"s": 9332,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 9444,
"s": 9400,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 9476,
"s": 9444,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 9524,
"s": 9476,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 9538,
"s": 9524,
"text": "Linear Search"
},
{
"code": null,
"e": 9589,
"s": 9538,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 9640,
"s": 9589,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 9700,
"s": 9640,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 9758,
"s": 9700,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
}
] |
Dart – Break Statement
|
15 Jul, 2020
The break statement in Dart inside any loop gives you a way to break or terminate the execution of the loop containing it, and hence transfers the execution to the next statement following the loop. It is always used with the if-else construct.
Syntax: break;
Example 1:
Dart
// Dart program in Dart to // illustrate Break statement void main(){ var count = 0; print("GeeksforGeeks - Break Statement in Dart"); while(count<=10) { count++; if(count == 5) { //break statement break; } print("Inside loop ${count}"); } print("Out of while Loop");}
Output:
In this above program, the variable count is initialized as 0. Then a while loop is executed as long as the variable count is less than 10.
Inside the while loop, the count variable is incremented by 1 with each iteration (count = count + 1). Next, we have an If statement that checks the variable count is equal to 5, if it returns TRUE causes loop to break or terminate, Within the loop, there is a cout statement that will execute with each iteration of the while loop until the loop breaks. Then, there is a final cout statement outside of the while loop.
Example 2:
Dart
// Dart program in Dart to // illustrate Break statement void main() { var i = 1; while(i<=10) { if (i % == 0) { print("The first multiple of 2 between 1 and 10 is : ${i}"); break ; // exit the loop if the // first multiple is found } i++; }}
Output:
The first multiple of 5 between 1 and 10 is: 2
Dart Control-Flow
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ListView Class in Flutter
Flutter - Search Bar
Flutter - Dialogs
Flutter - FutureBuilder Widget
Flutter - Flexible Widget
Flutter - Pop Up Menu
What is widgets in Flutter?
Android Studio Setup for Flutter Development
Flutter - CircleAvatar Widget
Flutter - RichText Widget
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Jul, 2020"
},
{
"code": null,
"e": 273,
"s": 28,
"text": "The break statement in Dart inside any loop gives you a way to break or terminate the execution of the loop containing it, and hence transfers the execution to the next statement following the loop. It is always used with the if-else construct."
},
{
"code": null,
"e": 289,
"s": 273,
"text": "Syntax: break;\n"
},
{
"code": null,
"e": 300,
"s": 289,
"text": "Example 1:"
},
{
"code": null,
"e": 305,
"s": 300,
"text": "Dart"
},
{
"code": "// Dart program in Dart to // illustrate Break statement void main(){ var count = 0; print(\"GeeksforGeeks - Break Statement in Dart\"); while(count<=10) { count++; if(count == 5) { //break statement break; } print(\"Inside loop ${count}\"); } print(\"Out of while Loop\");}",
"e": 616,
"s": 305,
"text": null
},
{
"code": null,
"e": 624,
"s": 616,
"text": "Output:"
},
{
"code": null,
"e": 764,
"s": 624,
"text": "In this above program, the variable count is initialized as 0. Then a while loop is executed as long as the variable count is less than 10."
},
{
"code": null,
"e": 1184,
"s": 764,
"text": "Inside the while loop, the count variable is incremented by 1 with each iteration (count = count + 1). Next, we have an If statement that checks the variable count is equal to 5, if it returns TRUE causes loop to break or terminate, Within the loop, there is a cout statement that will execute with each iteration of the while loop until the loop breaks. Then, there is a final cout statement outside of the while loop."
},
{
"code": null,
"e": 1195,
"s": 1184,
"text": "Example 2:"
},
{
"code": null,
"e": 1200,
"s": 1195,
"text": "Dart"
},
{
"code": "// Dart program in Dart to // illustrate Break statement void main() { var i = 1; while(i<=10) { if (i % == 0) { print(\"The first multiple of 2 between 1 and 10 is : ${i}\"); break ; // exit the loop if the // first multiple is found } i++; }}",
"e": 1511,
"s": 1200,
"text": null
},
{
"code": null,
"e": 1519,
"s": 1511,
"text": "Output:"
},
{
"code": null,
"e": 1568,
"s": 1519,
"text": "The first multiple of 5 between 1 and 10 is: 2 \n"
},
{
"code": null,
"e": 1586,
"s": 1568,
"text": "Dart Control-Flow"
},
{
"code": null,
"e": 1591,
"s": 1586,
"text": "Dart"
},
{
"code": null,
"e": 1689,
"s": 1591,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1715,
"s": 1689,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 1736,
"s": 1715,
"text": "Flutter - Search Bar"
},
{
"code": null,
"e": 1754,
"s": 1736,
"text": "Flutter - Dialogs"
},
{
"code": null,
"e": 1785,
"s": 1754,
"text": "Flutter - FutureBuilder Widget"
},
{
"code": null,
"e": 1811,
"s": 1785,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 1833,
"s": 1811,
"text": "Flutter - Pop Up Menu"
},
{
"code": null,
"e": 1861,
"s": 1833,
"text": "What is widgets in Flutter?"
},
{
"code": null,
"e": 1906,
"s": 1861,
"text": "Android Studio Setup for Flutter Development"
},
{
"code": null,
"e": 1936,
"s": 1906,
"text": "Flutter - CircleAvatar Widget"
}
] |
Distance of closest zero to every element - GeeksforGeeks
|
22 Feb, 2022
Given an array of n integers, for each element, print the distance to the closest zero. Array has a minimum of 1 zero in it.Examples:
Input: 5 6 0 1 -2 3 4
Output: 2 1 0 1 2 3 4
Explanation : The nearest 0(indexed 2) to
5(indexed 0) is at a distance of 2, so we
print 2. Same is done for the rest of elements.
Naive Approach: A naive approach is, for every element, slide towards left and find out the nearest 0 and again slide towards the right to find out the nearest zero if any, and print the minimum of both the distances. It will be space efficient but the time complexity will be high as we have to iterate for every element till we find the 0, and in worst case we may not find in one direction. Time Complexity: O(n^2) Auxiliary Space: O(1) Efficient Approach: An efficient approach is to use sliding window technique two time. One is traversing from right to left and other from left right. Initialize ans[0] with a max value. Iterate over array from left to right. If value in current position is 0, then set distance to 0, otherwise increase distance by 1. In each step, write value of distance to the answer array. Do the same thing but going from right to left. This will find closest zero to the right. Now we should store the minimum of current value of distance and value that’s already in answer array. Below is the implementation of the above approach.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find closest 0 for every element#include <bits/stdc++.h>using namespace std; // Print the distance with zeroes of every elementvoid print_distance(int arr[], int n){ // initializes an array of size n with 0 int ans[n]; memset(arr, 0, sizeof(arr)); // if first element is 0 then the distance // will be 0 if (arr[0] == 0) ans[0] = 0; else ans[0] = INT_MAX; // if not 0 then initialize // with a maximum value // traverse in loop from 1 to n and store // the distance from left for (int i = 1; i < n; ++i) { // add 1 to the distance from previous one ans[i] = ans[i - 1] + 1; // if the present element is 0 then distance // will be 0 if (arr[i] == 0) ans[i] = 0; } // if last element is zero then it will be 0 else // let the answer be what was found when traveled // from left to right if (arr[n - 1] == 0) ans[n - 1] = 0; // traverse from right to left and store the minimum // of distance if found from right to left or left // to right for (int i = n - 2; i >= 0; --i) { // store the minimum of distance from left to // right or right to left ans[i] = min(ans[i], ans[i + 1] + 1); // if it is 0 then minimum will always be 0 if (arr[i] == 0) ans[i] = 0; } // print the answer array for (int i = 0; i < n; ++i) cout << ans[i] << " "; } // driver program to test the above functionint main(){ int a[] = { 2, 1, 0, 3, 0, 0, 3, 2, 4 }; int n = sizeof(a) / sizeof(a[0]); printDistances(a, n); return 0;}
// Java program to find closest// 0 for every elementimport java.util.Arrays; class GFG{ // Print the distance with zeroes of every element static void print_distance(int arr[], int n) { // initializes an array of size n with 0 int ans[]=new int[n]; Arrays.fill(ans,0); // if first element is 0 then the distance // will be 0 if (arr[0] == 0) ans[0] = 0; // if not 0 then initialize // with a maximum value else ans[0] = +2147483647; // traverse in loop from 1 to n and store // the distance from left for (int i = 1; i < n; ++i) { // add 1 to the distance // from previous one ans[i] = ans[i - 1] + 1; // if the present element is // 0 then distance will be 0 if (arr[i] == 0) ans[i] = 0; } // if last element is zero // then it will be 0 else // let the answer be what was // found when traveled // from left to right if (arr[n - 1] == 0) ans[n - 1] = 0; // traverse from right to // left and store the minimum // of distance if found from // right to left or left // to right for (int i = n - 2; i >= 0; --i) { // store the minimum of distance // from left to right or right to left ans[i] = Math.min(ans[i], ans[i + 1] + 1); // if it is 0 then minimum // will always be 0 if (arr[i] == 0) ans[i] = 0; } // print the answer array for (int i = 0; i < n; ++i) System.out.print(ans[i] + " "); } // Driver code public static void main (String[] args) { int a[] = { 2, 1, 0, 3, 0, 0, 3, 2, 4 }; int n = a.length; print_distance(a, n); }} // This code is contributed by Anant Agarwal.
# Python3 program to find closest 0# for every element # Print the distance with zeroes of# every elementdef print_distance(arr, n): # initializes an array of size n with 0 ans = [0 for i in range(n)] # if first element is 0 then the # distance will be 0 if (arr[0] == 0): ans[0] = 0 else: ans[0] = 10**9 # if not 0 then initialize # with a maximum value # traverse in loop from 1 to n and # store the distance from left for i in range(1, n): # add 1 to the distance from # previous one ans[i] = ans[i - 1] + 1 # if the present element is 0 then # distance will be 0 if (arr[i] == 0): ans[i] = 0 # if last element is zero then it will be 0 # else let the answer be what was found when # traveled from left to right if (arr[n - 1] == 0): ans[n - 1] = 0 # traverse from right to left and store # the minimum of distance if found from # right to left or left to right for i in range(n - 2, -1, -1): # store the minimum of distance from # left to right or right to left ans[i] = min(ans[i], ans[i + 1] + 1) # if it is 0 then minimum will # always be 0 if (arr[i] == 0): ans[i] = 0 # print the answer array for i in ans: print(i, end = " ") # Driver Codea = [2, 1, 0, 3, 0, 0, 3, 2, 4]n = len(a)print_distance(a, n) # This code is contributed# by Mohit Kumar
// C# program to find closest// 0 for every elementusing System;class GFG{ // Print the distance with zeroes of every element static void print_distance(int []arr, int n) { // initializes an array of size n with 0 int []ans=new int[n]; for(int i = 0; i < n; i++) ans[i] = 0; // if first element is 0 then the distance // will be 0 if (arr[0] == 0) ans[0] = 0; // if not 0 then initialize // with a maximum value else ans[0] = +2147483646; // traverse in loop from 1 to n and store // the distance from left for (int i = 1; i < n; ++i) { // add 1 to the distance // from previous one ans[i] = ans[i - 1] + 1; // if the present element is // 0 then distance will be 0 if (arr[i] == 0) ans[i] = 0; } // if last element is zero // then it will be 0 else // let the answer be what was // found when traveled // from left to right if (arr[n - 1] == 0) ans[n - 1] = 0; // traverse from right to // left and store the minimum // of distance if found from // right to left or left // to right for (int i = n - 2; i >= 0; --i) { // store the minimum of distance // from left to right or right to left ans[i] = Math.Min(ans[i], ans[i + 1] + 1); // if it is 0 then minimum // will always be 0 if (arr[i] == 0) ans[i] = 0; } // print the answer array for (int i = 0; i < n; ++i) Console.Write(ans[i] + " "); } // Driver code public static void Main (String[] args) { int []a = { 2, 1, 0, 3, 0, 0, 3, 2, 4 }; int n = a.Length; print_distance(a, n); }} // This code is contributed by PrinciRaj1992
<?php// PHP program to find closest 0// for every element // Print the distance with zeroes// of every elementfunction print_distance($arr, $n){ // initializes an array of size n with 0 $ans[$n] = array(); $ans = array_fill(0, $n, true); // if first element is 0 then the // distance will be 0 if ($arr[0] == 0) $ans[0] = 0; else $ans[0] = PHP_INT_MAX; // if not 0 then initialize // with a maximum value // traverse in loop from 1 to n and // store the distance from left for ( $i = 1; $i < $n; ++$i) { // add 1 to the distance from // previous one $ans[$i] = $ans[$i - 1] + 1; // if the present element is 0 // then distance will be 0 if ($arr[$i] == 0) $ans[$i] = 0; } // if last element is zero then it will // be 0 else let the answer be what was // found when traveled from left to right if ($arr[$n - 1] == 0) $ans[$n - 1] = 0; // traverse from right to left and store // the minimum of distance if found from // right to left or left to right for ($i = $n - 2; $i >= 0; --$i) { // store the minimum of distance from // left to right or right to left $ans[$i] = min($ans[$i], $ans[$i + 1] + 1); // if it is 0 then minimum will // always be 0 if ($arr[$i] == 0) $ans[$i] = 0; } // print the answer array for ($i = 0; $i < $n; ++$i) echo $ans[$i] , " ";} // Driver Code$a = array( 2, 1, 0, 3, 0, 0, 3, 2, 4 );$n = sizeof($a);print_distance($a, $n); // This code is contributed by Sachin?>
<script>// javascript program to find closest// 0 for every element// Print the distance with zeroes of every element function print_distance(arr , n) { // initializes an array of size n with 0 var ans = Array(n).fill(0); // if first element is 0 then the distance // will be 0 if (arr[0] == 0) ans[0] = 0; // if not 0 then initialize // with a maximum value else ans[0] = +2147483647; // traverse in loop from 1 to n and store // the distance from left for (i = 1; i < n; ++i) { // add 1 to the distance // from previous one ans[i] = ans[i - 1] + 1; // if the present element is // 0 then distance will be 0 if (arr[i] == 0) ans[i] = 0; } // if last element is zero // then it will be 0 else // let the answer be what was // found when traveled // from left to right if (arr[n - 1] == 0) ans[n - 1] = 0; // traverse from right to // left and store the minimum // of distance if found from // right to left or left // to right for (i = n - 2; i >= 0; --i) { // store the minimum of distance // from left to right or right to left ans[i] = Math.min(ans[i], ans[i + 1] + 1); // if it is 0 then minimum // will always be 0 if (arr[i] == 0) ans[i] = 0; } // print the answer array for (i = 0; i < n; ++i) document.write(ans[i] + " "); } // Driver code var a = [ 2, 1, 0, 3, 0, 0, 3, 2, 4 ]; var n = a.length; print_distance(a, n); // This code is contributed by Rajput-Ji</script>
Output:
2 1 0 1 0 0 1 2 3
Time complexity: O(n) Auxiliary Space: O(n)This article is contributed by Raja Vikramaditya. 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.
Sach_Code
princiraj1992
mohit kumar 29
Rajput-Ji
arorakashish0911
simmytarika5
sliding-window
Arrays
sliding-window
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Move all negative numbers to beginning and positive to end with constant extra space
Program to find sum of elements in a given array
Building Heap from Array
Find duplicates in O(n) time and O(1) extra space | Set 1
Next Greater Element
Count pairs with given sum
Remove duplicates from sorted array
|
[
{
"code": null,
"e": 24822,
"s": 24794,
"text": "\n22 Feb, 2022"
},
{
"code": null,
"e": 24958,
"s": 24822,
"text": "Given an array of n integers, for each element, print the distance to the closest zero. Array has a minimum of 1 zero in it.Examples: "
},
{
"code": null,
"e": 25137,
"s": 24958,
"text": "Input: 5 6 0 1 -2 3 4\nOutput: 2 1 0 1 2 3 4 \nExplanation : The nearest 0(indexed 2) to \n5(indexed 0) is at a distance of 2, so we \nprint 2. Same is done for the rest of elements."
},
{
"code": null,
"e": 26203,
"s": 25139,
"text": "Naive Approach: A naive approach is, for every element, slide towards left and find out the nearest 0 and again slide towards the right to find out the nearest zero if any, and print the minimum of both the distances. It will be space efficient but the time complexity will be high as we have to iterate for every element till we find the 0, and in worst case we may not find in one direction. Time Complexity: O(n^2) Auxiliary Space: O(1) Efficient Approach: An efficient approach is to use sliding window technique two time. One is traversing from right to left and other from left right. Initialize ans[0] with a max value. Iterate over array from left to right. If value in current position is 0, then set distance to 0, otherwise increase distance by 1. In each step, write value of distance to the answer array. Do the same thing but going from right to left. This will find closest zero to the right. Now we should store the minimum of current value of distance and value that’s already in answer array. Below is the implementation of the above approach. "
},
{
"code": null,
"e": 26207,
"s": 26203,
"text": "C++"
},
{
"code": null,
"e": 26212,
"s": 26207,
"text": "Java"
},
{
"code": null,
"e": 26220,
"s": 26212,
"text": "Python3"
},
{
"code": null,
"e": 26223,
"s": 26220,
"text": "C#"
},
{
"code": null,
"e": 26227,
"s": 26223,
"text": "PHP"
},
{
"code": null,
"e": 26238,
"s": 26227,
"text": "Javascript"
},
{
"code": "// CPP program to find closest 0 for every element#include <bits/stdc++.h>using namespace std; // Print the distance with zeroes of every elementvoid print_distance(int arr[], int n){ // initializes an array of size n with 0 int ans[n]; memset(arr, 0, sizeof(arr)); // if first element is 0 then the distance // will be 0 if (arr[0] == 0) ans[0] = 0; else ans[0] = INT_MAX; // if not 0 then initialize // with a maximum value // traverse in loop from 1 to n and store // the distance from left for (int i = 1; i < n; ++i) { // add 1 to the distance from previous one ans[i] = ans[i - 1] + 1; // if the present element is 0 then distance // will be 0 if (arr[i] == 0) ans[i] = 0; } // if last element is zero then it will be 0 else // let the answer be what was found when traveled // from left to right if (arr[n - 1] == 0) ans[n - 1] = 0; // traverse from right to left and store the minimum // of distance if found from right to left or left // to right for (int i = n - 2; i >= 0; --i) { // store the minimum of distance from left to // right or right to left ans[i] = min(ans[i], ans[i + 1] + 1); // if it is 0 then minimum will always be 0 if (arr[i] == 0) ans[i] = 0; } // print the answer array for (int i = 0; i < n; ++i) cout << ans[i] << \" \"; } // driver program to test the above functionint main(){ int a[] = { 2, 1, 0, 3, 0, 0, 3, 2, 4 }; int n = sizeof(a) / sizeof(a[0]); printDistances(a, n); return 0;}",
"e": 27898,
"s": 26238,
"text": null
},
{
"code": "// Java program to find closest// 0 for every elementimport java.util.Arrays; class GFG{ // Print the distance with zeroes of every element static void print_distance(int arr[], int n) { // initializes an array of size n with 0 int ans[]=new int[n]; Arrays.fill(ans,0); // if first element is 0 then the distance // will be 0 if (arr[0] == 0) ans[0] = 0; // if not 0 then initialize // with a maximum value else ans[0] = +2147483647; // traverse in loop from 1 to n and store // the distance from left for (int i = 1; i < n; ++i) { // add 1 to the distance // from previous one ans[i] = ans[i - 1] + 1; // if the present element is // 0 then distance will be 0 if (arr[i] == 0) ans[i] = 0; } // if last element is zero // then it will be 0 else // let the answer be what was // found when traveled // from left to right if (arr[n - 1] == 0) ans[n - 1] = 0; // traverse from right to // left and store the minimum // of distance if found from // right to left or left // to right for (int i = n - 2; i >= 0; --i) { // store the minimum of distance // from left to right or right to left ans[i] = Math.min(ans[i], ans[i + 1] + 1); // if it is 0 then minimum // will always be 0 if (arr[i] == 0) ans[i] = 0; } // print the answer array for (int i = 0; i < n; ++i) System.out.print(ans[i] + \" \"); } // Driver code public static void main (String[] args) { int a[] = { 2, 1, 0, 3, 0, 0, 3, 2, 4 }; int n = a.length; print_distance(a, n); }} // This code is contributed by Anant Agarwal.",
"e": 29907,
"s": 27898,
"text": null
},
{
"code": "# Python3 program to find closest 0# for every element # Print the distance with zeroes of# every elementdef print_distance(arr, n): # initializes an array of size n with 0 ans = [0 for i in range(n)] # if first element is 0 then the # distance will be 0 if (arr[0] == 0): ans[0] = 0 else: ans[0] = 10**9 # if not 0 then initialize # with a maximum value # traverse in loop from 1 to n and # store the distance from left for i in range(1, n): # add 1 to the distance from # previous one ans[i] = ans[i - 1] + 1 # if the present element is 0 then # distance will be 0 if (arr[i] == 0): ans[i] = 0 # if last element is zero then it will be 0 # else let the answer be what was found when # traveled from left to right if (arr[n - 1] == 0): ans[n - 1] = 0 # traverse from right to left and store # the minimum of distance if found from # right to left or left to right for i in range(n - 2, -1, -1): # store the minimum of distance from # left to right or right to left ans[i] = min(ans[i], ans[i + 1] + 1) # if it is 0 then minimum will # always be 0 if (arr[i] == 0): ans[i] = 0 # print the answer array for i in ans: print(i, end = \" \") # Driver Codea = [2, 1, 0, 3, 0, 0, 3, 2, 4]n = len(a)print_distance(a, n) # This code is contributed# by Mohit Kumar",
"e": 31398,
"s": 29907,
"text": null
},
{
"code": "// C# program to find closest// 0 for every elementusing System;class GFG{ // Print the distance with zeroes of every element static void print_distance(int []arr, int n) { // initializes an array of size n with 0 int []ans=new int[n]; for(int i = 0; i < n; i++) ans[i] = 0; // if first element is 0 then the distance // will be 0 if (arr[0] == 0) ans[0] = 0; // if not 0 then initialize // with a maximum value else ans[0] = +2147483646; // traverse in loop from 1 to n and store // the distance from left for (int i = 1; i < n; ++i) { // add 1 to the distance // from previous one ans[i] = ans[i - 1] + 1; // if the present element is // 0 then distance will be 0 if (arr[i] == 0) ans[i] = 0; } // if last element is zero // then it will be 0 else // let the answer be what was // found when traveled // from left to right if (arr[n - 1] == 0) ans[n - 1] = 0; // traverse from right to // left and store the minimum // of distance if found from // right to left or left // to right for (int i = n - 2; i >= 0; --i) { // store the minimum of distance // from left to right or right to left ans[i] = Math.Min(ans[i], ans[i + 1] + 1); // if it is 0 then minimum // will always be 0 if (arr[i] == 0) ans[i] = 0; } // print the answer array for (int i = 0; i < n; ++i) Console.Write(ans[i] + \" \"); } // Driver code public static void Main (String[] args) { int []a = { 2, 1, 0, 3, 0, 0, 3, 2, 4 }; int n = a.Length; print_distance(a, n); }} // This code is contributed by PrinciRaj1992",
"e": 33412,
"s": 31398,
"text": null
},
{
"code": "<?php// PHP program to find closest 0// for every element // Print the distance with zeroes// of every elementfunction print_distance($arr, $n){ // initializes an array of size n with 0 $ans[$n] = array(); $ans = array_fill(0, $n, true); // if first element is 0 then the // distance will be 0 if ($arr[0] == 0) $ans[0] = 0; else $ans[0] = PHP_INT_MAX; // if not 0 then initialize // with a maximum value // traverse in loop from 1 to n and // store the distance from left for ( $i = 1; $i < $n; ++$i) { // add 1 to the distance from // previous one $ans[$i] = $ans[$i - 1] + 1; // if the present element is 0 // then distance will be 0 if ($arr[$i] == 0) $ans[$i] = 0; } // if last element is zero then it will // be 0 else let the answer be what was // found when traveled from left to right if ($arr[$n - 1] == 0) $ans[$n - 1] = 0; // traverse from right to left and store // the minimum of distance if found from // right to left or left to right for ($i = $n - 2; $i >= 0; --$i) { // store the minimum of distance from // left to right or right to left $ans[$i] = min($ans[$i], $ans[$i + 1] + 1); // if it is 0 then minimum will // always be 0 if ($arr[$i] == 0) $ans[$i] = 0; } // print the answer array for ($i = 0; $i < $n; ++$i) echo $ans[$i] , \" \";} // Driver Code$a = array( 2, 1, 0, 3, 0, 0, 3, 2, 4 );$n = sizeof($a);print_distance($a, $n); // This code is contributed by Sachin?>",
"e": 35056,
"s": 33412,
"text": null
},
{
"code": "<script>// javascript program to find closest// 0 for every element// Print the distance with zeroes of every element function print_distance(arr , n) { // initializes an array of size n with 0 var ans = Array(n).fill(0); // if first element is 0 then the distance // will be 0 if (arr[0] == 0) ans[0] = 0; // if not 0 then initialize // with a maximum value else ans[0] = +2147483647; // traverse in loop from 1 to n and store // the distance from left for (i = 1; i < n; ++i) { // add 1 to the distance // from previous one ans[i] = ans[i - 1] + 1; // if the present element is // 0 then distance will be 0 if (arr[i] == 0) ans[i] = 0; } // if last element is zero // then it will be 0 else // let the answer be what was // found when traveled // from left to right if (arr[n - 1] == 0) ans[n - 1] = 0; // traverse from right to // left and store the minimum // of distance if found from // right to left or left // to right for (i = n - 2; i >= 0; --i) { // store the minimum of distance // from left to right or right to left ans[i] = Math.min(ans[i], ans[i + 1] + 1); // if it is 0 then minimum // will always be 0 if (arr[i] == 0) ans[i] = 0; } // print the answer array for (i = 0; i < n; ++i) document.write(ans[i] + \" \"); } // Driver code var a = [ 2, 1, 0, 3, 0, 0, 3, 2, 4 ]; var n = a.length; print_distance(a, n); // This code is contributed by Rajput-Ji</script>",
"e": 36878,
"s": 35056,
"text": null
},
{
"code": null,
"e": 36888,
"s": 36878,
"text": "Output: "
},
{
"code": null,
"e": 36907,
"s": 36888,
"text": "2 1 0 1 0 0 1 2 3 "
},
{
"code": null,
"e": 37376,
"s": 36907,
"text": "Time complexity: O(n) Auxiliary Space: O(n)This article is contributed by Raja Vikramaditya. 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": 37386,
"s": 37376,
"text": "Sach_Code"
},
{
"code": null,
"e": 37400,
"s": 37386,
"text": "princiraj1992"
},
{
"code": null,
"e": 37415,
"s": 37400,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 37425,
"s": 37415,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 37442,
"s": 37425,
"text": "arorakashish0911"
},
{
"code": null,
"e": 37455,
"s": 37442,
"text": "simmytarika5"
},
{
"code": null,
"e": 37470,
"s": 37455,
"text": "sliding-window"
},
{
"code": null,
"e": 37477,
"s": 37470,
"text": "Arrays"
},
{
"code": null,
"e": 37492,
"s": 37477,
"text": "sliding-window"
},
{
"code": null,
"e": 37499,
"s": 37492,
"text": "Arrays"
},
{
"code": null,
"e": 37597,
"s": 37499,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37622,
"s": 37597,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 37642,
"s": 37622,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 37680,
"s": 37642,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 37765,
"s": 37680,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 37814,
"s": 37765,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 37839,
"s": 37814,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 37897,
"s": 37839,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 37918,
"s": 37897,
"text": "Next Greater Element"
},
{
"code": null,
"e": 37945,
"s": 37918,
"text": "Count pairs with given sum"
}
] |
Count triples with Bitwise AND equal to Zero - GeeksforGeeks
|
31 May, 2021
Given an array of integers A[] consisting of N integers, find the number of triples of indices (i, j, k) such that A[i] & A[j] & A[k] is 0(<0 ≤ i, j, k ≤ N and & denotes Bitwise AND operator.
Examples:
Input: A[]={2, 1, 3}Output: 12Explanation: The following i, j, k triples can be chosen whose bitwise AND is zero:(i=0, j=0, k=1) : 2 & 2 & 1(i=0, j=1, k=0) : 2 & 1 & 2(i=0, j=1, k=1) : 2 & 1 & 1(i=0, j=1, k=2) : 2 & 1 & 3(i=0, j=2, k=1) : 2 & 3 & 1(i=1, j=0, k=0) : 1 & 2 & 2(i=1, j=0, k=1) : 1 & 2 & 1(i=1, j=0, k=2) : 1 & 2 & 3(i=1, j=1, k=0) : 1 & 1 & 2(i=1, j=2, k=0) : 1 & 3 & 2(i=2, j=0, k=1) : 3 & 2 & 1(i=2, j=1, k=0) : 3 & 1 & 2
Input: A[]={21, 15, 6}Output: 0Explanation: No such triplets exist.
Approach: The idea to solve this problem is to use a Map to process the array solving elements. Follow the steps below to solve the problem:
Initialize a Map to store frequencies of every possible value of A[i] & A[j]. Also, initialize a variable answer with 0, to store the required count.
Traverse the array and for each array element, traverse the map and check for each map if key, if it’s Bitwise AND with the current array element is 0 or not. For every array element for which it is found to be true, increase answer by frequency of the key.
After completing the traversal of the array, print answer.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>#include <iostream>using namespace std; // Function to find the number of// triplets whose Bitwise AND is 0.int countTriplets(vector<int>& A){ // Stores the count of triplets // having bitwise AND equal to 0 int cnt = 0; // Stores frequencies of all possible A[i] & A[j] unordered_map<int, int> tuples; // Traverse the array for (auto a : A) // Update frequency of Bitwise AND // of all array elements with a for (auto b : A) ++tuples[a & b]; // Traverse the array for (auto a : A) // Iterate the map for (auto t : tuples) // If bitwise AND of triplet // is zero, increment cnt if ((t.first & a) == 0) cnt += t.second; // Return the number of triplets // whose Bitwise AND is 0. return cnt;} // Driver Codeint main(){ // Input Array vector<int> A = { 2, 1, 3 }; // Function Call cout << countTriplets(A); return 0;}
// Java program for the above approachimport java.util.*;class GFG{ // Function to find the number of// triplets whose Bitwise AND is 0.static int countTriplets(int []A){ // Stores the count of triplets // having bitwise AND equal to 0 int cnt = 0; // Stores frequencies of all possible A[i] & A[j] HashMap<Integer,Integer> tuples = new HashMap<Integer,Integer>(); // Traverse the array for (int a : A) // Update frequency of Bitwise AND // of all array elements with a for (int b : A) { if(tuples.containsKey(a & b)) tuples.put(a & b, tuples.get(a & b) + 1); else tuples.put(a & b, 1); } // Traverse the array for (int a : A) // Iterate the map for (Map.Entry<Integer, Integer> t : tuples.entrySet()) // If bitwise AND of triplet // is zero, increment cnt if ((t.getKey() & a) == 0) cnt += t.getValue(); // Return the number of triplets // whose Bitwise AND is 0. return cnt;} // Driver Codepublic static void main(String[] args){ // Input Array int []A = { 2, 1, 3 }; // Function Call System.out.print(countTriplets(A));}} // This code is contributed by shikhasingrajput
# Python3 program for the above approach # Function to find the number of# triplets whose Bitwise AND is 0.def countTriplets(A) : # Stores the count of triplets # having bitwise AND equal to 0 cnt = 0; # Stores frequencies of all possible A[i] & A[j] tuples = {}; # Traverse the array for a in A: # Update frequency of Bitwise AND # of all array elements with a for b in A: if (a & b) in tuples: tuples[a & b] += 1; else: tuples[a & b] = 1; # Traverse the array for a in A: # Iterate the map for t in tuples: # If bitwise AND of triplet # is zero, increment cnt if ((t & a) == 0): cnt += tuples[t]; # Return the number of triplets # whose Bitwise AND is 0. return cnt; # Driver Codeif __name__ == "__main__" : # Input Array A = [ 2, 1, 3 ]; # Function Call print(countTriplets(A)); # This code is contributed by AnkThon
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the number of// triplets whose Bitwise AND is 0.static int countTriplets(int []A){ // Stores the count of triplets // having bitwise AND equal to 0 int cnt = 0; // Stores frequencies of all possible A[i] & A[j] Dictionary<int,int> tuples = new Dictionary<int,int>(); // Traverse the array foreach (int a in A) // Update frequency of Bitwise AND // of all array elements with a foreach (int b in A) { if(tuples.ContainsKey(a & b)) tuples[a & b] = tuples[a & b] + 1; else tuples.Add(a & b, 1); } // Traverse the array foreach (int a in A) // Iterate the map foreach (KeyValuePair<int, int> t in tuples) // If bitwise AND of triplet // is zero, increment cnt if ((t.Key & a) == 0) cnt += t.Value; // Return the number of triplets // whose Bitwise AND is 0. return cnt;} // Driver Codepublic static void Main(String[] args){ // Input Array int []A = { 2, 1, 3 }; // Function Call Console.Write(countTriplets(A));}} // This code is contributed by 29AjayKumar
<script> // Javascript program for the above approach // Function to find the number of// triplets whose Bitwise AND is 0.function countTriplets(A){ // Stores the count of triplets // having bitwise AND equal to 0 var cnt = 0; // Stores frequencies of all possible A[i] & A[j] var tuples = new Map(); // Traverse the array A.forEach(a => { // Update frequency of Bitwise AND // of all array elements with a A.forEach(b => { if(tuples.has(a & b)) tuples.set(a & b, tuples.get(a & b)+1) else tuples.set(a & b, 1) }); }); // Traverse the array A.forEach(a => { // Update frequency of Bitwise AND // of all array elements with a tuples.forEach((value, key) => { // If bitwise AND of triplet // is zero, increment cnt if ((key & a) == 0) cnt += value; }); }); // Return the number of triplets // whose Bitwise AND is 0. return cnt;} // Driver Code// Input Arrayvar A = [2, 1, 3];// Function Calldocument.write( countTriplets(A)); </script>
12
Time Complexity: O(max(M, N2)) where M is the maximum element present in the given arrayAuxiliary Space: O(M)
shikhasingrajput
ankthon
29AjayKumar
importantly
Bitwise-AND
frequency-counting
Arrays
Bit Magic
Dynamic Programming
Hash
Mathematical
Arrays
Hash
Dynamic Programming
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Cyclic Redundancy Check and Modulo-2 Division
Count set bits in an integer
|
[
{
"code": null,
"e": 25168,
"s": 25140,
"text": "\n31 May, 2021"
},
{
"code": null,
"e": 25360,
"s": 25168,
"text": "Given an array of integers A[] consisting of N integers, find the number of triples of indices (i, j, k) such that A[i] & A[j] & A[k] is 0(<0 ≤ i, j, k ≤ N and & denotes Bitwise AND operator."
},
{
"code": null,
"e": 25370,
"s": 25360,
"text": "Examples:"
},
{
"code": null,
"e": 25808,
"s": 25370,
"text": "Input: A[]={2, 1, 3}Output: 12Explanation: The following i, j, k triples can be chosen whose bitwise AND is zero:(i=0, j=0, k=1) : 2 & 2 & 1(i=0, j=1, k=0) : 2 & 1 & 2(i=0, j=1, k=1) : 2 & 1 & 1(i=0, j=1, k=2) : 2 & 1 & 3(i=0, j=2, k=1) : 2 & 3 & 1(i=1, j=0, k=0) : 1 & 2 & 2(i=1, j=0, k=1) : 1 & 2 & 1(i=1, j=0, k=2) : 1 & 2 & 3(i=1, j=1, k=0) : 1 & 1 & 2(i=1, j=2, k=0) : 1 & 3 & 2(i=2, j=0, k=1) : 3 & 2 & 1(i=2, j=1, k=0) : 3 & 1 & 2"
},
{
"code": null,
"e": 25876,
"s": 25808,
"text": "Input: A[]={21, 15, 6}Output: 0Explanation: No such triplets exist."
},
{
"code": null,
"e": 26017,
"s": 25876,
"text": "Approach: The idea to solve this problem is to use a Map to process the array solving elements. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 26167,
"s": 26017,
"text": "Initialize a Map to store frequencies of every possible value of A[i] & A[j]. Also, initialize a variable answer with 0, to store the required count."
},
{
"code": null,
"e": 26425,
"s": 26167,
"text": "Traverse the array and for each array element, traverse the map and check for each map if key, if it’s Bitwise AND with the current array element is 0 or not. For every array element for which it is found to be true, increase answer by frequency of the key."
},
{
"code": null,
"e": 26484,
"s": 26425,
"text": "After completing the traversal of the array, print answer."
},
{
"code": null,
"e": 26535,
"s": 26484,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26539,
"s": 26535,
"text": "C++"
},
{
"code": null,
"e": 26544,
"s": 26539,
"text": "Java"
},
{
"code": null,
"e": 26552,
"s": 26544,
"text": "Python3"
},
{
"code": null,
"e": 26555,
"s": 26552,
"text": "C#"
},
{
"code": null,
"e": 26566,
"s": 26555,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>#include <iostream>using namespace std; // Function to find the number of// triplets whose Bitwise AND is 0.int countTriplets(vector<int>& A){ // Stores the count of triplets // having bitwise AND equal to 0 int cnt = 0; // Stores frequencies of all possible A[i] & A[j] unordered_map<int, int> tuples; // Traverse the array for (auto a : A) // Update frequency of Bitwise AND // of all array elements with a for (auto b : A) ++tuples[a & b]; // Traverse the array for (auto a : A) // Iterate the map for (auto t : tuples) // If bitwise AND of triplet // is zero, increment cnt if ((t.first & a) == 0) cnt += t.second; // Return the number of triplets // whose Bitwise AND is 0. return cnt;} // Driver Codeint main(){ // Input Array vector<int> A = { 2, 1, 3 }; // Function Call cout << countTriplets(A); return 0;}",
"e": 27599,
"s": 26566,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to find the number of// triplets whose Bitwise AND is 0.static int countTriplets(int []A){ // Stores the count of triplets // having bitwise AND equal to 0 int cnt = 0; // Stores frequencies of all possible A[i] & A[j] HashMap<Integer,Integer> tuples = new HashMap<Integer,Integer>(); // Traverse the array for (int a : A) // Update frequency of Bitwise AND // of all array elements with a for (int b : A) { if(tuples.containsKey(a & b)) tuples.put(a & b, tuples.get(a & b) + 1); else tuples.put(a & b, 1); } // Traverse the array for (int a : A) // Iterate the map for (Map.Entry<Integer, Integer> t : tuples.entrySet()) // If bitwise AND of triplet // is zero, increment cnt if ((t.getKey() & a) == 0) cnt += t.getValue(); // Return the number of triplets // whose Bitwise AND is 0. return cnt;} // Driver Codepublic static void main(String[] args){ // Input Array int []A = { 2, 1, 3 }; // Function Call System.out.print(countTriplets(A));}} // This code is contributed by shikhasingrajput",
"e": 28881,
"s": 27599,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the number of# triplets whose Bitwise AND is 0.def countTriplets(A) : # Stores the count of triplets # having bitwise AND equal to 0 cnt = 0; # Stores frequencies of all possible A[i] & A[j] tuples = {}; # Traverse the array for a in A: # Update frequency of Bitwise AND # of all array elements with a for b in A: if (a & b) in tuples: tuples[a & b] += 1; else: tuples[a & b] = 1; # Traverse the array for a in A: # Iterate the map for t in tuples: # If bitwise AND of triplet # is zero, increment cnt if ((t & a) == 0): cnt += tuples[t]; # Return the number of triplets # whose Bitwise AND is 0. return cnt; # Driver Codeif __name__ == \"__main__\" : # Input Array A = [ 2, 1, 3 ]; # Function Call print(countTriplets(A)); # This code is contributed by AnkThon",
"e": 29922,
"s": 28881,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the number of// triplets whose Bitwise AND is 0.static int countTriplets(int []A){ // Stores the count of triplets // having bitwise AND equal to 0 int cnt = 0; // Stores frequencies of all possible A[i] & A[j] Dictionary<int,int> tuples = new Dictionary<int,int>(); // Traverse the array foreach (int a in A) // Update frequency of Bitwise AND // of all array elements with a foreach (int b in A) { if(tuples.ContainsKey(a & b)) tuples[a & b] = tuples[a & b] + 1; else tuples.Add(a & b, 1); } // Traverse the array foreach (int a in A) // Iterate the map foreach (KeyValuePair<int, int> t in tuples) // If bitwise AND of triplet // is zero, increment cnt if ((t.Key & a) == 0) cnt += t.Value; // Return the number of triplets // whose Bitwise AND is 0. return cnt;} // Driver Codepublic static void Main(String[] args){ // Input Array int []A = { 2, 1, 3 }; // Function Call Console.Write(countTriplets(A));}} // This code is contributed by 29AjayKumar",
"e": 31199,
"s": 29922,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to find the number of// triplets whose Bitwise AND is 0.function countTriplets(A){ // Stores the count of triplets // having bitwise AND equal to 0 var cnt = 0; // Stores frequencies of all possible A[i] & A[j] var tuples = new Map(); // Traverse the array A.forEach(a => { // Update frequency of Bitwise AND // of all array elements with a A.forEach(b => { if(tuples.has(a & b)) tuples.set(a & b, tuples.get(a & b)+1) else tuples.set(a & b, 1) }); }); // Traverse the array A.forEach(a => { // Update frequency of Bitwise AND // of all array elements with a tuples.forEach((value, key) => { // If bitwise AND of triplet // is zero, increment cnt if ((key & a) == 0) cnt += value; }); }); // Return the number of triplets // whose Bitwise AND is 0. return cnt;} // Driver Code// Input Arrayvar A = [2, 1, 3];// Function Calldocument.write( countTriplets(A)); </script>",
"e": 32385,
"s": 31199,
"text": null
},
{
"code": null,
"e": 32391,
"s": 32388,
"text": "12"
},
{
"code": null,
"e": 32503,
"s": 32393,
"text": "Time Complexity: O(max(M, N2)) where M is the maximum element present in the given arrayAuxiliary Space: O(M)"
},
{
"code": null,
"e": 32520,
"s": 32503,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 32528,
"s": 32520,
"text": "ankthon"
},
{
"code": null,
"e": 32540,
"s": 32528,
"text": "29AjayKumar"
},
{
"code": null,
"e": 32552,
"s": 32540,
"text": "importantly"
},
{
"code": null,
"e": 32564,
"s": 32552,
"text": "Bitwise-AND"
},
{
"code": null,
"e": 32583,
"s": 32564,
"text": "frequency-counting"
},
{
"code": null,
"e": 32590,
"s": 32583,
"text": "Arrays"
},
{
"code": null,
"e": 32600,
"s": 32590,
"text": "Bit Magic"
},
{
"code": null,
"e": 32620,
"s": 32600,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 32625,
"s": 32620,
"text": "Hash"
},
{
"code": null,
"e": 32638,
"s": 32625,
"text": "Mathematical"
},
{
"code": null,
"e": 32645,
"s": 32638,
"text": "Arrays"
},
{
"code": null,
"e": 32650,
"s": 32645,
"text": "Hash"
},
{
"code": null,
"e": 32670,
"s": 32650,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 32683,
"s": 32670,
"text": "Mathematical"
},
{
"code": null,
"e": 32693,
"s": 32683,
"text": "Bit Magic"
},
{
"code": null,
"e": 32791,
"s": 32693,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32800,
"s": 32791,
"text": "Comments"
},
{
"code": null,
"e": 32813,
"s": 32800,
"text": "Old Comments"
},
{
"code": null,
"e": 32857,
"s": 32813,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 32889,
"s": 32857,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 32912,
"s": 32889,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 32926,
"s": 32912,
"text": "Linear Search"
},
{
"code": null,
"e": 32994,
"s": 32926,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 33021,
"s": 32994,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 33067,
"s": 33021,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 33135,
"s": 33067,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 33181,
"s": 33135,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
}
] |
Logistic Regression Explained. [ — Logistic Regression explained... | by z_ai | Towards Data Science
|
In this post, I will explain Logistic Regression in simple terms. It could be considered a Logistic Regression for dummies post, however, I’ve never really liked that expression.
Before we start, here you have some additional resources to skyrocket your Machine Learning career:
Awesome Machine Learning Resources:- For learning resources go to How to Learn Machine Learning! - For professional resources (jobs, events, skill tests) go to AIgents.co — A career community for Data Scientists & Machine Learning Engineers.
z-ai.medium.com
Lets get to it and learn it all about Logistic Regression.
In the Machine Learning world, Logistic Regression is a kind of parametric classification model, despite having the word ‘regression’ in its name.
This means that logistic regression models are models that have a certain fixed number of parameters that depend on the number of input features, and they output categorical prediction, like for example if a plant belongs to a certain species or not.
In reality, the theory behind Logistic Regression is very similar to the one from Linear Regression, so if you don’t know what Linear Regression is, take 5 minutes to read this super easy guide:
towardsdatascience.com
In Logistic Regression, we don’t directly fit a straight line to our data like in linear regression. Instead, we fit a S shaped curve, called Sigmoid, to our observations.
Let's examine this figure closely.
First of all, like we said before, Logistic Regression models are classification models; specifically binary classification models (they can only be used to distinguish between 2 different categories — like if a person is obese or not given its weight, or if a house is big or small given its size). This means that our data has two kinds of observations (Category 1 and Category 2 observations) like we can observe in the figure.
Note: This is a very simple example of Logistic Regression, in practice much harder problems can be solved using these models, using a wide range of features and not just a single one.
Secondly, as we can see, the Y-axis goes from 0 to 1. This is because the sigmoid function always takes as maximum and minimum these two values, and this fits very well our goal of classifying samples in two different categories. By computing the sigmoid function of X (that is a weighted sum of the input features, just like in Linear Regression), we get a probability (between 0 and 1 obviously) of an observation belonging to one of the two categories.
The formula for the sigmoid function is the following:
If we wanted to predict if a person was obese or not given their weight, we would first compute a weighted sum of their weight (sorry for the lexical redundancy) and then input this into the sigmoid function:
Alright, this looks cool and all, but isn’t this meant to be a Machine Learning model? How do we train it? That is a good question. There are multiple ways to train a Logistic Regression model (fit the S shaped line to our data). We can use an iterative optimisation algorithm like Gradient Descent to calculate the parameters of the model (the weights) or we can use probabilistic methods like Maximum likelihood.
If you don’t know what any of these are, Gradient Descent was explained in the Linear Regression post, and an explanation of Maximum Likelihood for Machine Learning can be found here:
towardsdatascience.com
Once we have used one of these methods to train our model, we are ready to make some predictions. Let's see an example of how the process of training a Logistic Regression model and using it to make predictions would go:
First, we would collect a Dataset of patients who have and who have not been diagnosed as obese, along with their corresponding weights.After this, we would train our model, to fit our S shape line to the data and obtain the parameters of the model. After training using Maximum Likelihood, we got the following parameters:
First, we would collect a Dataset of patients who have and who have not been diagnosed as obese, along with their corresponding weights.
After this, we would train our model, to fit our S shape line to the data and obtain the parameters of the model. After training using Maximum Likelihood, we got the following parameters:
3. Now, we are ready to make some predictions: imagine we got two patients; one is 120 kg and one is 60 kg. Let's see what happens when we plug these numbers into the model:
As we can see, the first patient (60 kg) has a very low probability of being obese, however, the second one (120 kg) has a very high one.
In the previous figure, we can see the results given by the Logistic Regression model for the discussed examples. Now, given the weight of any patient, we could calculate their probability of being obese, and give our doctors a quick first round of information!
z-ai.medium.com
Logistic regression is one of the most simple Machine Learning models. They are easy to understand, interpretable, and can give pretty good results. The goal of this post was to provide an easy way to understand logistic regression in a non-mathematical manner for people who are not Machine Learning practitioners, so if you want to go deeper, or are looking for a more profound of mathematical explanation, take a look at the following video, it explains very well everything we have mentioned in this post.
For further resources on Machine Learning and Data Science check out the following repository: How to Learn Machine Learning! For career resources (jobs, events, skill tests) go to AIgents.co — A career community for Data Scientists & Machine Learning Engineers.
Awesome Logistic Regression!
Also, to go further into Logistic Regression and Machine Learning in general, take a look at the book described in the following article:
|
[
{
"code": null,
"e": 350,
"s": 171,
"text": "In this post, I will explain Logistic Regression in simple terms. It could be considered a Logistic Regression for dummies post, however, I’ve never really liked that expression."
},
{
"code": null,
"e": 450,
"s": 350,
"text": "Before we start, here you have some additional resources to skyrocket your Machine Learning career:"
},
{
"code": null,
"e": 692,
"s": 450,
"text": "Awesome Machine Learning Resources:- For learning resources go to How to Learn Machine Learning! - For professional resources (jobs, events, skill tests) go to AIgents.co — A career community for Data Scientists & Machine Learning Engineers."
},
{
"code": null,
"e": 708,
"s": 692,
"text": "z-ai.medium.com"
},
{
"code": null,
"e": 767,
"s": 708,
"text": "Lets get to it and learn it all about Logistic Regression."
},
{
"code": null,
"e": 914,
"s": 767,
"text": "In the Machine Learning world, Logistic Regression is a kind of parametric classification model, despite having the word ‘regression’ in its name."
},
{
"code": null,
"e": 1165,
"s": 914,
"text": "This means that logistic regression models are models that have a certain fixed number of parameters that depend on the number of input features, and they output categorical prediction, like for example if a plant belongs to a certain species or not."
},
{
"code": null,
"e": 1360,
"s": 1165,
"text": "In reality, the theory behind Logistic Regression is very similar to the one from Linear Regression, so if you don’t know what Linear Regression is, take 5 minutes to read this super easy guide:"
},
{
"code": null,
"e": 1383,
"s": 1360,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1555,
"s": 1383,
"text": "In Logistic Regression, we don’t directly fit a straight line to our data like in linear regression. Instead, we fit a S shaped curve, called Sigmoid, to our observations."
},
{
"code": null,
"e": 1590,
"s": 1555,
"text": "Let's examine this figure closely."
},
{
"code": null,
"e": 2021,
"s": 1590,
"text": "First of all, like we said before, Logistic Regression models are classification models; specifically binary classification models (they can only be used to distinguish between 2 different categories — like if a person is obese or not given its weight, or if a house is big or small given its size). This means that our data has two kinds of observations (Category 1 and Category 2 observations) like we can observe in the figure."
},
{
"code": null,
"e": 2206,
"s": 2021,
"text": "Note: This is a very simple example of Logistic Regression, in practice much harder problems can be solved using these models, using a wide range of features and not just a single one."
},
{
"code": null,
"e": 2662,
"s": 2206,
"text": "Secondly, as we can see, the Y-axis goes from 0 to 1. This is because the sigmoid function always takes as maximum and minimum these two values, and this fits very well our goal of classifying samples in two different categories. By computing the sigmoid function of X (that is a weighted sum of the input features, just like in Linear Regression), we get a probability (between 0 and 1 obviously) of an observation belonging to one of the two categories."
},
{
"code": null,
"e": 2717,
"s": 2662,
"text": "The formula for the sigmoid function is the following:"
},
{
"code": null,
"e": 2926,
"s": 2717,
"text": "If we wanted to predict if a person was obese or not given their weight, we would first compute a weighted sum of their weight (sorry for the lexical redundancy) and then input this into the sigmoid function:"
},
{
"code": null,
"e": 3341,
"s": 2926,
"text": "Alright, this looks cool and all, but isn’t this meant to be a Machine Learning model? How do we train it? That is a good question. There are multiple ways to train a Logistic Regression model (fit the S shaped line to our data). We can use an iterative optimisation algorithm like Gradient Descent to calculate the parameters of the model (the weights) or we can use probabilistic methods like Maximum likelihood."
},
{
"code": null,
"e": 3525,
"s": 3341,
"text": "If you don’t know what any of these are, Gradient Descent was explained in the Linear Regression post, and an explanation of Maximum Likelihood for Machine Learning can be found here:"
},
{
"code": null,
"e": 3548,
"s": 3525,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3769,
"s": 3548,
"text": "Once we have used one of these methods to train our model, we are ready to make some predictions. Let's see an example of how the process of training a Logistic Regression model and using it to make predictions would go:"
},
{
"code": null,
"e": 4093,
"s": 3769,
"text": "First, we would collect a Dataset of patients who have and who have not been diagnosed as obese, along with their corresponding weights.After this, we would train our model, to fit our S shape line to the data and obtain the parameters of the model. After training using Maximum Likelihood, we got the following parameters:"
},
{
"code": null,
"e": 4230,
"s": 4093,
"text": "First, we would collect a Dataset of patients who have and who have not been diagnosed as obese, along with their corresponding weights."
},
{
"code": null,
"e": 4418,
"s": 4230,
"text": "After this, we would train our model, to fit our S shape line to the data and obtain the parameters of the model. After training using Maximum Likelihood, we got the following parameters:"
},
{
"code": null,
"e": 4592,
"s": 4418,
"text": "3. Now, we are ready to make some predictions: imagine we got two patients; one is 120 kg and one is 60 kg. Let's see what happens when we plug these numbers into the model:"
},
{
"code": null,
"e": 4730,
"s": 4592,
"text": "As we can see, the first patient (60 kg) has a very low probability of being obese, however, the second one (120 kg) has a very high one."
},
{
"code": null,
"e": 4992,
"s": 4730,
"text": "In the previous figure, we can see the results given by the Logistic Regression model for the discussed examples. Now, given the weight of any patient, we could calculate their probability of being obese, and give our doctors a quick first round of information!"
},
{
"code": null,
"e": 5008,
"s": 4992,
"text": "z-ai.medium.com"
},
{
"code": null,
"e": 5518,
"s": 5008,
"text": "Logistic regression is one of the most simple Machine Learning models. They are easy to understand, interpretable, and can give pretty good results. The goal of this post was to provide an easy way to understand logistic regression in a non-mathematical manner for people who are not Machine Learning practitioners, so if you want to go deeper, or are looking for a more profound of mathematical explanation, take a look at the following video, it explains very well everything we have mentioned in this post."
},
{
"code": null,
"e": 5781,
"s": 5518,
"text": "For further resources on Machine Learning and Data Science check out the following repository: How to Learn Machine Learning! For career resources (jobs, events, skill tests) go to AIgents.co — A career community for Data Scientists & Machine Learning Engineers."
},
{
"code": null,
"e": 5810,
"s": 5781,
"text": "Awesome Logistic Regression!"
}
] |
Through the proxy — conda, git and pip | by Thomas Bury | Towards Data Science
|
Have you ever been tempted to burn your company down to ashes, up to the last server and leave to start a hermit life in the Siberian tundra because of the company’s proxy?
If yes, don’t buy yet your survival kit. Here is an effortless way to automate the proxy settings for Conda, GIT and pip in a single step.
When working for a company, you will, most than likely, be working with a proxy. Without setting the proxy, conda, pip and git will not be able to connect to the outside world. And therefore, you’ll not be able to install packages and reach out GitHub or any remote VCS.
The security settings might also prevent you to download packages. For setting up conda, pip and git, you can either modify manually the configuration files (e.g. .condarc and pip.ini). However, that can be painful. Especially if there are several users on the laptop. You can also use the command line way but that can be tedious to remember the commands for the three components.
For simplifying the proxy, settings, I’m using either a PowerShell script or a batch script (yes, my company laptop is a windows machine) that you can find in this repo. I’ll explain how to use them to set up the proxy in a single and easy step.
If you can run PowerShell scripts, the easiest is to proceed as follows. If you can’t, I explain at the end how to use a batch script to achieve the same results, still in single step.
Save the PowerShell script cpg-config.ps1 script in a folder of your choice
Open a Windows PowerShell (or an anaconda PowerShell if you have one), ideally as admin (right click --> run as admin)
Navigate to the folder where you saved the script: cd c:\user\folder_name
Run the script: .\cpg-config.ps1 [proxy_address] then enter
PS C:\WINDOWS\system32> cd C:\Users\Projects\cgp-proxyPS C:\Users\Projects\cgp-proxy> .\cpg-config.ps1 [proxy_address]
just replace `[proxy_address]` by your proxy address and all, conda, git and pip will be configured.
You can also configure only one or two of the three components using the optional argument as:
PS C:\WINDOWS\system32> cd C:\Users\Projects\cgp-proxyPS C:\Users\Projects\cgp-proxy> .\cpg-config.ps1 [proxy_address] pip
for configuring only pip for instance. The other possible values are all, conda, pip, git, git-conda, git-pip, conda-pip.
Note that for conda, the script will update the channel order to put defaults as the highest priority and disable ssl_verify.
After running the script, conda, pip and git should be able to connect to the different servers without any issue
While trying to run the PowerShell script, you might encounter the error not digitally signed. If so, you can type the following command in the PowerShell window:
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
And type “yes” or “yes to all”
In case conda is not recognize by PowerShell, simply open an anaconda prompt, and use the command
conda init powershell
This step is only necessary for conda users. If you want only to configure pip and git, you can simply use
PS C:\WINDOWS\system32> cd C:\Users\Projects\cgp-proxyPS C:\Users\Projects\cgp-proxy> .\cpg-config.ps1 [proxy_address] git-pip
The “git-pip” value of the optional argument will make the script bypass the conda part of the script.
If you prefer using the command prompt rather than PowerShell, you can use the batch script as follows
Save the cpg-config.bat script in a folder of your choice
Open a Command Prompt, ideally as admin (right click --> run as admin). It is equivalent to do it with Anaconda CMD, not mandatory though.
navigate to the folder where you saved the script: cd c:\user\folder_name
use this command line: cpg-config.bat [proxy_url] all flexible then enter. Replace [proxy_url] by your proxy url (e.g. https://xyz.proxy.company-name:8080)
Of course, you can unset the proxy at any time using
conda config --remove-key proxy_servers.httppip config unset global.proxygit config --global --unset http.proxy
|
[
{
"code": null,
"e": 345,
"s": 172,
"text": "Have you ever been tempted to burn your company down to ashes, up to the last server and leave to start a hermit life in the Siberian tundra because of the company’s proxy?"
},
{
"code": null,
"e": 484,
"s": 345,
"text": "If yes, don’t buy yet your survival kit. Here is an effortless way to automate the proxy settings for Conda, GIT and pip in a single step."
},
{
"code": null,
"e": 755,
"s": 484,
"text": "When working for a company, you will, most than likely, be working with a proxy. Without setting the proxy, conda, pip and git will not be able to connect to the outside world. And therefore, you’ll not be able to install packages and reach out GitHub or any remote VCS."
},
{
"code": null,
"e": 1137,
"s": 755,
"text": "The security settings might also prevent you to download packages. For setting up conda, pip and git, you can either modify manually the configuration files (e.g. .condarc and pip.ini). However, that can be painful. Especially if there are several users on the laptop. You can also use the command line way but that can be tedious to remember the commands for the three components."
},
{
"code": null,
"e": 1383,
"s": 1137,
"text": "For simplifying the proxy, settings, I’m using either a PowerShell script or a batch script (yes, my company laptop is a windows machine) that you can find in this repo. I’ll explain how to use them to set up the proxy in a single and easy step."
},
{
"code": null,
"e": 1568,
"s": 1383,
"text": "If you can run PowerShell scripts, the easiest is to proceed as follows. If you can’t, I explain at the end how to use a batch script to achieve the same results, still in single step."
},
{
"code": null,
"e": 1644,
"s": 1568,
"text": "Save the PowerShell script cpg-config.ps1 script in a folder of your choice"
},
{
"code": null,
"e": 1763,
"s": 1644,
"text": "Open a Windows PowerShell (or an anaconda PowerShell if you have one), ideally as admin (right click --> run as admin)"
},
{
"code": null,
"e": 1837,
"s": 1763,
"text": "Navigate to the folder where you saved the script: cd c:\\user\\folder_name"
},
{
"code": null,
"e": 1897,
"s": 1837,
"text": "Run the script: .\\cpg-config.ps1 [proxy_address] then enter"
},
{
"code": null,
"e": 2016,
"s": 1897,
"text": "PS C:\\WINDOWS\\system32> cd C:\\Users\\Projects\\cgp-proxyPS C:\\Users\\Projects\\cgp-proxy> .\\cpg-config.ps1 [proxy_address]"
},
{
"code": null,
"e": 2117,
"s": 2016,
"text": "just replace `[proxy_address]` by your proxy address and all, conda, git and pip will be configured."
},
{
"code": null,
"e": 2212,
"s": 2117,
"text": "You can also configure only one or two of the three components using the optional argument as:"
},
{
"code": null,
"e": 2335,
"s": 2212,
"text": "PS C:\\WINDOWS\\system32> cd C:\\Users\\Projects\\cgp-proxyPS C:\\Users\\Projects\\cgp-proxy> .\\cpg-config.ps1 [proxy_address] pip"
},
{
"code": null,
"e": 2457,
"s": 2335,
"text": "for configuring only pip for instance. The other possible values are all, conda, pip, git, git-conda, git-pip, conda-pip."
},
{
"code": null,
"e": 2583,
"s": 2457,
"text": "Note that for conda, the script will update the channel order to put defaults as the highest priority and disable ssl_verify."
},
{
"code": null,
"e": 2697,
"s": 2583,
"text": "After running the script, conda, pip and git should be able to connect to the different servers without any issue"
},
{
"code": null,
"e": 2860,
"s": 2697,
"text": "While trying to run the PowerShell script, you might encounter the error not digitally signed. If so, you can type the following command in the PowerShell window:"
},
{
"code": null,
"e": 2919,
"s": 2860,
"text": "Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass"
},
{
"code": null,
"e": 2950,
"s": 2919,
"text": "And type “yes” or “yes to all”"
},
{
"code": null,
"e": 3048,
"s": 2950,
"text": "In case conda is not recognize by PowerShell, simply open an anaconda prompt, and use the command"
},
{
"code": null,
"e": 3070,
"s": 3048,
"text": "conda init powershell"
},
{
"code": null,
"e": 3177,
"s": 3070,
"text": "This step is only necessary for conda users. If you want only to configure pip and git, you can simply use"
},
{
"code": null,
"e": 3304,
"s": 3177,
"text": "PS C:\\WINDOWS\\system32> cd C:\\Users\\Projects\\cgp-proxyPS C:\\Users\\Projects\\cgp-proxy> .\\cpg-config.ps1 [proxy_address] git-pip"
},
{
"code": null,
"e": 3407,
"s": 3304,
"text": "The “git-pip” value of the optional argument will make the script bypass the conda part of the script."
},
{
"code": null,
"e": 3510,
"s": 3407,
"text": "If you prefer using the command prompt rather than PowerShell, you can use the batch script as follows"
},
{
"code": null,
"e": 3568,
"s": 3510,
"text": "Save the cpg-config.bat script in a folder of your choice"
},
{
"code": null,
"e": 3707,
"s": 3568,
"text": "Open a Command Prompt, ideally as admin (right click --> run as admin). It is equivalent to do it with Anaconda CMD, not mandatory though."
},
{
"code": null,
"e": 3781,
"s": 3707,
"text": "navigate to the folder where you saved the script: cd c:\\user\\folder_name"
},
{
"code": null,
"e": 3937,
"s": 3781,
"text": "use this command line: cpg-config.bat [proxy_url] all flexible then enter. Replace [proxy_url] by your proxy url (e.g. https://xyz.proxy.company-name:8080)"
},
{
"code": null,
"e": 3990,
"s": 3937,
"text": "Of course, you can unset the proxy at any time using"
}
] |
Nodejs | Web Crawling using Cheerio - GeeksforGeeks
|
10 Nov, 2021
By sending HTTP request to a particular URL and then by extracting HTML of that web page for getting useful information is known as crawling or web scraping.
Modules to be used for crawling in Nodejs:
request: For sending HTTP request to the URLcheerio: For parsing DOM and extracting HTML of web pagefs: For reading or writing the data into the file
request: For sending HTTP request to the URL
cheerio: For parsing DOM and extracting HTML of web page
fs: For reading or writing the data into the file
Installation of these modules:The easiest way to install modules in Nodejs is using NPM.it can be done in two ways:
Globally Installation: If we install any module globally then we can use it anywhere in our system.It can be done by the following command:npm i -g package_nameLocally Installation: If we install any module locally then we can use it only within that particular project directory.It can be done by the following command:npm i package_name
Globally Installation: If we install any module globally then we can use it anywhere in our system.It can be done by the following command:npm i -g package_name
npm i -g package_name
Locally Installation: If we install any module locally then we can use it only within that particular project directory.It can be done by the following command:npm i package_name
npm i package_name
For this task we will use the local installation:
Steps for Web Crawling using Cheerio:
Step 1: create a folder for this project
Step 2: Open the terminal inside the project directory and then type the following command:npm initIt will create a file namedpackage.jsonwhich contains all information about the modules, author, github repository and its versions as well.For know more about package.json please visit this link:explanation of package.jsonTo install the modules locally using NPM simply do:npm install request
npm install cheerio
npm install fs
This can be done in the single line as well using NPM:npm install request cheerio fsAfter successfully installing modules our package.json will have structure like this :Here in this screenshot we can see all our dependencies have been listed within the dependencies object, It implies we have successfully installed all of them in our current project directory.
npm init
It will create a file named
package.json
which contains all information about the modules, author, github repository and its versions as well.For know more about package.json please visit this link:explanation of package.json
To install the modules locally using NPM simply do:
npm install request
npm install cheerio
npm install fs
This can be done in the single line as well using NPM:
npm install request cheerio fs
After successfully installing modules our package.json will have structure like this :
Here in this screenshot we can see all our dependencies have been listed within the dependencies object, It implies we have successfully installed all of them in our current project directory.
Step 3: Now we will code for crawlerSteps for coding:First we will import all our required modulesThen, we will send a HTTP request to the URL and then server of the desired website will respond with an web page, it will be done with the request moduleNow, we have the HTML of the web page, our task is to extract the useful information from it, so we will traverse the DOM tree and will find out the selectorsAfter extracting our information, we will save it into a file, this task will be done with the help of fs moduleCode for Crawler:Create a file called server.js and add the following lines:const request = require('request');
const cheerio = require('cheerio');
const mongoose = require('fs');
Explanation of these lines of code:Here in these three lines, we are importing all these three modules, required for crawling and data saving into a file.We will hit the URL from where we want to crawl data:Here we are going to crawl the list of smartphones from an e-commerce website Flipkart.URL for showing smartphones list are as follows in flipkart:const URL = "https://www.flipkart.com/search?q=mobiles";On this URL web page looks like this:Now we will hit this URL with the help ofrequestmodule:request(URL, function (err, res, body) {
if(err)
{
console.log(err, "error occured while hitting URL");
}
else
{
console.log(body);
}
});
Let’s understand these piece of code:Here we are using request module to send the HTTP request to the flipkart’s URL of smartphones, and the function within the request module takes three parameters error, response, body respectively.Here if error comes then we log it otherwise we log the body.For testing it, when we will run our script bynode server.jswe can see the whole HTML of the page in our console.It is the complete HTML of the web page for this URL.Now our task is to extract the useful information so we will visit the DOM tree and find out the selectors by inspecting element.For doing it right click on the web page and go to the inspect element like it:Now we will visit the DOM:Now we will change our request to hit the URL accordingly to the inspection:request(URL, function (err, res, body) {
if(err)
{
console.log(err);
}
else
{
let $ = cheerio.load(body); //loading of complete HTML body
$('div._1HmYoV > div.col-10-12>div.bhgxx2>div._3O0U0u').each(function(index){
const link = $(this).find('div._1UoZlX>a').attr('href');
const name = $(this).find('div._1-2Iqu>div.col-7-12>div._3wU53n').text();
console.log(link); //link for smartphone
console.log(name); //name of smartphone
});
}
});
Saving the data into the fileFor doing it we will create an array and an objectlet arr = []; //creating an array
let object =
{
link : link,
name : name,
} //creating an object
fs.writeFile('data.txt', arr, function (err) {
if(err) {
console.log(err);
}
else{
console.log("success");
}
});
And over each iteration we will push our object into the array after converting it into string;At last we will write the whole array into the file. by this method our complete data will be saved in the file successfully!Now our whole code will like it:// Write Javascript code hereconst request = require('request');const cheerio = require('cheerio');const fs = require('fs'); const URL = "https://www.flipkart.com/search?q=mobiles"; request(URL, function (err, res, body) { if(err) { console.log(err); } else { const arr = []; let $ = cheerio.load(body); $('div._1HmYoV > div.col-10-12>div.bhgxx2>div._3O0U0u').each(function(index){ const data = $(this).find('div._1UoZlX>a').attr('href'); const name = $(this).find('div._1-2Iqu>div.col-7-12>div._3wU53n').text(); const obj = { data : data, name : name }; console.log(obj); arr.push(JSON.stringify(obj)); }); console.log(arr.toString()); fs.writeFile('data.txt', arr, function (err) { if(err) { console.log(err); } else{ console.log("success"); } }); }});Now run the code:node server.jsYou can see the output on terminal like this while running the code:After successfully running the code, there is a file named data.txt also which has all the data extracted! we can find this file in our project directory.So, it is a simple example of how to create a web scraper in nodejs using cheerio module. From here, you can try to scrap any other website of your choice. In case of any queries, post them below in comments section.My Personal Notes
arrow_drop_upSave
Steps for coding:
First we will import all our required modulesThen, we will send a HTTP request to the URL and then server of the desired website will respond with an web page, it will be done with the request moduleNow, we have the HTML of the web page, our task is to extract the useful information from it, so we will traverse the DOM tree and will find out the selectorsAfter extracting our information, we will save it into a file, this task will be done with the help of fs module
First we will import all our required modules
Then, we will send a HTTP request to the URL and then server of the desired website will respond with an web page, it will be done with the request module
Now, we have the HTML of the web page, our task is to extract the useful information from it, so we will traverse the DOM tree and will find out the selectors
After extracting our information, we will save it into a file, this task will be done with the help of fs module
Code for Crawler:Create a file called server.js and add the following lines:const request = require('request');
const cheerio = require('cheerio');
const mongoose = require('fs');
Explanation of these lines of code:Here in these three lines, we are importing all these three modules, required for crawling and data saving into a file.We will hit the URL from where we want to crawl data:Here we are going to crawl the list of smartphones from an e-commerce website Flipkart.URL for showing smartphones list are as follows in flipkart:const URL = "https://www.flipkart.com/search?q=mobiles";On this URL web page looks like this:Now we will hit this URL with the help ofrequestmodule:request(URL, function (err, res, body) {
if(err)
{
console.log(err, "error occured while hitting URL");
}
else
{
console.log(body);
}
});
Let’s understand these piece of code:Here we are using request module to send the HTTP request to the flipkart’s URL of smartphones, and the function within the request module takes three parameters error, response, body respectively.Here if error comes then we log it otherwise we log the body.For testing it, when we will run our script bynode server.jswe can see the whole HTML of the page in our console.It is the complete HTML of the web page for this URL.Now our task is to extract the useful information so we will visit the DOM tree and find out the selectors by inspecting element.For doing it right click on the web page and go to the inspect element like it:Now we will visit the DOM:Now we will change our request to hit the URL accordingly to the inspection:request(URL, function (err, res, body) {
if(err)
{
console.log(err);
}
else
{
let $ = cheerio.load(body); //loading of complete HTML body
$('div._1HmYoV > div.col-10-12>div.bhgxx2>div._3O0U0u').each(function(index){
const link = $(this).find('div._1UoZlX>a').attr('href');
const name = $(this).find('div._1-2Iqu>div.col-7-12>div._3wU53n').text();
console.log(link); //link for smartphone
console.log(name); //name of smartphone
});
}
});
Saving the data into the fileFor doing it we will create an array and an objectlet arr = []; //creating an array
let object =
{
link : link,
name : name,
} //creating an object
fs.writeFile('data.txt', arr, function (err) {
if(err) {
console.log(err);
}
else{
console.log("success");
}
});
And over each iteration we will push our object into the array after converting it into string;At last we will write the whole array into the file. by this method our complete data will be saved in the file successfully!Now our whole code will like it:// Write Javascript code hereconst request = require('request');const cheerio = require('cheerio');const fs = require('fs'); const URL = "https://www.flipkart.com/search?q=mobiles"; request(URL, function (err, res, body) { if(err) { console.log(err); } else { const arr = []; let $ = cheerio.load(body); $('div._1HmYoV > div.col-10-12>div.bhgxx2>div._3O0U0u').each(function(index){ const data = $(this).find('div._1UoZlX>a').attr('href'); const name = $(this).find('div._1-2Iqu>div.col-7-12>div._3wU53n').text(); const obj = { data : data, name : name }; console.log(obj); arr.push(JSON.stringify(obj)); }); console.log(arr.toString()); fs.writeFile('data.txt', arr, function (err) { if(err) { console.log(err); } else{ console.log("success"); } }); }});
Create a file called server.js and add the following lines:const request = require('request');
const cheerio = require('cheerio');
const mongoose = require('fs');
Explanation of these lines of code:Here in these three lines, we are importing all these three modules, required for crawling and data saving into a file.
const request = require('request');
const cheerio = require('cheerio');
const mongoose = require('fs');
Explanation of these lines of code:Here in these three lines, we are importing all these three modules, required for crawling and data saving into a file.
We will hit the URL from where we want to crawl data:Here we are going to crawl the list of smartphones from an e-commerce website Flipkart.URL for showing smartphones list are as follows in flipkart:const URL = "https://www.flipkart.com/search?q=mobiles";On this URL web page looks like this:Now we will hit this URL with the help ofrequestmodule:request(URL, function (err, res, body) {
if(err)
{
console.log(err, "error occured while hitting URL");
}
else
{
console.log(body);
}
});
Let’s understand these piece of code:Here we are using request module to send the HTTP request to the flipkart’s URL of smartphones, and the function within the request module takes three parameters error, response, body respectively.Here if error comes then we log it otherwise we log the body.For testing it, when we will run our script bynode server.jswe can see the whole HTML of the page in our console.It is the complete HTML of the web page for this URL.Now our task is to extract the useful information so we will visit the DOM tree and find out the selectors by inspecting element.For doing it right click on the web page and go to the inspect element like it:Now we will visit the DOM:Now we will change our request to hit the URL accordingly to the inspection:request(URL, function (err, res, body) {
if(err)
{
console.log(err);
}
else
{
let $ = cheerio.load(body); //loading of complete HTML body
$('div._1HmYoV > div.col-10-12>div.bhgxx2>div._3O0U0u').each(function(index){
const link = $(this).find('div._1UoZlX>a').attr('href');
const name = $(this).find('div._1-2Iqu>div.col-7-12>div._3wU53n').text();
console.log(link); //link for smartphone
console.log(name); //name of smartphone
});
}
});
URL for showing smartphones list are as follows in flipkart:
const URL = "https://www.flipkart.com/search?q=mobiles";
On this URL web page looks like this:
Now we will hit this URL with the help of
request
module:
request(URL, function (err, res, body) {
if(err)
{
console.log(err, "error occured while hitting URL");
}
else
{
console.log(body);
}
});
Let’s understand these piece of code:Here we are using request module to send the HTTP request to the flipkart’s URL of smartphones, and the function within the request module takes three parameters error, response, body respectively.Here if error comes then we log it otherwise we log the body.
For testing it, when we will run our script by
node server.js
we can see the whole HTML of the page in our console.It is the complete HTML of the web page for this URL.
Now our task is to extract the useful information so we will visit the DOM tree and find out the selectors by inspecting element.For doing it right click on the web page and go to the inspect element like it:
Now we will visit the DOM:
Now we will change our request to hit the URL accordingly to the inspection:
request(URL, function (err, res, body) {
if(err)
{
console.log(err);
}
else
{
let $ = cheerio.load(body); //loading of complete HTML body
$('div._1HmYoV > div.col-10-12>div.bhgxx2>div._3O0U0u').each(function(index){
const link = $(this).find('div._1UoZlX>a').attr('href');
const name = $(this).find('div._1-2Iqu>div.col-7-12>div._3wU53n').text();
console.log(link); //link for smartphone
console.log(name); //name of smartphone
});
}
});
Saving the data into the fileFor doing it we will create an array and an objectlet arr = []; //creating an array
let object =
{
link : link,
name : name,
} //creating an object
fs.writeFile('data.txt', arr, function (err) {
if(err) {
console.log(err);
}
else{
console.log("success");
}
});
And over each iteration we will push our object into the array after converting it into string;At last we will write the whole array into the file. by this method our complete data will be saved in the file successfully!Now our whole code will like it:// Write Javascript code hereconst request = require('request');const cheerio = require('cheerio');const fs = require('fs'); const URL = "https://www.flipkart.com/search?q=mobiles"; request(URL, function (err, res, body) { if(err) { console.log(err); } else { const arr = []; let $ = cheerio.load(body); $('div._1HmYoV > div.col-10-12>div.bhgxx2>div._3O0U0u').each(function(index){ const data = $(this).find('div._1UoZlX>a').attr('href'); const name = $(this).find('div._1-2Iqu>div.col-7-12>div._3wU53n').text(); const obj = { data : data, name : name }; console.log(obj); arr.push(JSON.stringify(obj)); }); console.log(arr.toString()); fs.writeFile('data.txt', arr, function (err) { if(err) { console.log(err); } else{ console.log("success"); } }); }});
let arr = []; //creating an array
let object =
{
link : link,
name : name,
} //creating an object
fs.writeFile('data.txt', arr, function (err) {
if(err) {
console.log(err);
}
else{
console.log("success");
}
});
And over each iteration we will push our object into the array after converting it into string;At last we will write the whole array into the file. by this method our complete data will be saved in the file successfully!
Now our whole code will like it:
// Write Javascript code hereconst request = require('request');const cheerio = require('cheerio');const fs = require('fs'); const URL = "https://www.flipkart.com/search?q=mobiles"; request(URL, function (err, res, body) { if(err) { console.log(err); } else { const arr = []; let $ = cheerio.load(body); $('div._1HmYoV > div.col-10-12>div.bhgxx2>div._3O0U0u').each(function(index){ const data = $(this).find('div._1UoZlX>a').attr('href'); const name = $(this).find('div._1-2Iqu>div.col-7-12>div._3wU53n').text(); const obj = { data : data, name : name }; console.log(obj); arr.push(JSON.stringify(obj)); }); console.log(arr.toString()); fs.writeFile('data.txt', arr, function (err) { if(err) { console.log(err); } else{ console.log("success"); } }); }});
Now run the code:
node server.js
You can see the output on terminal like this while running the code:
After successfully running the code, there is a file named data.txt also which has all the data extracted! we can find this file in our project directory.
So, it is a simple example of how to create a web scraper in nodejs using cheerio module. From here, you can try to scrap any other website of your choice. In case of any queries, post them below in comments section.
prachisoda1234
Node.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Convert a string to an integer in JavaScript
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24948,
"s": 24920,
"text": "\n10 Nov, 2021"
},
{
"code": null,
"e": 25106,
"s": 24948,
"text": "By sending HTTP request to a particular URL and then by extracting HTML of that web page for getting useful information is known as crawling or web scraping."
},
{
"code": null,
"e": 25149,
"s": 25106,
"text": "Modules to be used for crawling in Nodejs:"
},
{
"code": null,
"e": 25299,
"s": 25149,
"text": "request: For sending HTTP request to the URLcheerio: For parsing DOM and extracting HTML of web pagefs: For reading or writing the data into the file"
},
{
"code": null,
"e": 25344,
"s": 25299,
"text": "request: For sending HTTP request to the URL"
},
{
"code": null,
"e": 25401,
"s": 25344,
"text": "cheerio: For parsing DOM and extracting HTML of web page"
},
{
"code": null,
"e": 25451,
"s": 25401,
"text": "fs: For reading or writing the data into the file"
},
{
"code": null,
"e": 25567,
"s": 25451,
"text": "Installation of these modules:The easiest way to install modules in Nodejs is using NPM.it can be done in two ways:"
},
{
"code": null,
"e": 25906,
"s": 25567,
"text": "Globally Installation: If we install any module globally then we can use it anywhere in our system.It can be done by the following command:npm i -g package_nameLocally Installation: If we install any module locally then we can use it only within that particular project directory.It can be done by the following command:npm i package_name"
},
{
"code": null,
"e": 26067,
"s": 25906,
"text": "Globally Installation: If we install any module globally then we can use it anywhere in our system.It can be done by the following command:npm i -g package_name"
},
{
"code": null,
"e": 26089,
"s": 26067,
"text": "npm i -g package_name"
},
{
"code": null,
"e": 26268,
"s": 26089,
"text": "Locally Installation: If we install any module locally then we can use it only within that particular project directory.It can be done by the following command:npm i package_name"
},
{
"code": null,
"e": 26287,
"s": 26268,
"text": "npm i package_name"
},
{
"code": null,
"e": 26337,
"s": 26287,
"text": "For this task we will use the local installation:"
},
{
"code": null,
"e": 26375,
"s": 26337,
"text": "Steps for Web Crawling using Cheerio:"
},
{
"code": null,
"e": 26416,
"s": 26375,
"text": "Step 1: create a folder for this project"
},
{
"code": null,
"e": 27207,
"s": 26416,
"text": "Step 2: Open the terminal inside the project directory and then type the following command:npm initIt will create a file namedpackage.jsonwhich contains all information about the modules, author, github repository and its versions as well.For know more about package.json please visit this link:explanation of package.jsonTo install the modules locally using NPM simply do:npm install request\nnpm install cheerio\nnpm install fs\nThis can be done in the single line as well using NPM:npm install request cheerio fsAfter successfully installing modules our package.json will have structure like this :Here in this screenshot we can see all our dependencies have been listed within the dependencies object, It implies we have successfully installed all of them in our current project directory."
},
{
"code": null,
"e": 27216,
"s": 27207,
"text": "npm init"
},
{
"code": null,
"e": 27244,
"s": 27216,
"text": "It will create a file named"
},
{
"code": null,
"e": 27257,
"s": 27244,
"text": "package.json"
},
{
"code": null,
"e": 27442,
"s": 27257,
"text": "which contains all information about the modules, author, github repository and its versions as well.For know more about package.json please visit this link:explanation of package.json"
},
{
"code": null,
"e": 27494,
"s": 27442,
"text": "To install the modules locally using NPM simply do:"
},
{
"code": null,
"e": 27550,
"s": 27494,
"text": "npm install request\nnpm install cheerio\nnpm install fs\n"
},
{
"code": null,
"e": 27605,
"s": 27550,
"text": "This can be done in the single line as well using NPM:"
},
{
"code": null,
"e": 27636,
"s": 27605,
"text": "npm install request cheerio fs"
},
{
"code": null,
"e": 27723,
"s": 27636,
"text": "After successfully installing modules our package.json will have structure like this :"
},
{
"code": null,
"e": 27916,
"s": 27723,
"text": "Here in this screenshot we can see all our dependencies have been listed within the dependencies object, It implies we have successfully installed all of them in our current project directory."
},
{
"code": null,
"e": 32813,
"s": 27916,
"text": "Step 3: Now we will code for crawlerSteps for coding:First we will import all our required modulesThen, we will send a HTTP request to the URL and then server of the desired website will respond with an web page, it will be done with the request moduleNow, we have the HTML of the web page, our task is to extract the useful information from it, so we will traverse the DOM tree and will find out the selectorsAfter extracting our information, we will save it into a file, this task will be done with the help of fs moduleCode for Crawler:Create a file called server.js and add the following lines:const request = require('request');\nconst cheerio = require('cheerio');\nconst mongoose = require('fs');\nExplanation of these lines of code:Here in these three lines, we are importing all these three modules, required for crawling and data saving into a file.We will hit the URL from where we want to crawl data:Here we are going to crawl the list of smartphones from an e-commerce website Flipkart.URL for showing smartphones list are as follows in flipkart:const URL = \"https://www.flipkart.com/search?q=mobiles\";On this URL web page looks like this:Now we will hit this URL with the help ofrequestmodule:request(URL, function (err, res, body) {\n if(err)\n {\n console.log(err, \"error occured while hitting URL\");\n }\n else\n {\n console.log(body);\n }\n});\nLet’s understand these piece of code:Here we are using request module to send the HTTP request to the flipkart’s URL of smartphones, and the function within the request module takes three parameters error, response, body respectively.Here if error comes then we log it otherwise we log the body.For testing it, when we will run our script bynode server.jswe can see the whole HTML of the page in our console.It is the complete HTML of the web page for this URL.Now our task is to extract the useful information so we will visit the DOM tree and find out the selectors by inspecting element.For doing it right click on the web page and go to the inspect element like it:Now we will visit the DOM:Now we will change our request to hit the URL accordingly to the inspection:request(URL, function (err, res, body) {\n if(err)\n {\n console.log(err);\n }\n else\n {\n\n let $ = cheerio.load(body); //loading of complete HTML body\n \n $('div._1HmYoV > div.col-10-12>div.bhgxx2>div._3O0U0u').each(function(index){\n const link = $(this).find('div._1UoZlX>a').attr('href');\n const name = $(this).find('div._1-2Iqu>div.col-7-12>div._3wU53n').text();\n console.log(link); //link for smartphone\n console.log(name); //name of smartphone\n });\n }\n});\nSaving the data into the fileFor doing it we will create an array and an objectlet arr = []; //creating an array\n\nlet object = \n{\n link : link,\n name : name,\n} //creating an object\n\n fs.writeFile('data.txt', arr, function (err) {\n if(err) {\n console.log(err);\n }\n else{\n console.log(\"success\");\n }\n });\nAnd over each iteration we will push our object into the array after converting it into string;At last we will write the whole array into the file. by this method our complete data will be saved in the file successfully!Now our whole code will like it:// Write Javascript code hereconst request = require('request');const cheerio = require('cheerio');const fs = require('fs'); const URL = \"https://www.flipkart.com/search?q=mobiles\"; request(URL, function (err, res, body) { if(err) { console.log(err); } else { const arr = []; let $ = cheerio.load(body); $('div._1HmYoV > div.col-10-12>div.bhgxx2>div._3O0U0u').each(function(index){ const data = $(this).find('div._1UoZlX>a').attr('href'); const name = $(this).find('div._1-2Iqu>div.col-7-12>div._3wU53n').text(); const obj = { data : data, name : name }; console.log(obj); arr.push(JSON.stringify(obj)); }); console.log(arr.toString()); fs.writeFile('data.txt', arr, function (err) { if(err) { console.log(err); } else{ console.log(\"success\"); } }); }});Now run the code:node server.jsYou can see the output on terminal like this while running the code:After successfully running the code, there is a file named data.txt also which has all the data extracted! we can find this file in our project directory.So, it is a simple example of how to create a web scraper in nodejs using cheerio module. From here, you can try to scrap any other website of your choice. In case of any queries, post them below in comments section.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 32831,
"s": 32813,
"text": "Steps for coding:"
},
{
"code": null,
"e": 33301,
"s": 32831,
"text": "First we will import all our required modulesThen, we will send a HTTP request to the URL and then server of the desired website will respond with an web page, it will be done with the request moduleNow, we have the HTML of the web page, our task is to extract the useful information from it, so we will traverse the DOM tree and will find out the selectorsAfter extracting our information, we will save it into a file, this task will be done with the help of fs module"
},
{
"code": null,
"e": 33347,
"s": 33301,
"text": "First we will import all our required modules"
},
{
"code": null,
"e": 33502,
"s": 33347,
"text": "Then, we will send a HTTP request to the URL and then server of the desired website will respond with an web page, it will be done with the request module"
},
{
"code": null,
"e": 33661,
"s": 33502,
"text": "Now, we have the HTML of the web page, our task is to extract the useful information from it, so we will traverse the DOM tree and will find out the selectors"
},
{
"code": null,
"e": 33774,
"s": 33661,
"text": "After extracting our information, we will save it into a file, this task will be done with the help of fs module"
},
{
"code": null,
"e": 37645,
"s": 33774,
"text": "Code for Crawler:Create a file called server.js and add the following lines:const request = require('request');\nconst cheerio = require('cheerio');\nconst mongoose = require('fs');\nExplanation of these lines of code:Here in these three lines, we are importing all these three modules, required for crawling and data saving into a file.We will hit the URL from where we want to crawl data:Here we are going to crawl the list of smartphones from an e-commerce website Flipkart.URL for showing smartphones list are as follows in flipkart:const URL = \"https://www.flipkart.com/search?q=mobiles\";On this URL web page looks like this:Now we will hit this URL with the help ofrequestmodule:request(URL, function (err, res, body) {\n if(err)\n {\n console.log(err, \"error occured while hitting URL\");\n }\n else\n {\n console.log(body);\n }\n});\nLet’s understand these piece of code:Here we are using request module to send the HTTP request to the flipkart’s URL of smartphones, and the function within the request module takes three parameters error, response, body respectively.Here if error comes then we log it otherwise we log the body.For testing it, when we will run our script bynode server.jswe can see the whole HTML of the page in our console.It is the complete HTML of the web page for this URL.Now our task is to extract the useful information so we will visit the DOM tree and find out the selectors by inspecting element.For doing it right click on the web page and go to the inspect element like it:Now we will visit the DOM:Now we will change our request to hit the URL accordingly to the inspection:request(URL, function (err, res, body) {\n if(err)\n {\n console.log(err);\n }\n else\n {\n\n let $ = cheerio.load(body); //loading of complete HTML body\n \n $('div._1HmYoV > div.col-10-12>div.bhgxx2>div._3O0U0u').each(function(index){\n const link = $(this).find('div._1UoZlX>a').attr('href');\n const name = $(this).find('div._1-2Iqu>div.col-7-12>div._3wU53n').text();\n console.log(link); //link for smartphone\n console.log(name); //name of smartphone\n });\n }\n});\nSaving the data into the fileFor doing it we will create an array and an objectlet arr = []; //creating an array\n\nlet object = \n{\n link : link,\n name : name,\n} //creating an object\n\n fs.writeFile('data.txt', arr, function (err) {\n if(err) {\n console.log(err);\n }\n else{\n console.log(\"success\");\n }\n });\nAnd over each iteration we will push our object into the array after converting it into string;At last we will write the whole array into the file. by this method our complete data will be saved in the file successfully!Now our whole code will like it:// Write Javascript code hereconst request = require('request');const cheerio = require('cheerio');const fs = require('fs'); const URL = \"https://www.flipkart.com/search?q=mobiles\"; request(URL, function (err, res, body) { if(err) { console.log(err); } else { const arr = []; let $ = cheerio.load(body); $('div._1HmYoV > div.col-10-12>div.bhgxx2>div._3O0U0u').each(function(index){ const data = $(this).find('div._1UoZlX>a').attr('href'); const name = $(this).find('div._1-2Iqu>div.col-7-12>div._3wU53n').text(); const obj = { data : data, name : name }; console.log(obj); arr.push(JSON.stringify(obj)); }); console.log(arr.toString()); fs.writeFile('data.txt', arr, function (err) { if(err) { console.log(err); } else{ console.log(\"success\"); } }); }});"
},
{
"code": null,
"e": 37963,
"s": 37645,
"text": "Create a file called server.js and add the following lines:const request = require('request');\nconst cheerio = require('cheerio');\nconst mongoose = require('fs');\nExplanation of these lines of code:Here in these three lines, we are importing all these three modules, required for crawling and data saving into a file."
},
{
"code": null,
"e": 38068,
"s": 37963,
"text": "const request = require('request');\nconst cheerio = require('cheerio');\nconst mongoose = require('fs');\n"
},
{
"code": null,
"e": 38223,
"s": 38068,
"text": "Explanation of these lines of code:Here in these three lines, we are importing all these three modules, required for crawling and data saving into a file."
},
{
"code": null,
"e": 40074,
"s": 38223,
"text": "We will hit the URL from where we want to crawl data:Here we are going to crawl the list of smartphones from an e-commerce website Flipkart.URL for showing smartphones list are as follows in flipkart:const URL = \"https://www.flipkart.com/search?q=mobiles\";On this URL web page looks like this:Now we will hit this URL with the help ofrequestmodule:request(URL, function (err, res, body) {\n if(err)\n {\n console.log(err, \"error occured while hitting URL\");\n }\n else\n {\n console.log(body);\n }\n});\nLet’s understand these piece of code:Here we are using request module to send the HTTP request to the flipkart’s URL of smartphones, and the function within the request module takes three parameters error, response, body respectively.Here if error comes then we log it otherwise we log the body.For testing it, when we will run our script bynode server.jswe can see the whole HTML of the page in our console.It is the complete HTML of the web page for this URL.Now our task is to extract the useful information so we will visit the DOM tree and find out the selectors by inspecting element.For doing it right click on the web page and go to the inspect element like it:Now we will visit the DOM:Now we will change our request to hit the URL accordingly to the inspection:request(URL, function (err, res, body) {\n if(err)\n {\n console.log(err);\n }\n else\n {\n\n let $ = cheerio.load(body); //loading of complete HTML body\n \n $('div._1HmYoV > div.col-10-12>div.bhgxx2>div._3O0U0u').each(function(index){\n const link = $(this).find('div._1UoZlX>a').attr('href');\n const name = $(this).find('div._1-2Iqu>div.col-7-12>div._3wU53n').text();\n console.log(link); //link for smartphone\n console.log(name); //name of smartphone\n });\n }\n});\n"
},
{
"code": null,
"e": 40135,
"s": 40074,
"text": "URL for showing smartphones list are as follows in flipkart:"
},
{
"code": null,
"e": 40192,
"s": 40135,
"text": "const URL = \"https://www.flipkart.com/search?q=mobiles\";"
},
{
"code": null,
"e": 40230,
"s": 40192,
"text": "On this URL web page looks like this:"
},
{
"code": null,
"e": 40272,
"s": 40230,
"text": "Now we will hit this URL with the help of"
},
{
"code": null,
"e": 40280,
"s": 40272,
"text": "request"
},
{
"code": null,
"e": 40288,
"s": 40280,
"text": "module:"
},
{
"code": null,
"e": 40467,
"s": 40288,
"text": "request(URL, function (err, res, body) {\n if(err)\n {\n console.log(err, \"error occured while hitting URL\");\n }\n else\n {\n console.log(body);\n }\n});\n"
},
{
"code": null,
"e": 40763,
"s": 40467,
"text": "Let’s understand these piece of code:Here we are using request module to send the HTTP request to the flipkart’s URL of smartphones, and the function within the request module takes three parameters error, response, body respectively.Here if error comes then we log it otherwise we log the body."
},
{
"code": null,
"e": 40810,
"s": 40763,
"text": "For testing it, when we will run our script by"
},
{
"code": null,
"e": 40825,
"s": 40810,
"text": "node server.js"
},
{
"code": null,
"e": 40932,
"s": 40825,
"text": "we can see the whole HTML of the page in our console.It is the complete HTML of the web page for this URL."
},
{
"code": null,
"e": 41141,
"s": 40932,
"text": "Now our task is to extract the useful information so we will visit the DOM tree and find out the selectors by inspecting element.For doing it right click on the web page and go to the inspect element like it:"
},
{
"code": null,
"e": 41168,
"s": 41141,
"text": "Now we will visit the DOM:"
},
{
"code": null,
"e": 41245,
"s": 41168,
"text": "Now we will change our request to hit the URL accordingly to the inspection:"
},
{
"code": null,
"e": 41799,
"s": 41245,
"text": "request(URL, function (err, res, body) {\n if(err)\n {\n console.log(err);\n }\n else\n {\n\n let $ = cheerio.load(body); //loading of complete HTML body\n \n $('div._1HmYoV > div.col-10-12>div.bhgxx2>div._3O0U0u').each(function(index){\n const link = $(this).find('div._1UoZlX>a').attr('href');\n const name = $(this).find('div._1-2Iqu>div.col-7-12>div._3wU53n').text();\n console.log(link); //link for smartphone\n console.log(name); //name of smartphone\n });\n }\n});\n"
},
{
"code": null,
"e": 43486,
"s": 41799,
"text": "Saving the data into the fileFor doing it we will create an array and an objectlet arr = []; //creating an array\n\nlet object = \n{\n link : link,\n name : name,\n} //creating an object\n\n fs.writeFile('data.txt', arr, function (err) {\n if(err) {\n console.log(err);\n }\n else{\n console.log(\"success\");\n }\n });\nAnd over each iteration we will push our object into the array after converting it into string;At last we will write the whole array into the file. by this method our complete data will be saved in the file successfully!Now our whole code will like it:// Write Javascript code hereconst request = require('request');const cheerio = require('cheerio');const fs = require('fs'); const URL = \"https://www.flipkart.com/search?q=mobiles\"; request(URL, function (err, res, body) { if(err) { console.log(err); } else { const arr = []; let $ = cheerio.load(body); $('div._1HmYoV > div.col-10-12>div.bhgxx2>div._3O0U0u').each(function(index){ const data = $(this).find('div._1UoZlX>a').attr('href'); const name = $(this).find('div._1-2Iqu>div.col-7-12>div._3wU53n').text(); const obj = { data : data, name : name }; console.log(obj); arr.push(JSON.stringify(obj)); }); console.log(arr.toString()); fs.writeFile('data.txt', arr, function (err) { if(err) { console.log(err); } else{ console.log(\"success\"); } }); }});"
},
{
"code": null,
"e": 43812,
"s": 43486,
"text": "let arr = []; //creating an array\n\nlet object = \n{\n link : link,\n name : name,\n} //creating an object\n\n fs.writeFile('data.txt', arr, function (err) {\n if(err) {\n console.log(err);\n }\n else{\n console.log(\"success\");\n }\n });\n"
},
{
"code": null,
"e": 44033,
"s": 43812,
"text": "And over each iteration we will push our object into the array after converting it into string;At last we will write the whole array into the file. by this method our complete data will be saved in the file successfully!"
},
{
"code": null,
"e": 44066,
"s": 44033,
"text": "Now our whole code will like it:"
},
{
"code": "// Write Javascript code hereconst request = require('request');const cheerio = require('cheerio');const fs = require('fs'); const URL = \"https://www.flipkart.com/search?q=mobiles\"; request(URL, function (err, res, body) { if(err) { console.log(err); } else { const arr = []; let $ = cheerio.load(body); $('div._1HmYoV > div.col-10-12>div.bhgxx2>div._3O0U0u').each(function(index){ const data = $(this).find('div._1UoZlX>a').attr('href'); const name = $(this).find('div._1-2Iqu>div.col-7-12>div._3wU53n').text(); const obj = { data : data, name : name }; console.log(obj); arr.push(JSON.stringify(obj)); }); console.log(arr.toString()); fs.writeFile('data.txt', arr, function (err) { if(err) { console.log(err); } else{ console.log(\"success\"); } }); }});",
"e": 45097,
"s": 44066,
"text": null
},
{
"code": null,
"e": 45115,
"s": 45097,
"text": "Now run the code:"
},
{
"code": null,
"e": 45130,
"s": 45115,
"text": "node server.js"
},
{
"code": null,
"e": 45199,
"s": 45130,
"text": "You can see the output on terminal like this while running the code:"
},
{
"code": null,
"e": 45354,
"s": 45199,
"text": "After successfully running the code, there is a file named data.txt also which has all the data extracted! we can find this file in our project directory."
},
{
"code": null,
"e": 45571,
"s": 45354,
"text": "So, it is a simple example of how to create a web scraper in nodejs using cheerio module. From here, you can try to scrap any other website of your choice. In case of any queries, post them below in comments section."
},
{
"code": null,
"e": 45586,
"s": 45571,
"text": "prachisoda1234"
},
{
"code": null,
"e": 45594,
"s": 45586,
"text": "Node.js"
},
{
"code": null,
"e": 45605,
"s": 45594,
"text": "JavaScript"
},
{
"code": null,
"e": 45622,
"s": 45605,
"text": "Web Technologies"
},
{
"code": null,
"e": 45720,
"s": 45622,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 45729,
"s": 45720,
"text": "Comments"
},
{
"code": null,
"e": 45742,
"s": 45729,
"text": "Old Comments"
},
{
"code": null,
"e": 45803,
"s": 45742,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 45875,
"s": 45803,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 45920,
"s": 45875,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 45972,
"s": 45920,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 46013,
"s": 45972,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 46046,
"s": 46013,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 46088,
"s": 46046,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 46131,
"s": 46088,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 46193,
"s": 46131,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Five R Markdown tricks that you may not know about | by Keith McNulty | Towards Data Science
|
Many of you who regularly read my articles will know how much of a fan of R Markdown I am. It is hands down the best data science publishing software, and as well as being completely free it is also constantly being developed to be better and more flexible.
As I go along, I keep picking up new tricks to make my life easier or to get the most out of R Markdown. I’m sharing the latest five with you here. Hope you find them useful.
Many of you likely know about chunk options in R Markdown. When you write a code chunk you can add numerous options to instruct on what you want to do with that chunk. For example:
```{r, echo = FALSE}# some R code ```
This will display the results of the code chunk but will not display the code itself. Or:
```{python, eval = FALSE}# some python code```
This will display the code but will not run it. In fact there are a very wide array of chunk options available, and it can sometimes get untidy and difficult to follow if you have to put a lot of them in curlys {}.
If you install knitr version 1.35+ you can now type your chunk options line by line inside the chunk using a new chunk option special comment #| , for example:
```{r}#| echo = FALSE, out.width = "80%"#| fig.cap = "My caption"my_plot```
Did you know that you can put conditions in your chunk options? This can be super useful and can allow you to run a chunk only if certain conditions are satisfied. For example, this chunk will only be evaluated if the object my_data has more than three rows:
```{r}#| eval = nrow(my_data) > 3my_data```
You can also use conditional chunks to show different things depending on whether you are rendering to PDF or HTML — meaning you only have to keep one Rmd file irrelevant of your intended output. For example:
```{r}#| eval = knitr::is_html_output()# code for html output (eg interactive graphic)``````{r}#| eval = knitr::is_latex_output()# code for pdf output (eg static graphic)```
You can also use these knitr output functions in if statements, so another way of doing the above is:
```{r}if (knitr::is_html_output()) { # code for html output} else { # code for latex output}```
Some of you may write your Shiny apps in using two separate ui.R and server.R files, but you can also write your full app in a single R Markdown file. One of the advantages of doing this is that you can customize your app using Javascript by simply typing the Javascript directly in a js chunk.
Let’s look at a simple example. In Shiny, there is currently no direct option to limit the number of characters in a textarea input box. So if I use this standard Shiny UI function:
```{r}shiny::textAreaInput( "comment", "Enter your comment:")```
This will create a textarea box with the ID of comment. However, if I want to keep all comments limited to, say, 1,000 characters, I have no easy way of doing this in the textAreaInput() function.
Never fear though — if you know a little Javascript/jQuery, you can add a js chunk to add a maxlength attribute to the textarea box, like this:
```{js}$('[id="comment"]').attr('maxlength', 1000)```
If your document or application is getting very long and has a lot of code inside the chunks, that can get annoying to follow and difficult to maintain. Instead, you can take the code from inside the chunks and save them in R files, and then use the code chunk option to read that code from the R or Python file. For example:
```{python}#| code = readLines("my_setup_code.py")# python code for setup```
If you want to customize the style of your document or application, you can use CSS code chunks to do this really easily. You may have to render the document and then inspect it in Google Chrome to identify the class or ID of the specific element you want to customize, but as a simple example, if you wanted to change the background color of the main body of your document to a nice light blue, you can simply insert this chunk:
```{css}body { background-color: #d0e3f1;}```
Hope you found these neat little tricks useful. If you have any others that you’d like to suggest please do so in the comments.
Originally I was a Pure Mathematician, then I became a Psychometrician and a Data Scientist. I am passionate about applying the rigor of all those disciplines to complex people questions. I’m also a coding geek and a massive fan of Japanese RPGs. Find me on LinkedIn or on Twitter. Also check out my blog on drkeithmcnulty.com.
|
[
{
"code": null,
"e": 430,
"s": 172,
"text": "Many of you who regularly read my articles will know how much of a fan of R Markdown I am. It is hands down the best data science publishing software, and as well as being completely free it is also constantly being developed to be better and more flexible."
},
{
"code": null,
"e": 605,
"s": 430,
"text": "As I go along, I keep picking up new tricks to make my life easier or to get the most out of R Markdown. I’m sharing the latest five with you here. Hope you find them useful."
},
{
"code": null,
"e": 786,
"s": 605,
"text": "Many of you likely know about chunk options in R Markdown. When you write a code chunk you can add numerous options to instruct on what you want to do with that chunk. For example:"
},
{
"code": null,
"e": 824,
"s": 786,
"text": "```{r, echo = FALSE}# some R code ```"
},
{
"code": null,
"e": 914,
"s": 824,
"text": "This will display the results of the code chunk but will not display the code itself. Or:"
},
{
"code": null,
"e": 961,
"s": 914,
"text": "```{python, eval = FALSE}# some python code```"
},
{
"code": null,
"e": 1176,
"s": 961,
"text": "This will display the code but will not run it. In fact there are a very wide array of chunk options available, and it can sometimes get untidy and difficult to follow if you have to put a lot of them in curlys {}."
},
{
"code": null,
"e": 1336,
"s": 1176,
"text": "If you install knitr version 1.35+ you can now type your chunk options line by line inside the chunk using a new chunk option special comment #| , for example:"
},
{
"code": null,
"e": 1412,
"s": 1336,
"text": "```{r}#| echo = FALSE, out.width = \"80%\"#| fig.cap = \"My caption\"my_plot```"
},
{
"code": null,
"e": 1671,
"s": 1412,
"text": "Did you know that you can put conditions in your chunk options? This can be super useful and can allow you to run a chunk only if certain conditions are satisfied. For example, this chunk will only be evaluated if the object my_data has more than three rows:"
},
{
"code": null,
"e": 1715,
"s": 1671,
"text": "```{r}#| eval = nrow(my_data) > 3my_data```"
},
{
"code": null,
"e": 1924,
"s": 1715,
"text": "You can also use conditional chunks to show different things depending on whether you are rendering to PDF or HTML — meaning you only have to keep one Rmd file irrelevant of your intended output. For example:"
},
{
"code": null,
"e": 2098,
"s": 1924,
"text": "```{r}#| eval = knitr::is_html_output()# code for html output (eg interactive graphic)``````{r}#| eval = knitr::is_latex_output()# code for pdf output (eg static graphic)```"
},
{
"code": null,
"e": 2200,
"s": 2098,
"text": "You can also use these knitr output functions in if statements, so another way of doing the above is:"
},
{
"code": null,
"e": 2298,
"s": 2200,
"text": "```{r}if (knitr::is_html_output()) { # code for html output} else { # code for latex output}```"
},
{
"code": null,
"e": 2593,
"s": 2298,
"text": "Some of you may write your Shiny apps in using two separate ui.R and server.R files, but you can also write your full app in a single R Markdown file. One of the advantages of doing this is that you can customize your app using Javascript by simply typing the Javascript directly in a js chunk."
},
{
"code": null,
"e": 2775,
"s": 2593,
"text": "Let’s look at a simple example. In Shiny, there is currently no direct option to limit the number of characters in a textarea input box. So if I use this standard Shiny UI function:"
},
{
"code": null,
"e": 2842,
"s": 2775,
"text": "```{r}shiny::textAreaInput( \"comment\", \"Enter your comment:\")```"
},
{
"code": null,
"e": 3039,
"s": 2842,
"text": "This will create a textarea box with the ID of comment. However, if I want to keep all comments limited to, say, 1,000 characters, I have no easy way of doing this in the textAreaInput() function."
},
{
"code": null,
"e": 3183,
"s": 3039,
"text": "Never fear though — if you know a little Javascript/jQuery, you can add a js chunk to add a maxlength attribute to the textarea box, like this:"
},
{
"code": null,
"e": 3237,
"s": 3183,
"text": "```{js}$('[id=\"comment\"]').attr('maxlength', 1000)```"
},
{
"code": null,
"e": 3563,
"s": 3237,
"text": "If your document or application is getting very long and has a lot of code inside the chunks, that can get annoying to follow and difficult to maintain. Instead, you can take the code from inside the chunks and save them in R files, and then use the code chunk option to read that code from the R or Python file. For example:"
},
{
"code": null,
"e": 3640,
"s": 3563,
"text": "```{python}#| code = readLines(\"my_setup_code.py\")# python code for setup```"
},
{
"code": null,
"e": 4070,
"s": 3640,
"text": "If you want to customize the style of your document or application, you can use CSS code chunks to do this really easily. You may have to render the document and then inspect it in Google Chrome to identify the class or ID of the specific element you want to customize, but as a simple example, if you wanted to change the background color of the main body of your document to a nice light blue, you can simply insert this chunk:"
},
{
"code": null,
"e": 4116,
"s": 4070,
"text": "```{css}body { background-color: #d0e3f1;}```"
},
{
"code": null,
"e": 4244,
"s": 4116,
"text": "Hope you found these neat little tricks useful. If you have any others that you’d like to suggest please do so in the comments."
}
] |
Understanding HTML Form Encoding: URL Encoded and Multipart Forms - GeeksforGeeks
|
08 Mar, 2021
HTML forms contain two encodings, the URL Encoded Forms and the multipart Forms. The encoding in an HTML form is determined by an attribute named ‘enctype‘. This attribute can have three values:
application/x-www-form-urlencoded: This value represents a URL (Uniform Resource Locator) encoded form. By default, it is assigned to the enctype attribute.
multipart/form-data: This value represents a multipart form. It is used to upload files by the user.
text/plain: This value represents a form that is newly introduced in the latest HTML5 which is used to send the data without any encoding.
URL Encoded Forms: The data that is submitted using this type of form encoding is URL encoded, as very clear from its name.
Example:
HTML
<!DOCTYPE html><html> <head> <meta charset="UTF-8" /> <title>URL Encoded Forms</title> </head> <body> <form action="/urlencoded?firstname=Geeks&lastname=forGeeks" method="POST" enctype="application/x-www-form-urlencoded"> <input type="text" name="username" value="GeeksforGeeks" /> <input type="text" name="password" value="GFG@123" /> <input type="submit" value="Submit" /> </form> </body></html>
The above form is submitted to the server using the POST request, suggesting that it’s a body and the body in this form is URL encoded. It is created by an extended string of (name, value) pairs. Each pair of these strings are separated by a &(ampersand) sign and the name is separated by an = (equals) sign from the ‘value’.
For the above form, the (name, value) pairs are as follows.username=GeeksforGeeks&password=GFG@123
For the above form, the (name, value) pairs are as follows.
username=GeeksforGeeks&password=GFG@123
Some parameters in the query that are passed in the URL action are as follows./urlencoded?firstname=Geeks&lastname=forGeeks
Some parameters in the query that are passed in the URL action are as follows.
/urlencoded?firstname=Geeks&lastname=forGeeks
It is clearly visible that the URL encoded body and the query parameters look similar. In fact, they are similar.
Multipart Forms: These types of forms are used when the user uploads some files on the server.
Example:
HTML
<!DOCTYPE html><html> <head> <meta charset="UTF-8" /> <title>Multipart Forms</title> </head> <body> <form action="/multipart?firstname=Geeks for&lastname=Geeks" method="POST" enctype="multipart/form-data"> <input type="text" name="username" value="Geeks for Geeks" /> <input type="text" name="password" value="GFG@123" /> <input type="submit" value="Submit" /> </form> </body></html>
In the above form, some spaces are introduced in the username value and the action value in the form is changed to ‘multipart/form-data‘ to use the functionality of multipart forms.
For the above form, the (name, value) pairs are as followsusername=Geeks%20for%20Geeks&password=GFG@123
For the above form, the (name, value) pairs are as follows
username=Geeks%20for%20Geeks&password=GFG@123
Some parameters in the query that are passed in the URL action are as follows./multipart?firstname=Geeks%20for%20&lastname=Geeks
Some parameters in the query that are passed in the URL action are as follows.
/multipart?firstname=Geeks%20for%20&lastname=Geeks
It can be clearly seen from above in the query parameters and the form body that the spaces are replaced by ‘%20’.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
Picked
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
REST API (Introduction)
Design a web page using HTML and CSS
Form validation using jQuery
How to place text on image using HTML and CSS?
How to auto-resize an image to fit a div container using CSS?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24503,
"s": 24475,
"text": "\n08 Mar, 2021"
},
{
"code": null,
"e": 24698,
"s": 24503,
"text": "HTML forms contain two encodings, the URL Encoded Forms and the multipart Forms. The encoding in an HTML form is determined by an attribute named ‘enctype‘. This attribute can have three values:"
},
{
"code": null,
"e": 24855,
"s": 24698,
"text": "application/x-www-form-urlencoded: This value represents a URL (Uniform Resource Locator) encoded form. By default, it is assigned to the enctype attribute."
},
{
"code": null,
"e": 24956,
"s": 24855,
"text": "multipart/form-data: This value represents a multipart form. It is used to upload files by the user."
},
{
"code": null,
"e": 25095,
"s": 24956,
"text": "text/plain: This value represents a form that is newly introduced in the latest HTML5 which is used to send the data without any encoding."
},
{
"code": null,
"e": 25219,
"s": 25095,
"text": "URL Encoded Forms: The data that is submitted using this type of form encoding is URL encoded, as very clear from its name."
},
{
"code": null,
"e": 25228,
"s": 25219,
"text": "Example:"
},
{
"code": null,
"e": 25233,
"s": 25228,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\" /> <title>URL Encoded Forms</title> </head> <body> <form action=\"/urlencoded?firstname=Geeks&lastname=forGeeks\" method=\"POST\" enctype=\"application/x-www-form-urlencoded\"> <input type=\"text\" name=\"username\" value=\"GeeksforGeeks\" /> <input type=\"text\" name=\"password\" value=\"GFG@123\" /> <input type=\"submit\" value=\"Submit\" /> </form> </body></html>",
"e": 25677,
"s": 25233,
"text": null
},
{
"code": null,
"e": 26003,
"s": 25677,
"text": "The above form is submitted to the server using the POST request, suggesting that it’s a body and the body in this form is URL encoded. It is created by an extended string of (name, value) pairs. Each pair of these strings are separated by a &(ampersand) sign and the name is separated by an = (equals) sign from the ‘value’."
},
{
"code": null,
"e": 26102,
"s": 26003,
"text": "For the above form, the (name, value) pairs are as follows.username=GeeksforGeeks&password=GFG@123"
},
{
"code": null,
"e": 26162,
"s": 26102,
"text": "For the above form, the (name, value) pairs are as follows."
},
{
"code": null,
"e": 26202,
"s": 26162,
"text": "username=GeeksforGeeks&password=GFG@123"
},
{
"code": null,
"e": 26326,
"s": 26202,
"text": "Some parameters in the query that are passed in the URL action are as follows./urlencoded?firstname=Geeks&lastname=forGeeks"
},
{
"code": null,
"e": 26405,
"s": 26326,
"text": "Some parameters in the query that are passed in the URL action are as follows."
},
{
"code": null,
"e": 26451,
"s": 26405,
"text": "/urlencoded?firstname=Geeks&lastname=forGeeks"
},
{
"code": null,
"e": 26565,
"s": 26451,
"text": "It is clearly visible that the URL encoded body and the query parameters look similar. In fact, they are similar."
},
{
"code": null,
"e": 26660,
"s": 26565,
"text": "Multipart Forms: These types of forms are used when the user uploads some files on the server."
},
{
"code": null,
"e": 26669,
"s": 26660,
"text": "Example:"
},
{
"code": null,
"e": 26674,
"s": 26669,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\" /> <title>Multipart Forms</title> </head> <body> <form action=\"/multipart?firstname=Geeks for&lastname=Geeks\" method=\"POST\" enctype=\"multipart/form-data\"> <input type=\"text\" name=\"username\" value=\"Geeks for Geeks\" /> <input type=\"text\" name=\"password\" value=\"GFG@123\" /> <input type=\"submit\" value=\"Submit\" /> </form> </body></html>",
"e": 27104,
"s": 26674,
"text": null
},
{
"code": null,
"e": 27286,
"s": 27104,
"text": "In the above form, some spaces are introduced in the username value and the action value in the form is changed to ‘multipart/form-data‘ to use the functionality of multipart forms."
},
{
"code": null,
"e": 27390,
"s": 27286,
"text": "For the above form, the (name, value) pairs are as followsusername=Geeks%20for%20Geeks&password=GFG@123"
},
{
"code": null,
"e": 27449,
"s": 27390,
"text": "For the above form, the (name, value) pairs are as follows"
},
{
"code": null,
"e": 27495,
"s": 27449,
"text": "username=Geeks%20for%20Geeks&password=GFG@123"
},
{
"code": null,
"e": 27624,
"s": 27495,
"text": "Some parameters in the query that are passed in the URL action are as follows./multipart?firstname=Geeks%20for%20&lastname=Geeks"
},
{
"code": null,
"e": 27703,
"s": 27624,
"text": "Some parameters in the query that are passed in the URL action are as follows."
},
{
"code": null,
"e": 27754,
"s": 27703,
"text": "/multipart?firstname=Geeks%20for%20&lastname=Geeks"
},
{
"code": null,
"e": 27869,
"s": 27754,
"text": "It can be clearly seen from above in the query parameters and the form body that the spaces are replaced by ‘%20’."
},
{
"code": null,
"e": 28006,
"s": 27869,
"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": 28013,
"s": 28006,
"text": "Picked"
},
{
"code": null,
"e": 28018,
"s": 28013,
"text": "HTML"
},
{
"code": null,
"e": 28035,
"s": 28018,
"text": "Web Technologies"
},
{
"code": null,
"e": 28062,
"s": 28035,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28067,
"s": 28062,
"text": "HTML"
},
{
"code": null,
"e": 28165,
"s": 28067,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28174,
"s": 28165,
"text": "Comments"
},
{
"code": null,
"e": 28187,
"s": 28174,
"text": "Old Comments"
},
{
"code": null,
"e": 28211,
"s": 28187,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 28248,
"s": 28211,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 28277,
"s": 28248,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 28324,
"s": 28277,
"text": "How to place text on image using HTML and CSS?"
},
{
"code": null,
"e": 28386,
"s": 28324,
"text": "How to auto-resize an image to fit a div container using CSS?"
},
{
"code": null,
"e": 28442,
"s": 28386,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 28475,
"s": 28442,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28518,
"s": 28475,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28579,
"s": 28518,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
R Squared Interpretation | R Squared Linear Regression | by Cory Maklin | Towards Data Science
|
Machine learning involves a lot of statistics. In the proceeding article, we’ll take a look at the concept of R-Squared which is useful in feature selection.
Correlation (otherwise known as “R”) is a number between 1 and -1 where a value of +1 implies that an increase in x results in some increase in y, -1 implies that an increase in x results in a decrease in y, and 0 means that there isn’t any relationship between x and y. Like correlation, R2 tells you how related two things are. However, we tend to use R2 because it’s easier to interpret. R2 is the percentage of variation (i.e. varies from 0 to 1) explained by the relationship between two variables.
The latter sounds rather convoluted so let’s take a look at an example. Suppose we decided to plot the relationship between salary and years of experience. In the proceeding graph, every data point represents an individual.
We can calculate the mean or average by taking the sum of all the individuals in the sample and dividing it by the total number of individuals in the sample.
The variance of the entire dataset is equal to the sum of the distance between every data point and the mean squared. The difference is squared such that points below the mean don’t cancel out with points above the mean.
var(mean) = sum(pi - mean)2
Now say, we took the same people but this time, we decided to plot the relationship between their salary and height.
Notice how the average salary remains the same irrespective of what we take to be the independent variable. In other words, we can use other aspects of the people’s lives as x but the salary will remain the same.
Suppose that we used linear regression to find the best fitting line.
The value of R2 can then be expressed as:
R2 = (var(mean) - var(line)) / var(mean)
where var(mean) is the variance with respect to the mean and var(line) is the variance with respect to line.
Like we mentioned previously, the variance can be calculated by taking the sum of the differences between individual salaries and the mean squared.
Using the same logic, we can determine the variation around the orange line.
Assuming that we obtained the following values for the variance of the line and mean.
We can calculate R2 using the formula described previously.
The R2 value implies that there is 96% less variation around the line than the mean. In other words, the relationship between salary and years of experience accounts for 96% of the variation. Said yet another way, years of experience is a good predictor of salary because when the years of experience go up so does the salary and vice versa.
Let’s take a look at how we could go about using R2 to evaluate a linear regression model. To start, import the following libraries.
import pandas as pdimport numpy as npfrom matplotlib import pyplot as pltimport seaborn as snsfrom sklearn.metrics import r2_scorefrom sklearn.linear_model import LinearRegressionsns.set()
We’ll be using the following dataset. If you would like to follow along, copy its contents into a csv file.
YearsExperience,Salary1.1,39343.001.3,46205.001.5,37731.002.0,43525.002.2,39891.002.9,56642.003.0,60150.003.2,54445.003.2,64445.003.7,57189.003.9,63218.004.0,55794.004.0,56957.004.1,57081.004.5,61111.004.9,67938.005.1,66029.005.3,83088.005.9,81363.006.0,93940.006.8,91738.007.1,98273.007.9,101302.008.2,113812.008.7,109431.009.0,105582.009.5,116969.009.6,112635.0010.3,122391.0010.5,121872.00
We load the data into our program using pandas and plot it using matplotlib.
df = pd.read_csv('data.csv')plt.scatter(df['YearsExperience'], df['Salary'])
Next, we train a linear regression model on our salary data.
X = np.array(df['YearsExperience']).reshape(-1, 1)y = df['Salary']rf = LinearRegression()rf.fit(X, y)y_pred = rf.predict(X)
We can view the best fitting line produced by our model by running the following lines.
plt.scatter(df['YearsExperience'], df['Salary'])plt.plot(X, y_pred, color='red')
Then, we compute R2 using the formula discussed in the preceding section.
def r2_score_from_scratch(ys_orig, ys_line): y_mean_line = [ys_orig.mean() for y in ys_orig] squared_error_regr = squared_error(ys_orig, ys_line) squared_error_y_mean = squared_error(ys_orig, y_mean_line) return 1 - (squared_error_regr / squared_error_y_mean)def squared_error(ys_orig, ys_line): return sum((ys_line - ys_orig) * (ys_line - ys_orig))r_squared = r2_score_from_scratch(y, y_pred)print(r_squared)
Rather than implement it from scratch every time, we can leverage the sklearn r2_score function.
|
[
{
"code": null,
"e": 330,
"s": 172,
"text": "Machine learning involves a lot of statistics. In the proceeding article, we’ll take a look at the concept of R-Squared which is useful in feature selection."
},
{
"code": null,
"e": 834,
"s": 330,
"text": "Correlation (otherwise known as “R”) is a number between 1 and -1 where a value of +1 implies that an increase in x results in some increase in y, -1 implies that an increase in x results in a decrease in y, and 0 means that there isn’t any relationship between x and y. Like correlation, R2 tells you how related two things are. However, we tend to use R2 because it’s easier to interpret. R2 is the percentage of variation (i.e. varies from 0 to 1) explained by the relationship between two variables."
},
{
"code": null,
"e": 1058,
"s": 834,
"text": "The latter sounds rather convoluted so let’s take a look at an example. Suppose we decided to plot the relationship between salary and years of experience. In the proceeding graph, every data point represents an individual."
},
{
"code": null,
"e": 1216,
"s": 1058,
"text": "We can calculate the mean or average by taking the sum of all the individuals in the sample and dividing it by the total number of individuals in the sample."
},
{
"code": null,
"e": 1437,
"s": 1216,
"text": "The variance of the entire dataset is equal to the sum of the distance between every data point and the mean squared. The difference is squared such that points below the mean don’t cancel out with points above the mean."
},
{
"code": null,
"e": 1465,
"s": 1437,
"text": "var(mean) = sum(pi - mean)2"
},
{
"code": null,
"e": 1582,
"s": 1465,
"text": "Now say, we took the same people but this time, we decided to plot the relationship between their salary and height."
},
{
"code": null,
"e": 1795,
"s": 1582,
"text": "Notice how the average salary remains the same irrespective of what we take to be the independent variable. In other words, we can use other aspects of the people’s lives as x but the salary will remain the same."
},
{
"code": null,
"e": 1865,
"s": 1795,
"text": "Suppose that we used linear regression to find the best fitting line."
},
{
"code": null,
"e": 1907,
"s": 1865,
"text": "The value of R2 can then be expressed as:"
},
{
"code": null,
"e": 1948,
"s": 1907,
"text": "R2 = (var(mean) - var(line)) / var(mean)"
},
{
"code": null,
"e": 2057,
"s": 1948,
"text": "where var(mean) is the variance with respect to the mean and var(line) is the variance with respect to line."
},
{
"code": null,
"e": 2205,
"s": 2057,
"text": "Like we mentioned previously, the variance can be calculated by taking the sum of the differences between individual salaries and the mean squared."
},
{
"code": null,
"e": 2282,
"s": 2205,
"text": "Using the same logic, we can determine the variation around the orange line."
},
{
"code": null,
"e": 2368,
"s": 2282,
"text": "Assuming that we obtained the following values for the variance of the line and mean."
},
{
"code": null,
"e": 2428,
"s": 2368,
"text": "We can calculate R2 using the formula described previously."
},
{
"code": null,
"e": 2770,
"s": 2428,
"text": "The R2 value implies that there is 96% less variation around the line than the mean. In other words, the relationship between salary and years of experience accounts for 96% of the variation. Said yet another way, years of experience is a good predictor of salary because when the years of experience go up so does the salary and vice versa."
},
{
"code": null,
"e": 2903,
"s": 2770,
"text": "Let’s take a look at how we could go about using R2 to evaluate a linear regression model. To start, import the following libraries."
},
{
"code": null,
"e": 3092,
"s": 2903,
"text": "import pandas as pdimport numpy as npfrom matplotlib import pyplot as pltimport seaborn as snsfrom sklearn.metrics import r2_scorefrom sklearn.linear_model import LinearRegressionsns.set()"
},
{
"code": null,
"e": 3200,
"s": 3092,
"text": "We’ll be using the following dataset. If you would like to follow along, copy its contents into a csv file."
},
{
"code": null,
"e": 3593,
"s": 3200,
"text": "YearsExperience,Salary1.1,39343.001.3,46205.001.5,37731.002.0,43525.002.2,39891.002.9,56642.003.0,60150.003.2,54445.003.2,64445.003.7,57189.003.9,63218.004.0,55794.004.0,56957.004.1,57081.004.5,61111.004.9,67938.005.1,66029.005.3,83088.005.9,81363.006.0,93940.006.8,91738.007.1,98273.007.9,101302.008.2,113812.008.7,109431.009.0,105582.009.5,116969.009.6,112635.0010.3,122391.0010.5,121872.00"
},
{
"code": null,
"e": 3670,
"s": 3593,
"text": "We load the data into our program using pandas and plot it using matplotlib."
},
{
"code": null,
"e": 3747,
"s": 3670,
"text": "df = pd.read_csv('data.csv')plt.scatter(df['YearsExperience'], df['Salary'])"
},
{
"code": null,
"e": 3808,
"s": 3747,
"text": "Next, we train a linear regression model on our salary data."
},
{
"code": null,
"e": 3932,
"s": 3808,
"text": "X = np.array(df['YearsExperience']).reshape(-1, 1)y = df['Salary']rf = LinearRegression()rf.fit(X, y)y_pred = rf.predict(X)"
},
{
"code": null,
"e": 4020,
"s": 3932,
"text": "We can view the best fitting line produced by our model by running the following lines."
},
{
"code": null,
"e": 4101,
"s": 4020,
"text": "plt.scatter(df['YearsExperience'], df['Salary'])plt.plot(X, y_pred, color='red')"
},
{
"code": null,
"e": 4175,
"s": 4101,
"text": "Then, we compute R2 using the formula discussed in the preceding section."
},
{
"code": null,
"e": 4600,
"s": 4175,
"text": "def r2_score_from_scratch(ys_orig, ys_line): y_mean_line = [ys_orig.mean() for y in ys_orig] squared_error_regr = squared_error(ys_orig, ys_line) squared_error_y_mean = squared_error(ys_orig, y_mean_line) return 1 - (squared_error_regr / squared_error_y_mean)def squared_error(ys_orig, ys_line): return sum((ys_line - ys_orig) * (ys_line - ys_orig))r_squared = r2_score_from_scratch(y, y_pred)print(r_squared)"
}
] |
C# Enum TryParse() Method
|
The TryParse() method converts the string representation of one or more enumerated constants to an equivalent enumerated object.
Firstly, set an enum.
enum Vehicle { Bus = 2, Truck = 4, Car = 10 };
Now, let us declare a string array and set some values.
string[] VehicleList = { "2", "3", "4", "bus", "Truck", "CAR" };
Now parse the values accordingly using Enum TryParse() method.
Live Demo
using System;
public class Demo {
enum Vehicle { Bus = 2, Truck = 4, Car = 10 };
public static void Main() {
string[] VehicleList = { "2", "3", "4", "bus", "Truck", "CAR" };
foreach (string val in VehicleList) {
Vehicle vehicle;
if (Enum.TryParse(val, true, out vehicle))
if (Enum.IsDefined(typeof(Vehicle), vehicle) | vehicle.ToString().Contains(","))
Console.WriteLine("Converted '{0}' to {1}", val, vehicle.ToString());
else
Console.WriteLine("{0} is not a value of the enum", val);
else
Console.WriteLine("{0} is not a member of the enum", val);
}
}
}
Converted '2' to Bus
3 is not a value of the enum
Converted '4' to Truck
Converted 'bus' to Bus
Converted 'Truck' to Truck
Converted 'CAR' to Car
|
[
{
"code": null,
"e": 1191,
"s": 1062,
"text": "The TryParse() method converts the string representation of one or more enumerated constants to an equivalent enumerated object."
},
{
"code": null,
"e": 1213,
"s": 1191,
"text": "Firstly, set an enum."
},
{
"code": null,
"e": 1260,
"s": 1213,
"text": "enum Vehicle { Bus = 2, Truck = 4, Car = 10 };"
},
{
"code": null,
"e": 1316,
"s": 1260,
"text": "Now, let us declare a string array and set some values."
},
{
"code": null,
"e": 1381,
"s": 1316,
"text": "string[] VehicleList = { \"2\", \"3\", \"4\", \"bus\", \"Truck\", \"CAR\" };"
},
{
"code": null,
"e": 1444,
"s": 1381,
"text": "Now parse the values accordingly using Enum TryParse() method."
},
{
"code": null,
"e": 1455,
"s": 1444,
"text": " Live Demo"
},
{
"code": null,
"e": 2110,
"s": 1455,
"text": "using System;\npublic class Demo {\n enum Vehicle { Bus = 2, Truck = 4, Car = 10 };\n public static void Main() {\n string[] VehicleList = { \"2\", \"3\", \"4\", \"bus\", \"Truck\", \"CAR\" };\n foreach (string val in VehicleList) {\n Vehicle vehicle;\n if (Enum.TryParse(val, true, out vehicle))\n if (Enum.IsDefined(typeof(Vehicle), vehicle) | vehicle.ToString().Contains(\",\"))\n Console.WriteLine(\"Converted '{0}' to {1}\", val, vehicle.ToString());\n else\n Console.WriteLine(\"{0} is not a value of the enum\", val);\n else\n Console.WriteLine(\"{0} is not a member of the enum\", val);\n }\n }\n}"
},
{
"code": null,
"e": 2256,
"s": 2110,
"text": "Converted '2' to Bus\n3 is not a value of the enum\nConverted '4' to Truck\nConverted 'bus' to Bus\nConverted 'Truck' to Truck\nConverted 'CAR' to Car"
}
] |
Convex Hull Example in Data Structures
|
Here we will see one example on convex hull. Suppose we have a set of points. We have to make a polygon by taking less amount of points, that will cover all given points. In this section we will see the Jarvis March algorithm to get the convex hull.
Jarvis March algorithm is used to detect the corner points of a convex hull from a given set of data points.
Starting from left most point of the data set, we keep the points in the convex hull by anti-clockwise rotation. From a current point, we can choose the next point by checking the orientations of those points from current point. When the angle is largest, the point is chosen. After completing all points, when the next point is the start point, stop the algorithm.
Input − Set of points: {(-7,8), (-4,6), (2,6), (6,4), (8,6), (7,-2), (4,-6), (8,-7),(0,0), (3,-2),(6,-10),(0,-6),(-9,-5),(-8,-2),(-8,0),(-10,3),(-2,2),(-10,4)}
Output − Boundary points of convex hull are −
(-9, -5) (6, -10) (8, -7) (8, 6) (-7, 8) (-10, 4) (-10, 3)
findConvexHull(points, n)
Input: The points, number of points.
Output: Corner points of convex hull.
Begin
start := points[0]
for each point i, do
if points[i].x < start.x, then // get the left most point
start := points[i]
done
current := start
add start point to the result set.
define colPts set to store collinear points
while true, do //start an infinite loop
next := points[i]
for all points i except 0th point, do
if points[i] = current, then
skip the next part, go for next iteration
val := cross product of current, next, points[i]
if val > 0, then
next := points[i]
clear the colPts array
else if cal = 0, then
if next is closer to current than points[i], then
add next in the colPts
next := points[i]
else
add points[i] in the colPts
done
add all items in the colPts into the result
if next = start, then
break the loop
insert next into the result
current := next
done
return result
End
Live Demo
#include<iostream>
#include<set>
#include<vector>
using namespace std;
struct point{ //define points for 2d plane
int x, y;
bool operator==(point p2){
if(x == p2.x && y == p2.y)
return 1;
return 0;
}
bool operator<(const point &p2)const{ //dummy compare function used to sort in set
return true;
}
};
int crossProduct(point a, point b, point c){ //finds the place of c from ab vector
int y1 = a.y - b.y;
int y2 = a.y - c.y;
int x1 = a.x - b.x;
int x2 = a.x - c.x;
return y2*x1 - y1*x2; //if result < 0, c in the left, > 0, c in the right, = 0, a,b,c are collinear
}
int distance(point a, point b, point c){
int y1 = a.y - b.y;
int y2 = a.y - c.y;
int x1 = a.x - b.x;
int x2 = a.x - c.x;
int item1 = (y1*y1 + x1*x1);
int item2 = (y2*y2 + x2*x2);
if(item1 == item2)
return 0; //when b and c are in same distance from a
else if(item1 < item2)
return -1; //when b is closer to a
return 1; //when c is closer to a
}
set<point> findConvexHull(point points[], int n){
point start = points[0];
for(int i = 1; i<n; i++){ //find the left most point for starting
if(points[i].x < start.x)
start = points[i];
}
point current = start;
set<point> result; //set is used to avoid entry of duplicate points
result.insert(start);
vector<point> *collinearPoints = new vector<point>;
while(true){
point nextTarget = points[0];
for(int i = 1; i<n; i++){
if(points[i] == current) //when selected point is current point, ignore rest part
continue;
int val = crossProduct(current, nextTarget, points[i]);
if(val > 0){ //when ith point is on the left side
nextTarget = points[i];
collinearPoints = new vector<point>; //reset collinear points
}else if(val == 0){ //if three points are collinear
if(distance(current, nextTarget, points[i]) < 0){ //add closer one to collinear list
collinearPoints->push_back(nextTarget);
nextTarget = points[i];
}else{
collinearPoints->push_back(points[i]); //when ith point is closer or same as nextTarget
}
}
}
vector<point>::iterator it;
for(it = collinearPoints->begin(); it != collinearPoints->end(); it++){
result.insert(*it); //add allpoints in collinear points to result set
}
if(nextTarget == start) //when next point is start it means, the area covered
break;
result.insert(nextTarget);
current = nextTarget;
}
return result;
}
int main(){
point points[] = {
{-7,8},{-4,6},{2,6},{6,4},{8,6},{7,-2},{4,-6},{8,-7},{0,0},
{3,-2},{6,-10},{0,-6},{-9,-5},{-8,-2},{-8,0},{-10,3},{-2,2},{-10,4}};
int n = 18;
set<point> result;
result = findConvexHull(points, n);
cout << "Boundary points of convex hull are: "<<endl;
set<point>::iterator it;
for(it = result.begin(); it!=result.end(); it++)
cout << "(" << it->x << ", " <<it->y <<") ";
}
Boundary points of convex hull are:
(-9, -5) (6, -10) (8, -7) (8, 6) (-7, 8) (-10, 4) (-10, 3)
|
[
{
"code": null,
"e": 1312,
"s": 1062,
"text": "Here we will see one example on convex hull. Suppose we have a set of points. We have to make a polygon by taking less amount of points, that will cover all given points. In this section we will see the Jarvis March algorithm to get the convex hull."
},
{
"code": null,
"e": 1421,
"s": 1312,
"text": "Jarvis March algorithm is used to detect the corner points of a convex hull from a given set of data points."
},
{
"code": null,
"e": 1787,
"s": 1421,
"text": "Starting from left most point of the data set, we keep the points in the convex hull by anti-clockwise rotation. From a current point, we can choose the next point by checking the orientations of those points from current point. When the angle is largest, the point is chosen. After completing all points, when the next point is the start point, stop the algorithm."
},
{
"code": null,
"e": 1947,
"s": 1787,
"text": "Input − Set of points: {(-7,8), (-4,6), (2,6), (6,4), (8,6), (7,-2), (4,-6), (8,-7),(0,0), (3,-2),(6,-10),(0,-6),(-9,-5),(-8,-2),(-8,0),(-10,3),(-2,2),(-10,4)}"
},
{
"code": null,
"e": 1993,
"s": 1947,
"text": "Output − Boundary points of convex hull are −"
},
{
"code": null,
"e": 2052,
"s": 1993,
"text": "(-9, -5) (6, -10) (8, -7) (8, 6) (-7, 8) (-10, 4) (-10, 3)"
},
{
"code": null,
"e": 3184,
"s": 2052,
"text": "findConvexHull(points, n)\nInput: The points, number of points.\nOutput: Corner points of convex hull.\nBegin\n start := points[0]\n for each point i, do\n if points[i].x < start.x, then // get the left most point\n start := points[i]\n done\n current := start\n add start point to the result set.\n define colPts set to store collinear points\n while true, do //start an infinite loop\n next := points[i]\n for all points i except 0th point, do\n if points[i] = current, then\n skip the next part, go for next iteration\n val := cross product of current, next, points[i]\n if val > 0, then\n next := points[i]\n clear the colPts array\n else if cal = 0, then\n if next is closer to current than points[i], then\n add next in the colPts\n next := points[i]\n else\n add points[i] in the colPts\n done\n add all items in the colPts into the result\n if next = start, then\n break the loop\n insert next into the result\n current := next\n done\n return result\nEnd"
},
{
"code": null,
"e": 3195,
"s": 3184,
"text": " Live Demo"
},
{
"code": null,
"e": 6277,
"s": 3195,
"text": "#include<iostream>\n#include<set>\n#include<vector>\nusing namespace std;\nstruct point{ //define points for 2d plane\n int x, y;\n bool operator==(point p2){\n if(x == p2.x && y == p2.y)\n return 1;\n return 0;\n }\n bool operator<(const point &p2)const{ //dummy compare function used to sort in set\n return true;\n }\n};\nint crossProduct(point a, point b, point c){ //finds the place of c from ab vector\n int y1 = a.y - b.y;\n int y2 = a.y - c.y;\n int x1 = a.x - b.x;\n int x2 = a.x - c.x;\n return y2*x1 - y1*x2; //if result < 0, c in the left, > 0, c in the right, = 0, a,b,c are collinear\n}\nint distance(point a, point b, point c){\n int y1 = a.y - b.y;\n int y2 = a.y - c.y;\n int x1 = a.x - b.x;\n int x2 = a.x - c.x;\n int item1 = (y1*y1 + x1*x1);\n int item2 = (y2*y2 + x2*x2);\n if(item1 == item2)\n return 0; //when b and c are in same distance from a\n else if(item1 < item2)\n return -1; //when b is closer to a\n return 1; //when c is closer to a\n}\nset<point> findConvexHull(point points[], int n){\n point start = points[0];\n for(int i = 1; i<n; i++){ //find the left most point for starting\n if(points[i].x < start.x)\n start = points[i];\n }\n point current = start;\n set<point> result; //set is used to avoid entry of duplicate points\n result.insert(start);\n vector<point> *collinearPoints = new vector<point>;\n while(true){\n point nextTarget = points[0];\n for(int i = 1; i<n; i++){\n if(points[i] == current) //when selected point is current point, ignore rest part\n continue;\n int val = crossProduct(current, nextTarget, points[i]);\n if(val > 0){ //when ith point is on the left side\n nextTarget = points[i];\n collinearPoints = new vector<point>; //reset collinear points\n }else if(val == 0){ //if three points are collinear\n if(distance(current, nextTarget, points[i]) < 0){ //add closer one to collinear list\n collinearPoints->push_back(nextTarget);\n nextTarget = points[i];\n }else{\n collinearPoints->push_back(points[i]); //when ith point is closer or same as nextTarget\n }\n }\n }\n vector<point>::iterator it;\n for(it = collinearPoints->begin(); it != collinearPoints->end(); it++){\n result.insert(*it); //add allpoints in collinear points to result set\n }\n if(nextTarget == start) //when next point is start it means, the area covered\n break;\n result.insert(nextTarget);\n current = nextTarget;\n }\n return result;\n}\nint main(){\n point points[] = {\n {-7,8},{-4,6},{2,6},{6,4},{8,6},{7,-2},{4,-6},{8,-7},{0,0},\n {3,-2},{6,-10},{0,-6},{-9,-5},{-8,-2},{-8,0},{-10,3},{-2,2},{-10,4}};\n int n = 18;\n set<point> result;\n result = findConvexHull(points, n);\n cout << \"Boundary points of convex hull are: \"<<endl;\n set<point>::iterator it;\n for(it = result.begin(); it!=result.end(); it++)\n cout << \"(\" << it->x << \", \" <<it->y <<\") \";\n}"
},
{
"code": null,
"e": 6372,
"s": 6277,
"text": "Boundary points of convex hull are:\n(-9, -5) (6, -10) (8, -7) (8, 6) (-7, 8) (-10, 4) (-10, 3)"
}
] |
How to Extract Relevant Keywords with KeyBERT | by Ahmed Besbes | Towards Data Science
|
There are many powerful techniques that perform keywords extraction (e.g. Rake, YAKE!, TF-IDF). However, they are mainly based on the statistical properties of the text and don’t necessarily take into account the semantic aspects of the full document.
KeyBERT is a minimal and easy-to-use keyword extraction technique that aims at solving this issue. It leverages the BERT language model and relies on the 🤗transformers library.
KeyBERT is developed and maintained by Maarten Grootendorst. So go check his repo (and clone it) if you’re interested in using it.
In this post, I’ll briefly present KeyBERT: how it works and how you can use it
PS: If you want to see a video tutorial on how to use KeyBERT and how to embed it in a Streamlit app, you can have a look at my video:
You can install KeyBERT with pip.
pip install keybert
If you need embeddings from other sources than 🤗transformers, you can install them as well:
pip install keybert[flair]pip install keybert[gensim]pip install keybert[spacy]pip install keybert[use]
Calling KeyBERT is straightforward: you initialize a keyword extraction model based on a 🤗transformers model and apply the extract_keywords method on it.
KeyBERT extracts keywords by performing the following steps:
1 — The input document is embedded using a pre-trained BERT model. You can pick any BERT model your want from 🤗transformers. This turns a chunk of text into a fixed-size vector that is meant the represent the semantic aspect of the document
2 — Keywords and expressions (n-grams) are extracted from the same document using Bag Of Words techniques (such as a TfidfVectorizer or CountVectorizer). This is a classical step that you may be familiar with if you’ve performed keywords extraction in the past
3 — Each keyword is then embedded into a fixed-size vector with the same model used to embed the document
4 — Now that the keywords and the document are represented in the same space, KeyBERT computes a cosine similarity between the keyword embeddings and the document embedding. Then, the most similar keywords (with the highest cosine similarity score) are extracted.
The idea is pretty simple: you can think of it as an enhanced version of a classical keyword extraction technique in which the BERT language model comes in to add its semantic capability.
This doesn’t stop here: KeyBERT includes two methods to introduce diversity in the resulting keywords.
1 — Max Sum Similarity (MSS)
To use this method, you start by setting the top_n argument to a value, say 20. Then 2 x top_n keywords are extracted from the document. Pairwise similarities are computed between these keywords. Finally, the method extracts the most relevant keywords that are the least similar to each other.
Here’s an example from the KeyBERT’s repository:
2 — Maximal Marginal Relevance (MMR)This method is similar to the previous one: it adds a diversity argument
MMR tries to minimize redundancy and maximize the diversity of results in text summarization tasks.
It starts by selecting the keywords that are the most similar to the document. Then, it iteratively selects new candidates that are both similar to the document and not similar to the already selected keywords
You can choose a low-diversity threshold:
or a high one:
One limitation that KeyBERT may suffer from though is the execution time: if you have large documents and need real-time results, KeyBERT may not be the best solution (unless you have dedicated GPUs in your production environment). The reason being that BERT models are notoriously huge and consume a lot of resources especially when they have to process large documents.
You can probably find some hacks to speed up the inference time by picking smaller models (DistilBERT), using mixed precision or even convert your model to ONNX format.
If this still doesn’t work out for you, check other classical methods: you’d be surprised by their efficiency despite their relative simplicity.
That’s it for today. I hope you’ll find this small method useful for your NLP projects if you’re performing keywords extraction.
You can learn more about KeyBERT here:
|
[
{
"code": null,
"e": 424,
"s": 172,
"text": "There are many powerful techniques that perform keywords extraction (e.g. Rake, YAKE!, TF-IDF). However, they are mainly based on the statistical properties of the text and don’t necessarily take into account the semantic aspects of the full document."
},
{
"code": null,
"e": 601,
"s": 424,
"text": "KeyBERT is a minimal and easy-to-use keyword extraction technique that aims at solving this issue. It leverages the BERT language model and relies on the 🤗transformers library."
},
{
"code": null,
"e": 732,
"s": 601,
"text": "KeyBERT is developed and maintained by Maarten Grootendorst. So go check his repo (and clone it) if you’re interested in using it."
},
{
"code": null,
"e": 812,
"s": 732,
"text": "In this post, I’ll briefly present KeyBERT: how it works and how you can use it"
},
{
"code": null,
"e": 947,
"s": 812,
"text": "PS: If you want to see a video tutorial on how to use KeyBERT and how to embed it in a Streamlit app, you can have a look at my video:"
},
{
"code": null,
"e": 981,
"s": 947,
"text": "You can install KeyBERT with pip."
},
{
"code": null,
"e": 1001,
"s": 981,
"text": "pip install keybert"
},
{
"code": null,
"e": 1093,
"s": 1001,
"text": "If you need embeddings from other sources than 🤗transformers, you can install them as well:"
},
{
"code": null,
"e": 1197,
"s": 1093,
"text": "pip install keybert[flair]pip install keybert[gensim]pip install keybert[spacy]pip install keybert[use]"
},
{
"code": null,
"e": 1351,
"s": 1197,
"text": "Calling KeyBERT is straightforward: you initialize a keyword extraction model based on a 🤗transformers model and apply the extract_keywords method on it."
},
{
"code": null,
"e": 1412,
"s": 1351,
"text": "KeyBERT extracts keywords by performing the following steps:"
},
{
"code": null,
"e": 1653,
"s": 1412,
"text": "1 — The input document is embedded using a pre-trained BERT model. You can pick any BERT model your want from 🤗transformers. This turns a chunk of text into a fixed-size vector that is meant the represent the semantic aspect of the document"
},
{
"code": null,
"e": 1914,
"s": 1653,
"text": "2 — Keywords and expressions (n-grams) are extracted from the same document using Bag Of Words techniques (such as a TfidfVectorizer or CountVectorizer). This is a classical step that you may be familiar with if you’ve performed keywords extraction in the past"
},
{
"code": null,
"e": 2020,
"s": 1914,
"text": "3 — Each keyword is then embedded into a fixed-size vector with the same model used to embed the document"
},
{
"code": null,
"e": 2284,
"s": 2020,
"text": "4 — Now that the keywords and the document are represented in the same space, KeyBERT computes a cosine similarity between the keyword embeddings and the document embedding. Then, the most similar keywords (with the highest cosine similarity score) are extracted."
},
{
"code": null,
"e": 2472,
"s": 2284,
"text": "The idea is pretty simple: you can think of it as an enhanced version of a classical keyword extraction technique in which the BERT language model comes in to add its semantic capability."
},
{
"code": null,
"e": 2575,
"s": 2472,
"text": "This doesn’t stop here: KeyBERT includes two methods to introduce diversity in the resulting keywords."
},
{
"code": null,
"e": 2604,
"s": 2575,
"text": "1 — Max Sum Similarity (MSS)"
},
{
"code": null,
"e": 2898,
"s": 2604,
"text": "To use this method, you start by setting the top_n argument to a value, say 20. Then 2 x top_n keywords are extracted from the document. Pairwise similarities are computed between these keywords. Finally, the method extracts the most relevant keywords that are the least similar to each other."
},
{
"code": null,
"e": 2947,
"s": 2898,
"text": "Here’s an example from the KeyBERT’s repository:"
},
{
"code": null,
"e": 3056,
"s": 2947,
"text": "2 — Maximal Marginal Relevance (MMR)This method is similar to the previous one: it adds a diversity argument"
},
{
"code": null,
"e": 3156,
"s": 3056,
"text": "MMR tries to minimize redundancy and maximize the diversity of results in text summarization tasks."
},
{
"code": null,
"e": 3366,
"s": 3156,
"text": "It starts by selecting the keywords that are the most similar to the document. Then, it iteratively selects new candidates that are both similar to the document and not similar to the already selected keywords"
},
{
"code": null,
"e": 3408,
"s": 3366,
"text": "You can choose a low-diversity threshold:"
},
{
"code": null,
"e": 3423,
"s": 3408,
"text": "or a high one:"
},
{
"code": null,
"e": 3795,
"s": 3423,
"text": "One limitation that KeyBERT may suffer from though is the execution time: if you have large documents and need real-time results, KeyBERT may not be the best solution (unless you have dedicated GPUs in your production environment). The reason being that BERT models are notoriously huge and consume a lot of resources especially when they have to process large documents."
},
{
"code": null,
"e": 3964,
"s": 3795,
"text": "You can probably find some hacks to speed up the inference time by picking smaller models (DistilBERT), using mixed precision or even convert your model to ONNX format."
},
{
"code": null,
"e": 4109,
"s": 3964,
"text": "If this still doesn’t work out for you, check other classical methods: you’d be surprised by their efficiency despite their relative simplicity."
},
{
"code": null,
"e": 4238,
"s": 4109,
"text": "That’s it for today. I hope you’ll find this small method useful for your NLP projects if you’re performing keywords extraction."
}
] |
C++ Program to Implement Multiset in STL
|
A multiset is a type of associative container in which has multiple elements can have same values.
Functions are used here:
ms.size() = Returns the size of multiset.
ms.insert) = It is used to insert elements to the multiset.
ms.erase() = Removes the value from the multiset.
ms.find() = Returns an iterator to the search element in the multiset if found,
else returns the iterator to end.
ms.count() = Returns the number of matches element in the multiset.
ms.begin() = Returns an iterator to the first element in the multiset.
ms.end() = Returns an iterator to the last element in the multiset
#include<iostream>
#include <set>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
multiset<int> ms;
multiset<int>::iterator it, it1;
int c, i;
while (1) {
cout<<"1.Size of the Multiset"<<endl;
cout<<"2.Insert Element into the Multiset"<<endl;
cout<<"3.Delete Element from the Multiset"<<endl;
cout<<"4.Find Element in a Multiset"<<endl;
cout<<"5.Count Elements with a specific key"<<endl;
cout<<"6.Display Multiset"<<endl;
cout<<"7.Exit"<<endl;
cout<<"Enter your Choice: ";
cin>>c;
switch(c) {
case 1:
cout<<"Size of the Multiset: "<<ms.size()<<endl;
break;
case 2:
cout<<"Enter value to be inserted: ";
cin>>i;
if (ms.empty())
it1 = ms.insert(i);
else
it1 = ms.insert(it1, i);
break;
case 3:
cout<<"Enter value to be deleted: ";
cin>>i;
ms.erase(i);
break;
case 4:
cout<<"Enter element to find ";
cin>>i;
it = ms.find(i);
if (it != ms.end())
cout<<"Element found"<<endl;
else
cout<<"Element not found"<<endl;
break;
case 5:
cout<<"Enter element to be counted: ";
cin>>i;
cout<<i<<" appears "<<ms.count(i)<<" times."<<endl;
break;
case 6:
cout<<"Elements of the Multiset: ";
for (it = ms.begin(); it != ms.end(); it++)
cout<<*it<<" ";
cout<<endl;
break;
case 7:
exit(1);
break;
default:
cout<<"Wrong Choice"<<endl;
}
}
return 0;
}
1.Size of the Multiset
2.Insert Element into the Multiset
3.Delete Element from the Multiset
4.Find Element in a Multiset
5.Count Elements with a specific key
6.Display Multiset
7.Exit
Enter your Choice: 1
Size of the Multiset: 0
1.Size of the Multiset
2.Insert Element into the Multiset
3.Delete Element from the Multiset
4.Find Element in a Multiset
5.Count Elements with a specific key
6.Display Multiset
7.Exit
Enter your Choice: 2
Enter value to be inserted: 1
1.Size of the Multiset
2.Insert Element into the Multiset
3.Delete Element from the Multiset
4.Find Element in a Multiset
5.Count Elements with a specific key
6.Display Multiset
7.Exit
Enter your Choice: 2
Enter value to be inserted: 2
1.Size of the Multiset
2.Insert Element into the Multiset
3.Delete Element from the Multiset
4.Find Element in a Multiset
5.Count Elements with a specific key
6.Display Multiset
7.Exit
Enter your Choice: 2
Enter value to be inserted: 3
1.Size of the Multiset
2.Insert Element into the Multiset
3.Delete Element from the Multiset
4.Find Element in a Multiset
5.Count Elements with a specific key
6.Display Multiset
7.Exit
Enter your Choice: 2
Enter value to be inserted: 4
1.Size of the Multiset
2.Insert Element into the Multiset
3.Delete Element from the Multiset
4.Find Element in a Multiset
5.Count Elements with a specific key
6.Display Multiset
7.Exit
Enter your Choice: 6
Elements of the Multiset: 1 2 3 4
1.Size of the Multiset
2.Insert Element into the Multiset
3.Delete Element from the Multiset
4.Find Element in a Multiset
5.Count Elements with a specific key
6.Display Multiset
7.Exit
Enter your Choice: 3
Enter value to be deleted: 4
1.Size of the Multiset
2.Insert Element into the Multiset
3.Delete Element from the Multiset
4.Find Element in a Multiset
5.Count Elements with a specific key
6.Display Multiset
7.Exit
Enter your Choice: 4
Enter element to find 1
Element found
1.Size of the Multiset
2.Insert Element into the Multiset
3.Delete Element from the Multiset
4.Find Element in a Multiset
5.Count Elements with a specific key
6.Display Multiset
7.Exit
Enter your Choice: 5
Enter element to be counted: 2
2 appears 1 times.
1.Size of the Multiset
2.Insert Element into the Multiset
3.Delete Element from the Multiset
4.Find Element in a Multiset
5.Count Elements with a specific key
6.Display Multiset
7.Exit
Enter your Choice: 7
Exit code: 1
|
[
{
"code": null,
"e": 1161,
"s": 1062,
"text": "A multiset is a type of associative container in which has multiple elements can have same values."
},
{
"code": null,
"e": 1682,
"s": 1161,
"text": "Functions are used here:\n ms.size() = Returns the size of multiset.\n ms.insert) = It is used to insert elements to the multiset.\n ms.erase() = Removes the value from the multiset.\n ms.find() = Returns an iterator to the search element in the multiset if found,\n else returns the iterator to end.\n ms.count() = Returns the number of matches element in the multiset.\n ms.begin() = Returns an iterator to the first element in the multiset.\n ms.end() = Returns an iterator to the last element in the multiset"
},
{
"code": null,
"e": 3482,
"s": 1682,
"text": "#include<iostream>\n#include <set>\n#include <string>\n#include <cstdlib>\nusing namespace std;\nint main() {\n multiset<int> ms;\n multiset<int>::iterator it, it1;\n int c, i;\n while (1) {\n cout<<\"1.Size of the Multiset\"<<endl;\n cout<<\"2.Insert Element into the Multiset\"<<endl;\n cout<<\"3.Delete Element from the Multiset\"<<endl;\n cout<<\"4.Find Element in a Multiset\"<<endl;\n cout<<\"5.Count Elements with a specific key\"<<endl;\n cout<<\"6.Display Multiset\"<<endl;\n cout<<\"7.Exit\"<<endl;\n cout<<\"Enter your Choice: \";\n cin>>c;\n switch(c) {\n case 1:\n cout<<\"Size of the Multiset: \"<<ms.size()<<endl;\n break;\n case 2:\n cout<<\"Enter value to be inserted: \";\n cin>>i;\n if (ms.empty())\n it1 = ms.insert(i);\n else\n it1 = ms.insert(it1, i);\n break;\n case 3:\n cout<<\"Enter value to be deleted: \";\n cin>>i;\n ms.erase(i);\n break;\n case 4:\n cout<<\"Enter element to find \";\n cin>>i;\n it = ms.find(i);\n if (it != ms.end())\n cout<<\"Element found\"<<endl;\n else\n cout<<\"Element not found\"<<endl;\n break;\n case 5:\n cout<<\"Enter element to be counted: \";\n cin>>i;\n cout<<i<<\" appears \"<<ms.count(i)<<\" times.\"<<endl;\n break;\n case 6:\n cout<<\"Elements of the Multiset: \";\n for (it = ms.begin(); it != ms.end(); it++)\n cout<<*it<<\" \";\n cout<<endl;\n break;\n case 7:\n exit(1);\n break;\n default:\n cout<<\"Wrong Choice\"<<endl;\n }\n }\n return 0;\n}"
},
{
"code": null,
"e": 5850,
"s": 3482,
"text": "1.Size of the Multiset\n2.Insert Element into the Multiset\n3.Delete Element from the Multiset\n4.Find Element in a Multiset\n5.Count Elements with a specific key\n6.Display Multiset\n7.Exit\nEnter your Choice: 1\nSize of the Multiset: 0\n1.Size of the Multiset\n2.Insert Element into the Multiset\n3.Delete Element from the Multiset\n4.Find Element in a Multiset\n5.Count Elements with a specific key\n6.Display Multiset\n7.Exit\nEnter your Choice: 2\nEnter value to be inserted: 1\n1.Size of the Multiset\n2.Insert Element into the Multiset\n3.Delete Element from the Multiset\n4.Find Element in a Multiset\n5.Count Elements with a specific key\n6.Display Multiset\n7.Exit\nEnter your Choice: 2\nEnter value to be inserted: 2\n1.Size of the Multiset\n2.Insert Element into the Multiset\n3.Delete Element from the Multiset\n4.Find Element in a Multiset\n5.Count Elements with a specific key\n6.Display Multiset\n7.Exit\nEnter your Choice: 2\nEnter value to be inserted: 3\n1.Size of the Multiset\n2.Insert Element into the Multiset\n3.Delete Element from the Multiset\n4.Find Element in a Multiset\n5.Count Elements with a specific key\n6.Display Multiset\n7.Exit\nEnter your Choice: 2\nEnter value to be inserted: 4\n1.Size of the Multiset\n2.Insert Element into the Multiset\n3.Delete Element from the Multiset\n4.Find Element in a Multiset\n5.Count Elements with a specific key\n6.Display Multiset\n7.Exit\nEnter your Choice: 6\nElements of the Multiset: 1 2 3 4\n1.Size of the Multiset\n2.Insert Element into the Multiset\n3.Delete Element from the Multiset\n4.Find Element in a Multiset\n5.Count Elements with a specific key\n6.Display Multiset\n7.Exit\nEnter your Choice: 3\nEnter value to be deleted: 4\n1.Size of the Multiset\n2.Insert Element into the Multiset\n3.Delete Element from the Multiset\n4.Find Element in a Multiset\n5.Count Elements with a specific key\n6.Display Multiset\n7.Exit\nEnter your Choice: 4\nEnter element to find 1\nElement found\n1.Size of the Multiset\n2.Insert Element into the Multiset\n3.Delete Element from the Multiset\n4.Find Element in a Multiset\n5.Count Elements with a specific key\n6.Display Multiset\n7.Exit\nEnter your Choice: 5\nEnter element to be counted: 2\n2 appears 1 times.\n1.Size of the Multiset\n2.Insert Element into the Multiset\n3.Delete Element from the Multiset\n4.Find Element in a Multiset\n5.Count Elements with a specific key\n6.Display Multiset\n7.Exit\nEnter your Choice: 7\nExit code: 1"
}
] |
How to declare, define and call a method in Java?
|
Following is the syntax to declare a method in Java.
modifier return_type method_name(parameters_list){
//method body
}
Where,
modifier − It defines the access type of the method and it is optional to use.
modifier − It defines the access type of the method and it is optional to use.
return_type − Method may return a value.
return_type − Method may return a value.
method_name − This is the method name. The method signature consists of the method name and the parameter list.
method_name − This is the method name. The method signature consists of the method name and the parameter list.
parameters_list − The list of parameters, it is the type, order, and a number of parameters of a method. These are optional, method may contain zero parameters.
parameters_list − The list of parameters, it is the type, order, and a number of parameters of a method. These are optional, method may contain zero parameters.
method body − The method body defines what the method does with the statements.
method body − The method body defines what the method does with the statements.
For using a method, it should be called. There are two ways in which a method is called i.e., method returns a value or returning nothing (no return value).
Following is the example to demonstrate how to define a method and how to call it −
Live Demo
public class ExampleMinNumber {
public static void main(String[] args) {
int a = 11;
int b = 6;
int c = minFunction(a, b);
System.out.println("Minimum Value = " + c);
}
/** Returns the minimum of two numbers */
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2){
min = n2;
} else {
min = n1;
}
return min;
}
}
Minimum value = 6
|
[
{
"code": null,
"e": 1115,
"s": 1062,
"text": "Following is the syntax to declare a method in Java."
},
{
"code": null,
"e": 1186,
"s": 1115,
"text": "modifier return_type method_name(parameters_list){\n //method body\n}\n"
},
{
"code": null,
"e": 1193,
"s": 1186,
"text": "Where,"
},
{
"code": null,
"e": 1272,
"s": 1193,
"text": "modifier − It defines the access type of the method and it is optional to use."
},
{
"code": null,
"e": 1351,
"s": 1272,
"text": "modifier − It defines the access type of the method and it is optional to use."
},
{
"code": null,
"e": 1392,
"s": 1351,
"text": "return_type − Method may return a value."
},
{
"code": null,
"e": 1433,
"s": 1392,
"text": "return_type − Method may return a value."
},
{
"code": null,
"e": 1545,
"s": 1433,
"text": "method_name − This is the method name. The method signature consists of the method name and the parameter list."
},
{
"code": null,
"e": 1657,
"s": 1545,
"text": "method_name − This is the method name. The method signature consists of the method name and the parameter list."
},
{
"code": null,
"e": 1818,
"s": 1657,
"text": "parameters_list − The list of parameters, it is the type, order, and a number of parameters of a method. These are optional, method may contain zero parameters."
},
{
"code": null,
"e": 1979,
"s": 1818,
"text": "parameters_list − The list of parameters, it is the type, order, and a number of parameters of a method. These are optional, method may contain zero parameters."
},
{
"code": null,
"e": 2059,
"s": 1979,
"text": "method body − The method body defines what the method does with the statements."
},
{
"code": null,
"e": 2139,
"s": 2059,
"text": "method body − The method body defines what the method does with the statements."
},
{
"code": null,
"e": 2296,
"s": 2139,
"text": "For using a method, it should be called. There are two ways in which a method is called i.e., method returns a value or returning nothing (no return value)."
},
{
"code": null,
"e": 2380,
"s": 2296,
"text": "Following is the example to demonstrate how to define a method and how to call it −"
},
{
"code": null,
"e": 2391,
"s": 2380,
"text": " Live Demo"
},
{
"code": null,
"e": 2811,
"s": 2391,
"text": "public class ExampleMinNumber {\n public static void main(String[] args) {\n int a = 11;\n int b = 6;\n int c = minFunction(a, b);\n System.out.println(\"Minimum Value = \" + c);\n }\n \n /** Returns the minimum of two numbers */\n public static int minFunction(int n1, int n2) {\n int min;\n if (n1 > n2){\n min = n2;\n } else {\n min = n1;\n }\n return min;\n }\n}"
},
{
"code": null,
"e": 2830,
"s": 2811,
"text": "Minimum value = 6\n"
}
] |
Image Clustering Using k-Means. Using transfer learning model for... | by Shubham Gupta | Towards Data Science
|
In an image classification problem we have to classify a given set of images into a given number of categories. Training data is available in classification problem but what to do when there is no training data available, to solve this problem we can use clustering to group similar images together.
Clustering is an unsupervised machine learning where we group similar features together. It interprets the input data and finds natural groups or clusters in feature space.
Here I have used k-means for image clustering. I have taken cats vs dogs dataset.
I have separated cat and dog images into separate folders and show how clustering can be done in images.
I have used transfer learning model InceptionV3 to extract features from images and use those features for clustering.
First, let us get all the required libraries,
from tensorflow.keras.applications.inception_v3 import InceptionV3from tensorflow.keras.applications.inception_v3 import preprocess_inputfrom tensorflow.keras.preprocessing import imagefrom tensorflow.keras.preprocessing.image import img_to_arrayfrom sklearn.cluster import KMeansimport pandas as pdimport numpy as npfrom tqdm import tqdmimport osimport shutil
The dataset is available on Kaggle, it can be downloaded from here. I have taken only 700 images for clustering, 350 images of each class.
These images are put in one folder and the features are extracted using transfer learning model. Below is the method to extract features from the images using InceptionV3 model and I have saved the image name in order to tell which image is in which cluster.
# Function to Extract features from the imagesdef image_feature(direc): model = InceptionV3(weights='imagenet', include_top=False) features = []; img_name = []; for i in tqdm(direc): fname='cluster'+'/'+i img=image.load_img(fname,target_size=(224,224)) x = img_to_array(img) x=np.expand_dims(x,axis=0) x=preprocess_input(x) feat=model.predict(x) feat=feat.flatten() features.append(feat) img_name.append(i) return features,img_name
Using the above function, I extracted the features and name and stored them in img_features,img_name.
img_path=os.listdir('cluster')img_features,img_name=image_feature(img_path)
Now, these extracted features are used for clustering, k-Means clustering is used. Below is the code for k-Means clustering, The value of k is 2 because there are only 2 classes.
#Creating Clustersk = 2clusters = KMeans(k, random_state = 40)clusters.fit(img_features)
The 2 clusters are created, the img_name that was extracted was converted to dataframe and I added another column to show which image belongs to which cluster and after that, I saved the images in their respective cluster.
image_cluster = pd.DataFrame(img_name,columns=['image'])image_cluster["clusterid"] = clusters.labels_image_cluster # 0 denotes cat and 1 denotes dog
Now I have saved images of cats and dogs in a separate folder.
# Made folder to seperate imagesos.mkdir('cats')os.mkdir('dogs')# Images will be seperated according to cluster they belongfor i in range(len(image_cluster)): if image_cluster['clusterid'][i]==0: shutil.move(os.path.join('cluster', image_cluster['image'] [i]), 'cats') else: shutil.move(os.path.join('cluster', image_cluster['image'][i]), 'dogs')
The above code will separate the images in different files based on the clusterid.
In this blog, we have discussed how to extract features from images using transfer learning and then perform clustering to separate images of cats and dogs in a different folders. It can be used for labelling where we don’t know about the classes of the images as manually labelling will be a challenge.
All the code in this article resides on this Github link:
|
[
{
"code": null,
"e": 472,
"s": 172,
"text": "In an image classification problem we have to classify a given set of images into a given number of categories. Training data is available in classification problem but what to do when there is no training data available, to solve this problem we can use clustering to group similar images together."
},
{
"code": null,
"e": 645,
"s": 472,
"text": "Clustering is an unsupervised machine learning where we group similar features together. It interprets the input data and finds natural groups or clusters in feature space."
},
{
"code": null,
"e": 727,
"s": 645,
"text": "Here I have used k-means for image clustering. I have taken cats vs dogs dataset."
},
{
"code": null,
"e": 832,
"s": 727,
"text": "I have separated cat and dog images into separate folders and show how clustering can be done in images."
},
{
"code": null,
"e": 951,
"s": 832,
"text": "I have used transfer learning model InceptionV3 to extract features from images and use those features for clustering."
},
{
"code": null,
"e": 997,
"s": 951,
"text": "First, let us get all the required libraries,"
},
{
"code": null,
"e": 1358,
"s": 997,
"text": "from tensorflow.keras.applications.inception_v3 import InceptionV3from tensorflow.keras.applications.inception_v3 import preprocess_inputfrom tensorflow.keras.preprocessing import imagefrom tensorflow.keras.preprocessing.image import img_to_arrayfrom sklearn.cluster import KMeansimport pandas as pdimport numpy as npfrom tqdm import tqdmimport osimport shutil"
},
{
"code": null,
"e": 1497,
"s": 1358,
"text": "The dataset is available on Kaggle, it can be downloaded from here. I have taken only 700 images for clustering, 350 images of each class."
},
{
"code": null,
"e": 1756,
"s": 1497,
"text": "These images are put in one folder and the features are extracted using transfer learning model. Below is the method to extract features from the images using InceptionV3 model and I have saved the image name in order to tell which image is in which cluster."
},
{
"code": null,
"e": 2266,
"s": 1756,
"text": "# Function to Extract features from the imagesdef image_feature(direc): model = InceptionV3(weights='imagenet', include_top=False) features = []; img_name = []; for i in tqdm(direc): fname='cluster'+'/'+i img=image.load_img(fname,target_size=(224,224)) x = img_to_array(img) x=np.expand_dims(x,axis=0) x=preprocess_input(x) feat=model.predict(x) feat=feat.flatten() features.append(feat) img_name.append(i) return features,img_name"
},
{
"code": null,
"e": 2368,
"s": 2266,
"text": "Using the above function, I extracted the features and name and stored them in img_features,img_name."
},
{
"code": null,
"e": 2444,
"s": 2368,
"text": "img_path=os.listdir('cluster')img_features,img_name=image_feature(img_path)"
},
{
"code": null,
"e": 2623,
"s": 2444,
"text": "Now, these extracted features are used for clustering, k-Means clustering is used. Below is the code for k-Means clustering, The value of k is 2 because there are only 2 classes."
},
{
"code": null,
"e": 2712,
"s": 2623,
"text": "#Creating Clustersk = 2clusters = KMeans(k, random_state = 40)clusters.fit(img_features)"
},
{
"code": null,
"e": 2935,
"s": 2712,
"text": "The 2 clusters are created, the img_name that was extracted was converted to dataframe and I added another column to show which image belongs to which cluster and after that, I saved the images in their respective cluster."
},
{
"code": null,
"e": 3084,
"s": 2935,
"text": "image_cluster = pd.DataFrame(img_name,columns=['image'])image_cluster[\"clusterid\"] = clusters.labels_image_cluster # 0 denotes cat and 1 denotes dog"
},
{
"code": null,
"e": 3147,
"s": 3084,
"text": "Now I have saved images of cats and dogs in a separate folder."
},
{
"code": null,
"e": 3528,
"s": 3147,
"text": "# Made folder to seperate imagesos.mkdir('cats')os.mkdir('dogs')# Images will be seperated according to cluster they belongfor i in range(len(image_cluster)): if image_cluster['clusterid'][i]==0: shutil.move(os.path.join('cluster', image_cluster['image'] [i]), 'cats') else: shutil.move(os.path.join('cluster', image_cluster['image'][i]), 'dogs')"
},
{
"code": null,
"e": 3611,
"s": 3528,
"text": "The above code will separate the images in different files based on the clusterid."
},
{
"code": null,
"e": 3915,
"s": 3611,
"text": "In this blog, we have discussed how to extract features from images using transfer learning and then perform clustering to separate images of cats and dogs in a different folders. It can be used for labelling where we don’t know about the classes of the images as manually labelling will be a challenge."
}
] |
What is the difference between ng-if and data-ng-if directives ? - GeeksforGeeks
|
23 Jul, 2019
The ng-if is a directive in AngularJS which is used to remove the HTML element if the value of the expression or variable is false, unlike ng-hide which just hides the HTML element from the DOM.
Syntax:
<element angular_directive=expression> Contents... </element>
There are few other options which behave like ng-if. There is no difference among them in functionality wise.
ng:if
ng_if
x-ng-if
data-ng-if
Note: The best practice is to use ng-if only.
The reason behind why these options come into the picture is that in AngularJS we refer to the directive using camel case (example:ngIf) but when we use it in HTML since HTML is case insensitive we use a dash-delimited form (example:ng-if) or other delimiters as mentioned in the list above. So the AngularJS normalizes (It means it converts the delimiter form into camelcase.) the element’s tag and figures out to which directive does the element belong.
Example 1: This example uses “data-ng-if” directive.
<!DOCTYPE html><html> <head> <title> What is the difference between ng-if and data-ng-if directives ? </title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body ng-app=""> <center> <h1 style="color:green"> GeeksforGeeks </h1> <input ng-model="var1"> <div data-ng-if="var1"> <h3> This will disappear if the value of input var1 is set to false and will appear again when true </h3> </div> </center></body> </html>
Output:
Example 2: This example uses “ng-if” directive.
<!DOCTYPE html><html> <head> <title> What is the difference between ng-if and data-ng-if directives ? </title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body ng-app=""> <center> <h1 style="color:green"> GeeksforGeeks </h1> <input ng-model="var1"> <div ng-if="var1"> <h3> This will disappear if the value of input var1 is set to false and will appear again when true </h3> </div> </center></body> </html>
Output:
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Angular PrimeNG Dropdown Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular 10 (blur) Event
How to setup 404 page in angular routing ?
How to create module with Routing in Angular 9 ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24718,
"s": 24690,
"text": "\n23 Jul, 2019"
},
{
"code": null,
"e": 24913,
"s": 24718,
"text": "The ng-if is a directive in AngularJS which is used to remove the HTML element if the value of the expression or variable is false, unlike ng-hide which just hides the HTML element from the DOM."
},
{
"code": null,
"e": 24921,
"s": 24913,
"text": "Syntax:"
},
{
"code": null,
"e": 24983,
"s": 24921,
"text": "<element angular_directive=expression> Contents... </element>"
},
{
"code": null,
"e": 25093,
"s": 24983,
"text": "There are few other options which behave like ng-if. There is no difference among them in functionality wise."
},
{
"code": null,
"e": 25099,
"s": 25093,
"text": "ng:if"
},
{
"code": null,
"e": 25105,
"s": 25099,
"text": "ng_if"
},
{
"code": null,
"e": 25113,
"s": 25105,
"text": "x-ng-if"
},
{
"code": null,
"e": 25124,
"s": 25113,
"text": "data-ng-if"
},
{
"code": null,
"e": 25170,
"s": 25124,
"text": "Note: The best practice is to use ng-if only."
},
{
"code": null,
"e": 25626,
"s": 25170,
"text": "The reason behind why these options come into the picture is that in AngularJS we refer to the directive using camel case (example:ngIf) but when we use it in HTML since HTML is case insensitive we use a dash-delimited form (example:ng-if) or other delimiters as mentioned in the list above. So the AngularJS normalizes (It means it converts the delimiter form into camelcase.) the element’s tag and figures out to which directive does the element belong."
},
{
"code": null,
"e": 25679,
"s": 25626,
"text": "Example 1: This example uses “data-ng-if” directive."
},
{
"code": "<!DOCTYPE html><html> <head> <title> What is the difference between ng-if and data-ng-if directives ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body ng-app=\"\"> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <input ng-model=\"var1\"> <div data-ng-if=\"var1\"> <h3> This will disappear if the value of input var1 is set to false and will appear again when true </h3> </div> </center></body> </html>",
"e": 26307,
"s": 25679,
"text": null
},
{
"code": null,
"e": 26315,
"s": 26307,
"text": "Output:"
},
{
"code": null,
"e": 26363,
"s": 26315,
"text": "Example 2: This example uses “ng-if” directive."
},
{
"code": "<!DOCTYPE html><html> <head> <title> What is the difference between ng-if and data-ng-if directives ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body ng-app=\"\"> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <input ng-model=\"var1\"> <div ng-if=\"var1\"> <h3> This will disappear if the value of input var1 is set to false and will appear again when true </h3> </div> </center></body> </html>",
"e": 26986,
"s": 26363,
"text": null
},
{
"code": null,
"e": 26994,
"s": 26986,
"text": "Output:"
},
{
"code": null,
"e": 27009,
"s": 26994,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 27016,
"s": 27009,
"text": "Picked"
},
{
"code": null,
"e": 27026,
"s": 27016,
"text": "AngularJS"
},
{
"code": null,
"e": 27043,
"s": 27026,
"text": "Web Technologies"
},
{
"code": null,
"e": 27141,
"s": 27043,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27150,
"s": 27141,
"text": "Comments"
},
{
"code": null,
"e": 27163,
"s": 27150,
"text": "Old Comments"
},
{
"code": null,
"e": 27198,
"s": 27163,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 27251,
"s": 27198,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 27275,
"s": 27251,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 27318,
"s": 27275,
"text": "How to setup 404 page in angular routing ?"
},
{
"code": null,
"e": 27367,
"s": 27318,
"text": "How to create module with Routing in Angular 9 ?"
},
{
"code": null,
"e": 27423,
"s": 27367,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 27456,
"s": 27423,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27518,
"s": 27456,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27561,
"s": 27518,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
GATE | GATE CS 2019 | Question 6 - GeeksforGeeks
|
13 Feb, 2019
Ten friends planned to share equally the cost of buying a gifts for their teacher. When two of them decided not to contribute, each of the other friends had to pay Rs. 150 more. The cost of the gift was Rs. _________ .(A) 666(B) 3000(C) 6000(D) 12000Answer: (C)Explanation: Let share of each student = x
Since cost of gift will be same in both situation, therefore,
→ 10*x = 8*(x + 150)
→ 10*x = 8*x + 8*150
→ 2*x = 8*150
→ x = 8*150 / 2
→ x = 600
Therefore, cost of gift is,
10*x = 10*600 = 6000
Option (C) is correct.Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2007 | Question 17
GATE | GATE CS 2019 | Question 37
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 1997 | Question 25
GATE | GATE-CS-2007 | Question 64
GATE | GATE-CS-2015 (Set 1) | Question 62
|
[
{
"code": null,
"e": 24368,
"s": 24340,
"text": "\n13 Feb, 2019"
},
{
"code": null,
"e": 24672,
"s": 24368,
"text": "Ten friends planned to share equally the cost of buying a gifts for their teacher. When two of them decided not to contribute, each of the other friends had to pay Rs. 150 more. The cost of the gift was Rs. _________ .(A) 666(B) 3000(C) 6000(D) 12000Answer: (C)Explanation: Let share of each student = x"
},
{
"code": null,
"e": 24734,
"s": 24672,
"text": "Since cost of gift will be same in both situation, therefore,"
},
{
"code": null,
"e": 24818,
"s": 24734,
"text": "→ 10*x = 8*(x + 150) \n→ 10*x = 8*x + 8*150\n→ 2*x = 8*150\n→ x = 8*150 / 2\n→ x = 600 "
},
{
"code": null,
"e": 24846,
"s": 24818,
"text": "Therefore, cost of gift is,"
},
{
"code": null,
"e": 24868,
"s": 24846,
"text": "10*x = 10*600 = 6000 "
},
{
"code": null,
"e": 24912,
"s": 24868,
"text": "Option (C) is correct.Quiz of this Question"
},
{
"code": null,
"e": 24917,
"s": 24912,
"text": "GATE"
},
{
"code": null,
"e": 25015,
"s": 24917,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25024,
"s": 25015,
"text": "Comments"
},
{
"code": null,
"e": 25037,
"s": 25024,
"text": "Old Comments"
},
{
"code": null,
"e": 25071,
"s": 25037,
"text": "GATE | GATE-IT-2004 | Question 83"
},
{
"code": null,
"e": 25113,
"s": 25071,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 65"
},
{
"code": null,
"e": 25155,
"s": 25113,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 25197,
"s": 25155,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 25231,
"s": 25197,
"text": "GATE | GATE-CS-2007 | Question 17"
},
{
"code": null,
"e": 25265,
"s": 25231,
"text": "GATE | GATE CS 2019 | Question 37"
},
{
"code": null,
"e": 25307,
"s": 25265,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 25341,
"s": 25307,
"text": "GATE | GATE CS 1997 | Question 25"
},
{
"code": null,
"e": 25375,
"s": 25341,
"text": "GATE | GATE-CS-2007 | Question 64"
}
] |
Check whether two strings are equivalent or not according to given condition in Python
|
Suppose we have two strings s and t of same size. We have to check whether s and t are equivalent or not. There are few conditions to check:
They both are equal. Or,
If we divide the s into two contiguous substrings of same size and the substrings are s1 and s2 and also divide t same like, s into t1 and t2, then one of the following should be valid:s1 is recursively equivalent to t1 and s2 is recursively equivalent to t2s1 is recursively equivalent to t2 and s2 is recursively equivalent to t1
s1 is recursively equivalent to t1 and s2 is recursively equivalent to t2
s1 is recursively equivalent to t2 and s2 is recursively equivalent to t1
So, if the input is like s = "ppqp" t = "pqpp", then the output will be True as if we divide s and t into two parts s1 = "pp", s2 = "qp" and t1 = "pq", t2 = "pp", here s1 = t2 and if we divide s2 and t1 into two parts s21 = "q", s22 = "p", t11 = "p", t12 = "q", here also s21 = t12 and s22 = t11, so they are recursively equivalent.
To solve this, we will follow these steps −
Define a function util() . This will take s
if size of s is odd, thenreturn s
return s
left := util(left half part of s)
right := util(right half part of s)
return minimum of (left concatenate right), (right concatenate left)
From the main method return true when util(s) is same as util(t) otherwise false
Let us see the following implementation to get better understanding −
Live Demo
def util(s):
if len(s) & 1 != 0:
return s
left = util(s[0:int(len(s) / 2)])
right = util(s[int(len(s) / 2):len(s)])
return min(left + right, right + left)
def solve(s,t):
return util(s) == util(t)
s = "ppqp"
t = "pqpp"
print(solve(s, t))
"ppqp", "pqpp"
True
|
[
{
"code": null,
"e": 1203,
"s": 1062,
"text": "Suppose we have two strings s and t of same size. We have to check whether s and t are equivalent or not. There are few conditions to check:"
},
{
"code": null,
"e": 1228,
"s": 1203,
"text": "They both are equal. Or,"
},
{
"code": null,
"e": 1560,
"s": 1228,
"text": "If we divide the s into two contiguous substrings of same size and the substrings are s1 and s2 and also divide t same like, s into t1 and t2, then one of the following should be valid:s1 is recursively equivalent to t1 and s2 is recursively equivalent to t2s1 is recursively equivalent to t2 and s2 is recursively equivalent to t1"
},
{
"code": null,
"e": 1634,
"s": 1560,
"text": "s1 is recursively equivalent to t1 and s2 is recursively equivalent to t2"
},
{
"code": null,
"e": 1708,
"s": 1634,
"text": "s1 is recursively equivalent to t2 and s2 is recursively equivalent to t1"
},
{
"code": null,
"e": 2041,
"s": 1708,
"text": "So, if the input is like s = \"ppqp\" t = \"pqpp\", then the output will be True as if we divide s and t into two parts s1 = \"pp\", s2 = \"qp\" and t1 = \"pq\", t2 = \"pp\", here s1 = t2 and if we divide s2 and t1 into two parts s21 = \"q\", s22 = \"p\", t11 = \"p\", t12 = \"q\", here also s21 = t12 and s22 = t11, so they are recursively equivalent."
},
{
"code": null,
"e": 2085,
"s": 2041,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 2129,
"s": 2085,
"text": "Define a function util() . This will take s"
},
{
"code": null,
"e": 2163,
"s": 2129,
"text": "if size of s is odd, thenreturn s"
},
{
"code": null,
"e": 2172,
"s": 2163,
"text": "return s"
},
{
"code": null,
"e": 2206,
"s": 2172,
"text": "left := util(left half part of s)"
},
{
"code": null,
"e": 2242,
"s": 2206,
"text": "right := util(right half part of s)"
},
{
"code": null,
"e": 2311,
"s": 2242,
"text": "return minimum of (left concatenate right), (right concatenate left)"
},
{
"code": null,
"e": 2392,
"s": 2311,
"text": "From the main method return true when util(s) is same as util(t) otherwise false"
},
{
"code": null,
"e": 2462,
"s": 2392,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2472,
"s": 2462,
"text": "Live Demo"
},
{
"code": null,
"e": 2738,
"s": 2472,
"text": "def util(s):\n if len(s) & 1 != 0:\n return s\n \n left = util(s[0:int(len(s) / 2)])\n right = util(s[int(len(s) / 2):len(s)])\n \n return min(left + right, right + left)\n \ndef solve(s,t):\n return util(s) == util(t)\n\ns = \"ppqp\"\nt = \"pqpp\"\nprint(solve(s, t))"
},
{
"code": null,
"e": 2754,
"s": 2738,
"text": "\"ppqp\", \"pqpp\"\n"
},
{
"code": null,
"e": 2759,
"s": 2754,
"text": "True"
}
] |
Building Your Own Deep Learning Computer And Saving Money on Cloud Services | by Chris Fotache | Towards Data Science
|
After struggling with Microsoft Azure’s GPU VM’s for a few years, and hearing that Amazon’s AWS is not much better, I decided it’s time to have my own local deep learning machine.
One of my main reasons was that the cloud VM doesn’t have a display, therefore you can’t do anything visually. No big deal if you just train there and then run the model on a local computer but if you need to work on simulation-based robotics projects, those won’t run at all in a virtual environment.
I later found that not only building an almost state-of-the-art machine pays for itself in about 4 months, but it is significantly faster than a cloud server (mainly because of local data transfer speed, since everything is in the same box on the same bus, while the cloud service might have the compute units and storage in different racks — so even if the GPU is faster, it can’t get the data fast enough to benefit from that speed).
My system ended costing just under $3K (compare that to about $800/month you’d pay for an entry-level cloud GPU from AWS or Azure). That was in May 2019, and prices tend to vary a lot so it can be 10% lower and higher at any time. Also, by the time you read this technology might’ve already evolved.
You might ask why go to the pain of building the computer yourself instead of buying a high-end super-computer. It’s because ready-built deep learning systems are insanely expensive. But if you are still afraid to tinker with expensive components and are interested in a pre-built system, I found that Exxact sells some of the most affordable deep learning systems starting at $5,899 (2x NVIDIA RTX 2080 Ti + Intel Core i9) which also includes a 3 year warranty and deep learning stack. They are also recommended by another AI engineer, Jeff Chen.
To make sure everything works together, I recommend using PC Part Picker. It will both show you the lowest price for each component, and ensure that you don’t pick incompatible parts. As for putting things together, YouTube rules. Just type the name of the component and you’ll find several very explanatory videos on how to install it. So now lets go over the components that are required:
CPU
Here you’ll have to make a big choice: AMD or Intel. For my entire life I’ve been an Intel fan, but for this machine the CPU is not the most important part. That is the GPU. And Intel CPU’s can cost twice as much as the AMD counterpart. AMD’s new Ryzen line has very good reviews, and I don’t need to overclock it since I’m not playing video games with it. Therefore I went for the AMD Threadripper 1920x, which has 12 cores and 24 threads, more than enough for my case. It was reasonable priced around $350 but prices were dropping. The alternative would be the 10-core Intel i9–7900 at over $900.
CPU Cooler
AMD CPUs have always ran very hot (one of the main reasons they weren’t that reliable). They still are, so you definitely need a liquid cooler. I went with the Fractal S24 which has 2 fans, at about $115. An alternative is the Corsair H100i.
Motherboard
The main choice about the motherboard is the chipset. The simple rule is: For AMD Threadripper, use X399. For Intel 7900, use X299.
Based on reviews, I went with the MSI X399 Gaming Pro Carbon AC, which has everything I needed for deep learning. You’ll find it at just over $300. Other good alternatives are the Asus ROG, Gigabyte Aorus and Asrock Taichi (just make sure it has at least 40 PCIe lanes). You have to make sure the board design accomodates the size of the GPU, and maybe adding multiple GPU’s. The MSI one has plenty of room, and everything is well placed.
GPU
Now this is the most important component of your deep learning system. You have to go with an Nvidia GPU, and the minimum recommended is the GTX 1080 Ti. Unfortunately, when I was looking, that was impossible to find at its regular price of about $800 (blame gamers? crypto miners?). So I had to go to the next level, the RTX 2080 Ti, which is not easy to find either, but I was lucky to get on an excellent $1,187 deal from EVGA. RTX is the newer generation, with one of the best performance among early 2019 consumer GPU’s. I’m glad I was “forced” to make that choice. If you look around, you might still find deals around $1,200. I think EVGA and Gigabyte are the top manufacturers, and the choices you make are about the cooling system. The EVGA RTX 2080 Ti XC Ultra has dual air coolers and that proved enough so far, it never got to critical overheating.
Memory
For the configuration above, DDR4 is the best choice. Corsair is probably the main manufacturer. And it’s 2019, you need 64Gb. So I ended up with 4x16Gb Corsair Vengeance LPX DDR4. I paid $399 but prices are dropping dramatically, they’re well under $300 by now.
Hard-Drive
SSD is old tech by now. The state-of-the-art is the M.2 standard, and that drive plugs right into the motherboard into a PCIe slot. Going at the main bus speed, this is basically a high-capacity, persistent memory chip. I really liked the 1Tb Samsung EVO SSD M.2. I paid $241 but prices for this also went down towards $200. If you need more storage, you can add a regular SSD drive which should be less than $100.
Power Supply
PCPartPicker will make sure you pick a power supply big enough for your system. There are also other online wattage calculators. With one GPU you probably won’t get close to 1,000W but if you plan to add a second GPU, then you need 1,200W to be safe. EVGA is a solid manufacturer and I picked the EVGA SuperNOVA P2 Platinum 1200 which is around $250.
Case
There are plenty of options here, and it might come down to personal preferences and design, but it’s important to make sure it’s big enough to fit all the components in without being cramped, and to have good air circulation. I went with the Lian-Li PC-O11AIR at $114 because it fit those requirements. It’s very roomy, everything is well placed inside, and there’s good cooling.
Additional Cooling
After you’re done with your build, you might want to add additional fans to improve the air flow. My case came with several fans, but I got additional ones, to fill almost every mounting location. It can never get too cold in a GPU machine that’s gonna crank up convolutional networks. I got an 80mm Noctua for the back, and also a regular 120mm Corsair that I added on top. And yes, I got theRGB one. I didn’t care much about bright shiny colors in my case (since it’s under the desk anyway), but in the end I gave in and bought a cool fan.
Assembly
Like I said, search for each component on YouTube and you’re sure to find detailed walkthroughs about installation. As an example, here are a few that I followed: a build similar to mine, a walkthrough of the MSI X399 motherboard and its components, and a focus on the Threadripper mounting. And read all the installation instructions in the manuals. For example, be careful about the slot locations of the memory units.
Basically, the order of operations is this:
First, prep the case, install the power supply and pull the power cables. Then prep the motherboard, install the CPU and then the M.2 drive. Mount the motherboard in the case and add the CPU cooler. Then add the other fans and connect the power and button / lights wires. Finally install the memory modules and the GPU.
After you’re done and you power up the system, finish with cable management and optimize cooling. For example, I ended up removing most dust filters that were covering the fans. I made an intense GPU-heavy test protocol (training a Yolo model) and kept moving fans around until I got the lowest temperatures.
Software Installation
That’s where the fun really begins, but it’s not the focus of this story. Spring of 2019 — you’ll probably go with Ubuntu 18.04, the Nvidia drivers for your GPU version (do that quick, or the display will pretty much suck), CUDA 10, and then whatever frameworks you use (PyTorch, Tensorflow, etc). And enjoy higher speeds than any cloud GPU you’ve tried at a one time price that pays off in a few months.
Component List
Here’s my parts list, with the prices from April 2019. You can also see updated prices on my PCPartPicker list.
CPU: AMD Threadripper 1920x 12-core ($356)GPU: EVGA RTX 2080 Ti XC Ultra ($1,187)CPU Cooler: Fractal S24 ($114)Motherboard: MSI X399 Gaming Pro Carbon AC ($305)Memory: Corsair Vengeance LPX DDR4 4x16Gb ($399)Hard-drive: Samsung 1TB Evo SSD M.2 PCIe ($241)Power: EVGA SuperNOVA P2 Platinum 1200W ($249)Case: Lian-Li PC-O11AIR ($114)
Here are a few other alternative builds, that I’ve used for inspiration and education: Jeff Chen’s, Colin Shaw’s and Wayde Gilliam’s.
Chris Fotache is an AI researcher with CYNET.ai based in New Jersey. He covers topics related to artificial intelligence in our life, Python programming, machine learning, computer vision, natural language processing, robotics and more.
|
[
{
"code": null,
"e": 352,
"s": 172,
"text": "After struggling with Microsoft Azure’s GPU VM’s for a few years, and hearing that Amazon’s AWS is not much better, I decided it’s time to have my own local deep learning machine."
},
{
"code": null,
"e": 654,
"s": 352,
"text": "One of my main reasons was that the cloud VM doesn’t have a display, therefore you can’t do anything visually. No big deal if you just train there and then run the model on a local computer but if you need to work on simulation-based robotics projects, those won’t run at all in a virtual environment."
},
{
"code": null,
"e": 1090,
"s": 654,
"text": "I later found that not only building an almost state-of-the-art machine pays for itself in about 4 months, but it is significantly faster than a cloud server (mainly because of local data transfer speed, since everything is in the same box on the same bus, while the cloud service might have the compute units and storage in different racks — so even if the GPU is faster, it can’t get the data fast enough to benefit from that speed)."
},
{
"code": null,
"e": 1390,
"s": 1090,
"text": "My system ended costing just under $3K (compare that to about $800/month you’d pay for an entry-level cloud GPU from AWS or Azure). That was in May 2019, and prices tend to vary a lot so it can be 10% lower and higher at any time. Also, by the time you read this technology might’ve already evolved."
},
{
"code": null,
"e": 1938,
"s": 1390,
"text": "You might ask why go to the pain of building the computer yourself instead of buying a high-end super-computer. It’s because ready-built deep learning systems are insanely expensive. But if you are still afraid to tinker with expensive components and are interested in a pre-built system, I found that Exxact sells some of the most affordable deep learning systems starting at $5,899 (2x NVIDIA RTX 2080 Ti + Intel Core i9) which also includes a 3 year warranty and deep learning stack. They are also recommended by another AI engineer, Jeff Chen."
},
{
"code": null,
"e": 2329,
"s": 1938,
"text": "To make sure everything works together, I recommend using PC Part Picker. It will both show you the lowest price for each component, and ensure that you don’t pick incompatible parts. As for putting things together, YouTube rules. Just type the name of the component and you’ll find several very explanatory videos on how to install it. So now lets go over the components that are required:"
},
{
"code": null,
"e": 2333,
"s": 2329,
"text": "CPU"
},
{
"code": null,
"e": 2932,
"s": 2333,
"text": "Here you’ll have to make a big choice: AMD or Intel. For my entire life I’ve been an Intel fan, but for this machine the CPU is not the most important part. That is the GPU. And Intel CPU’s can cost twice as much as the AMD counterpart. AMD’s new Ryzen line has very good reviews, and I don’t need to overclock it since I’m not playing video games with it. Therefore I went for the AMD Threadripper 1920x, which has 12 cores and 24 threads, more than enough for my case. It was reasonable priced around $350 but prices were dropping. The alternative would be the 10-core Intel i9–7900 at over $900."
},
{
"code": null,
"e": 2943,
"s": 2932,
"text": "CPU Cooler"
},
{
"code": null,
"e": 3185,
"s": 2943,
"text": "AMD CPUs have always ran very hot (one of the main reasons they weren’t that reliable). They still are, so you definitely need a liquid cooler. I went with the Fractal S24 which has 2 fans, at about $115. An alternative is the Corsair H100i."
},
{
"code": null,
"e": 3197,
"s": 3185,
"text": "Motherboard"
},
{
"code": null,
"e": 3329,
"s": 3197,
"text": "The main choice about the motherboard is the chipset. The simple rule is: For AMD Threadripper, use X399. For Intel 7900, use X299."
},
{
"code": null,
"e": 3768,
"s": 3329,
"text": "Based on reviews, I went with the MSI X399 Gaming Pro Carbon AC, which has everything I needed for deep learning. You’ll find it at just over $300. Other good alternatives are the Asus ROG, Gigabyte Aorus and Asrock Taichi (just make sure it has at least 40 PCIe lanes). You have to make sure the board design accomodates the size of the GPU, and maybe adding multiple GPU’s. The MSI one has plenty of room, and everything is well placed."
},
{
"code": null,
"e": 3772,
"s": 3768,
"text": "GPU"
},
{
"code": null,
"e": 4633,
"s": 3772,
"text": "Now this is the most important component of your deep learning system. You have to go with an Nvidia GPU, and the minimum recommended is the GTX 1080 Ti. Unfortunately, when I was looking, that was impossible to find at its regular price of about $800 (blame gamers? crypto miners?). So I had to go to the next level, the RTX 2080 Ti, which is not easy to find either, but I was lucky to get on an excellent $1,187 deal from EVGA. RTX is the newer generation, with one of the best performance among early 2019 consumer GPU’s. I’m glad I was “forced” to make that choice. If you look around, you might still find deals around $1,200. I think EVGA and Gigabyte are the top manufacturers, and the choices you make are about the cooling system. The EVGA RTX 2080 Ti XC Ultra has dual air coolers and that proved enough so far, it never got to critical overheating."
},
{
"code": null,
"e": 4640,
"s": 4633,
"text": "Memory"
},
{
"code": null,
"e": 4903,
"s": 4640,
"text": "For the configuration above, DDR4 is the best choice. Corsair is probably the main manufacturer. And it’s 2019, you need 64Gb. So I ended up with 4x16Gb Corsair Vengeance LPX DDR4. I paid $399 but prices are dropping dramatically, they’re well under $300 by now."
},
{
"code": null,
"e": 4914,
"s": 4903,
"text": "Hard-Drive"
},
{
"code": null,
"e": 5329,
"s": 4914,
"text": "SSD is old tech by now. The state-of-the-art is the M.2 standard, and that drive plugs right into the motherboard into a PCIe slot. Going at the main bus speed, this is basically a high-capacity, persistent memory chip. I really liked the 1Tb Samsung EVO SSD M.2. I paid $241 but prices for this also went down towards $200. If you need more storage, you can add a regular SSD drive which should be less than $100."
},
{
"code": null,
"e": 5342,
"s": 5329,
"text": "Power Supply"
},
{
"code": null,
"e": 5693,
"s": 5342,
"text": "PCPartPicker will make sure you pick a power supply big enough for your system. There are also other online wattage calculators. With one GPU you probably won’t get close to 1,000W but if you plan to add a second GPU, then you need 1,200W to be safe. EVGA is a solid manufacturer and I picked the EVGA SuperNOVA P2 Platinum 1200 which is around $250."
},
{
"code": null,
"e": 5698,
"s": 5693,
"text": "Case"
},
{
"code": null,
"e": 6079,
"s": 5698,
"text": "There are plenty of options here, and it might come down to personal preferences and design, but it’s important to make sure it’s big enough to fit all the components in without being cramped, and to have good air circulation. I went with the Lian-Li PC-O11AIR at $114 because it fit those requirements. It’s very roomy, everything is well placed inside, and there’s good cooling."
},
{
"code": null,
"e": 6098,
"s": 6079,
"text": "Additional Cooling"
},
{
"code": null,
"e": 6640,
"s": 6098,
"text": "After you’re done with your build, you might want to add additional fans to improve the air flow. My case came with several fans, but I got additional ones, to fill almost every mounting location. It can never get too cold in a GPU machine that’s gonna crank up convolutional networks. I got an 80mm Noctua for the back, and also a regular 120mm Corsair that I added on top. And yes, I got theRGB one. I didn’t care much about bright shiny colors in my case (since it’s under the desk anyway), but in the end I gave in and bought a cool fan."
},
{
"code": null,
"e": 6649,
"s": 6640,
"text": "Assembly"
},
{
"code": null,
"e": 7070,
"s": 6649,
"text": "Like I said, search for each component on YouTube and you’re sure to find detailed walkthroughs about installation. As an example, here are a few that I followed: a build similar to mine, a walkthrough of the MSI X399 motherboard and its components, and a focus on the Threadripper mounting. And read all the installation instructions in the manuals. For example, be careful about the slot locations of the memory units."
},
{
"code": null,
"e": 7114,
"s": 7070,
"text": "Basically, the order of operations is this:"
},
{
"code": null,
"e": 7434,
"s": 7114,
"text": "First, prep the case, install the power supply and pull the power cables. Then prep the motherboard, install the CPU and then the M.2 drive. Mount the motherboard in the case and add the CPU cooler. Then add the other fans and connect the power and button / lights wires. Finally install the memory modules and the GPU."
},
{
"code": null,
"e": 7743,
"s": 7434,
"text": "After you’re done and you power up the system, finish with cable management and optimize cooling. For example, I ended up removing most dust filters that were covering the fans. I made an intense GPU-heavy test protocol (training a Yolo model) and kept moving fans around until I got the lowest temperatures."
},
{
"code": null,
"e": 7765,
"s": 7743,
"text": "Software Installation"
},
{
"code": null,
"e": 8170,
"s": 7765,
"text": "That’s where the fun really begins, but it’s not the focus of this story. Spring of 2019 — you’ll probably go with Ubuntu 18.04, the Nvidia drivers for your GPU version (do that quick, or the display will pretty much suck), CUDA 10, and then whatever frameworks you use (PyTorch, Tensorflow, etc). And enjoy higher speeds than any cloud GPU you’ve tried at a one time price that pays off in a few months."
},
{
"code": null,
"e": 8185,
"s": 8170,
"text": "Component List"
},
{
"code": null,
"e": 8297,
"s": 8185,
"text": "Here’s my parts list, with the prices from April 2019. You can also see updated prices on my PCPartPicker list."
},
{
"code": null,
"e": 8629,
"s": 8297,
"text": "CPU: AMD Threadripper 1920x 12-core ($356)GPU: EVGA RTX 2080 Ti XC Ultra ($1,187)CPU Cooler: Fractal S24 ($114)Motherboard: MSI X399 Gaming Pro Carbon AC ($305)Memory: Corsair Vengeance LPX DDR4 4x16Gb ($399)Hard-drive: Samsung 1TB Evo SSD M.2 PCIe ($241)Power: EVGA SuperNOVA P2 Platinum 1200W ($249)Case: Lian-Li PC-O11AIR ($114)"
},
{
"code": null,
"e": 8763,
"s": 8629,
"text": "Here are a few other alternative builds, that I’ve used for inspiration and education: Jeff Chen’s, Colin Shaw’s and Wayde Gilliam’s."
}
] |
ps command in Linux with Examples - GeeksforGeeks
|
10 Jan, 2022
As we all know Linux is a multitasking and multi-user systems. So, it allows multiple processes to operate simultaneously without interfering with each other. Process is one of the important fundamental concept of the Linux OS. A process is an executing instance of a program and carry out different tasks within the operating system.
Linux provides us a utility called ps for viewing information related with the processes on a system which stands as abbreviation for “Process Status”. ps command is used to list the currently running processes and their PIDs along with some other information depends on different options. It reads the process information from the virtual files in /proc file-system. /proc contains virtual files, this is the reason it’s referred as a virtual file system.
ps provides numerous options for manipulating the output according to our need.
Syntax –
ps [options]
Options for ps Command :
Simple process selection : Shows the processes for the current shell –
Simple process selection : Shows the processes for the current shell –
[root@rhel7 ~]# ps
PID TTY TIME CMD
12330 pts/0 00:00:00 bash
21621 pts/0 00:00:00 ps
Result contains four columns of information. Where, PID – the unique process ID TTY – terminal type that the user is logged into TIME – amount of CPU in minutes and seconds that the process has been running CMD – name of the command that launched the process.
Note – Sometimes when we execute ps command, it shows TIME as 00:00:00. It is nothing but the total accumulated CPU utilization time for any process and 00:00:00 indicates no CPU time has been given by the kernel till now. In above example we found that, for bash no CPU time has been given. This is because bash is just a parent process for different processes which needs bash for their execution and bash itself is not utilizing any CPU time till now.
View Processes : View all the running processes use either of the following option with ps –
Result contains four columns of information. Where, PID – the unique process ID TTY – terminal type that the user is logged into TIME – amount of CPU in minutes and seconds that the process has been running CMD – name of the command that launched the process.
Note – Sometimes when we execute ps command, it shows TIME as 00:00:00. It is nothing but the total accumulated CPU utilization time for any process and 00:00:00 indicates no CPU time has been given by the kernel till now. In above example we found that, for bash no CPU time has been given. This is because bash is just a parent process for different processes which needs bash for their execution and bash itself is not utilizing any CPU time till now.
Note – Sometimes when we execute ps command, it shows TIME as 00:00:00. It is nothing but the total accumulated CPU utilization time for any process and 00:00:00 indicates no CPU time has been given by the kernel till now. In above example we found that, for bash no CPU time has been given. This is because bash is just a parent process for different processes which needs bash for their execution and bash itself is not utilizing any CPU time till now.
View Processes : View all the running processes use either of the following option with ps –
[root@rhel7 ~]# ps -A
[root@rhel7 ~]# ps -e
View Processes not associated with a terminal : View all processes except both session leaders and processes not associated with a terminal.
View Processes not associated with a terminal : View all processes except both session leaders and processes not associated with a terminal.
[root@rhel7 ~]# ps -a
PID TTY TIME CMD
27011 pts/0 00:00:00 man
27016 pts/0 00:00:00 less
27499 pts/1 00:00:00 ps
Note – You may be thinking that what is session leader? A unique session is assign to every process group. So, session leader is a process which kicks off other processes. The process ID of first process of any session is similar as the session ID.
View all the processes except session leaders :
View all the processes except session leaders :
[root@rhel7 ~]# ps -d
View all processes except those that fulfill the specified conditions (negates the selection) : Example – If you want to see only session leader and processes not associated with a terminal. Then, run
View all processes except those that fulfill the specified conditions (negates the selection) : Example – If you want to see only session leader and processes not associated with a terminal. Then, run
[root@rhel7 ~]# ps -a -N
OR
[root@rhel7 ~]# ps -a --deselect
View all processes associated with this terminal :
View all processes associated with this terminal :
[root@rhel7 ~]# ps -T
View all the running processes :
View all the running processes :
[root@rhel7 ~]# ps -r
View all processes owned by you : Processes i.e same EUID as ps which means runner of the ps command, root in this case –
View all processes owned by you : Processes i.e same EUID as ps which means runner of the ps command, root in this case –
[root@rhel7 ~]# ps -x
Process selection by list
Here we will discuss how to get the specific processes list with the help of ps command. These options accept a single argument in the form of a blank-separated or comma-separated list. They can be used multiple times. For example: ps -p “1 2” -p 3,4
Select the process by the command name. This selects the processes whose executable name is given in cmdlist. There may be a chance you won’t know the process ID and with this command it is easier to search. Syntax : ps -C command_name
Select the process by the command name. This selects the processes whose executable name is given in cmdlist. There may be a chance you won’t know the process ID and with this command it is easier to search. Syntax : ps -C command_name
Syntax :
ps -C command_name
Example :
[root@rhel7 ~]# ps -C dhclient
PID TTY TIME CMD
19805 ? 00:00:00 dhclient
Select by group ID or name. The group ID identifies the group of the user who created the process.
Select by group ID or name. The group ID identifies the group of the user who created the process.
Syntax :
ps -G group_name
ps --Group group_name
Example :
[root@rhel7 ~]# ps -G root
View by group id :
View by group id :
Syntax :
ps -g group_id
ps -group group_id
Example :
[root@rhel7 ~]# ps -g 1
PID TTY TIME CMD
1 ? 00:00:13 systemd
View process by process ID.
View process by process ID.
Syntax :
ps p process_id
ps -p process_id
ps --pid process_id
Example :
[root@rhel7 ~]# ps p 27223
PID TTY STAT TIME COMMAND
27223 ? Ss 0:01 sshd: root@pts/2
[root@rhel7 ~]# ps -p 27223
PID TTY TIME CMD
27223 ? 00:00:01 sshd
[root@rhel7 ~]# ps --pid 27223
PID TTY TIME CMD
27223 ? 00:00:01 sshd
You can view multiple processes by specifying multiple process IDs separated by blank or comma – Example :
[root@rhel7 ~]# ps -p 1 904 27223
PID TTY STAT TIME COMMAND
1 ? Ss 0:13 /usr/lib/systemd/systemd --switched-root --system --d
904 tty1 Ssl+ 1:02 /usr/bin/X -core -noreset :0 -seat seat0 -auth /var/r
27223 ? Ss 0:01 sshd: root@pts/2
Here, we mentioned three process IDs – 1, 904 and 27223 which are separated by blank.
Select by parent process ID. By using this command we can view all the processes owned by parent process except the parent process.
Here, we mentioned three process IDs – 1, 904 and 27223 which are separated by blank.
Select by parent process ID. By using this command we can view all the processes owned by parent process except the parent process.
[root@rhel7 ~]# ps -p 766
PID TTY TIME CMD
766 ? 00:00:06 NetworkManager
[root@rhel7 ~]# ps --ppid 766
PID TTY TIME CMD
19805 ? 00:00:00 dhclient
In above example process ID 766 is assigned to NetworkManager and this is the parent process for dhclient with process ID 19805.
View all the processes belongs to any session ID.
View all the processes belongs to any session ID.
Syntax :
ps -s session_id
ps --sid session_id
Example :
[root@rhel7 ~]# ps -s 1248
PID TTY TIME CMD
1248 ? 00:00:00 dbus-daemon
1276 ? 00:00:00 dconf-service
1302 ? 00:00:00 gvfsd
1310 ? 00:00:00 gvfsd-fuse
1369 ? 00:00:00 gvfs-udisks2-vo
1400 ? 00:00:00 gvfsd-trash
1418 ? 00:00:00 gvfs-mtp-volume
1432 ? 00:00:00 gvfs-gphoto2-vo
1437 ? 00:00:00 gvfs-afc-volume
1447 ? 00:00:00 wnck-applet
1453 ? 00:00:00 notification-ar
1454 ? 00:00:02 clock-applet
Select by tty. This selects the processes associated with the mentioned tty :
Select by tty. This selects the processes associated with the mentioned tty :
Syntax :
ps t tty
ps -t tty
ps --tty tty
Example :
[root@rhel7 ~]# ps -t pts/0
PID TTY TIME CMD
31199 pts/0 00:00:00 bash
31275 pts/0 00:00:00 man
31280 pts/0 00:00:00 less
Select by effective user ID or name. Syntax : ps U user_name/ID ps -U user_name/ID ps -u user_name/ID ps –User user_name/ID ps –user user_name/ID
Use -f to view full-format listing.
Select by effective user ID or name. Syntax : ps U user_name/ID ps -U user_name/ID ps -u user_name/ID ps –User user_name/ID ps –user user_name/ID
Use -f to view full-format listing.
Use -f to view full-format listing.
Use -f to view full-format listing.
[tux@rhel7 ~]$ ps -af
tux 17327 17326 0 12:42 pts/0 00:00:00 -bash
tux 17918 17327 0 12:50 pts/0 00:00:00 ps -af
Use -F to view Extra full format.
Use -F to view Extra full format.
[tux@rhel7 ~]$ ps -F
UID PID PPID C SZ RSS PSR STIME TTY TIME CMD
tux 17327 17326 0 28848 2040 0 12:42 pts/0 00:00:00 -bash
tux 17942 17327 0 37766 1784 0 12:50 pts/0 00:00:00 ps -F
To view process according to user-defined format.
To view process according to user-defined format.
Syntax :
[root@rhel7 ~]# ps --format column_name
[root@rhel7 ~]# ps -o column_name
[root@rhel7 ~]# ps o column_name
Example :
[root@rhel7 ~]# ps -aN --format cmd,pid,user,ppid
CMD PID USER PPID
/usr/lib/systemd/systemd -- 1 root 0
[kthreadd] 2 root 0
[ksoftirqd/0] 3 root 2
[kworker/0:0H] 5 root 2
[migration/0] 7 root 2
[rcu_bh] 8 root 2
[rcu_sched] 9 root 2
[watchdog/0] 10 root 2
In this example I wish to see command, process ID, username and parent process ID, so I pass the arguments cmd, pid, user and ppid respectively.
View in BSD job control format :
In this example I wish to see command, process ID, username and parent process ID, so I pass the arguments cmd, pid, user and ppid respectively.
View in BSD job control format :
[root@rhel7 ~]# ps -j
PID PGID SID TTY TIME CMD
16373 16373 16373 pts/0 00:00:00 bash
19734 19734 16373 pts/0 00:00:00 ps
Display BSD long format :
Display BSD long format :
[root@rhel7 ~]# ps l
F UID PID PPID PRI NI VSZ RSS WCHAN STAT TTY TIME COMMAND
4 0 904 826 20 0 306560 51456 ep_pol Ssl+ tty1 1:32 /usr/bin/X -core -noreset :0 -seat seat0 -auth /var/run/lightdm/root/:0 -noli
4 0 11692 11680 20 0 115524 2132 do_wai Ss pts/2 0:00 -bash
Add a column of security data.
Add a column of security data.
[root@rhel7 ~]# ps -aM
LABEL PID TTY TIME CMD
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 19534 pts/2 00:00:00 man
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 19543 pts/2 00:00:00 less
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 20469 pts/0 00:00:00 ps
View command with signal format.
View command with signal format.
[root@rhel7 ~]# ps s 766
Display user-oriented format
Display user-oriented format
[root@rhel7 ~]# ps u 1
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.6 128168 6844 ? Ss Apr08 0:16 /usr/lib/systemd/systemd --switched-root --system --deserialize 21
Display virtual memory format
Display virtual memory format
[root@rhel7 ~]# ps v 1
PID TTY STAT TIME MAJFL TRS DRS RSS %MEM COMMAND
1 ? Ss 0:16 62 1317 126850 6844 0.6 /usr/lib/systemd/systemd --switched-root --system --deserialize 21
If you want to see environment of any command. Then use option **e** –
If you want to see environment of any command. Then use option **e** –
[root@rhel7 ~]# ps ev 766
PID TTY STAT TIME MAJFL TRS DRS RSS %MEM COMMAND
766 ? Ssl 0:08 47 2441 545694 10448 1.0 /usr/sbin/NetworkManager --no-daemon LANG=en_US.UTF-8 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
View processes using highest memory.
View processes using highest memory.
ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem
12 – print a process tree
[root@rhel7 ~]# ps --forest -C sshd
PID TTY TIME CMD
797 ? 00:00:00 sshd
11680 ? 00:00:03 \_ sshd
16361 ? 00:00:02 \_ sshd
List all threads for a particular process. Use either the -T or -L option to display threads of a process.
List all threads for a particular process. Use either the -T or -L option to display threads of a process.
[root@rhel7 ~]# ps -C sshd -L
PID LWP TTY TIME CMD
797 797 ? 00:00:00 sshd
11680 11680 ? 00:00:03 sshd
16361 16361 ? 00:00:02 sshd
Note – For the explanation of different column contents refer man page.
rajeev0719singh
as5853535
sweetyty
linux-command
Linux-system-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
UDP Server-Client implementation in C
Conditional Statements | Shell Script
'crontab' in Linux with Examples
tee command in Linux with examples
echo command in Linux with Examples
Cat command in Linux with examples
touch command in Linux with Examples
Mutex lock for Linux Thread Synchronization
Tail command in Linux with examples
|
[
{
"code": null,
"e": 24550,
"s": 24519,
"text": " \n10 Jan, 2022\n"
},
{
"code": null,
"e": 24886,
"s": 24550,
"text": "As we all know Linux is a multitasking and multi-user systems. So, it allows multiple processes to operate simultaneously without interfering with each other. Process is one of the important fundamental concept of the Linux OS. A process is an executing instance of a program and carry out different tasks within the operating system. "
},
{
"code": null,
"e": 25344,
"s": 24886,
"text": "Linux provides us a utility called ps for viewing information related with the processes on a system which stands as abbreviation for “Process Status”. ps command is used to list the currently running processes and their PIDs along with some other information depends on different options. It reads the process information from the virtual files in /proc file-system. /proc contains virtual files, this is the reason it’s referred as a virtual file system. "
},
{
"code": null,
"e": 25425,
"s": 25344,
"text": "ps provides numerous options for manipulating the output according to our need. "
},
{
"code": null,
"e": 25436,
"s": 25425,
"text": "Syntax – "
},
{
"code": null,
"e": 25449,
"s": 25436,
"text": "ps [options]"
},
{
"code": null,
"e": 25476,
"s": 25449,
"text": "Options for ps Command : "
},
{
"code": null,
"e": 25551,
"s": 25476,
"text": "\nSimple process selection : Shows the processes for the current shell – \n"
},
{
"code": null,
"e": 25624,
"s": 25551,
"text": "Simple process selection : Shows the processes for the current shell – "
},
{
"code": null,
"e": 25727,
"s": 25624,
"text": "[root@rhel7 ~]# ps\n PID TTY TIME CMD\n12330 pts/0 00:00:00 bash\n21621 pts/0 00:00:00 ps"
},
{
"code": null,
"e": 26542,
"s": 25727,
"text": "\nResult contains four columns of information. Where, PID – the unique process ID TTY – terminal type that the user is logged into TIME – amount of CPU in minutes and seconds that the process has been running CMD – name of the command that launched the process. \nNote – Sometimes when we execute ps command, it shows TIME as 00:00:00. It is nothing but the total accumulated CPU utilization time for any process and 00:00:00 indicates no CPU time has been given by the kernel till now. In above example we found that, for bash no CPU time has been given. This is because bash is just a parent process for different processes which needs bash for their execution and bash itself is not utilizing any CPU time till now. \nView Processes : View all the running processes use either of the following option with ps – \n"
},
{
"code": null,
"e": 27260,
"s": 26542,
"text": "Result contains four columns of information. Where, PID – the unique process ID TTY – terminal type that the user is logged into TIME – amount of CPU in minutes and seconds that the process has been running CMD – name of the command that launched the process. \nNote – Sometimes when we execute ps command, it shows TIME as 00:00:00. It is nothing but the total accumulated CPU utilization time for any process and 00:00:00 indicates no CPU time has been given by the kernel till now. In above example we found that, for bash no CPU time has been given. This is because bash is just a parent process for different processes which needs bash for their execution and bash itself is not utilizing any CPU time till now. "
},
{
"code": null,
"e": 27717,
"s": 27260,
"text": "Note – Sometimes when we execute ps command, it shows TIME as 00:00:00. It is nothing but the total accumulated CPU utilization time for any process and 00:00:00 indicates no CPU time has been given by the kernel till now. In above example we found that, for bash no CPU time has been given. This is because bash is just a parent process for different processes which needs bash for their execution and bash itself is not utilizing any CPU time till now. "
},
{
"code": null,
"e": 27812,
"s": 27717,
"text": "View Processes : View all the running processes use either of the following option with ps – "
},
{
"code": null,
"e": 27856,
"s": 27812,
"text": "[root@rhel7 ~]# ps -A\n[root@rhel7 ~]# ps -e"
},
{
"code": null,
"e": 28001,
"s": 27856,
"text": "\nView Processes not associated with a terminal : View all processes except both session leaders and processes not associated with a terminal. \n"
},
{
"code": null,
"e": 28144,
"s": 28001,
"text": "View Processes not associated with a terminal : View all processes except both session leaders and processes not associated with a terminal. "
},
{
"code": null,
"e": 28278,
"s": 28144,
"text": "[root@rhel7 ~]# ps -a\n PID TTY TIME CMD\n27011 pts/0 00:00:00 man\n27016 pts/0 00:00:00 less\n27499 pts/1 00:00:00 ps"
},
{
"code": null,
"e": 28527,
"s": 28278,
"text": "Note – You may be thinking that what is session leader? A unique session is assign to every process group. So, session leader is a process which kicks off other processes. The process ID of first process of any session is similar as the session ID."
},
{
"code": null,
"e": 28579,
"s": 28527,
"text": "\nView all the processes except session leaders : \n"
},
{
"code": null,
"e": 28629,
"s": 28579,
"text": "View all the processes except session leaders : "
},
{
"code": null,
"e": 28651,
"s": 28629,
"text": "[root@rhel7 ~]# ps -d"
},
{
"code": null,
"e": 28856,
"s": 28651,
"text": "\nView all processes except those that fulfill the specified conditions (negates the selection) : Example – If you want to see only session leader and processes not associated with a terminal. Then, run \n"
},
{
"code": null,
"e": 29059,
"s": 28856,
"text": "View all processes except those that fulfill the specified conditions (negates the selection) : Example – If you want to see only session leader and processes not associated with a terminal. Then, run "
},
{
"code": null,
"e": 29120,
"s": 29059,
"text": "[root@rhel7 ~]# ps -a -N\nOR\n[root@rhel7 ~]# ps -a --deselect"
},
{
"code": null,
"e": 29175,
"s": 29120,
"text": "\nView all processes associated with this terminal : \n"
},
{
"code": null,
"e": 29228,
"s": 29175,
"text": "View all processes associated with this terminal : "
},
{
"code": null,
"e": 29250,
"s": 29228,
"text": "[root@rhel7 ~]# ps -T"
},
{
"code": null,
"e": 29287,
"s": 29250,
"text": "\nView all the running processes : \n"
},
{
"code": null,
"e": 29322,
"s": 29287,
"text": "View all the running processes : "
},
{
"code": null,
"e": 29344,
"s": 29322,
"text": "[root@rhel7 ~]# ps -r"
},
{
"code": null,
"e": 29470,
"s": 29344,
"text": "\nView all processes owned by you : Processes i.e same EUID as ps which means runner of the ps command, root in this case – \n"
},
{
"code": null,
"e": 29594,
"s": 29470,
"text": "View all processes owned by you : Processes i.e same EUID as ps which means runner of the ps command, root in this case – "
},
{
"code": null,
"e": 29616,
"s": 29594,
"text": "[root@rhel7 ~]# ps -x"
},
{
"code": null,
"e": 29642,
"s": 29616,
"text": "Process selection by list"
},
{
"code": null,
"e": 29895,
"s": 29642,
"text": "Here we will discuss how to get the specific processes list with the help of ps command. These options accept a single argument in the form of a blank-separated or comma-separated list. They can be used multiple times. For example: ps -p “1 2” -p 3,4 "
},
{
"code": null,
"e": 30135,
"s": 29895,
"text": "\nSelect the process by the command name. This selects the processes whose executable name is given in cmdlist. There may be a chance you won’t know the process ID and with this command it is easier to search. Syntax : ps -C command_name \n"
},
{
"code": null,
"e": 30373,
"s": 30135,
"text": "Select the process by the command name. This selects the processes whose executable name is given in cmdlist. There may be a chance you won’t know the process ID and with this command it is easier to search. Syntax : ps -C command_name "
},
{
"code": null,
"e": 30504,
"s": 30373,
"text": "Syntax :\nps -C command_name\n\nExample :\n[root@rhel7 ~]# ps -C dhclient\n PID TTY TIME CMD\n19805 ? 00:00:00 dhclient"
},
{
"code": null,
"e": 30607,
"s": 30504,
"text": "\nSelect by group ID or name. The group ID identifies the group of the user who created the process. \n"
},
{
"code": null,
"e": 30708,
"s": 30607,
"text": "Select by group ID or name. The group ID identifies the group of the user who created the process. "
},
{
"code": null,
"e": 30794,
"s": 30708,
"text": "Syntax :\nps -G group_name\nps --Group group_name\n\nExample :\n[root@rhel7 ~]# ps -G root"
},
{
"code": null,
"e": 30817,
"s": 30794,
"text": "\nView by group id : \n"
},
{
"code": null,
"e": 30838,
"s": 30817,
"text": "View by group id : "
},
{
"code": null,
"e": 30976,
"s": 30838,
"text": "Syntax :\nps -g group_id\nps -group group_id\n\nExample :\n[root@rhel7 ~]# ps -g 1\n PID TTY TIME CMD\n 1 ? 00:00:13 systemd"
},
{
"code": null,
"e": 31008,
"s": 30976,
"text": "\nView process by process ID. \n"
},
{
"code": null,
"e": 31038,
"s": 31008,
"text": "View process by process ID. "
},
{
"code": null,
"e": 31395,
"s": 31038,
"text": "Syntax :\nps p process_id\nps -p process_id\nps --pid process_id\n\nExample :\n[root@rhel7 ~]# ps p 27223\n PID TTY STAT TIME COMMAND\n27223 ? Ss 0:01 sshd: root@pts/2\n\n[root@rhel7 ~]# ps -p 27223\n PID TTY TIME CMD\n27223 ? 00:00:01 sshd\n\n[root@rhel7 ~]# ps --pid 27223\n PID TTY TIME CMD\n27223 ? 00:00:01 sshd"
},
{
"code": null,
"e": 31504,
"s": 31395,
"text": "You can view multiple processes by specifying multiple process IDs separated by blank or comma – Example : "
},
{
"code": null,
"e": 31780,
"s": 31504,
"text": "[root@rhel7 ~]# ps -p 1 904 27223\n PID TTY STAT TIME COMMAND\n 1 ? Ss 0:13 /usr/lib/systemd/systemd --switched-root --system --d\n 904 tty1 Ssl+ 1:02 /usr/bin/X -core -noreset :0 -seat seat0 -auth /var/r\n27223 ? Ss 0:01 sshd: root@pts/2"
},
{
"code": null,
"e": 32004,
"s": 31780,
"text": "\nHere, we mentioned three process IDs – 1, 904 and 27223 which are separated by blank. \nSelect by parent process ID. By using this command we can view all the processes owned by parent process except the parent process. \n"
},
{
"code": null,
"e": 32092,
"s": 32004,
"text": "Here, we mentioned three process IDs – 1, 904 and 27223 which are separated by blank. "
},
{
"code": null,
"e": 32226,
"s": 32092,
"text": "Select by parent process ID. By using this command we can view all the processes owned by parent process except the parent process. "
},
{
"code": null,
"e": 32411,
"s": 32226,
"text": "[root@rhel7 ~]# ps -p 766\n PID TTY TIME CMD\n 766 ? 00:00:06 NetworkManager\n\n[root@rhel7 ~]# ps --ppid 766\n PID TTY TIME CMD\n19805 ? 00:00:00 dhclient"
},
{
"code": null,
"e": 32542,
"s": 32411,
"text": "In above example process ID 766 is assigned to NetworkManager and this is the parent process for dhclient with process ID 19805. "
},
{
"code": null,
"e": 32596,
"s": 32542,
"text": "\nView all the processes belongs to any session ID. \n"
},
{
"code": null,
"e": 32648,
"s": 32596,
"text": "View all the processes belongs to any session ID. "
},
{
"code": null,
"e": 33208,
"s": 32648,
"text": "Syntax :\nps -s session_id\nps --sid session_id\n\nExample :\n[root@rhel7 ~]# ps -s 1248\n PID TTY TIME CMD\n 1248 ? 00:00:00 dbus-daemon\n 1276 ? 00:00:00 dconf-service\n 1302 ? 00:00:00 gvfsd\n 1310 ? 00:00:00 gvfsd-fuse\n 1369 ? 00:00:00 gvfs-udisks2-vo\n 1400 ? 00:00:00 gvfsd-trash\n 1418 ? 00:00:00 gvfs-mtp-volume\n 1432 ? 00:00:00 gvfs-gphoto2-vo\n 1437 ? 00:00:00 gvfs-afc-volume\n 1447 ? 00:00:00 wnck-applet\n 1453 ? 00:00:00 notification-ar\n 1454 ? 00:00:02 clock-applet"
},
{
"code": null,
"e": 33290,
"s": 33208,
"text": "\nSelect by tty. This selects the processes associated with the mentioned tty : \n"
},
{
"code": null,
"e": 33370,
"s": 33290,
"text": "Select by tty. This selects the processes associated with the mentioned tty : "
},
{
"code": null,
"e": 33564,
"s": 33370,
"text": "Syntax :\nps t tty\nps -t tty\nps --tty tty\n\nExample :\n[root@rhel7 ~]# ps -t pts/0\n PID TTY TIME CMD\n31199 pts/0 00:00:00 bash\n31275 pts/0 00:00:00 man\n31280 pts/0 00:00:00 less"
},
{
"code": null,
"e": 33754,
"s": 33564,
"text": "\nSelect by effective user ID or name. Syntax : ps U user_name/ID ps -U user_name/ID ps -u user_name/ID ps –User user_name/ID ps –user user_name/ID \n\nUse -f to view full-format listing. \n\n\n"
},
{
"code": null,
"e": 33942,
"s": 33754,
"text": "Select by effective user ID or name. Syntax : ps U user_name/ID ps -U user_name/ID ps -u user_name/ID ps –User user_name/ID ps –user user_name/ID \n\nUse -f to view full-format listing. \n\n"
},
{
"code": null,
"e": 33982,
"s": 33942,
"text": "\nUse -f to view full-format listing. \n"
},
{
"code": null,
"e": 34020,
"s": 33982,
"text": "Use -f to view full-format listing. "
},
{
"code": null,
"e": 34151,
"s": 34020,
"text": "[tux@rhel7 ~]$ ps -af\ntux 17327 17326 0 12:42 pts/0 00:00:00 -bash\ntux 17918 17327 0 12:50 pts/0 00:00:00 ps -af"
},
{
"code": null,
"e": 34189,
"s": 34151,
"text": "\nUse -F to view Extra full format. \n"
},
{
"code": null,
"e": 34225,
"s": 34189,
"text": "Use -F to view Extra full format. "
},
{
"code": null,
"e": 34454,
"s": 34225,
"text": "[tux@rhel7 ~]$ ps -F\nUID PID PPID C SZ RSS PSR STIME TTY TIME CMD\ntux 17327 17326 0 28848 2040 0 12:42 pts/0 00:00:00 -bash\ntux 17942 17327 0 37766 1784 0 12:50 pts/0 00:00:00 ps -F"
},
{
"code": null,
"e": 34508,
"s": 34454,
"text": "\nTo view process according to user-defined format. \n"
},
{
"code": null,
"e": 34560,
"s": 34508,
"text": "To view process according to user-defined format. "
},
{
"code": null,
"e": 35182,
"s": 34560,
"text": "Syntax :\n[root@rhel7 ~]# ps --format column_name\n[root@rhel7 ~]# ps -o column_name\n[root@rhel7 ~]# ps o column_name\n\nExample :\n[root@rhel7 ~]# ps -aN --format cmd,pid,user,ppid\nCMD PID USER PPID\n/usr/lib/systemd/systemd -- 1 root 0\n[kthreadd] 2 root 0\n[ksoftirqd/0] 3 root 2\n[kworker/0:0H] 5 root 2\n[migration/0] 7 root 2\n[rcu_bh] 8 root 2\n[rcu_sched] 9 root 2\n[watchdog/0] 10 root 2"
},
{
"code": null,
"e": 35366,
"s": 35182,
"text": "\nIn this example I wish to see command, process ID, username and parent process ID, so I pass the arguments cmd, pid, user and ppid respectively. \nView in BSD job control format : \n"
},
{
"code": null,
"e": 35513,
"s": 35366,
"text": "In this example I wish to see command, process ID, username and parent process ID, so I pass the arguments cmd, pid, user and ppid respectively. "
},
{
"code": null,
"e": 35548,
"s": 35513,
"text": "View in BSD job control format : "
},
{
"code": null,
"e": 35690,
"s": 35548,
"text": "[root@rhel7 ~]# ps -j\n PID PGID SID TTY TIME CMD\n16373 16373 16373 pts/0 00:00:00 bash\n19734 19734 16373 pts/0 00:00:00 ps"
},
{
"code": null,
"e": 35722,
"s": 35692,
"text": "\nDisplay BSD long format : \n"
},
{
"code": null,
"e": 35750,
"s": 35722,
"text": "Display BSD long format : "
},
{
"code": null,
"e": 36070,
"s": 35750,
"text": "[root@rhel7 ~]# ps l\nF UID PID PPID PRI NI VSZ RSS WCHAN STAT TTY TIME COMMAND\n4 0 904 826 20 0 306560 51456 ep_pol Ssl+ tty1 1:32 /usr/bin/X -core -noreset :0 -seat seat0 -auth /var/run/lightdm/root/:0 -noli\n4 0 11692 11680 20 0 115524 2132 do_wai Ss pts/2 0:00 -bash"
},
{
"code": null,
"e": 36105,
"s": 36070,
"text": "\nAdd a column of security data. \n"
},
{
"code": null,
"e": 36138,
"s": 36105,
"text": "Add a column of security data. "
},
{
"code": null,
"e": 36477,
"s": 36138,
"text": "[root@rhel7 ~]# ps -aM\nLABEL PID TTY TIME CMD\nunconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 19534 pts/2 00:00:00 man\nunconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 19543 pts/2 00:00:00 less\nunconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 20469 pts/0 00:00:00 ps"
},
{
"code": null,
"e": 36514,
"s": 36477,
"text": "\nView command with signal format. \n"
},
{
"code": null,
"e": 36549,
"s": 36514,
"text": "View command with signal format. "
},
{
"code": null,
"e": 36574,
"s": 36549,
"text": "[root@rhel7 ~]# ps s 766"
},
{
"code": null,
"e": 36609,
"s": 36576,
"text": "\nDisplay user-oriented format \n"
},
{
"code": null,
"e": 36640,
"s": 36609,
"text": "Display user-oriented format "
},
{
"code": null,
"e": 36868,
"s": 36640,
"text": "[root@rhel7 ~]# ps u 1\nUSER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND\nroot 1 0.0 0.6 128168 6844 ? Ss Apr08 0:16 /usr/lib/systemd/systemd --switched-root --system --deserialize 21"
},
{
"code": null,
"e": 36902,
"s": 36868,
"text": "\nDisplay virtual memory format \n"
},
{
"code": null,
"e": 36934,
"s": 36902,
"text": "Display virtual memory format "
},
{
"code": null,
"e": 37146,
"s": 36934,
"text": "[root@rhel7 ~]# ps v 1\n PID TTY STAT TIME MAJFL TRS DRS RSS %MEM COMMAND\n 1 ? Ss 0:16 62 1317 126850 6844 0.6 /usr/lib/systemd/systemd --switched-root --system --deserialize 21"
},
{
"code": null,
"e": 37221,
"s": 37146,
"text": "\nIf you want to see environment of any command. Then use option **e** – \n"
},
{
"code": null,
"e": 37294,
"s": 37221,
"text": "If you want to see environment of any command. Then use option **e** – "
},
{
"code": null,
"e": 37552,
"s": 37294,
"text": "[root@rhel7 ~]# ps ev 766\n PID TTY STAT TIME MAJFL TRS DRS RSS %MEM COMMAND\n 766 ? Ssl 0:08 47 2441 545694 10448 1.0 /usr/sbin/NetworkManager --no-daemon LANG=en_US.UTF-8 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin"
},
{
"code": null,
"e": 37593,
"s": 37552,
"text": "\nView processes using highest memory. \n"
},
{
"code": null,
"e": 37632,
"s": 37593,
"text": "View processes using highest memory. "
},
{
"code": null,
"e": 37675,
"s": 37632,
"text": "ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem"
},
{
"code": null,
"e": 37703,
"s": 37675,
"text": "12 – print a process tree "
},
{
"code": null,
"e": 37862,
"s": 37703,
"text": "[root@rhel7 ~]# ps --forest -C sshd\n PID TTY TIME CMD\n 797 ? 00:00:00 sshd\n11680 ? 00:00:03 \\_ sshd\n16361 ? 00:00:02 \\_ sshd"
},
{
"code": null,
"e": 37973,
"s": 37862,
"text": "\nList all threads for a particular process. Use either the -T or -L option to display threads of a process. \n"
},
{
"code": null,
"e": 38082,
"s": 37973,
"text": "List all threads for a particular process. Use either the -T or -L option to display threads of a process. "
},
{
"code": null,
"e": 38251,
"s": 38082,
"text": "[root@rhel7 ~]# ps -C sshd -L\n PID LWP TTY TIME CMD\n 797 797 ? 00:00:00 sshd\n11680 11680 ? 00:00:03 sshd\n16361 16361 ? 00:00:02 sshd"
},
{
"code": null,
"e": 38325,
"s": 38251,
"text": "Note – For the explanation of different column contents refer man page. "
},
{
"code": null,
"e": 38341,
"s": 38325,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 38351,
"s": 38341,
"text": "as5853535"
},
{
"code": null,
"e": 38360,
"s": 38351,
"text": "sweetyty"
},
{
"code": null,
"e": 38376,
"s": 38360,
"text": "\nlinux-command\n"
},
{
"code": null,
"e": 38400,
"s": 38376,
"text": "\nLinux-system-commands\n"
},
{
"code": null,
"e": 38413,
"s": 38400,
"text": "\nLinux-Unix\n"
},
{
"code": null,
"e": 38618,
"s": 38413,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 38653,
"s": 38618,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 38691,
"s": 38653,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 38729,
"s": 38691,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 38762,
"s": 38729,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 38797,
"s": 38762,
"text": "tee command in Linux with examples"
},
{
"code": null,
"e": 38833,
"s": 38797,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 38868,
"s": 38833,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 38905,
"s": 38868,
"text": "touch command in Linux with Examples"
},
{
"code": null,
"e": 38949,
"s": 38905,
"text": "Mutex lock for Linux Thread Synchronization"
}
] |
How to set margin of ImageView using code in Android?
|
This example demonstrates how do I set margin of ImageView using code in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/image"/>
</RelativeLayout>
Step 3 – Copy an image file and paste in the res/drawable
Step 4 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
final RelativeLayout.LayoutParams layoutparams = (RelativeLayout.LayoutParams)imageView.getLayoutParams();
layoutparams.setMargins(100,100,100,100);
imageView.setLayoutParams(layoutparams);
}
}
Step 5 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
|
[
{
"code": null,
"e": 1144,
"s": 1062,
"text": "This example demonstrates how do I set margin of ImageView using code in android."
},
{
"code": null,
"e": 1273,
"s": 1144,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1338,
"s": 1273,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1813,
"s": 1338,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n\n <ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:background=\"@drawable/image\"/>\n\n</RelativeLayout>"
},
{
"code": null,
"e": 1871,
"s": 1813,
"text": "Step 3 – Copy an image file and paste in the res/drawable"
},
{
"code": null,
"e": 1928,
"s": 1871,
"text": "Step 4 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2575,
"s": 1928,
"text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.ImageView;\nimport android.widget.RelativeLayout;\n\npublic class MainActivity extends AppCompatActivity {\n\n ImageView imageView;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n imageView = findViewById(R.id.imageView);\n final RelativeLayout.LayoutParams layoutparams = (RelativeLayout.LayoutParams)imageView.getLayoutParams();\n layoutparams.setMargins(100,100,100,100);\n imageView.setLayoutParams(layoutparams);\n }\n}"
},
{
"code": null,
"e": 2630,
"s": 2575,
"text": "Step 5 - Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3304,
"s": 2630,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 3651,
"s": 3304,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
}
] |
Differentiate the modulo and division by using C Programming language?
|
Modulo − Represents as % operator.
And gives the value of the remainder of an integer division.
Division − represents as / operator.
And gives the value of the quotient of a division.
#include<stdio.h>
int main(){
int a,b,c;
printf("enter a,b,c values:");
scanf("%d%d%d,&a,&b,&c);
printf("a/b=%d a%b=%d\n",a/b,a%b);
printf("(a+10)%b=%d (a+10)/b=%d\n",(a+10)%b,(a+10)/b);
}
enter a,b,c values:2 4 6
a/b=0 ab=2
(a+10)b=0 (a+10)/b=3
Applying pointer variables to perform modulo and division operation −
Live Demo
#include<stdio.h>
void main(){
//Declaring pointers and variables//
int num1,num2;
int *p1,*p2;
p1=&num1;
p2=&num2;
int div,mod;
//Reading User I/p//
printf("Enter the values of num1 & num2: ");
scanf("%d,%d",&num1,&num2);
div=*p1/ *p2;
mod=*p1%*p2;
//Printing O/p//
printf("Division value = %d\n",div);
printf("Modulus value = %d\n",mod);
}
Enter the values of num1 & num2: 30,20
Division value = 1
Modulus value = 10
|
[
{
"code": null,
"e": 1097,
"s": 1062,
"text": "Modulo − Represents as % operator."
},
{
"code": null,
"e": 1159,
"s": 1097,
"text": " And gives the value of the remainder of an integer division."
},
{
"code": null,
"e": 1196,
"s": 1159,
"text": "Division − represents as / operator."
},
{
"code": null,
"e": 1248,
"s": 1196,
"text": " And gives the value of the quotient of a division."
},
{
"code": null,
"e": 1452,
"s": 1248,
"text": "#include<stdio.h>\nint main(){\n int a,b,c;\n printf(\"enter a,b,c values:\");\n scanf(\"%d%d%d,&a,&b,&c);\n printf(\"a/b=%d a%b=%d\\n\",a/b,a%b);\n printf(\"(a+10)%b=%d (a+10)/b=%d\\n\",(a+10)%b,(a+10)/b);\n}"
},
{
"code": null,
"e": 1509,
"s": 1452,
"text": "enter a,b,c values:2 4 6\na/b=0 ab=2\n(a+10)b=0 (a+10)/b=3"
},
{
"code": null,
"e": 1579,
"s": 1509,
"text": "Applying pointer variables to perform modulo and division operation −"
},
{
"code": null,
"e": 1590,
"s": 1579,
"text": " Live Demo"
},
{
"code": null,
"e": 1974,
"s": 1590,
"text": "#include<stdio.h>\nvoid main(){\n //Declaring pointers and variables//\n int num1,num2;\n int *p1,*p2;\n p1=&num1;\n p2=&num2;\n int div,mod;\n //Reading User I/p//\n printf(\"Enter the values of num1 & num2: \");\n scanf(\"%d,%d\",&num1,&num2);\n div=*p1/ *p2;\n mod=*p1%*p2;\n //Printing O/p//\n printf(\"Division value = %d\\n\",div);\n printf(\"Modulus value = %d\\n\",mod);\n}"
},
{
"code": null,
"e": 2051,
"s": 1974,
"text": "Enter the values of num1 & num2: 30,20\nDivision value = 1\nModulus value = 10"
}
] |
Date Class in C#
|
To set dates in C#, use DateTime class. The DateTime value is between 12:00:00 midnight, January 1, 0001 to 11:59:59 P.M., December 31, 9999 A.D.
Let’s create a DateTime object.
Live Demo
using System;
class Test {
static void Main() {
DateTime dt = new DateTime(2018, 7, 24);
Console.WriteLine (dt.ToString());
}
}
7/24/2018 12:00:00 AM
Let us now get the current date and time.
Live Demo
using System;
class Test {
static void Main() {
Console.WriteLine (DateTime.Now.ToString());
}
}
9/17/2018 5:49:21 AM
Now using the method Add(), we will add days in a date with the DateTime structure.
Live Demo
using System;
class Test {
static void Main() {
DateTime dt1 = new DateTime(2018, 7, 23, 08, 20, 10);
Console.WriteLine ("Old Date: "+dt1.ToString());
DateTime dt2 = dt1.AddDays(7);
Console.WriteLine ("New Date: "+dt2.ToString());
}
}
Old Date: 7/23/2018 8:20:10 AM
New Date: 7/30/2018 8:20:10 AM
|
[
{
"code": null,
"e": 1208,
"s": 1062,
"text": "To set dates in C#, use DateTime class. The DateTime value is between 12:00:00 midnight, January 1, 0001 to 11:59:59 P.M., December 31, 9999 A.D."
},
{
"code": null,
"e": 1240,
"s": 1208,
"text": "Let’s create a DateTime object."
},
{
"code": null,
"e": 1251,
"s": 1240,
"text": " Live Demo"
},
{
"code": null,
"e": 1397,
"s": 1251,
"text": "using System;\nclass Test {\n static void Main() {\n DateTime dt = new DateTime(2018, 7, 24);\n Console.WriteLine (dt.ToString());\n }\n}"
},
{
"code": null,
"e": 1419,
"s": 1397,
"text": "7/24/2018 12:00:00 AM"
},
{
"code": null,
"e": 1461,
"s": 1419,
"text": "Let us now get the current date and time."
},
{
"code": null,
"e": 1472,
"s": 1461,
"text": " Live Demo"
},
{
"code": null,
"e": 1581,
"s": 1472,
"text": "using System;\nclass Test {\n static void Main() {\n Console.WriteLine (DateTime.Now.ToString());\n }\n}"
},
{
"code": null,
"e": 1602,
"s": 1581,
"text": "9/17/2018 5:49:21 AM"
},
{
"code": null,
"e": 1686,
"s": 1602,
"text": "Now using the method Add(), we will add days in a date with the DateTime structure."
},
{
"code": null,
"e": 1697,
"s": 1686,
"text": " Live Demo"
},
{
"code": null,
"e": 1962,
"s": 1697,
"text": "using System;\nclass Test {\n static void Main() {\n DateTime dt1 = new DateTime(2018, 7, 23, 08, 20, 10);\n Console.WriteLine (\"Old Date: \"+dt1.ToString());\n DateTime dt2 = dt1.AddDays(7);\n Console.WriteLine (\"New Date: \"+dt2.ToString());\n }\n}"
},
{
"code": null,
"e": 2024,
"s": 1962,
"text": "Old Date: 7/23/2018 8:20:10 AM\nNew Date: 7/30/2018 8:20:10 AM"
}
] |
How to use #if..#elif...#else...#endif directives in C#?
|
All preprocessor directives begin with #, and only white-space characters may appear before a preprocessor directive on a line. Preprocessor directives are not statements, so they do not end with a semicolon (;).
The #if directive allows testing a symbol or symbols to see if they evaluate to true.
It allows to create a compound conditional directive, along with #if.
It allows creating a compound conditional directive.
The #endif specifies the end of a conditional directive.
The following is an example showing the usage of #if, #elif, #else and #endif directives −
Live Demo
#define One
#undef Two
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
#if (One && TWO)
Console.WriteLine("Both are defined");
#elif (ONE && !TWO)
Console.WriteLine("ONE is defined and TWO is undefined");
#elif (!ONE && TWO)
Console.WriteLine("ONE is defined and TWO is undefined");
#else
Console.WriteLine("Both are undefined");
#endif
}
}
}
Both are undefined
|
[
{
"code": null,
"e": 1275,
"s": 1062,
"text": "All preprocessor directives begin with #, and only white-space characters may appear before a preprocessor directive on a line. Preprocessor directives are not statements, so they do not end with a semicolon (;)."
},
{
"code": null,
"e": 1361,
"s": 1275,
"text": "The #if directive allows testing a symbol or symbols to see if they evaluate to true."
},
{
"code": null,
"e": 1431,
"s": 1361,
"text": "It allows to create a compound conditional directive, along with #if."
},
{
"code": null,
"e": 1484,
"s": 1431,
"text": "It allows creating a compound conditional directive."
},
{
"code": null,
"e": 1541,
"s": 1484,
"text": "The #endif specifies the end of a conditional directive."
},
{
"code": null,
"e": 1632,
"s": 1541,
"text": "The following is an example showing the usage of #if, #elif, #else and #endif directives −"
},
{
"code": null,
"e": 1643,
"s": 1632,
"text": " Live Demo"
},
{
"code": null,
"e": 2120,
"s": 1643,
"text": "#define One\n#undef Two\n\nusing System;\n\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n #if (One && TWO)\n Console.WriteLine(\"Both are defined\");\n #elif (ONE && !TWO)\n Console.WriteLine(\"ONE is defined and TWO is undefined\");\n #elif (!ONE && TWO)\n Console.WriteLine(\"ONE is defined and TWO is undefined\");\n #else\n Console.WriteLine(\"Both are undefined\");\n #endif\n }\n }\n}"
},
{
"code": null,
"e": 2139,
"s": 2120,
"text": "Both are undefined"
}
] |
C++ Vector Library - size() Function
|
The C++ function std::vector::size() returns the number of elements present in the vector.
Following is the declaration for std::vector::size() function form std::vector header.
size_type size() const;
size_type size() const noexcept;
None
Returns the actual objects present in vector, which may be differ than storage capacity of vector.
This member function never throws exception.
Constant i.e. O(1)
The following example shows the usage of std::vector::size() function.
#include <iostream>
#include <vector>
using namespace std;
int main(void) {
vector<int> v;
cout << "Initial vector size = " << v.size() << endl;
v.resize(128);
cout << "Vector size after resize = " << v.size() << endl;
return 0;
}
Let us compile and run the above program, this will produce the following result −
Initial vector size = 0
Vector size after resize = 128
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2694,
"s": 2603,
"text": "The C++ function std::vector::size() returns the number of elements present in the vector."
},
{
"code": null,
"e": 2781,
"s": 2694,
"text": "Following is the declaration for std::vector::size() function form std::vector header."
},
{
"code": null,
"e": 2806,
"s": 2781,
"text": "size_type size() const;\n"
},
{
"code": null,
"e": 2840,
"s": 2806,
"text": "size_type size() const noexcept;\n"
},
{
"code": null,
"e": 2845,
"s": 2840,
"text": "None"
},
{
"code": null,
"e": 2944,
"s": 2845,
"text": "Returns the actual objects present in vector, which may be differ than storage capacity of vector."
},
{
"code": null,
"e": 2989,
"s": 2944,
"text": "This member function never throws exception."
},
{
"code": null,
"e": 3008,
"s": 2989,
"text": "Constant i.e. O(1)"
},
{
"code": null,
"e": 3079,
"s": 3008,
"text": "The following example shows the usage of std::vector::size() function."
},
{
"code": null,
"e": 3330,
"s": 3079,
"text": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main(void) {\n vector<int> v;\n\n cout << \"Initial vector size = \" << v.size() << endl;\n\n v.resize(128);\n cout << \"Vector size after resize = \" << v.size() << endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 3413,
"s": 3330,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 3469,
"s": 3413,
"text": "Initial vector size = 0\nVector size after resize = 128\n"
},
{
"code": null,
"e": 3476,
"s": 3469,
"text": " Print"
},
{
"code": null,
"e": 3487,
"s": 3476,
"text": " Add Notes"
}
] |
C++ Fstream Library - rdbuf Function
|
It returns a pointer to the internal filebuf object.
Following is the declaration for fstream::rduf.
filebuf* rdbuf() const;
It returns a pointer to the internal filebuf object.
Strong guarantee − if an exception is thrown, there are no changes in the stream buffer.
It accesses the stream object.
It accesses the stream object.
It concurrent access to the same stream object may cause data races.
It concurrent access to the same stream object may cause data races.
In below example explains about fstream rdbuf function.
#include <fstream>
#include <cstdio>
int main () {
std::fstream src,dest;
src.open ("test.txt");
dest.open ("copy.txt");
std::filebuf* inbuf = src.rdbuf();
std::filebuf* outbuf = dest.rdbuf();
char c = inbuf->sbumpc();
while (c != EOF) {
outbuf->sputc (c);
c = inbuf->sbumpc();
}
dest.close();
src.close();
return 0;
}
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2656,
"s": 2603,
"text": "It returns a pointer to the internal filebuf object."
},
{
"code": null,
"e": 2704,
"s": 2656,
"text": "Following is the declaration for fstream::rduf."
},
{
"code": null,
"e": 2728,
"s": 2704,
"text": "filebuf* rdbuf() const;"
},
{
"code": null,
"e": 2781,
"s": 2728,
"text": "It returns a pointer to the internal filebuf object."
},
{
"code": null,
"e": 2870,
"s": 2781,
"text": "Strong guarantee − if an exception is thrown, there are no changes in the stream buffer."
},
{
"code": null,
"e": 2901,
"s": 2870,
"text": "It accesses the stream object."
},
{
"code": null,
"e": 2932,
"s": 2901,
"text": "It accesses the stream object."
},
{
"code": null,
"e": 3001,
"s": 2932,
"text": "It concurrent access to the same stream object may cause data races."
},
{
"code": null,
"e": 3070,
"s": 3001,
"text": "It concurrent access to the same stream object may cause data races."
},
{
"code": null,
"e": 3126,
"s": 3070,
"text": "In below example explains about fstream rdbuf function."
},
{
"code": null,
"e": 3496,
"s": 3126,
"text": "#include <fstream>\n#include <cstdio>\n\nint main () {\n std::fstream src,dest;\n src.open (\"test.txt\");\n dest.open (\"copy.txt\");\n\n std::filebuf* inbuf = src.rdbuf();\n std::filebuf* outbuf = dest.rdbuf();\n\n char c = inbuf->sbumpc();\n while (c != EOF) {\n outbuf->sputc (c);\n c = inbuf->sbumpc();\n }\n\n dest.close();\n src.close();\n\n return 0;\n}"
},
{
"code": null,
"e": 3503,
"s": 3496,
"text": " Print"
},
{
"code": null,
"e": 3514,
"s": 3503,
"text": " Add Notes"
}
] |
Keyword arguments in Python
|
Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. You can also make keyword calls to the printme() function in the following ways −
Live Demo
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme( str = "My string")
When the above code is executed, it produces the following result −
My string
The following example gives more clear picture. Note that the order of parameters does not matter.
Live Demo
#!/usr/bin/python
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" )
When the above code is executed, it produces the following result −
Name: miki
Age 50
|
[
{
"code": null,
"e": 1225,
"s": 1062,
"text": "Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name."
},
{
"code": null,
"e": 1473,
"s": 1225,
"text": "This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. You can also make keyword calls to the printme() function in the following ways −"
},
{
"code": null,
"e": 1484,
"s": 1473,
"text": " Live Demo"
},
{
"code": null,
"e": 1683,
"s": 1484,
"text": "#!/usr/bin/python\n# Function definition is here\ndef printme( str ):\n\"This prints a passed string into this function\"\nprint str\nreturn;\n# Now you can call printme function\nprintme( str = \"My string\")"
},
{
"code": null,
"e": 1751,
"s": 1683,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 1762,
"s": 1751,
"text": "My string\n"
},
{
"code": null,
"e": 1861,
"s": 1762,
"text": "The following example gives more clear picture. Note that the order of parameters does not matter."
},
{
"code": null,
"e": 1872,
"s": 1861,
"text": " Live Demo"
},
{
"code": null,
"e": 2113,
"s": 1872,
"text": "#!/usr/bin/python\n# Function definition is here\ndef printinfo( name, age ):\n\"This prints a passed info into this function\"\nprint \"Name: \", name\nprint \"Age \", age\nreturn;\n# Now you can call printinfo function\nprintinfo( age=50, name=\"miki\" )"
},
{
"code": null,
"e": 2181,
"s": 2113,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 2199,
"s": 2181,
"text": "Name: miki\nAge 50"
}
] |
Solving Travelling Salesperson Problems with Python | by Genevieve Hayes | Towards Data Science
|
mlrose provides functionality for implementing some of the most popular randomization and search algorithms, and applying them to a range of different optimization problem domains.
In this tutorial, we will discuss what is meant by the travelling salesperson problem and step through an example of how mlrose can be used to solve it.
This is the second in a series of three tutorials about using mlrose to solve randomized optimization problems. Part 1 can be found here and Part 3 can be found here.
The travelling salesperson problem (TSP) is a classic optimization problem where the goal is to determine the shortest tour of a collection of n “cities” (i.e. nodes), starting and ending in the same city and visiting all of the other cities exactly once.
In such a situation, a solution can be represented by a vector of n integers, each in the range 0 to n-1, specifying the order in which the cities should be visited.
TSP is an NP-hard problem, meaning that, for larger values of n, it is not feasible to evaluate every possible problem solution within a reasonable period of time. Consequently, TSPs are well suited to solving using randomized optimization algorithms.
Consider the following map containing 8 cities, numbered 0 to 7.
A salesperson would like to travel to each of these cities, starting and ending in the same city and visiting each of the other cities exactly once.
One possible tour of the cities is illustrated below, and could be represented by the solution vector x = [0, 4, 2, 6, 5, 3, 7, 1] (assuming the tour starts and ends at City 0).
However, this is not the shortest tour of these cities. The aim of this problem is to find the shortest tour of the 8 cities.
Given the solution to the TSP can be represented by a vector of integers in the range 0 to n-1, we could define a discrete-state optimization problem object and use one of mlrose’s randomized optimization algorithms to solve it, as we did for the 8-Queens problem in the previous tutorial.
[Recall that a discrete-state optimization problem is one where each element of the state vector can only take on a discrete set of values. In mlrose, these values are assumed to be integers in the range 0 to (max_val -1), where max_val is defined at initialization.]
However, by defining the problem this way, we would end up potentially considering invalid “solutions”, which involve us visiting some cities more than once and some not at all.
An alternative is to define an optimization problem object that only allows us to consider valid tours of the n cities as potential solutions. This is a much more efficient approach to solving TSPs and can be implemented in mlrose using the TSPOpt() optimization problem class.
We will use this alternative approach to solve the TSP example given above.
The steps required to solve this problem are the same as those used to solve any optimization problem in mlrose. Specificially:
Define a fitness function object.Define an optimization problem object.Select and run a randomized optimization algorithm.
Define a fitness function object.
Define an optimization problem object.
Select and run a randomized optimization algorithm.
Before starting with the example, you will need to import the mlrose and Numpy Python packages.
import mlroseimport numpy as np
For the TSP in the example, the goal is to find the shortest tour of the eight cities. As a result, the fitness function should calculate the total length of a given tour. This is the fitness definition used in mlrose’s pre-defined TravellingSales() class.
The TSPOpt() optimization problem class assumes, by default, that the TravellingSales() class is used to define the fitness function for a TSP. As a result, if the TravellingSales() class is to be used to define the fitness function object, then this step can be skipped. However, it is also possible to manually define the fitness function object, if so desired.
To initialize a fitness function object for the TravellingSales() class, it is necessary to specify either the (x, y) coordinates of all the cities or the distances between each pair of cities for which travel is possible. If the former is specified, then it is assumed that travel between each pair of cities is possible and that the distance between the pairs of cities is the Euclidean distance.
If we choose to specify the coordinates, then these should be input as an ordered list of pairs (where pair i specifies the coordinates of city i), as follows:
Alternatively, if we choose to specify the distances, then these should be input as a list of triples giving the distances, d, between all pairs of cities, u and v, for which travel is possible, with each triple in the form (u, v, d).
The order in which the cities is specified does not matter (i.e., the distance between cities 1 and 2 is assumed to be the same as the distance between cities 2 and 1), and so each pair of cities need only be included in the list once.
Using the distance approach, the fitness function object can be initialized as follows:
If both a list of coordinates and a list of distances are specified in initializing the fitness function object, then the distance list will be ignored.
As mentioned previously, the most efficient approach to solving a TSP in mlrose is to define the optimization problem object using the TSPOpt() optimization problem class.
If a fitness function has already been manually defined, as demonstrated in the previous step, then the only additional information required to initialize a TSPOpt() object are the length of the problem (i.e. the number of cities to be visited on the tour) and whether our problem is a maximization or a minimization problem.
In our example, we want to solve a minimization problem of length 8. If we use the fitness_coords fitness function defined above, we can define an optimization problem object as follows:
problem_fit = mlrose.TSPOpt(length = 8, fitness_fn = fitness_coords, maximize=False)
Alternatively, if we had not previously defined a fitness function (and we wish to use the TravellingSales() class to define the fitness function), then this can be done as part of the optimization problem object initialization step by specifying either a list of coordinates or a list of distances, instead of a fitness function object, similar to what was done when manually initializing the fitness function object.
In the case of our example, if we choose to specify a list of coordinates, in place of a fitness function object, we can initialize our optimization problem object as:
coords_list = [(1, 1), (4, 2), (5, 2), (6, 4), (4, 4), (3, 6), (1, 5), (2, 3)]problem_no_fit = mlrose.TSPOpt(length = 8, coords = coords_list, maximize=False)
As with manually defining the fitness function object, if both a list of coordinates and a list of distances are specified in initializing the optimization problem object, then the distance list will be ignored. Furthermore, if a fitness function object is specified in addition to a list of coordinates and/or a list of distances, then the list of coordinates/distances will be ignored.
Once the optimization object is defined, all that is left to do is to select a randomized optimization algorithm and use it to solve our problem.
This time, suppose we wish to use a genetic algorithm with the default parameter settings of a population size (pop_size) of 200, a mutation probability (mutation_prob) of 0.1, a maximum of 10 attempts per step (max_attempts) and no limit on the maximum total number of iteration of the algorithm (max_iters).
This returns the following solution:
The best state found is: [1 3 4 5 6 7 0 2]The fitness at the best state is: 18.8958046604
The solution tour found by the algorithm is pictured below and has a total length of 18.896 units.
As in the 8-Queens example given in the previous tutorial, this solution can potentially be improved on by tuning the parameters of the optimization algorithm.
For example, increasing the maximum number of attempts per step to 100 and increasing the mutation probability to 0.2, yields a tour with a total length of 17.343 units.
The best state found is: [7 6 5 4 3 2 1 0]The fitness at the best state is: 17.3426175477
This solution is illustrated below and can be shown to be an optimal solution to this problem.
In this tutorial we introduced the travelling salesperson problem, and discussed how mlrose can be used to efficiently solve this problem. This is an example of how mlrose caters to solving one very specific type of optimization problem.
Another very specific type of optimization problem mlrose caters to solving is the machine learning weight optimization problem. That is, the problem of finding the optimal weights for machine learning models such as neural networks and regression models.
We will discuss how mlrose can be used to solve this problem next, in our third and final tutorial, which can be found here.
To learn more about mlrose, visit the GitHub repository for this package, available here.
|
[
{
"code": null,
"e": 353,
"s": 172,
"text": "mlrose provides functionality for implementing some of the most popular randomization and search algorithms, and applying them to a range of different optimization problem domains."
},
{
"code": null,
"e": 506,
"s": 353,
"text": "In this tutorial, we will discuss what is meant by the travelling salesperson problem and step through an example of how mlrose can be used to solve it."
},
{
"code": null,
"e": 673,
"s": 506,
"text": "This is the second in a series of three tutorials about using mlrose to solve randomized optimization problems. Part 1 can be found here and Part 3 can be found here."
},
{
"code": null,
"e": 929,
"s": 673,
"text": "The travelling salesperson problem (TSP) is a classic optimization problem where the goal is to determine the shortest tour of a collection of n “cities” (i.e. nodes), starting and ending in the same city and visiting all of the other cities exactly once."
},
{
"code": null,
"e": 1095,
"s": 929,
"text": "In such a situation, a solution can be represented by a vector of n integers, each in the range 0 to n-1, specifying the order in which the cities should be visited."
},
{
"code": null,
"e": 1347,
"s": 1095,
"text": "TSP is an NP-hard problem, meaning that, for larger values of n, it is not feasible to evaluate every possible problem solution within a reasonable period of time. Consequently, TSPs are well suited to solving using randomized optimization algorithms."
},
{
"code": null,
"e": 1412,
"s": 1347,
"text": "Consider the following map containing 8 cities, numbered 0 to 7."
},
{
"code": null,
"e": 1561,
"s": 1412,
"text": "A salesperson would like to travel to each of these cities, starting and ending in the same city and visiting each of the other cities exactly once."
},
{
"code": null,
"e": 1739,
"s": 1561,
"text": "One possible tour of the cities is illustrated below, and could be represented by the solution vector x = [0, 4, 2, 6, 5, 3, 7, 1] (assuming the tour starts and ends at City 0)."
},
{
"code": null,
"e": 1865,
"s": 1739,
"text": "However, this is not the shortest tour of these cities. The aim of this problem is to find the shortest tour of the 8 cities."
},
{
"code": null,
"e": 2155,
"s": 1865,
"text": "Given the solution to the TSP can be represented by a vector of integers in the range 0 to n-1, we could define a discrete-state optimization problem object and use one of mlrose’s randomized optimization algorithms to solve it, as we did for the 8-Queens problem in the previous tutorial."
},
{
"code": null,
"e": 2423,
"s": 2155,
"text": "[Recall that a discrete-state optimization problem is one where each element of the state vector can only take on a discrete set of values. In mlrose, these values are assumed to be integers in the range 0 to (max_val -1), where max_val is defined at initialization.]"
},
{
"code": null,
"e": 2601,
"s": 2423,
"text": "However, by defining the problem this way, we would end up potentially considering invalid “solutions”, which involve us visiting some cities more than once and some not at all."
},
{
"code": null,
"e": 2879,
"s": 2601,
"text": "An alternative is to define an optimization problem object that only allows us to consider valid tours of the n cities as potential solutions. This is a much more efficient approach to solving TSPs and can be implemented in mlrose using the TSPOpt() optimization problem class."
},
{
"code": null,
"e": 2955,
"s": 2879,
"text": "We will use this alternative approach to solve the TSP example given above."
},
{
"code": null,
"e": 3083,
"s": 2955,
"text": "The steps required to solve this problem are the same as those used to solve any optimization problem in mlrose. Specificially:"
},
{
"code": null,
"e": 3206,
"s": 3083,
"text": "Define a fitness function object.Define an optimization problem object.Select and run a randomized optimization algorithm."
},
{
"code": null,
"e": 3240,
"s": 3206,
"text": "Define a fitness function object."
},
{
"code": null,
"e": 3279,
"s": 3240,
"text": "Define an optimization problem object."
},
{
"code": null,
"e": 3331,
"s": 3279,
"text": "Select and run a randomized optimization algorithm."
},
{
"code": null,
"e": 3427,
"s": 3331,
"text": "Before starting with the example, you will need to import the mlrose and Numpy Python packages."
},
{
"code": null,
"e": 3459,
"s": 3427,
"text": "import mlroseimport numpy as np"
},
{
"code": null,
"e": 3716,
"s": 3459,
"text": "For the TSP in the example, the goal is to find the shortest tour of the eight cities. As a result, the fitness function should calculate the total length of a given tour. This is the fitness definition used in mlrose’s pre-defined TravellingSales() class."
},
{
"code": null,
"e": 4080,
"s": 3716,
"text": "The TSPOpt() optimization problem class assumes, by default, that the TravellingSales() class is used to define the fitness function for a TSP. As a result, if the TravellingSales() class is to be used to define the fitness function object, then this step can be skipped. However, it is also possible to manually define the fitness function object, if so desired."
},
{
"code": null,
"e": 4479,
"s": 4080,
"text": "To initialize a fitness function object for the TravellingSales() class, it is necessary to specify either the (x, y) coordinates of all the cities or the distances between each pair of cities for which travel is possible. If the former is specified, then it is assumed that travel between each pair of cities is possible and that the distance between the pairs of cities is the Euclidean distance."
},
{
"code": null,
"e": 4639,
"s": 4479,
"text": "If we choose to specify the coordinates, then these should be input as an ordered list of pairs (where pair i specifies the coordinates of city i), as follows:"
},
{
"code": null,
"e": 4874,
"s": 4639,
"text": "Alternatively, if we choose to specify the distances, then these should be input as a list of triples giving the distances, d, between all pairs of cities, u and v, for which travel is possible, with each triple in the form (u, v, d)."
},
{
"code": null,
"e": 5110,
"s": 4874,
"text": "The order in which the cities is specified does not matter (i.e., the distance between cities 1 and 2 is assumed to be the same as the distance between cities 2 and 1), and so each pair of cities need only be included in the list once."
},
{
"code": null,
"e": 5198,
"s": 5110,
"text": "Using the distance approach, the fitness function object can be initialized as follows:"
},
{
"code": null,
"e": 5351,
"s": 5198,
"text": "If both a list of coordinates and a list of distances are specified in initializing the fitness function object, then the distance list will be ignored."
},
{
"code": null,
"e": 5523,
"s": 5351,
"text": "As mentioned previously, the most efficient approach to solving a TSP in mlrose is to define the optimization problem object using the TSPOpt() optimization problem class."
},
{
"code": null,
"e": 5849,
"s": 5523,
"text": "If a fitness function has already been manually defined, as demonstrated in the previous step, then the only additional information required to initialize a TSPOpt() object are the length of the problem (i.e. the number of cities to be visited on the tour) and whether our problem is a maximization or a minimization problem."
},
{
"code": null,
"e": 6036,
"s": 5849,
"text": "In our example, we want to solve a minimization problem of length 8. If we use the fitness_coords fitness function defined above, we can define an optimization problem object as follows:"
},
{
"code": null,
"e": 6148,
"s": 6036,
"text": "problem_fit = mlrose.TSPOpt(length = 8, fitness_fn = fitness_coords, maximize=False)"
},
{
"code": null,
"e": 6567,
"s": 6148,
"text": "Alternatively, if we had not previously defined a fitness function (and we wish to use the TravellingSales() class to define the fitness function), then this can be done as part of the optimization problem object initialization step by specifying either a list of coordinates or a list of distances, instead of a fitness function object, similar to what was done when manually initializing the fitness function object."
},
{
"code": null,
"e": 6735,
"s": 6567,
"text": "In the case of our example, if we choose to specify a list of coordinates, in place of a fitness function object, we can initialize our optimization problem object as:"
},
{
"code": null,
"e": 6939,
"s": 6735,
"text": "coords_list = [(1, 1), (4, 2), (5, 2), (6, 4), (4, 4), (3, 6), (1, 5), (2, 3)]problem_no_fit = mlrose.TSPOpt(length = 8, coords = coords_list, maximize=False)"
},
{
"code": null,
"e": 7327,
"s": 6939,
"text": "As with manually defining the fitness function object, if both a list of coordinates and a list of distances are specified in initializing the optimization problem object, then the distance list will be ignored. Furthermore, if a fitness function object is specified in addition to a list of coordinates and/or a list of distances, then the list of coordinates/distances will be ignored."
},
{
"code": null,
"e": 7473,
"s": 7327,
"text": "Once the optimization object is defined, all that is left to do is to select a randomized optimization algorithm and use it to solve our problem."
},
{
"code": null,
"e": 7783,
"s": 7473,
"text": "This time, suppose we wish to use a genetic algorithm with the default parameter settings of a population size (pop_size) of 200, a mutation probability (mutation_prob) of 0.1, a maximum of 10 attempts per step (max_attempts) and no limit on the maximum total number of iteration of the algorithm (max_iters)."
},
{
"code": null,
"e": 7820,
"s": 7783,
"text": "This returns the following solution:"
},
{
"code": null,
"e": 7912,
"s": 7820,
"text": "The best state found is: [1 3 4 5 6 7 0 2]The fitness at the best state is: 18.8958046604"
},
{
"code": null,
"e": 8011,
"s": 7912,
"text": "The solution tour found by the algorithm is pictured below and has a total length of 18.896 units."
},
{
"code": null,
"e": 8171,
"s": 8011,
"text": "As in the 8-Queens example given in the previous tutorial, this solution can potentially be improved on by tuning the parameters of the optimization algorithm."
},
{
"code": null,
"e": 8341,
"s": 8171,
"text": "For example, increasing the maximum number of attempts per step to 100 and increasing the mutation probability to 0.2, yields a tour with a total length of 17.343 units."
},
{
"code": null,
"e": 8433,
"s": 8341,
"text": "The best state found is: [7 6 5 4 3 2 1 0]The fitness at the best state is: 17.3426175477"
},
{
"code": null,
"e": 8528,
"s": 8433,
"text": "This solution is illustrated below and can be shown to be an optimal solution to this problem."
},
{
"code": null,
"e": 8766,
"s": 8528,
"text": "In this tutorial we introduced the travelling salesperson problem, and discussed how mlrose can be used to efficiently solve this problem. This is an example of how mlrose caters to solving one very specific type of optimization problem."
},
{
"code": null,
"e": 9022,
"s": 8766,
"text": "Another very specific type of optimization problem mlrose caters to solving is the machine learning weight optimization problem. That is, the problem of finding the optimal weights for machine learning models such as neural networks and regression models."
},
{
"code": null,
"e": 9147,
"s": 9022,
"text": "We will discuss how mlrose can be used to solve this problem next, in our third and final tutorial, which can be found here."
}
] |
Job Sequencing with Deadline
|
In job sequencing problem, the objective is to find a sequence of jobs, which is completed within their deadlines and gives maximum profit.
Let us consider, a set of n given jobs which are associated with deadlines and profit is earned, if a job is completed by its deadline. These jobs need to be ordered in such a way that there is maximum profit.
It may happen that all of the given jobs may not be completed within their deadlines.
Assume, deadline of ith job Ji is di and the profit received from this job is pi. Hence, the optimal solution of this algorithm is a feasible solution with maximum profit.
Thus, D(i)>0 for 1⩽i⩽n.
Initially, these jobs are ordered according to profit, i.e. p1⩾p2⩾p3⩾...⩾pn.
Algorithm: Job-Sequencing-With-Deadline (D, J, n, k)
D(0) := J(0) := 0
k := 1
J(1) := 1 // means first job is selected
for i = 2 ... n do
r := k
while D(J(r)) > D(i) and D(J(r)) ≠ r do
r := r – 1
if D(J(r)) ≤ D(i) and D(i) > r then
for l = k ... r + 1 by -1 do
J(l + 1) := J(l)
J(r + 1) := i
k := k + 1
In this algorithm, we are using two loops, one is within another. Hence, the complexity of this algorithm is O(n2).
Let us consider a set of given jobs as shown in the following table. We have to find a sequence of jobs, which will be completed within their deadlines and will give maximum profit. Each job is associated with a deadline and profit.
To solve this problem, the given jobs are sorted according to their profit in a descending order. Hence, after sorting, the jobs are ordered as shown in the following table.
From this set of jobs, first we select J2, as it can be completed within its deadline and contributes maximum profit.
Next, J1 is selected as it gives more profit compared to J4.
Next, J1 is selected as it gives more profit compared to J4.
In the next clock, J4 cannot be selected as its deadline is over, hence J3 is selected as it executes within its deadline.
In the next clock, J4 cannot be selected as its deadline is over, hence J3 is selected as it executes within its deadline.
The job J5 is discarded as it cannot be executed within its deadline.
The job J5 is discarded as it cannot be executed within its deadline.
Thus, the solution is the sequence of jobs (J2, J1, J3), which are being executed within their deadline and gives maximum profit.
Total profit of this sequence is 100 + 60 + 20 = 180.
102 Lectures
10 hours
Arnab Chakraborty
30 Lectures
3 hours
Arnab Chakraborty
31 Lectures
4 hours
Arnab Chakraborty
43 Lectures
1.5 hours
Manoj Kumar
7 Lectures
1 hours
Zach Miller
54 Lectures
4 hours
Sasha Miller
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2739,
"s": 2599,
"text": "In job sequencing problem, the objective is to find a sequence of jobs, which is completed within their deadlines and gives maximum profit."
},
{
"code": null,
"e": 2949,
"s": 2739,
"text": "Let us consider, a set of n given jobs which are associated with deadlines and profit is earned, if a job is completed by its deadline. These jobs need to be ordered in such a way that there is maximum profit."
},
{
"code": null,
"e": 3035,
"s": 2949,
"text": "It may happen that all of the given jobs may not be completed within their deadlines."
},
{
"code": null,
"e": 3207,
"s": 3035,
"text": "Assume, deadline of ith job Ji is di and the profit received from this job is pi. Hence, the optimal solution of this algorithm is a feasible solution with maximum profit."
},
{
"code": null,
"e": 3231,
"s": 3207,
"text": "Thus, D(i)>0 for 1⩽i⩽n."
},
{
"code": null,
"e": 3308,
"s": 3231,
"text": "Initially, these jobs are ordered according to profit, i.e. p1⩾p2⩾p3⩾...⩾pn."
},
{
"code": null,
"e": 3676,
"s": 3308,
"text": "Algorithm: Job-Sequencing-With-Deadline (D, J, n, k) \nD(0) := J(0) := 0 \nk := 1 \nJ(1) := 1 // means first job is selected \nfor i = 2 ... n do \n r := k \n while D(J(r)) > D(i) and D(J(r)) ≠ r do \n r := r – 1 \n if D(J(r)) ≤ D(i) and D(i) > r then \n for l = k ... r + 1 by -1 do \n J(l + 1) := J(l) \n J(r + 1) := i \n k := k + 1 \n"
},
{
"code": null,
"e": 3792,
"s": 3676,
"text": "In this algorithm, we are using two loops, one is within another. Hence, the complexity of this algorithm is O(n2)."
},
{
"code": null,
"e": 4025,
"s": 3792,
"text": "Let us consider a set of given jobs as shown in the following table. We have to find a sequence of jobs, which will be completed within their deadlines and will give maximum profit. Each job is associated with a deadline and profit."
},
{
"code": null,
"e": 4199,
"s": 4025,
"text": "To solve this problem, the given jobs are sorted according to their profit in a descending order. Hence, after sorting, the jobs are ordered as shown in the following table."
},
{
"code": null,
"e": 4317,
"s": 4199,
"text": "From this set of jobs, first we select J2, as it can be completed within its deadline and contributes maximum profit."
},
{
"code": null,
"e": 4378,
"s": 4317,
"text": "Next, J1 is selected as it gives more profit compared to J4."
},
{
"code": null,
"e": 4439,
"s": 4378,
"text": "Next, J1 is selected as it gives more profit compared to J4."
},
{
"code": null,
"e": 4562,
"s": 4439,
"text": "In the next clock, J4 cannot be selected as its deadline is over, hence J3 is selected as it executes within its deadline."
},
{
"code": null,
"e": 4685,
"s": 4562,
"text": "In the next clock, J4 cannot be selected as its deadline is over, hence J3 is selected as it executes within its deadline."
},
{
"code": null,
"e": 4755,
"s": 4685,
"text": "The job J5 is discarded as it cannot be executed within its deadline."
},
{
"code": null,
"e": 4825,
"s": 4755,
"text": "The job J5 is discarded as it cannot be executed within its deadline."
},
{
"code": null,
"e": 4955,
"s": 4825,
"text": "Thus, the solution is the sequence of jobs (J2, J1, J3), which are being executed within their deadline and gives maximum profit."
},
{
"code": null,
"e": 5009,
"s": 4955,
"text": "Total profit of this sequence is 100 + 60 + 20 = 180."
},
{
"code": null,
"e": 5044,
"s": 5009,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 5063,
"s": 5044,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5096,
"s": 5063,
"text": "\n 30 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5115,
"s": 5096,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5148,
"s": 5115,
"text": "\n 31 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5167,
"s": 5148,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5202,
"s": 5167,
"text": "\n 43 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5215,
"s": 5202,
"text": " Manoj Kumar"
},
{
"code": null,
"e": 5247,
"s": 5215,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5260,
"s": 5247,
"text": " Zach Miller"
},
{
"code": null,
"e": 5293,
"s": 5260,
"text": "\n 54 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5307,
"s": 5293,
"text": " Sasha Miller"
},
{
"code": null,
"e": 5314,
"s": 5307,
"text": " Print"
},
{
"code": null,
"e": 5325,
"s": 5314,
"text": " Add Notes"
}
] |
GitLab - Referencing Issues
|
GitLab can be able to refer the specific issue from the commit message to solve a specific problem. In this chapter, we will discuss about how to reference a issue in the GitLab −
Step 1 − To reference a issue, you need to have an issue number of a created issue. To create an issue, refer the creating issue chapter.
Step 2 − To see the created issue, click on the List option under Issues tab −
Step 3 − Before making the changes in your local repository, check whether it is up to date or not by using the below command −
git checkout master && git pull
The git pull command downloads the latest changes from the remote server and integrates directly into current working files.
Step 4 − Now, create a new branch with the name issue-fix by using the git checkout command −
git checkout -b issue-fix
Step 5 − Now, add some content to the README.md file to fix the bug −
echo "fix this bug" >> README.md
Step 6 − Enter the commit message for the above change with the below command −
git commit -a
This command opens the below screen and press Insert key on the keyboard to add a commit message for the issue-fix branch.
Now press the Esc key, then colon(:) and type wq to save and exit from the screen.
Step 7 − Now push the branch to remote repository by using the below command −
git push origin issue-fix
Step 8 − Login to your GitLab account and create a new merge request. You can refer the merge request chapter for the creation of merge request.
Step 9 − Once you create the merge request, you will be redirected to the merge request page. When you click on the Close merge request button (refer the screenshot in the step (6) of merge request chapter), you will see the Closed option after closing merge request.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2504,
"s": 2324,
"text": "GitLab can be able to refer the specific issue from the commit message to solve a specific problem. In this chapter, we will discuss about how to reference a issue in the GitLab −"
},
{
"code": null,
"e": 2642,
"s": 2504,
"text": "Step 1 − To reference a issue, you need to have an issue number of a created issue. To create an issue, refer the creating issue chapter."
},
{
"code": null,
"e": 2721,
"s": 2642,
"text": "Step 2 − To see the created issue, click on the List option under Issues tab −"
},
{
"code": null,
"e": 2849,
"s": 2721,
"text": "Step 3 − Before making the changes in your local repository, check whether it is up to date or not by using the below command −"
},
{
"code": null,
"e": 2881,
"s": 2849,
"text": "git checkout master && git pull"
},
{
"code": null,
"e": 3006,
"s": 2881,
"text": "The git pull command downloads the latest changes from the remote server and integrates directly into current working files."
},
{
"code": null,
"e": 3100,
"s": 3006,
"text": "Step 4 − Now, create a new branch with the name issue-fix by using the git checkout command −"
},
{
"code": null,
"e": 3126,
"s": 3100,
"text": "git checkout -b issue-fix"
},
{
"code": null,
"e": 3196,
"s": 3126,
"text": "Step 5 − Now, add some content to the README.md file to fix the bug −"
},
{
"code": null,
"e": 3229,
"s": 3196,
"text": "echo \"fix this bug\" >> README.md"
},
{
"code": null,
"e": 3309,
"s": 3229,
"text": "Step 6 − Enter the commit message for the above change with the below command −"
},
{
"code": null,
"e": 3323,
"s": 3309,
"text": "git commit -a"
},
{
"code": null,
"e": 3446,
"s": 3323,
"text": "This command opens the below screen and press Insert key on the keyboard to add a commit message for the issue-fix branch."
},
{
"code": null,
"e": 3529,
"s": 3446,
"text": "Now press the Esc key, then colon(:) and type wq to save and exit from the screen."
},
{
"code": null,
"e": 3608,
"s": 3529,
"text": "Step 7 − Now push the branch to remote repository by using the below command −"
},
{
"code": null,
"e": 3634,
"s": 3608,
"text": "git push origin issue-fix"
},
{
"code": null,
"e": 3779,
"s": 3634,
"text": "Step 8 − Login to your GitLab account and create a new merge request. You can refer the merge request chapter for the creation of merge request."
},
{
"code": null,
"e": 4047,
"s": 3779,
"text": "Step 9 − Once you create the merge request, you will be redirected to the merge request page. When you click on the Close merge request button (refer the screenshot in the step (6) of merge request chapter), you will see the Closed option after closing merge request."
},
{
"code": null,
"e": 4054,
"s": 4047,
"text": " Print"
},
{
"code": null,
"e": 4065,
"s": 4054,
"text": " Add Notes"
}
] |
5 Awesome Things To Love About The Julia Language | by Emmett Boudreau | Towards Data Science
|
I have been using (and praising) the Julia programming language for years now. As of today, I have written 346 articles here on Medium, and those articles started from one source article, which was about the Julia language. In that article, I touched on the things a Data Scientist might want to know before picking up the Julia programming language. If you would like to read that article, you may certainly look into it here:
towardsdatascience.com
During my experience in Julia, which I believe to be a lot after all the modules, projects, and research I have written in Julia, there have been a number of features that I have simply found to be incredibly convenient. Today I wanted to reveal some of the cool features of the Julia language, why I think that those features are awesome. In some instances, I might even provide some real world examples where this has come in handy, and then compare this to other languages in the Data Science and Software Engineering domains. This will help us to get a better idea of why exactly this is a great feature, how it can be used, and where the industry is in comparison to Julia.
In my subjective view of this language, I feel it definitely has a lot of potential to help move things forward in at least the Data Science domain. Let us detail some of the great features about Julia, and why they happen to be so great.
If we refer to the Julia Github repository, we can see a very interesting balance of languages that are used for the core of Julia.
The Julia programming language is written in 69-percent Julia, itself! This provides a host of advantages when compared to most other programming languages, as some are written in C or Assembly, and often the actual base of the language is barely written in the language’s actual syntax. This means a few different things of end-users of the language like myself.
Researching the actual source-code for a portion of Julia that might not be documented super well is incredibly easy.
If someone had a propose change for the language, but did not know the first thing about C, C++, or the LLVM compiler library, they could still make contributions to the language.
Getting even more crazy, one could even write their own edition of the language and use it instead of the core language.
Contributing to the first point, I have been working on a Julia package called Jockey.jl. Jockey.jl is a notebook server session for the Julia programming language that I am developing. My original intention with this package, however, was to put notebooks into the terminal. I just thought given how awesome the Julia REPL actually is, maybe there could be a notebook session on the top half of the REPL, and then the regular Julia REPL below it.
Of course, that kind of work is going to require that we have knowledge of the Julia REPL’s internals, in order to alter the behavior of that terminal. The problem, however, is that the language does not have any explicit documentation on the Base.Terminals module. You can view the documentation markdown file, which does carry pretty well into Github-style markdown here:
github.com
Most of this documentation is meant for end-users, which I suppose makes a lot of since, since generally I think people are going to be concerned with how to use the REPL, change key-binds, that sort of thing rather than using the package to change the function of the terminal. Fortunately, since I was able to look through the source code of Terminals.jl, LineEdit.jl, and REPL.jl, I was able to get a simple, very buggy version of this package with that feature released. While this instance of using this was very cool, I did end up giving up on that approach to notebooks because I found it to be a hassle to use, as the terminal and the terminal’s cursor in tandem with having a REPL at the bottom was simply a lot to manage.
It is cool that even though I do not know the internals of the language, and have not really worked on the language, I was still able to go into this package and read all of the source code. And this would be the case even if I knew no other language except for Julia.
Multiple dispatch is a very obvious thing to love about the Julia programming language. The core paradigm of Julia revolves around this polymorphic concept. That being said, while multiple dispatch is certainly available in other programming languages, I genuinely believe that the Julia programming language has perfected the multiple dispatch concept. I detail exactly why I think that is in this old article:
towardsdatascience.com
That being said, I think I have talked about multiple dispatch a lot, and although it is a great way to program in my opinion, I think that beating a dead horse on it is probably not optimal. However, many who have not used Julia, or are new to Julia do not realize how constructors can be used with multiple dispatch to create some pretty incredible results. Consider the following constructor:
struct NormalDist <: Distribution σ::Float64 μ::Float64 N::Int64end
This is a regular constructor, the actual call for this constructor registered into Julia will look like this:
NormalDist(::Float64, ::Float64, ::Int64)
If we were to call the distribution with those values, we would get a return of a new NormalDist type. However, making someone calculate the standard deviation, the mean, and put the number of observations in themselves does not seem optimal, and is not typically how normal distribution types like this work. That being said, we can use multiple dispatch to write a new version of this call that will call a function instead by building an inner constructor:
struct NormalDist <: Distribution σ::Float64 μ::Float64 N::Int64 function NormalDist(x::Array) N = length(x) σ = std(x) μ = mean(x) new(σ, μ, N, cdf, apply) endend
Now we have two registered calls, one for the constructor and one for the inner constructor, which is a function that will return a new version of our constructor, which I will now refer to as the outer constructor. Now we have two calls, one is the regular constructor that we had before,
NormalDist(::Float64, ::Float64, ::Int64)
and the other is our new function:
NormalDist(::Array)
Whenever this function is used, it does not matter what the programmer on the other end intends to call. If they happen to have the standard deviation, mean, and N and provide those arguments, then we will get the type. If they do not and only pass the array, then they get the constructor. We can also build an infinite (besides in terms of hardware limitations,) number of these inner constructors in order to make our constructor have all the calls we could possibly want.
When it comes to Julia, the most obvious comparison to make is always going to be Python. Although in paradigm and syntax Julia is slightly different, the languages have a similar market niche and perhaps a similar objective. In the Python edition of this normal distribution, we instead define the type and then the equivalent to it is our __init__() function.
class NormalDist: def __init__(self, x): self.N = length(x) self.σ = std(x) self.μ = mean(x)
We lose performance with this function with all of the assertion we have to do to the things provided to the initialization. We also would not be able to make an infinite number of calls for different types an end-user might want to use.
We can also pass functions and types where we do not even know what type it is through an inner constructor. I have a video from the Comprehensive Julia Tutorials that goes into detail on constructors that you may watch by ctrl+clicking this text. That might provide a bit more information on constructors in Julia and all of the ins-and-outs, and if you are interested in learning Julia, that tutorial series might be a good place to start!
Now let us talk about the actual Julia compiler, and its speed. I must confess — there are a lot of ins and outs of bench-marking programming languages, and frankly fundamental problems with comparing benchmarks from said programming languages. That being said, I do not ever think that benchmarks are the end-all be-all of programming language speeds, as I am certain there are many instances where different languages might be faster at certain operations. That being said, however, we can still observe from benchmarks that Julia is obviously a pretty fast language.
I must confess, it is impossible to know how much of this JIT is responsible for. However, what I can say is that Julia is fast. This is especially the case when compared with languages that have similar syntax. The language typically falls around about the same speed as C and Rust. In some cases, those three can trade speeds in benchmarks between who is ultimately better. Some are amazed, and do not believe to learn that Julia can actually be faster than C. An important note to make, however is that those bench-marking measurements exclude precompilation of packages.
That being said, despite all of that the fact remains that Julia is fast. This is an advantages, especially when it comes to Data Science applications where some might be working with a lot of observations and operations on that data.
Another awesome thing in Julia is the package manager, Pkg. Compared to a lot of other package managers I have used in my experience as a programmer, Pkg is one of if not the best. At this rate, I wish I could use Pkg as the package manager for my entire operating system. The package manager handles all of the dependencies for us very easily, can generate project directories, and does so with ease. I think that handling virtual environments environments from within the package manager is far more ideal in my subjective opinion.
While I think other languages do have some pretty awesome package managers, I think Julia’s package manager is simply better. The package manager and TOML setup that the Julia language has tends to work very well. Packages and their respective dependencies are completely managed by Pkg, which makes convenience a key feature of this package manager and its capabilities.
Comparing this package manager to Node, as an example, I think that the way packages are added is simply a lot better. Typically in node, you would call npm in a project directory, which can be a bit confusing with some projects because sometimes this is not the home directory. Taking the same comparison over to Python, environments are a lot harder to source, and are nowhere near as easy to manage as Pkg packages. Being able to manage packages and environments with Pkg, and using Pkg as a regular Julia package means that there is a lot of flexibility with controlling Pkg to do different things.
The last Julia feature that I wanted to share is the Julia’s REPL. When it comes to REPL’s for programming languages, there are certainly some desirable options. Python’s REPL is a decent REPL, though it is somewhat minimalist. My favorite REPL prior to my experience was probably the Steel Bank Common Lisp (SBCL) REPL, as I found the declarative and functional nature of keeping the data in tact using saved states that can be reverted to be a really awesome feature. That being said, Julia completely toppled this REPL with its interactive, and dynamic REPL.
As I touched on in No1, I have worked with the REPL’s source code and types. The REPL is incredibly flexible, and has a lot of different capabilities. In a normal REPL-work scenario, cding around, listing directories, all of these things is sometimes not possible, or requires a method call in the programming language. Calling cd(“dir”) over and over again in tandem with some LS method can be extremely tedious for exploring files or looking at environments. Julia counters this by providing a Bash REPL, which can be accessed using ; from the Julia REPL.
julia > ;shell > ls
Even more, Pkg also has its own REPL, which can parse regular Pkg commands and arguments to add and source packages. Consider the following REPL session:
(@v1.6) pkg> activate Jockey(@v1.6) pkg> activate Jockey Activating environment at `~/dev/Jockey/Project.toml`shell> cd Jockey/home/emmac/dev/Jockeyshell> lsbin config Project.toml routes.jl testbootstrap.jl Manifest.toml public src usershell> cd src/home/emmac/dev/Jockey/srcshell> lscore Jockey.jl ServerControllershell> nano Jockey.jlshell>
It is pretty awesome to be able to work with directories in a conventional way that I am used to while also working with packages and files at the same time. It feels very fluid, and it feels like this is a very quick way to work in a REPL. This is especially the case whenever we compare it to other dull REPLs that do not contain these sorts of features and alternate REPLs.
Julia is my favorite programming language, and an awesome choice for any developer at that. I would highly recommend picking up the language if you are into scientific computing, as it is particularly good for that task. There are so many great things about Julia, but these are just a mere five that I think are incredible. If you would like to learn more about Julia in general, you can visit the Julia language website here:
julialang.org
Thank you very much for reading, and I hope some of these awesome things about the Julia language are maybe compelling enough to inspire some new learning. I think Julia is such an awesome language, and that is why I love to talk about and share its features, as this is the type of appreciation this fantastic language deserves. Have a fantastic day!
|
[
{
"code": null,
"e": 600,
"s": 172,
"text": "I have been using (and praising) the Julia programming language for years now. As of today, I have written 346 articles here on Medium, and those articles started from one source article, which was about the Julia language. In that article, I touched on the things a Data Scientist might want to know before picking up the Julia programming language. If you would like to read that article, you may certainly look into it here:"
},
{
"code": null,
"e": 623,
"s": 600,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1302,
"s": 623,
"text": "During my experience in Julia, which I believe to be a lot after all the modules, projects, and research I have written in Julia, there have been a number of features that I have simply found to be incredibly convenient. Today I wanted to reveal some of the cool features of the Julia language, why I think that those features are awesome. In some instances, I might even provide some real world examples where this has come in handy, and then compare this to other languages in the Data Science and Software Engineering domains. This will help us to get a better idea of why exactly this is a great feature, how it can be used, and where the industry is in comparison to Julia."
},
{
"code": null,
"e": 1541,
"s": 1302,
"text": "In my subjective view of this language, I feel it definitely has a lot of potential to help move things forward in at least the Data Science domain. Let us detail some of the great features about Julia, and why they happen to be so great."
},
{
"code": null,
"e": 1673,
"s": 1541,
"text": "If we refer to the Julia Github repository, we can see a very interesting balance of languages that are used for the core of Julia."
},
{
"code": null,
"e": 2037,
"s": 1673,
"text": "The Julia programming language is written in 69-percent Julia, itself! This provides a host of advantages when compared to most other programming languages, as some are written in C or Assembly, and often the actual base of the language is barely written in the language’s actual syntax. This means a few different things of end-users of the language like myself."
},
{
"code": null,
"e": 2155,
"s": 2037,
"text": "Researching the actual source-code for a portion of Julia that might not be documented super well is incredibly easy."
},
{
"code": null,
"e": 2335,
"s": 2155,
"text": "If someone had a propose change for the language, but did not know the first thing about C, C++, or the LLVM compiler library, they could still make contributions to the language."
},
{
"code": null,
"e": 2456,
"s": 2335,
"text": "Getting even more crazy, one could even write their own edition of the language and use it instead of the core language."
},
{
"code": null,
"e": 2904,
"s": 2456,
"text": "Contributing to the first point, I have been working on a Julia package called Jockey.jl. Jockey.jl is a notebook server session for the Julia programming language that I am developing. My original intention with this package, however, was to put notebooks into the terminal. I just thought given how awesome the Julia REPL actually is, maybe there could be a notebook session on the top half of the REPL, and then the regular Julia REPL below it."
},
{
"code": null,
"e": 3278,
"s": 2904,
"text": "Of course, that kind of work is going to require that we have knowledge of the Julia REPL’s internals, in order to alter the behavior of that terminal. The problem, however, is that the language does not have any explicit documentation on the Base.Terminals module. You can view the documentation markdown file, which does carry pretty well into Github-style markdown here:"
},
{
"code": null,
"e": 3289,
"s": 3278,
"text": "github.com"
},
{
"code": null,
"e": 4021,
"s": 3289,
"text": "Most of this documentation is meant for end-users, which I suppose makes a lot of since, since generally I think people are going to be concerned with how to use the REPL, change key-binds, that sort of thing rather than using the package to change the function of the terminal. Fortunately, since I was able to look through the source code of Terminals.jl, LineEdit.jl, and REPL.jl, I was able to get a simple, very buggy version of this package with that feature released. While this instance of using this was very cool, I did end up giving up on that approach to notebooks because I found it to be a hassle to use, as the terminal and the terminal’s cursor in tandem with having a REPL at the bottom was simply a lot to manage."
},
{
"code": null,
"e": 4290,
"s": 4021,
"text": "It is cool that even though I do not know the internals of the language, and have not really worked on the language, I was still able to go into this package and read all of the source code. And this would be the case even if I knew no other language except for Julia."
},
{
"code": null,
"e": 4702,
"s": 4290,
"text": "Multiple dispatch is a very obvious thing to love about the Julia programming language. The core paradigm of Julia revolves around this polymorphic concept. That being said, while multiple dispatch is certainly available in other programming languages, I genuinely believe that the Julia programming language has perfected the multiple dispatch concept. I detail exactly why I think that is in this old article:"
},
{
"code": null,
"e": 4725,
"s": 4702,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5121,
"s": 4725,
"text": "That being said, I think I have talked about multiple dispatch a lot, and although it is a great way to program in my opinion, I think that beating a dead horse on it is probably not optimal. However, many who have not used Julia, or are new to Julia do not realize how constructors can be used with multiple dispatch to create some pretty incredible results. Consider the following constructor:"
},
{
"code": null,
"e": 5219,
"s": 5121,
"text": "struct NormalDist <: Distribution σ::Float64 μ::Float64 N::Int64end"
},
{
"code": null,
"e": 5330,
"s": 5219,
"text": "This is a regular constructor, the actual call for this constructor registered into Julia will look like this:"
},
{
"code": null,
"e": 5372,
"s": 5330,
"text": "NormalDist(::Float64, ::Float64, ::Int64)"
},
{
"code": null,
"e": 5832,
"s": 5372,
"text": "If we were to call the distribution with those values, we would get a return of a new NormalDist type. However, making someone calculate the standard deviation, the mean, and put the number of observations in themselves does not seem optimal, and is not typically how normal distribution types like this work. That being said, we can use multiple dispatch to write a new version of this call that will call a function instead by building an inner constructor:"
},
{
"code": null,
"e": 6096,
"s": 5832,
"text": "struct NormalDist <: Distribution σ::Float64 μ::Float64 N::Int64 function NormalDist(x::Array) N = length(x) σ = std(x) μ = mean(x) new(σ, μ, N, cdf, apply) endend"
},
{
"code": null,
"e": 6386,
"s": 6096,
"text": "Now we have two registered calls, one for the constructor and one for the inner constructor, which is a function that will return a new version of our constructor, which I will now refer to as the outer constructor. Now we have two calls, one is the regular constructor that we had before,"
},
{
"code": null,
"e": 6428,
"s": 6386,
"text": "NormalDist(::Float64, ::Float64, ::Int64)"
},
{
"code": null,
"e": 6463,
"s": 6428,
"text": "and the other is our new function:"
},
{
"code": null,
"e": 6483,
"s": 6463,
"text": "NormalDist(::Array)"
},
{
"code": null,
"e": 6959,
"s": 6483,
"text": "Whenever this function is used, it does not matter what the programmer on the other end intends to call. If they happen to have the standard deviation, mean, and N and provide those arguments, then we will get the type. If they do not and only pass the array, then they get the constructor. We can also build an infinite (besides in terms of hardware limitations,) number of these inner constructors in order to make our constructor have all the calls we could possibly want."
},
{
"code": null,
"e": 7321,
"s": 6959,
"text": "When it comes to Julia, the most obvious comparison to make is always going to be Python. Although in paradigm and syntax Julia is slightly different, the languages have a similar market niche and perhaps a similar objective. In the Python edition of this normal distribution, we instead define the type and then the equivalent to it is our __init__() function."
},
{
"code": null,
"e": 7460,
"s": 7321,
"text": "class NormalDist: def __init__(self, x): self.N = length(x) self.σ = std(x) self.μ = mean(x)"
},
{
"code": null,
"e": 7698,
"s": 7460,
"text": "We lose performance with this function with all of the assertion we have to do to the things provided to the initialization. We also would not be able to make an infinite number of calls for different types an end-user might want to use."
},
{
"code": null,
"e": 8140,
"s": 7698,
"text": "We can also pass functions and types where we do not even know what type it is through an inner constructor. I have a video from the Comprehensive Julia Tutorials that goes into detail on constructors that you may watch by ctrl+clicking this text. That might provide a bit more information on constructors in Julia and all of the ins-and-outs, and if you are interested in learning Julia, that tutorial series might be a good place to start!"
},
{
"code": null,
"e": 8710,
"s": 8140,
"text": "Now let us talk about the actual Julia compiler, and its speed. I must confess — there are a lot of ins and outs of bench-marking programming languages, and frankly fundamental problems with comparing benchmarks from said programming languages. That being said, I do not ever think that benchmarks are the end-all be-all of programming language speeds, as I am certain there are many instances where different languages might be faster at certain operations. That being said, however, we can still observe from benchmarks that Julia is obviously a pretty fast language."
},
{
"code": null,
"e": 9285,
"s": 8710,
"text": "I must confess, it is impossible to know how much of this JIT is responsible for. However, what I can say is that Julia is fast. This is especially the case when compared with languages that have similar syntax. The language typically falls around about the same speed as C and Rust. In some cases, those three can trade speeds in benchmarks between who is ultimately better. Some are amazed, and do not believe to learn that Julia can actually be faster than C. An important note to make, however is that those bench-marking measurements exclude precompilation of packages."
},
{
"code": null,
"e": 9520,
"s": 9285,
"text": "That being said, despite all of that the fact remains that Julia is fast. This is an advantages, especially when it comes to Data Science applications where some might be working with a lot of observations and operations on that data."
},
{
"code": null,
"e": 10054,
"s": 9520,
"text": "Another awesome thing in Julia is the package manager, Pkg. Compared to a lot of other package managers I have used in my experience as a programmer, Pkg is one of if not the best. At this rate, I wish I could use Pkg as the package manager for my entire operating system. The package manager handles all of the dependencies for us very easily, can generate project directories, and does so with ease. I think that handling virtual environments environments from within the package manager is far more ideal in my subjective opinion."
},
{
"code": null,
"e": 10426,
"s": 10054,
"text": "While I think other languages do have some pretty awesome package managers, I think Julia’s package manager is simply better. The package manager and TOML setup that the Julia language has tends to work very well. Packages and their respective dependencies are completely managed by Pkg, which makes convenience a key feature of this package manager and its capabilities."
},
{
"code": null,
"e": 11029,
"s": 10426,
"text": "Comparing this package manager to Node, as an example, I think that the way packages are added is simply a lot better. Typically in node, you would call npm in a project directory, which can be a bit confusing with some projects because sometimes this is not the home directory. Taking the same comparison over to Python, environments are a lot harder to source, and are nowhere near as easy to manage as Pkg packages. Being able to manage packages and environments with Pkg, and using Pkg as a regular Julia package means that there is a lot of flexibility with controlling Pkg to do different things."
},
{
"code": null,
"e": 11591,
"s": 11029,
"text": "The last Julia feature that I wanted to share is the Julia’s REPL. When it comes to REPL’s for programming languages, there are certainly some desirable options. Python’s REPL is a decent REPL, though it is somewhat minimalist. My favorite REPL prior to my experience was probably the Steel Bank Common Lisp (SBCL) REPL, as I found the declarative and functional nature of keeping the data in tact using saved states that can be reverted to be a really awesome feature. That being said, Julia completely toppled this REPL with its interactive, and dynamic REPL."
},
{
"code": null,
"e": 12149,
"s": 11591,
"text": "As I touched on in No1, I have worked with the REPL’s source code and types. The REPL is incredibly flexible, and has a lot of different capabilities. In a normal REPL-work scenario, cding around, listing directories, all of these things is sometimes not possible, or requires a method call in the programming language. Calling cd(“dir”) over and over again in tandem with some LS method can be extremely tedious for exploring files or looking at environments. Julia counters this by providing a Bash REPL, which can be accessed using ; from the Julia REPL."
},
{
"code": null,
"e": 12169,
"s": 12149,
"text": "julia > ;shell > ls"
},
{
"code": null,
"e": 12323,
"s": 12169,
"text": "Even more, Pkg also has its own REPL, which can parse regular Pkg commands and arguments to add and source packages. Consider the following REPL session:"
},
{
"code": null,
"e": 12694,
"s": 12323,
"text": "(@v1.6) pkg> activate Jockey(@v1.6) pkg> activate Jockey Activating environment at `~/dev/Jockey/Project.toml`shell> cd Jockey/home/emmac/dev/Jockeyshell> lsbin config Project.toml routes.jl testbootstrap.jl Manifest.toml public src usershell> cd src/home/emmac/dev/Jockey/srcshell> lscore Jockey.jl ServerControllershell> nano Jockey.jlshell>"
},
{
"code": null,
"e": 13071,
"s": 12694,
"text": "It is pretty awesome to be able to work with directories in a conventional way that I am used to while also working with packages and files at the same time. It feels very fluid, and it feels like this is a very quick way to work in a REPL. This is especially the case whenever we compare it to other dull REPLs that do not contain these sorts of features and alternate REPLs."
},
{
"code": null,
"e": 13499,
"s": 13071,
"text": "Julia is my favorite programming language, and an awesome choice for any developer at that. I would highly recommend picking up the language if you are into scientific computing, as it is particularly good for that task. There are so many great things about Julia, but these are just a mere five that I think are incredible. If you would like to learn more about Julia in general, you can visit the Julia language website here:"
},
{
"code": null,
"e": 13513,
"s": 13499,
"text": "julialang.org"
}
] |
How to set icon to a window in PyQt5 ?
|
26 Mar, 2020
When we design a PyQt5 application we see an icon on the top left corner, by default it looks like this :
In this tutorial, we will see how to change the icon according to the user need, in order to do this we use setWindowIcon() method and to load the icon QIcon will be used which belongs to QtGui class.
Syntax : setWindowIcon(QtGui.QIcon(‘icon.png’))
Argument :bIt takes file name if file is in same folder else file path.
Code :
# importing the required libraries from PyQt5.QtWidgets import * from PyQt5 import QtCorefrom PyQt5 import QtGuiimport sys class Window(QMainWindow): def __init__(self): super().__init__() self.setWindowIcon(QtGui.QIcon('logo.png')) # set the title self.setWindowTitle("Icon") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget self.label = QLabel("Icon is set", self) # moving position self.label.move(100, 100) # setting up border self.label.setStyleSheet("border: 1px solid black;") # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
Python OOPs Concepts
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 159,
"s": 53,
"text": "When we design a PyQt5 application we see an icon on the top left corner, by default it looks like this :"
},
{
"code": null,
"e": 360,
"s": 159,
"text": "In this tutorial, we will see how to change the icon according to the user need, in order to do this we use setWindowIcon() method and to load the icon QIcon will be used which belongs to QtGui class."
},
{
"code": null,
"e": 408,
"s": 360,
"text": "Syntax : setWindowIcon(QtGui.QIcon(‘icon.png’))"
},
{
"code": null,
"e": 480,
"s": 408,
"text": "Argument :bIt takes file name if file is in same folder else file path."
},
{
"code": null,
"e": 487,
"s": 480,
"text": "Code :"
},
{
"code": "# importing the required libraries from PyQt5.QtWidgets import * from PyQt5 import QtCorefrom PyQt5 import QtGuiimport sys class Window(QMainWindow): def __init__(self): super().__init__() self.setWindowIcon(QtGui.QIcon('logo.png')) # set the title self.setWindowTitle(\"Icon\") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget self.label = QLabel(\"Icon is set\", self) # moving position self.label.move(100, 100) # setting up border self.label.setStyleSheet(\"border: 1px solid black;\") # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 1312,
"s": 487,
"text": null
},
{
"code": null,
"e": 1321,
"s": 1312,
"text": "Output :"
},
{
"code": null,
"e": 1332,
"s": 1321,
"text": "Python-gui"
},
{
"code": null,
"e": 1344,
"s": 1332,
"text": "Python-PyQt"
},
{
"code": null,
"e": 1351,
"s": 1344,
"text": "Python"
},
{
"code": null,
"e": 1449,
"s": 1351,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1491,
"s": 1449,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1513,
"s": 1491,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1548,
"s": 1513,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1574,
"s": 1548,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1606,
"s": 1574,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1635,
"s": 1606,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1662,
"s": 1635,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1692,
"s": 1662,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 1728,
"s": 1692,
"text": "Convert integer to string in Python"
}
] |
Java Program to Merge Two Arrays
|
15 Oct, 2020
Given two arrays, the task is to merge or concatenate them and store the result into another array.
Examples:
Input: arr1[] = { 1, 3, 4, 5}, arr2[] = {2, 4, 6, 8}Output: arr3[] = {1, 3, 4, 5, 2, 4, 6, 8}
Input: arr1[] = { 5, 8, 9}, arr2[] = {4, 7, 8}Output: arr3[] = {5, 8, 9, 4, 7, 8}
Method 1: Using Predefined function
First, we initialize two arrays lets say array a and array b, then we will store values in both the arrays.
After that, we will calculate the length of arrays a and b and will store it into the variables lets say a1 and b1. We need to calculate the length of the array because by using the length of these arrays we can predict the length of the resultant array in which the elements will be store after merging.
Then by using System.arraycopy(), we merge both the arrays and the result will be stored in the third array.
Below is the implementation of the above approach.
Java
// Java Program to demonstrate merging// two array using pre-defined method import java.util.Arrays; public class MergeTwoArrays1 { public static void main(String[] args) { // first array int[] a = { 10, 20, 30, 40 }; // second array int[] b = { 50, 60, 70, 80 }; // determines length of firstArray int a1 = a.length; // determines length of secondArray int b1 = b.length; // resultant array size int c1 = a1 + b1; // create the resultant array int[] c = new int[c1]; // using the pre-defined function arraycopy System.arraycopy(a, 0, c, 0, a1); System.arraycopy(b, 0, c, a1, b1); // prints the resultant array System.out.println(Arrays.toString(c)); }}
[10, 20, 30, 40, 50, 60, 70, 80]
Time Complexity: O(M + N)Auxiliary Space: O(M + N)
Here, M is the length of array a and N is the length of array b.
Method 2: Without using pre-defined function
First, we initialize two arrays lets say array a and array b, then we will store values in both the array.
After that, we will calculate the length of both the arrays and will store it into the variables lets say a1 and b1. We need to calculate the length of the array because by using the length of these arrays we can predict the length of the resultant array in which the elements will be store after merging.
Then the new array c which is the resultant array will be created.
Now, the first loop is used to store the elements of the first array into the resultant array one by one and the second for loop to store the elements of the second array into the resultant array one by one.
The final for loop is used to print the elements of the resultant array.
Below is the implementation of the above approach.
Java
// Java Program to demonstrate merging// two array without using pre-defined method import java.io.*; public class MergeTwoArrays2 { public static void main(String[] args) { // first array int a[] = { 30, 25, 40 }; // second array int b[] = { 45, 50, 55, 60, 65 }; // determining length of first array int a1 = a.length; // determining length of second array int b1 = b.length; // resultant array size int c1 = a1 + b1; // Creating a new array int[] c = new int[c1]; // Loop to store the elements of first // array into resultant array for (int i = 0; i < a1; i = i + 1) { // Storing the elements in // the resultant array c[i] = a[i]; } // Loop to concat the elements of second // array into resultant array for (int i = 0; i < b1; i = i + 1) { // Storing the elements in the // resultant array c[a1 + i] = b[i]; } // Loop to print the elements of // resultant array after merging for (int i = 0; i < c1; i = i + 1) { // print the element System.out.println(c[i]); } }}
30
25
40
45
50
55
60
65
Time Complexity: O(M + N)Auxiliary Space: O(M + N)
Here, M is the length of array a and N is the length of array b.
Java-Array-Programs
Java-Arrays
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n15 Oct, 2020"
},
{
"code": null,
"e": 153,
"s": 53,
"text": "Given two arrays, the task is to merge or concatenate them and store the result into another array."
},
{
"code": null,
"e": 163,
"s": 153,
"text": "Examples:"
},
{
"code": null,
"e": 257,
"s": 163,
"text": "Input: arr1[] = { 1, 3, 4, 5}, arr2[] = {2, 4, 6, 8}Output: arr3[] = {1, 3, 4, 5, 2, 4, 6, 8}"
},
{
"code": null,
"e": 339,
"s": 257,
"text": "Input: arr1[] = { 5, 8, 9}, arr2[] = {4, 7, 8}Output: arr3[] = {5, 8, 9, 4, 7, 8}"
},
{
"code": null,
"e": 375,
"s": 339,
"text": "Method 1: Using Predefined function"
},
{
"code": null,
"e": 483,
"s": 375,
"text": "First, we initialize two arrays lets say array a and array b, then we will store values in both the arrays."
},
{
"code": null,
"e": 788,
"s": 483,
"text": "After that, we will calculate the length of arrays a and b and will store it into the variables lets say a1 and b1. We need to calculate the length of the array because by using the length of these arrays we can predict the length of the resultant array in which the elements will be store after merging."
},
{
"code": null,
"e": 897,
"s": 788,
"text": "Then by using System.arraycopy(), we merge both the arrays and the result will be stored in the third array."
},
{
"code": null,
"e": 948,
"s": 897,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 953,
"s": 948,
"text": "Java"
},
{
"code": "// Java Program to demonstrate merging// two array using pre-defined method import java.util.Arrays; public class MergeTwoArrays1 { public static void main(String[] args) { // first array int[] a = { 10, 20, 30, 40 }; // second array int[] b = { 50, 60, 70, 80 }; // determines length of firstArray int a1 = a.length; // determines length of secondArray int b1 = b.length; // resultant array size int c1 = a1 + b1; // create the resultant array int[] c = new int[c1]; // using the pre-defined function arraycopy System.arraycopy(a, 0, c, 0, a1); System.arraycopy(b, 0, c, a1, b1); // prints the resultant array System.out.println(Arrays.toString(c)); }}",
"e": 1763,
"s": 953,
"text": null
},
{
"code": null,
"e": 1796,
"s": 1763,
"text": "[10, 20, 30, 40, 50, 60, 70, 80]"
},
{
"code": null,
"e": 1847,
"s": 1796,
"text": "Time Complexity: O(M + N)Auxiliary Space: O(M + N)"
},
{
"code": null,
"e": 1912,
"s": 1847,
"text": "Here, M is the length of array a and N is the length of array b."
},
{
"code": null,
"e": 1957,
"s": 1912,
"text": "Method 2: Without using pre-defined function"
},
{
"code": null,
"e": 2064,
"s": 1957,
"text": "First, we initialize two arrays lets say array a and array b, then we will store values in both the array."
},
{
"code": null,
"e": 2370,
"s": 2064,
"text": "After that, we will calculate the length of both the arrays and will store it into the variables lets say a1 and b1. We need to calculate the length of the array because by using the length of these arrays we can predict the length of the resultant array in which the elements will be store after merging."
},
{
"code": null,
"e": 2437,
"s": 2370,
"text": "Then the new array c which is the resultant array will be created."
},
{
"code": null,
"e": 2645,
"s": 2437,
"text": "Now, the first loop is used to store the elements of the first array into the resultant array one by one and the second for loop to store the elements of the second array into the resultant array one by one."
},
{
"code": null,
"e": 2718,
"s": 2645,
"text": "The final for loop is used to print the elements of the resultant array."
},
{
"code": null,
"e": 2769,
"s": 2718,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 2774,
"s": 2769,
"text": "Java"
},
{
"code": "// Java Program to demonstrate merging// two array without using pre-defined method import java.io.*; public class MergeTwoArrays2 { public static void main(String[] args) { // first array int a[] = { 30, 25, 40 }; // second array int b[] = { 45, 50, 55, 60, 65 }; // determining length of first array int a1 = a.length; // determining length of second array int b1 = b.length; // resultant array size int c1 = a1 + b1; // Creating a new array int[] c = new int[c1]; // Loop to store the elements of first // array into resultant array for (int i = 0; i < a1; i = i + 1) { // Storing the elements in // the resultant array c[i] = a[i]; } // Loop to concat the elements of second // array into resultant array for (int i = 0; i < b1; i = i + 1) { // Storing the elements in the // resultant array c[a1 + i] = b[i]; } // Loop to print the elements of // resultant array after merging for (int i = 0; i < c1; i = i + 1) { // print the element System.out.println(c[i]); } }}",
"e": 4046,
"s": 2774,
"text": null
},
{
"code": null,
"e": 4071,
"s": 4046,
"text": "30\n25\n40\n45\n50\n55\n60\n65\n"
},
{
"code": null,
"e": 4122,
"s": 4071,
"text": "Time Complexity: O(M + N)Auxiliary Space: O(M + N)"
},
{
"code": null,
"e": 4187,
"s": 4122,
"text": "Here, M is the length of array a and N is the length of array b."
},
{
"code": null,
"e": 4207,
"s": 4187,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 4219,
"s": 4207,
"text": "Java-Arrays"
},
{
"code": null,
"e": 4226,
"s": 4219,
"text": "Picked"
},
{
"code": null,
"e": 4231,
"s": 4226,
"text": "Java"
},
{
"code": null,
"e": 4245,
"s": 4231,
"text": "Java Programs"
},
{
"code": null,
"e": 4250,
"s": 4245,
"text": "Java"
}
] |
Move last element to front of a given Linked List
|
24 Jun, 2022
Write a function that moves the last element to the front in a given Singly Linked List. For example, if the given Linked List is 1->2->3->4->5, then the function should change the list to 5->1->2->3->4.
Algorithm: Traverse the list till last node. Use two pointers: one to store the address of last node and other for address of second last node. After the end of loop do following operations.
Make second last as last (secLast->next = NULL). Set next of last as head (last->next = *head_ref). Make last as head ( *head_ref = last)
Make second last as last (secLast->next = NULL).
Set next of last as head (last->next = *head_ref).
Make last as head ( *head_ref = last)
Implementation:
C++
C
Java
Python3
C#
Javascript
/* CPP Program to move last element to front in a given linked list */#include <bits/stdc++.h>using namespace std; /* A linked list node */class Node { public: int data; Node *next; }; /* We are using a double pointerhead_ref here because we change head of the linked list inside this function.*/void moveToFront(Node **head_ref) { /* If linked list is empty, or it contains only one node, then nothing needs to be done, simply return */ if (*head_ref == NULL || (*head_ref)->next == NULL) return; /* Initialize second last and last pointers */ Node *secLast = NULL; Node *last = *head_ref; /*After this loop secLast contains address of second last node and last contains address of last node in Linked List */ while (last->next != NULL) { secLast = last; last = last->next; } /* Set the next of second last as NULL */ secLast->next = NULL; /* Set next of last as head node */ last->next = *head_ref; /* Change the head pointer to point to last node now */ *head_ref = last; } /* UTILITY FUNCTIONS *//* Function to add a node at the beginning of Linked List */void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given linked list */void printList(Node *node) { while(node != NULL) { cout << node->data << " "; node = node->next; } } /* Driver code */int main() { Node *start = NULL; /* The constructed linked list is: 1->2->3->4->5 */ push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); cout<<"Linked list before moving last to front\n"; printList(start); moveToFront(&start); cout<<"\nLinked list after removing last to front\n"; printList(start); return 0; } // This code is contributed by rathbhupendra
/* C Program to move last element to front in a given linked list */#include<stdio.h>#include<stdlib.h> /* A linked list node */struct Node{ int data; struct Node *next;}; /* We are using a double pointer head_ref here because we change head of the linked list inside this function.*/void moveToFront(struct Node **head_ref){ /* If linked list is empty, or it contains only one node, then nothing needs to be done, simply return */ if (*head_ref == NULL || (*head_ref)->next == NULL) return; /* Initialize second last and last pointers */ struct Node *secLast = NULL; struct Node *last = *head_ref; /*After this loop secLast contains address of second last node and last contains address of last node in Linked List */ while (last->next != NULL) { secLast = last; last = last->next; } /* Set the next of second last as NULL */ secLast->next = NULL; /* Set next of last as head node */ last->next = *head_ref; /* Change the head pointer to point to last node now */ *head_ref = last;} /* UTILITY FUNCTIONS *//* Function to add a node at the beginning of Linked List */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node *node){ while(node != NULL) { printf("%d ", node->data); node = node->next; }} /* Driver program to test above function */int main(){ struct Node *start = NULL; /* The constructed linked list is: 1->2->3->4->5 */ push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); printf("\n Linked list before moving last to front\n"); printList(start); moveToFront(&start); printf("\n Linked list after removing last to front\n"); printList(start); return 0;}
/* Java Program to move last element to front in a given linked list */class LinkedList{ Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) {data = d; next = null; } } void moveToFront() { /* If linked list is empty or it contains only one node then simply return. */ if(head == null || head.next == null) return; /* Initialize second last and last pointers */ Node secLast = null; Node last = head; /* After this loop secLast contains address of second last node and last contains address of last node in Linked List */ while (last.next != null) { secLast = last; last = last.next; } /* Set the next of second last as null */ secLast.next = null; /* Set the next of last as head */ last.next = head; /* Change head to point to last node. */ head = last; } /* Utility functions */ /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ void printList() { Node temp = head; while(temp != null) { System.out.print(temp.data+" "); temp = temp.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist = new LinkedList(); /* Constructed Linked List is 1->2->3->4->5->null */ llist.push(5); llist.push(4); llist.push(3); llist.push(2); llist.push(1); System.out.println("Linked List before moving last to front "); llist.printList(); llist.moveToFront(); System.out.println("Linked List after moving last to front "); llist.printList(); }} /* This code is contributed by Rajat Mishra */
# Python3 code to move the last item to frontclass Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None # Function to add a node # at the beginning of Linked List def push(self, data): new_node = Node(data) new_node.next = self.head self.head = new_node # Function to print nodes in a # given linked list def printList(self): tmp = self.head while tmp is not None: print(tmp.data, end=", ") tmp = tmp.next print() # Function to bring the last node to the front def moveToFront(self): tmp = self.head sec_last = None # To maintain the track of # the second last node # To check whether we have not received # the empty list or list with a single node if not tmp or not tmp.next: return # Iterate till the end to get # the last and second last node while tmp and tmp.next : sec_last = tmp tmp = tmp.next # point the next of the second # last node to None sec_last.next = None # Make the last node as the first Node tmp.next = self.head self.head = tmp # Driver Codeif __name__ == '__main__': llist = LinkedList() # swap the 2 nodes llist.push(5) llist.push(4) llist.push(3) llist.push(2) llist.push(1) print ("Linked List before moving last to front ") llist.printList() llist.moveToFront() print ("Linked List after moving last to front ") llist.printList()
/* C# Program to move last element to front in a given linked list */using System;class LinkedList { Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) {data = d; next = null; } } void moveToFront() { /* If linked list is empty or it contains only one node then simply return. */ if(head == null || head.next == null) return; /* Initialize second last and last pointers */ Node secLast = null; Node last = head; /* After this loop secLast contains address of second last node and last contains address of last node in Linked List */ while (last.next != null) { secLast = last; last = last.next; } /* Set the next of second last as null */ secLast.next = null; /* Set the next of last as head */ last.next = head; /* Change head to point to last node. */ head = last; } /* Utility functions */ /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ void printList() { Node temp = head; while(temp != null) { Console.Write(temp.data+" "); temp = temp.next; } Console.WriteLine(); } /* Driver program to test above functions */ public static void Main(String []args) { LinkedList llist = new LinkedList(); /* Constructed Linked List is 1->2->3->4->5->null */ llist.push(5); llist.push(4); llist.push(3); llist.push(2); llist.push(1); Console.WriteLine("Linked List before moving last to front "); llist.printList(); llist.moveToFront(); Console.WriteLine("Linked List after moving last to front "); llist.printList(); } } // This code is contributed by Arnab Kundu
<script>/* javascript Program to move last element to front in a given linked list */ /* Linked list Node */ class Node { constructor(val) { this.data = val; this.next = null; } } var head; // head of list function moveToFront() { /* * If linked list is empty or it contains only one node then simply return. */ if (head == null || head.next == null) return; /* Initialize second last and last pointers */ var secLast = null; var last = head; /* * After this loop secLast contains address of second last node and last * contains address of last node in Linked List */ while (last.next != null) { secLast = last; last = last.next; } /* Set the next of second last as null */ secLast.next = null; /* Set the next of last as head */ last.next = head; /* Change head to point to last node. */ head = last; } /* Utility functions */ /* Inserts a new Node at front of the list. */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */ var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ function printList() { var temp = head; while (temp != null) { document.write(temp.data + " "); temp = temp.next; } document.write(); } /* Driver program to test above functions */ /* Constructed Linked List is 1->2->3->4->5->null */ push(5); push(4); push(3); push(2); push(1); document.write("Linked List before moving last to front<br/> "); printList(); moveToFront(); document.write("<br/>Linked List after moving last to front <br/>"); printList(); // This code is contributed by umadevi9616 </script>
Output:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Linked list before moving last to front
1 2 3 4 5
Linked list after removing last to front
5 1 2 3 4
Time Complexity: O(N)
As we need to traverse the list once.
Auxiliary Space: O(1)
As constant extra space is used.
Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem.
Soumith Bsv
andrew1234
rathbhupendra
Saurabh Singh 7
shubham_singh
nidhi_biet
umadevi9616
simranarora5sos
abhijeet19403
hardikkoriintern
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Jun, 2022"
},
{
"code": null,
"e": 257,
"s": 53,
"text": "Write a function that moves the last element to the front in a given Singly Linked List. For example, if the given Linked List is 1->2->3->4->5, then the function should change the list to 5->1->2->3->4."
},
{
"code": null,
"e": 449,
"s": 257,
"text": "Algorithm: Traverse the list till last node. Use two pointers: one to store the address of last node and other for address of second last node. After the end of loop do following operations. "
},
{
"code": null,
"e": 587,
"s": 449,
"text": "Make second last as last (secLast->next = NULL). Set next of last as head (last->next = *head_ref). Make last as head ( *head_ref = last)"
},
{
"code": null,
"e": 637,
"s": 587,
"text": "Make second last as last (secLast->next = NULL). "
},
{
"code": null,
"e": 689,
"s": 637,
"text": "Set next of last as head (last->next = *head_ref). "
},
{
"code": null,
"e": 727,
"s": 689,
"text": "Make last as head ( *head_ref = last)"
},
{
"code": null,
"e": 743,
"s": 727,
"text": "Implementation:"
},
{
"code": null,
"e": 747,
"s": 743,
"text": "C++"
},
{
"code": null,
"e": 749,
"s": 747,
"text": "C"
},
{
"code": null,
"e": 754,
"s": 749,
"text": "Java"
},
{
"code": null,
"e": 762,
"s": 754,
"text": "Python3"
},
{
"code": null,
"e": 765,
"s": 762,
"text": "C#"
},
{
"code": null,
"e": 776,
"s": 765,
"text": "Javascript"
},
{
"code": "/* CPP Program to move last element to front in a given linked list */#include <bits/stdc++.h>using namespace std; /* A linked list node */class Node { public: int data; Node *next; }; /* We are using a double pointerhead_ref here because we change head of the linked list inside this function.*/void moveToFront(Node **head_ref) { /* If linked list is empty, or it contains only one node, then nothing needs to be done, simply return */ if (*head_ref == NULL || (*head_ref)->next == NULL) return; /* Initialize second last and last pointers */ Node *secLast = NULL; Node *last = *head_ref; /*After this loop secLast contains address of second last node and last contains address of last node in Linked List */ while (last->next != NULL) { secLast = last; last = last->next; } /* Set the next of second last as NULL */ secLast->next = NULL; /* Set next of last as head node */ last->next = *head_ref; /* Change the head pointer to point to last node now */ *head_ref = last; } /* UTILITY FUNCTIONS *//* Function to add a node at the beginning of Linked List */void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given linked list */void printList(Node *node) { while(node != NULL) { cout << node->data << \" \"; node = node->next; } } /* Driver code */int main() { Node *start = NULL; /* The constructed linked list is: 1->2->3->4->5 */ push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); cout<<\"Linked list before moving last to front\\n\"; printList(start); moveToFront(&start); cout<<\"\\nLinked list after removing last to front\\n\"; printList(start); return 0; } // This code is contributed by rathbhupendra",
"e": 2940,
"s": 776,
"text": null
},
{
"code": "/* C Program to move last element to front in a given linked list */#include<stdio.h>#include<stdlib.h> /* A linked list node */struct Node{ int data; struct Node *next;}; /* We are using a double pointer head_ref here because we change head of the linked list inside this function.*/void moveToFront(struct Node **head_ref){ /* If linked list is empty, or it contains only one node, then nothing needs to be done, simply return */ if (*head_ref == NULL || (*head_ref)->next == NULL) return; /* Initialize second last and last pointers */ struct Node *secLast = NULL; struct Node *last = *head_ref; /*After this loop secLast contains address of second last node and last contains address of last node in Linked List */ while (last->next != NULL) { secLast = last; last = last->next; } /* Set the next of second last as NULL */ secLast->next = NULL; /* Set next of last as head node */ last->next = *head_ref; /* Change the head pointer to point to last node now */ *head_ref = last;} /* UTILITY FUNCTIONS *//* Function to add a node at the beginning of Linked List */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node *node){ while(node != NULL) { printf(\"%d \", node->data); node = node->next; }} /* Driver program to test above function */int main(){ struct Node *start = NULL; /* The constructed linked list is: 1->2->3->4->5 */ push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); printf(\"\\n Linked list before moving last to front\\n\"); printList(start); moveToFront(&start); printf(\"\\n Linked list after removing last to front\\n\"); printList(start); return 0;}",
"e": 5109,
"s": 2940,
"text": null
},
{
"code": "/* Java Program to move last element to front in a given linked list */class LinkedList{ Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) {data = d; next = null; } } void moveToFront() { /* If linked list is empty or it contains only one node then simply return. */ if(head == null || head.next == null) return; /* Initialize second last and last pointers */ Node secLast = null; Node last = head; /* After this loop secLast contains address of second last node and last contains address of last node in Linked List */ while (last.next != null) { secLast = last; last = last.next; } /* Set the next of second last as null */ secLast.next = null; /* Set the next of last as head */ last.next = head; /* Change head to point to last node. */ head = last; } /* Utility functions */ /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ void printList() { Node temp = head; while(temp != null) { System.out.print(temp.data+\" \"); temp = temp.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist = new LinkedList(); /* Constructed Linked List is 1->2->3->4->5->null */ llist.push(5); llist.push(4); llist.push(3); llist.push(2); llist.push(1); System.out.println(\"Linked List before moving last to front \"); llist.printList(); llist.moveToFront(); System.out.println(\"Linked List after moving last to front \"); llist.printList(); }} /* This code is contributed by Rajat Mishra */ ",
"e": 7444,
"s": 5109,
"text": null
},
{
"code": "# Python3 code to move the last item to frontclass Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None # Function to add a node # at the beginning of Linked List def push(self, data): new_node = Node(data) new_node.next = self.head self.head = new_node # Function to print nodes in a # given linked list def printList(self): tmp = self.head while tmp is not None: print(tmp.data, end=\", \") tmp = tmp.next print() # Function to bring the last node to the front def moveToFront(self): tmp = self.head sec_last = None # To maintain the track of # the second last node # To check whether we have not received # the empty list or list with a single node if not tmp or not tmp.next: return # Iterate till the end to get # the last and second last node while tmp and tmp.next : sec_last = tmp tmp = tmp.next # point the next of the second # last node to None sec_last.next = None # Make the last node as the first Node tmp.next = self.head self.head = tmp # Driver Codeif __name__ == '__main__': llist = LinkedList() # swap the 2 nodes llist.push(5) llist.push(4) llist.push(3) llist.push(2) llist.push(1) print (\"Linked List before moving last to front \") llist.printList() llist.moveToFront() print (\"Linked List after moving last to front \") llist.printList()",
"e": 9100,
"s": 7444,
"text": null
},
{
"code": "/* C# Program to move last element to front in a given linked list */using System;class LinkedList { Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) {data = d; next = null; } } void moveToFront() { /* If linked list is empty or it contains only one node then simply return. */ if(head == null || head.next == null) return; /* Initialize second last and last pointers */ Node secLast = null; Node last = head; /* After this loop secLast contains address of second last node and last contains address of last node in Linked List */ while (last.next != null) { secLast = last; last = last.next; } /* Set the next of second last as null */ secLast.next = null; /* Set the next of last as head */ last.next = head; /* Change head to point to last node. */ head = last; } /* Utility functions */ /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ void printList() { Node temp = head; while(temp != null) { Console.Write(temp.data+\" \"); temp = temp.next; } Console.WriteLine(); } /* Driver program to test above functions */ public static void Main(String []args) { LinkedList llist = new LinkedList(); /* Constructed Linked List is 1->2->3->4->5->null */ llist.push(5); llist.push(4); llist.push(3); llist.push(2); llist.push(1); Console.WriteLine(\"Linked List before moving last to front \"); llist.printList(); llist.moveToFront(); Console.WriteLine(\"Linked List after moving last to front \"); llist.printList(); } } // This code is contributed by Arnab Kundu",
"e": 11478,
"s": 9100,
"text": null
},
{
"code": "<script>/* javascript Program to move last element to front in a given linked list */ /* Linked list Node */ class Node { constructor(val) { this.data = val; this.next = null; } } var head; // head of list function moveToFront() { /* * If linked list is empty or it contains only one node then simply return. */ if (head == null || head.next == null) return; /* Initialize second last and last pointers */ var secLast = null; var last = head; /* * After this loop secLast contains address of second last node and last * contains address of last node in Linked List */ while (last.next != null) { secLast = last; last = last.next; } /* Set the next of second last as null */ secLast.next = null; /* Set the next of last as head */ last.next = head; /* Change head to point to last node. */ head = last; } /* Utility functions */ /* Inserts a new Node at front of the list. */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */ var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ function printList() { var temp = head; while (temp != null) { document.write(temp.data + \" \"); temp = temp.next; } document.write(); } /* Driver program to test above functions */ /* Constructed Linked List is 1->2->3->4->5->null */ push(5); push(4); push(3); push(2); push(1); document.write(\"Linked List before moving last to front<br/> \"); printList(); moveToFront(); document.write(\"<br/>Linked List after moving last to front <br/>\"); printList(); // This code is contributed by umadevi9616 </script>",
"e": 13611,
"s": 11478,
"text": null
},
{
"code": null,
"e": 13620,
"s": 13611,
"text": "Output: "
},
{
"code": null,
"e": 13629,
"s": 13620,
"text": "Chapters"
},
{
"code": null,
"e": 13656,
"s": 13629,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 13706,
"s": 13656,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 13729,
"s": 13706,
"text": "captions off, selected"
},
{
"code": null,
"e": 13737,
"s": 13729,
"text": "English"
},
{
"code": null,
"e": 13761,
"s": 13737,
"text": "This is a modal window."
},
{
"code": null,
"e": 13830,
"s": 13761,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 13852,
"s": 13830,
"text": "End of dialog window."
},
{
"code": null,
"e": 13958,
"s": 13852,
"text": " Linked list before moving last to front \n1 2 3 4 5 \n Linked list after removing last to front \n5 1 2 3 4"
},
{
"code": null,
"e": 13981,
"s": 13958,
"text": "Time Complexity: O(N) "
},
{
"code": null,
"e": 14019,
"s": 13981,
"text": "As we need to traverse the list once."
},
{
"code": null,
"e": 14041,
"s": 14019,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 14074,
"s": 14041,
"text": "As constant extra space is used."
},
{
"code": null,
"e": 14192,
"s": 14074,
"text": "Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem. "
},
{
"code": null,
"e": 14204,
"s": 14192,
"text": "Soumith Bsv"
},
{
"code": null,
"e": 14215,
"s": 14204,
"text": "andrew1234"
},
{
"code": null,
"e": 14229,
"s": 14215,
"text": "rathbhupendra"
},
{
"code": null,
"e": 14245,
"s": 14229,
"text": "Saurabh Singh 7"
},
{
"code": null,
"e": 14259,
"s": 14245,
"text": "shubham_singh"
},
{
"code": null,
"e": 14270,
"s": 14259,
"text": "nidhi_biet"
},
{
"code": null,
"e": 14282,
"s": 14270,
"text": "umadevi9616"
},
{
"code": null,
"e": 14298,
"s": 14282,
"text": "simranarora5sos"
},
{
"code": null,
"e": 14312,
"s": 14298,
"text": "abhijeet19403"
},
{
"code": null,
"e": 14329,
"s": 14312,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 14341,
"s": 14329,
"text": "Linked List"
},
{
"code": null,
"e": 14353,
"s": 14341,
"text": "Linked List"
}
] |
C Program to Multiply two Floating Point Numbers
|
22 Apr, 2022
Given two floating numbers A and B. The task is to write a program to find the product of these two numbers. Examples:
Input: A = 2.12, B = 3.88 Output: 8.225600 Input: A = 3.78, B = 6.32 Output: 23.889601
In the below program to multiply two floating point numbers, the user is first asked to enter two floating numbers and the input is scanned using the scanf() function and stored in the variables and . Then, the variables and are multiplied using the arithmetic operator and the product is stored in the variable product. Below is the C program to multiply two floating point numbers:
C
// C program to multiply two floating point numbers#include <stdio.h> int main(){ float A, B, product = 0.0f; // Ask user to enter the two numbers printf("Enter two floating numbers A and B : \n"); // Read two numbers from the user || A = 2.12, B = 3.88 scanf("%f%f", &A, &B); // Calculate the multiplication of A and B // using '*' operator product = A * B; // Print the product printf("Product of A and B is: %f", product); return 0;}
Time Complexity: O(1), as we are not using any loops.
Auxiliary Space: O(1), as we are not using any extra space.
gulshankumarar231
rohitsingh07052
C Language
C Programs
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
What is the purpose of a function prototype?
Operators in C / C++
Exception Handling in C++
TCP Server-Client implementation in C
Strings in C
Arrow operator -> in C/C++ with Examples
Basics of File Handling in C
UDP Server-Client implementation in C
Header files in C/C++ and its uses
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n22 Apr, 2022"
},
{
"code": null,
"e": 173,
"s": 53,
"text": "Given two floating numbers A and B. The task is to write a program to find the product of these two numbers. Examples:"
},
{
"code": null,
"e": 260,
"s": 173,
"text": "Input: A = 2.12, B = 3.88 Output: 8.225600 Input: A = 3.78, B = 6.32 Output: 23.889601"
},
{
"code": null,
"e": 645,
"s": 260,
"text": "In the below program to multiply two floating point numbers, the user is first asked to enter two floating numbers and the input is scanned using the scanf() function and stored in the variables and . Then, the variables and are multiplied using the arithmetic operator and the product is stored in the variable product. Below is the C program to multiply two floating point numbers: "
},
{
"code": null,
"e": 647,
"s": 645,
"text": "C"
},
{
"code": "// C program to multiply two floating point numbers#include <stdio.h> int main(){ float A, B, product = 0.0f; // Ask user to enter the two numbers printf(\"Enter two floating numbers A and B : \\n\"); // Read two numbers from the user || A = 2.12, B = 3.88 scanf(\"%f%f\", &A, &B); // Calculate the multiplication of A and B // using '*' operator product = A * B; // Print the product printf(\"Product of A and B is: %f\", product); return 0;}",
"e": 1122,
"s": 647,
"text": null
},
{
"code": null,
"e": 1176,
"s": 1122,
"text": "Time Complexity: O(1), as we are not using any loops."
},
{
"code": null,
"e": 1236,
"s": 1176,
"text": "Auxiliary Space: O(1), as we are not using any extra space."
},
{
"code": null,
"e": 1254,
"s": 1236,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 1270,
"s": 1254,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 1281,
"s": 1270,
"text": "C Language"
},
{
"code": null,
"e": 1292,
"s": 1281,
"text": "C Programs"
},
{
"code": null,
"e": 1311,
"s": 1292,
"text": "School Programming"
},
{
"code": null,
"e": 1409,
"s": 1311,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1457,
"s": 1409,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 1502,
"s": 1457,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 1523,
"s": 1502,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 1549,
"s": 1523,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 1587,
"s": 1549,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 1600,
"s": 1587,
"text": "Strings in C"
},
{
"code": null,
"e": 1641,
"s": 1600,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 1670,
"s": 1641,
"text": "Basics of File Handling in C"
},
{
"code": null,
"e": 1708,
"s": 1670,
"text": "UDP Server-Client implementation in C"
}
] |
SAP UI5 - Data binding
|
In SAP UI5, data binding concept is used to update the data automatically by binding the data with the controls that holds the application data. Using data binding, you can bind simple controls like text field, simple button to application data, and data is automatically updated when there is a new value.
Using two-way data binding, application data is updated when the value of bound control changes. The value can be changed via different methods, like user input, etc.
In SAP UI5, different data models can be used for data binding. These data models support different features −
JSON model is used to bind JavaScript objects to controls. This data model is a client-side model and is suggested for small data sets. It doesn’t provide any mechanism for serverside paging or loading.
Key features include −
JSON model for data binding supports data in JavaScript notation format.
It supports two-way data binding.
Creating a model instance −
Var oModel = new sap.ui.model.json.JSONModel(dataUrlorData);
XML model of data binding allows you to bind the controls to XML data. It is used for clientside objects and for small data sets. It doesn’t provide any mechanism for server-side paging or loading.
Key features include −
XML model of data binding supports XML data.
It also supports two-way data binding.
Creating a model instance −
Var oModel = new sap.ui.model.xml.XMLModel(dataUrlorData);
OData model is a server-side model, so entire data is available at the server side. Client side can see only rows and fields and you can’t use sorting and filtering at the client side. There is a need to send this request to the server to complete these tasks.
Data binding in OData model is one way but you can enable two-way binding using experimental write support.
Key features include −
OData model of data binding supports Odata compliant data.
This data model allows you to create OData requests and handle responses.
It supports experimental two-way binding.
Creating a model instance −
Var oModel = new sap.ui.model.odata.ODataModel (dataUrl [,useJSON, user, pass]);
You can use the setModel method to assign the model to specific controls or core.
Sap.ui.getcore().setModel(oModel);
To bind a model to view −
Var myView = sap.ui.view({type:sap.ui.core.mvc.ViewType.JS, viewname:”view name”});
myView.setModel(oModel);
To bind a model to a control −
Var oTable = sap.ui.getCore().byId(“table”);
oTable.setModel(oModel);
You can bind the properties of a control to model properties. You can bind the properties of a model to a control using bindproperty method −
oControl.bindProperty(“controlProperty”, “modelProperty”);
or by using below methodvar
oControl = new sap.ui.commons.TextView({
controlProperty: “{modelProperty}”
});
You can use aggregation binding to bind a collection of values like binding multiple rows to a table. To use aggregation, you have to use a control that acts as a template.
You can define aggregation binding using bindAgregation method.
oComboBox.bindaggregation( “items”, “/modelaggregation”, oItemTemplate);
|
[
{
"code": null,
"e": 2482,
"s": 2175,
"text": "In SAP UI5, data binding concept is used to update the data automatically by binding the data with the controls that holds the application data. Using data binding, you can bind simple controls like text field, simple button to application data, and data is automatically updated when there is a new value."
},
{
"code": null,
"e": 2649,
"s": 2482,
"text": "Using two-way data binding, application data is updated when the value of bound control changes. The value can be changed via different methods, like user input, etc."
},
{
"code": null,
"e": 2760,
"s": 2649,
"text": "In SAP UI5, different data models can be used for data binding. These data models support different features −"
},
{
"code": null,
"e": 2963,
"s": 2760,
"text": "JSON model is used to bind JavaScript objects to controls. This data model is a client-side model and is suggested for small data sets. It doesn’t provide any mechanism for serverside paging or loading."
},
{
"code": null,
"e": 2986,
"s": 2963,
"text": "Key features include −"
},
{
"code": null,
"e": 3059,
"s": 2986,
"text": "JSON model for data binding supports data in JavaScript notation format."
},
{
"code": null,
"e": 3093,
"s": 3059,
"text": "It supports two-way data binding."
},
{
"code": null,
"e": 3121,
"s": 3093,
"text": "Creating a model instance −"
},
{
"code": null,
"e": 3183,
"s": 3121,
"text": "Var oModel = new sap.ui.model.json.JSONModel(dataUrlorData);\n"
},
{
"code": null,
"e": 3381,
"s": 3183,
"text": "XML model of data binding allows you to bind the controls to XML data. It is used for clientside objects and for small data sets. It doesn’t provide any mechanism for server-side paging or loading."
},
{
"code": null,
"e": 3404,
"s": 3381,
"text": "Key features include −"
},
{
"code": null,
"e": 3449,
"s": 3404,
"text": "XML model of data binding supports XML data."
},
{
"code": null,
"e": 3488,
"s": 3449,
"text": "It also supports two-way data binding."
},
{
"code": null,
"e": 3516,
"s": 3488,
"text": "Creating a model instance −"
},
{
"code": null,
"e": 3576,
"s": 3516,
"text": "Var oModel = new sap.ui.model.xml.XMLModel(dataUrlorData);\n"
},
{
"code": null,
"e": 3837,
"s": 3576,
"text": "OData model is a server-side model, so entire data is available at the server side. Client side can see only rows and fields and you can’t use sorting and filtering at the client side. There is a need to send this request to the server to complete these tasks."
},
{
"code": null,
"e": 3945,
"s": 3837,
"text": "Data binding in OData model is one way but you can enable two-way binding using experimental write support."
},
{
"code": null,
"e": 3968,
"s": 3945,
"text": "Key features include −"
},
{
"code": null,
"e": 4027,
"s": 3968,
"text": "OData model of data binding supports Odata compliant data."
},
{
"code": null,
"e": 4101,
"s": 4027,
"text": "This data model allows you to create OData requests and handle responses."
},
{
"code": null,
"e": 4143,
"s": 4101,
"text": "It supports experimental two-way binding."
},
{
"code": null,
"e": 4171,
"s": 4143,
"text": "Creating a model instance −"
},
{
"code": null,
"e": 4253,
"s": 4171,
"text": "Var oModel = new sap.ui.model.odata.ODataModel (dataUrl [,useJSON, user, pass]);\n"
},
{
"code": null,
"e": 4335,
"s": 4253,
"text": "You can use the setModel method to assign the model to specific controls or core."
},
{
"code": null,
"e": 4371,
"s": 4335,
"text": "Sap.ui.getcore().setModel(oModel);\n"
},
{
"code": null,
"e": 4397,
"s": 4371,
"text": "To bind a model to view −"
},
{
"code": null,
"e": 4507,
"s": 4397,
"text": "Var myView = sap.ui.view({type:sap.ui.core.mvc.ViewType.JS, viewname:”view name”});\nmyView.setModel(oModel);\n"
},
{
"code": null,
"e": 4538,
"s": 4507,
"text": "To bind a model to a control −"
},
{
"code": null,
"e": 4609,
"s": 4538,
"text": "Var oTable = sap.ui.getCore().byId(“table”);\noTable.setModel(oModel);\n"
},
{
"code": null,
"e": 4751,
"s": 4609,
"text": "You can bind the properties of a control to model properties. You can bind the properties of a model to a control using bindproperty method −"
},
{
"code": null,
"e": 4922,
"s": 4751,
"text": "oControl.bindProperty(“controlProperty”, “modelProperty”);\nor by using below methodvar\noControl = new sap.ui.commons.TextView({\n controlProperty: “{modelProperty}”\n});\n"
},
{
"code": null,
"e": 5095,
"s": 4922,
"text": "You can use aggregation binding to bind a collection of values like binding multiple rows to a table. To use aggregation, you have to use a control that acts as a template."
},
{
"code": null,
"e": 5159,
"s": 5095,
"text": "You can define aggregation binding using bindAgregation method."
}
] |
Transparent Scatterplot Points in Base R and ggplot2
|
14 Sep, 2021
In this article, we are going to see how to make transparent scatterplot points in the R programming language.
Here we will use alpha parameter inside the plot. It is used to modify color transparency, alpha value=1 is by default and if we make the alpha value nearer to zero it will be making the object more transparent and on the other hand, the alpha value nearer to 1 will leading to make the object opaque.
In this approach to make transparent scatterplot points, the user needs to install and import the scales package in the working console of the R and this package here is responsible to adjust the alpha of given data points. Further, the user needs to simply call the plot function with the additional alpha argument with this function and specify the alpha value accordingly as per the requirements to make transparent scatterplot points in the base R programming language.
To install and import the scales package, the user needs to follow the below syntax:
install.packages("scales")
library("scales")
Example: In this example, we will be plotting an of the given data and will be setting the value of the alpha argument to 0.2 to transparent effect in the plotted scatterplot in the R programming language.
The plot without any transparent effect looks as below:
R
library("scales") gfg <- data.frame(x = c(1, 2.2, 2, 2, 3, 3, 4.2, 4.1, 5.2, 5.1), y = c(2, 2, 2.5, 2.1, 3.4, 4.1, 4, 4, 5, 5), group = as.factor(1:2)) plot(gfg$x, gfg$y, pch = 18, cex = 6, col = gfg$group)
Output:
Using alpha to create a transparent plot:
R
library("scales") gfg <- data.frame(x = c(1, 2.2, 2, 2, 3, 3, 4.2, 4.1, 5.2, 5.1), y = c(2, 2, 2.5, 2.1, 3.4, 4.1, 4, 4, 5, 5), group = as.factor(1:2)) plot(gfg$x,gfg$y, pch = 18, cex = 6, col = alpha(gfg$group, 0.2))
Output:
Transparent scatterplot points using the alpha argument of the geom_point() function, in this approach to make transparent scatterplot points, the user needs to install and import the ggplot2 package in the working console of the R and this package here is responsible to plot the ggplot2 scatter plot of given data points. Further, the user needs to call the geom_point() function of the ggplot2 package with the additional alpha argument with this function and specify the alpha value accordingly as per the requirements to make transparent scatterplot points in the gglot2 R programming language.
To install and import the scales package, the user needs to follow the below syntax:
install.packages("ggplot2")
library("ggplot2")
Example: In this example, we will be plotting an of the given data and will be setting the value of the alpha argument to 0.2 to transparent effect in the plotted scatterplot of the ggplot package in the R programming language.
The plot without any transparent effect looks as below:
R
library("ggplot2") gfg <- data.frame(x = c(1, 2.2, 2, 2, 3, 3, 4.2, 4.1, 5.2, 5.1), y = c(2, 2, 2.5, 2.1, 3.4, 4.1, 4, 4, 5, 5), group = as.factor(1:2)) ggplot(gfg, aes(x, y, col = group)) + geom_point(pch = 18,size = 12)
Output:
Using alpha to create a transparent plot:
R
library("ggplot2") gfg <- data.frame(x = c(1, 2.2, 2, 2, 3, 3, 4.2, 4.1, 5.2, 5.1), y = c(2, 2, 2.5, 2.1, 3.4, 4.1, 4, 4, 5, 5), group = as.factor(1:2))ggplot(gfg, aes(x, y, col = group)) + geom_point(pch = 18,size = 12, alpha = 0.2)
Output:
Picked
R-Charts
R-ggplot
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 139,
"s": 28,
"text": "In this article, we are going to see how to make transparent scatterplot points in the R programming language."
},
{
"code": null,
"e": 441,
"s": 139,
"text": "Here we will use alpha parameter inside the plot. It is used to modify color transparency, alpha value=1 is by default and if we make the alpha value nearer to zero it will be making the object more transparent and on the other hand, the alpha value nearer to 1 will leading to make the object opaque."
},
{
"code": null,
"e": 915,
"s": 441,
"text": "In this approach to make transparent scatterplot points, the user needs to install and import the scales package in the working console of the R and this package here is responsible to adjust the alpha of given data points. Further, the user needs to simply call the plot function with the additional alpha argument with this function and specify the alpha value accordingly as per the requirements to make transparent scatterplot points in the base R programming language."
},
{
"code": null,
"e": 1000,
"s": 915,
"text": "To install and import the scales package, the user needs to follow the below syntax:"
},
{
"code": null,
"e": 1085,
"s": 1000,
"text": "install.packages(\"scales\") \nlibrary(\"scales\") "
},
{
"code": null,
"e": 1291,
"s": 1085,
"text": "Example: In this example, we will be plotting an of the given data and will be setting the value of the alpha argument to 0.2 to transparent effect in the plotted scatterplot in the R programming language."
},
{
"code": null,
"e": 1347,
"s": 1291,
"text": "The plot without any transparent effect looks as below:"
},
{
"code": null,
"e": 1349,
"s": 1347,
"text": "R"
},
{
"code": "library(\"scales\") gfg <- data.frame(x = c(1, 2.2, 2, 2, 3, 3, 4.2, 4.1, 5.2, 5.1), y = c(2, 2, 2.5, 2.1, 3.4, 4.1, 4, 4, 5, 5), group = as.factor(1:2)) plot(gfg$x, gfg$y, pch = 18, cex = 6, col = gfg$group)",
"e": 1645,
"s": 1349,
"text": null
},
{
"code": null,
"e": 1653,
"s": 1645,
"text": "Output:"
},
{
"code": null,
"e": 1696,
"s": 1653,
"text": "Using alpha to create a transparent plot: "
},
{
"code": null,
"e": 1698,
"s": 1696,
"text": "R"
},
{
"code": "library(\"scales\") gfg <- data.frame(x = c(1, 2.2, 2, 2, 3, 3, 4.2, 4.1, 5.2, 5.1), y = c(2, 2, 2.5, 2.1, 3.4, 4.1, 4, 4, 5, 5), group = as.factor(1:2)) plot(gfg$x,gfg$y, pch = 18, cex = 6, col = alpha(gfg$group, 0.2))",
"e": 2005,
"s": 1698,
"text": null
},
{
"code": null,
"e": 2013,
"s": 2005,
"text": "Output:"
},
{
"code": null,
"e": 2615,
"s": 2013,
"text": "Transparent scatterplot points using the alpha argument of the geom_point() function, in this approach to make transparent scatterplot points, the user needs to install and import the ggplot2 package in the working console of the R and this package here is responsible to plot the ggplot2 scatter plot of given data points. Further, the user needs to call the geom_point() function of the ggplot2 package with the additional alpha argument with this function and specify the alpha value accordingly as per the requirements to make transparent scatterplot points in the gglot2 R programming language."
},
{
"code": null,
"e": 2700,
"s": 2615,
"text": "To install and import the scales package, the user needs to follow the below syntax:"
},
{
"code": null,
"e": 2786,
"s": 2700,
"text": "install.packages(\"ggplot2\") \nlibrary(\"ggplot2\") "
},
{
"code": null,
"e": 3014,
"s": 2786,
"text": "Example: In this example, we will be plotting an of the given data and will be setting the value of the alpha argument to 0.2 to transparent effect in the plotted scatterplot of the ggplot package in the R programming language."
},
{
"code": null,
"e": 3070,
"s": 3014,
"text": "The plot without any transparent effect looks as below:"
},
{
"code": null,
"e": 3072,
"s": 3070,
"text": "R"
},
{
"code": "library(\"ggplot2\") gfg <- data.frame(x = c(1, 2.2, 2, 2, 3, 3, 4.2, 4.1, 5.2, 5.1), y = c(2, 2, 2.5, 2.1, 3.4, 4.1, 4, 4, 5, 5), group = as.factor(1:2)) ggplot(gfg, aes(x, y, col = group)) + geom_point(pch = 18,size = 12)",
"e": 3379,
"s": 3072,
"text": null
},
{
"code": null,
"e": 3387,
"s": 3379,
"text": "Output:"
},
{
"code": null,
"e": 3429,
"s": 3387,
"text": "Using alpha to create a transparent plot:"
},
{
"code": null,
"e": 3431,
"s": 3429,
"text": "R"
},
{
"code": "library(\"ggplot2\") gfg <- data.frame(x = c(1, 2.2, 2, 2, 3, 3, 4.2, 4.1, 5.2, 5.1), y = c(2, 2, 2.5, 2.1, 3.4, 4.1, 4, 4, 5, 5), group = as.factor(1:2))ggplot(gfg, aes(x, y, col = group)) + geom_point(pch = 18,size = 12, alpha = 0.2)",
"e": 3749,
"s": 3431,
"text": null
},
{
"code": null,
"e": 3757,
"s": 3749,
"text": "Output:"
},
{
"code": null,
"e": 3764,
"s": 3757,
"text": "Picked"
},
{
"code": null,
"e": 3773,
"s": 3764,
"text": "R-Charts"
},
{
"code": null,
"e": 3782,
"s": 3773,
"text": "R-ggplot"
},
{
"code": null,
"e": 3791,
"s": 3782,
"text": "R-Graphs"
},
{
"code": null,
"e": 3799,
"s": 3791,
"text": "R-plots"
},
{
"code": null,
"e": 3810,
"s": 3799,
"text": "R Language"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.